Skip to content

fix(selection): close debounce timers safely#174

Open
ThomasK33 wants to merge 1 commit intomainfrom
fix/selection-debounce-timer-172
Open

fix(selection): close debounce timers safely#174
ThomasK33 wants to merge 1 commit intomainfrom
fix/selection-debounce-timer-172

Conversation

@ThomasK33
Copy link
Copy Markdown
Member

Fixes #172.

What changed

  • Replaced selection debouncing to use an explicit libuv timer (vim.uv/vim.loop) rather than vim.defer_fn().
  • Ensured debounce timers are always :stop()'d + :close()'d when cancelled or fired.
  • Guarded against stale timer callbacks (e.g. when a newer debounce supersedes an older one).
  • Ensured selection.disable() cancels any pending debounce/demotion timers.

Why

The previous code mixed vim.defer_fn() for creation with vim.loop.timer_stop() for cancellation and never closed the timer handle, which could lead to leaked handles and/or stale callbacks under rapid selection/cursor events.

Testing

  • nix develop .#ci -c luacheck lua/claudecode/selection.lua tests/selection_test.lua --no-unused-args --no-max-line-length
  • nix develop .#ci -c make test

📋 Implementation Plan

Plan: Fix issue #172 (timer API mismatch / unsafe debounce timer cleanup)

Context / Why

Issue #172 reports that lua/claudecode/selection.lua creates a debounce timer via vim.defer_fn() but cancels it via vim.loop.timer_stop(), and does not close() the timer handle. This can lead to inconsistent timer handling and (more importantly) leaked or double-closed timer handles under rapid events, which may contribute to crashes on newer Neovim versions.

Goal: Make selection debouncing use a single, consistent libuv timer API and ensure timers are always safely stopped + closed when cancelled or fired.

Evidence (verification)

  • GitHub issue Bug: Timer API mismatch in selection.lua - mixing vim.defer_fn with vim.loop.timer_stop #172 content (includes affected code, environment Neovim 0.11.5, suggested diff). (Fetched via tool.)
  • Current code confirms the reported pattern:
    • lua/claudecode/selection.lua:49 and :111 call vim.loop.timer_stop(M.state.debounce_timer).
    • lua/claudecode/selection.lua:114 assigns M.state.debounce_timer = vim.defer_fn(...).
  • Local Neovim probe (v0.12.0-dev in this workspace) confirms vim.defer_fn() returns a userdata timer handle with :stop() and :close() methods.

Plan

1) Implement a safe debounce timer using a libuv handle (no vim.defer_fn)

File: lua/claudecode/selection.lua

  • Replace the debounce implementation to use vim.loop.new_timer() (or local uv = vim.uv or vim.loop then uv.new_timer()), matching the rest of the module’s timer usage.
  • Key requirements:
    • Cancel path must stop() + close() the previous timer and set M.state.debounce_timer = nil before stopping/closing so any already-scheduled callback becomes a no-op.
    • Callback path must verify it is still the active timer (if M.state.debounce_timer ~= timer then return end) to avoid stale callbacks running after re-debounce.
    • Callback must stop() + close() the timer and clear state before calling M.update_selection().

Suggested structure (pseudocode):

  • M._cancel_debounce_timer() helper:
    • if M.state.debounce_timer then
      • local t = M.state.debounce_timer
      • M.state.debounce_timer = nil
      • t:stop(); t:close()
  • M.debounce_update():
    • call M._cancel_debounce_timer()
    • create timer = uv.new_timer()
    • M.state.debounce_timer = timer
    • timer:start(M.state.debounce_ms, 0, vim.schedule_wrap(function() ... end))

2) Fix disable() cleanup to stop + close the debounce timer

File: lua/claudecode/selection.lua

  • Replace the current vim.loop.timer_stop(M.state.debounce_timer) call with the same safe cancellation helper from step 1.
  • (Optional but recommended while touching cleanup): also cancel M.state.demotion_timer in disable() using the existing :stop(); :close(); nil pattern to prevent delayed callbacks firing after tracking is disabled.

3) Update/extend unit tests to cover the debounce contract

Files:

  • tests/selection_test.lua (standalone vim mock)
  • Potentially tests/mocks/vim.lua (shared mock) if needed

Add tests that validate:

  • Calling selection.debounce_update() twice rapidly cancels/cleans the previous timer (assert stop() and close() called once on the old handle).
  • A stale callback (from a cancelled timer) does not call update_selection().
  • selection.disable() cancels the active debounce timer without error.

To make this deterministic in unit tests, adjust the timer mock to:

  • store callback from timer:start(...) without auto-executing, and expose a timer:fire() helper for tests.

4) Regression check

  • Run make check (syntax + luacheck).
  • Run make test (busted).

Notes / Rationale

Why avoid “just change timer_stop to :stop()/:close()” while keeping vim.defer_fn?

vim.defer_fn() typically wraps a libuv timer and closes it internally when it fires. If we also close() the handle on cancel, there is a race where the timer fires, schedules its wrapper callback, then we cancel+close, and later the wrapper tries to close again. Implementing the debounce timer directly with uv.new_timer() gives us full control and enables a simple “stale timer” guard.


Generated with mux • Model: openai:gpt-5.2 • Thinking: xhigh

Change-Id: I4caa6d010f8f824aff1c38a7a73d08d47b400cce
Signed-off-by: Thomas Kosiewski <tk@coder.com>
@ThomasK33
Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector
Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@ThomasK33
Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector
Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@ThomasK33
Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector
Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ThomasK33
Copy link
Copy Markdown
Member Author

/coder-agents-review

Copy link
Copy Markdown

@coder-agents-review coder-agents-review Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The debounce timer rework is well done. The nil-before-stop pattern in _cancel_debounce_timer() and the identity-based stale guard in the callback together correctly eliminate the race between cancellation and scheduled callback execution. The test suite covers the three hardest scenarios: re-debounce cancellation, stale callback rejection, and cleanup on disable. The plan was thorough and the implementation matches it.

One P2, three P3s, three nits.

The P2 is that the demotion timer callback (line 258, pre-existing) has the same class of stale-callback bug this PR fixes for the debounce timer. Seven reviewers independently flagged it. The PR modified the demotion timer's cleanup path in disable() and demonstrated the correct identity-guard pattern for debounce; the same pattern should be applied to the demotion callback. Details in the inline comment.

"What happens when they are not the same timer? Shall I show you?" (Hisoka)


lua/claudecode/selection.lua:258-264

P2 [DEREM-3] The demotion timer callback lacks the identity guard that the debounce callback has at line 152. A stale callback from a cancelled timer can close a replacement timer or corrupt latest_selection across a disable/enable cycle.

Sequence (Hisoka):

  1. User exits visual mode. Demotion timer A starts (50ms).
  2. Timer A fires. vim.schedule_wrap queues callback_A.
  3. Before Neovim drains the queue, user types viw<Esc>. Entering visual cancels A (lines 209-212). Exiting creates timer B at line 254.
  4. callback_A runs. M.state.demotion_timer is truthy (points to B). Lines 260-262 stop, close, and nil timer B.
  5. Timer B's callback never fires. Demotion is permanently lost.

Separately (Meruem): after disable() nils and closes the timer, the queued callback still falls through to handle_selection_demotion(), which sets latest_selection. Since enable() does not reset latest_selection, this stale value persists into the next session.

The fix is the same pattern used for debounce: capture the timer instance in the closure and compare identity before acting.

local demotion_handle = vim.loop.new_timer()
M.state.demotion_timer = demotion_handle
demotion_handle:start(
  M.state.visual_demotion_delay_ms,
  0,
  vim.schedule_wrap(function()
    if M.state.demotion_timer ~= demotion_handle then
      return
    end
    M.state.demotion_timer = nil
    demotion_handle:stop()
    demotion_handle:close()
    M.handle_selection_demotion(current_buf)
  end)
)

(Hisoka P2, Meruem P2, Kite P3, Mafuuu P3, Takumi P3, Pariston P4, Chopper P4)

🤖

lua/claudecode/selection.lua:37

P3 [DEREM-7] The doc comment says "stops any active debounce timers" but this PR added demotion timer cleanup at lines 52-58. The doc now omits half the cleanup this function performs.

Suggestion: ---Clears autocommands, resets internal state, and cancels any pending debounce or demotion timers.

(Leorio P3)

🤖

🤖 This review was automatically generated with Coder Agents.

Comment on lines +72 to +73
assert(timer.stop, "Expected debounce timer to have :stop()")
assert(timer.close, "Expected debounce timer to have :close()")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 [DEREM-4] These asserts re-check timer.stop and timer.close on handles that already passed the same checks at creation (lines 141-143). They cannot fail for handles created through the normal code path.

More importantly, _cancel_debounce_timer() is called from disable() at line 50 before the demotion timer cleanup at lines 52-58. If these asserts throw (however unlikely), the demotion timer cleanup never runs and that handle leaks. Cleanup paths should not throw.

The codebase convention is to trust the libuv API contract: init.lua:95, server/tcp.lua:252, and the demotion timer at line 254 all call timer methods without asserting their existence first.

Consider removing lines 72-73 (and 141-143 in debounce_update). The useful asserts are line 137 (debounce_ms type check) and line 140 (nil-return guard from uv.new_timer()).

(Takumi P3, Hisoka P3, Zoro P3, Chopper Nit, Gon Nit, Kite Nit, Leorio Nit, Pariston Nit)

🤖

M.state.debounce_timer = nil
M._cancel_debounce_timer()

if M.state.demotion_timer then
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 [DEREM-1] The demotion timer cleanup (lines 52-58) is new code added by this PR but has no test coverage. The debounce timer cleanup in the same function is tested ("disable() should cancel an active debounce timer"), but no test sets up or checks demotion_timer during disable().

A test that enables tracking, assigns a mock timer to M.state.demotion_timer, calls disable(), and asserts stop/close/nil would cover this.

(Netero P3, Mafu-san P3)

🤖

Comment thread tests/selection_test.lua
describe("debounce_update", function()
it("should cancel and close previous debounce timer when re-debouncing", function()
local update_calls = 0
local old_update_selection = selection.update_selection
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 [DEREM-6] Tests 1 and 2 in this block patch selection.update_selection at the top and restore at the bottom. If any assertion between them fails, the restore never runs. Test 2 then saves the leaked closure as old_update_selection, patches over it, and restores the wrong function when it finishes. The real update_selection is lost for the rest of the suite.

Consider a before_each/after_each pair on the debounce_update describe block, or use finally inside each test.

(Bisky P3)

🤖

local logger = require("claudecode.logger")
local terminal = require("claudecode.terminal")

local uv = vim.uv or vim.loop
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit [DEREM-5] local uv = vim.uv or vim.loop is introduced for forward compatibility but only used at line 139. The demotion timer at line 254 (vim.loop.new_timer()) and line 221 (vim.loop.now()) still call vim.loop directly. If/when Neovim removes vim.loop, the debounce timer survives and the demotion timer breaks. Either apply uv to all timer/loop calls in the file, or drop the alias and use vim.loop consistently.

(Meruem P3, Gon Nit, Hisoka Nit, Mafuuu Nit, Zoro Nit)

🤖

return
end

-- Clear state before stopping/closing so cancellation is idempotent.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit [DEREM-8] Comment says "so cancellation is idempotent" but this is the fire path, not the cancel path. The nil here prevents a later _cancel_debounce_timer from double-stopping, but that's not what "cancellation is idempotent" communicates. Line 69 has the correct framing for the same pattern: "so any already-scheduled callback is a no-op."

(Gon Nit)

🤖

Comment thread tests/selection_test.lua

return timer
end,
timer_stop = function(timer)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit [DEREM-10] The timer_stop mock is dead code. This PR removed all vim.loop.timer_stop() calls from production. No test exercises this mock. Could be removed to avoid implying the function is still used.

(Meruem Nit)

🤖

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Timer API mismatch in selection.lua - mixing vim.defer_fn with vim.loop.timer_stop

1 participant