Skip to content

fix(picker): cancel background commands when the picker exits - #3560

Merged
max-sixty merged 8 commits into
mainfrom
picker-cancel-previews
Jul 24, 2026
Merged

max-sixty merged 8 commits into
mainfrom
picker-cancel-previews

Conversation

@max-sixty

@max-sixty max-sixty commented Jul 24, 2026 •

Copy link
Copy Markdown
Owner

What

shell_exec gains cancel_background_commands(): it latches a flag that stops
background Cmd::run / Cmd::pipe_into before they spawn, and SIGTERMs the
PIDs of those already running (tracked in a registry each capture-mode command
joins for its lifetime). The picker calls it once, after skim releases the
terminal and after the stashed-warning drain.

Preview diffs pick up --no-optional-locks, matching what wt list's
git status already does: a preview reads a worktree the user may be working
in, and can now be signalled mid-run.

Cancellation covers both accept and abort, and only ever targets background
threads — the foreground thread is the one cancelling, and goes on to run the
switch itself.

Why

Accepting the picker abandoned its preview work rather than stopping it. wt's
exit ends the pool's threads but not the git children they spawned, so those
children kept running, orphaned, computing diffs into an in-memory cache that no
longer existed — churning disk on a repo the user had already left.

Measured on a 5-worktree fixture whose git diff sleeps 15s, with a shell (not
wt) as the PTY session leader, since wt as session leader SIGHUPs its own
children on exit and hides the effect entirely:

children alive at t+0 / +1 / +3 / +6s after wt exits
without cancellation 12 / 12 / 12 / 12
with cancellation 0 / 0 / 0 / 0

Single-variable control: same build, same fixture, cancellation gated off.
Accept latency is unchanged (0.13s).

Why a latch, not just a sweep

A one-shot sweep over live PIDs isn't enough on its own. A task that has already
cleared its caller's supersede check and parked on CMD_SEMAPHORE holds no PID
for the sweep to find, and spawns the moment a permit frees — the very permits
the sweep just freed by signalling everything holding one.

Capping concurrency at 2 to force a queue reproduces it: sweep-only still leaves
survivors, the latch reaches 0. For the same reason a freshly spawned child
re-reads the flag as it registers, so a child spawned into the sweep's window
escapes neither.

This also replaced a first attempt that bumped the preview orchestrator's spawn
generation. That stops queued tasks, but those tasks had already passed the
generation check before parking on the semaphore, so it measured no better than
the sweep alone. One mechanism in shell_exec covers all three states — queued,
parked, running — so the orchestrator is untouched.

Notes

  • alt-x removals are exempt. A removal is dispatched to its own thread so
    the picker stays live, so pressing Enter straight after can leave a
    git worktree remove in flight when the sweep fires. Its result is
    discardable; its effects are not, and a signal between the worktree remove
    and the branch delete would strand the user half-removed.
    shell_exec::uninterruptible exempts a thread from both halves — the sweep
    skips its PIDs, and the latch doesn't refuse the calls it makes afterwards,
    since a removal is several git calls rather than one. The picker routes every
    removal dispatch through one spawn_removal helper that applies the
    exemption, so it's carried by the spawn path itself rather than remembered at
    each call site.

  • SIGTERM, not SIGKILL, so git's lockfile handlers run rather than stranding
    an index.lock in a worktree the user is about to work in.

  • Cancel is ordered after drain_stashed_warnings. A --prs forge call
    killed mid-flight fails like any other and stashes that failure as a warning;
    cancelling first would print a spurious "couldn't fetch PRs" to the user.

  • Cmd::run's plain branch now spawns explicitly instead of calling
    cmd.output(), whose stdio defaults it reproduces exactly — output() hands
    back only the finished result, never the running child.

  • Windows gets the latch but not the signal; a command already running there
    still finishes. Bounding those would take a job object.

  • Tests. The cancelled paths (both refusals and the mid-flight signal) are
    covered by tests/cancel_background.rs, deliberately its own test binary:
    cancellation latches process-wide state and signals every background PID in
    the process, so beside other tests it takes them out — TestRepo's helpers
    drive git through the same Cmd path, and this is a real failure, not a
    theoretical one. Alone in its process it has nothing to collide with, and the
    test is deterministic (a file marker for readiness, not a sleep).

    An earlier revision of this description claimed codecov/patch contradicted
    its own line data. That was wrong — a mis-read of the API on my part, and the
    check was right. Local cargo llvm-cov had been failing to build skim
    (E0554), so I'd taken the API as a substitute for measuring. The build failure
    was a stale local tool: cargo-llvm-cov ≥ 0.7.0 instruments only workspace
    crates instead of the whole dependency graph, so on CI's pinned 0.8.7 skim
    never sees the cfg(coverage) that trips its nightly feature gate. With that
    upgraded, local coverage reproduces codecov's four missed lines exactly.

    Three were in test_background_command_registers_while_running, now removed —
    its poll loop's body only ran when the spawned thread hadn't registered yet.
    Coverage is the lesser reason: the test polled a process-global registry for
    non-emptiness, so under the shared-process runner the coverage job uses it
    could be satisfied by another test's PID and pass without its own command ever
    registering. tests/cancel_background.rs pins that property correctly, and
    more strongly — the sweep reaches a running command only if it registered.

    Three lines are left uncovered, knowingly. One is the spawn-race re-check,
    which by construction only fires on a race that can't be scheduled
    deterministically — covering it would need a scheduling hook in library code,
    which the repo's "no test code in library code" rule rules out. The other two
    are pre-existing: the spawn_removal refactor re-indents the dispatch
    closures, which codecov counts as new patch lines, pulling in the
    morph-failure backstop (the warn and revert_morph calls). That backstop
    only fires when a file appears in the TOCTOU window between the removal's
    safety check and the rename, so it can't be deterministically tested either.
    If codecov/patch reads red, this is why — the structural exemption was
    judged worth more than the metric.

  • PID reuse. Between the kernel reaping a child and the guard's Drop
    removing its PID, a freed PID is briefly still listed. Inherent to signalling
    by PID — the reap and the deregistration aren't one operation — and
    deregistering before the wait isn't a fix but a removal, since the wait is
    the command's lifetime. Documented on BackgroundPid rather than mitigated.

This was written by Claude Code on behalf of Maximilian Roos

## What

`shell_exec` gains `cancel_background_commands()`: it latches a flag that
stops background `Cmd::run` / `Cmd::pipe_into` before they spawn, and
SIGTERMs the PIDs of those already running (tracked in a registry each
capture-mode command joins for its lifetime). The picker calls it once,
after skim releases the terminal and after the stashed-warning drain.

Preview diffs pick up `--no-optional-locks`, matching what `wt list`'s
`git status` already does: a preview reads a worktree the user may be
working in, and can now be signalled mid-run.

Cancellation covers both accept and abort, and only ever targets
background threads — the foreground thread is the one cancelling, and
goes on to run the switch itself.

## Why

Accepting the picker abandoned its preview work rather than stopping it.
`wt`'s exit ends the pool's threads but not the `git` children they
spawned, so those children kept running, orphaned, computing diffs into
an in-memory cache that no longer existed — churning disk on a repo the
user had already left.

Measured on a 5-worktree fixture whose `git diff` sleeps 15s, with a
shell (not `wt`) as the PTY session leader, since `wt` as session leader
SIGHUPs its own children on exit and hides the effect:

    without cancellation:  12 children alive at t+0/1/3/6s after exit
    with cancellation:      0 at every sample, accept latency unchanged

A one-shot sweep is not enough on its own. A task that has cleared its
caller's supersede check and parked on `CMD_SEMAPHORE` holds no PID for
the sweep to find, and spawns the moment a permit frees — the very
permits the sweep just freed. Capping concurrency at 2 to force a queue
reproduces it: sweep-only still leaves survivors, the latch reaches 0.
For the same reason a freshly spawned child re-reads the flag as it
registers, so one spawned into the sweep's window doesn't escape both.

SIGTERM, not SIGKILL, so git's lockfile handlers run rather than
stranding an `index.lock` in a worktree the user is about to work in.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewing as a draft — flagging anything that looks worth a quick fix. Mark ready for a full review.

The latch-plus-registry design reads well: the register-then-re-read-the-flag handshake in track_if_background closes the spawn/sweep window, and checking background_cancelled() after the semaphore permit covers the parked-task case the "Why a latch, not just a sweep" section describes. --no-optional-locks matches working_tree.rs's git status, and SIGTERM-not-SIGKILL is the right call for the index.lock handlers. One residual PID-lifecycle question inline — low severity, likely not worth changing, but worth a conscious call.

Comment thread src/shell_exec.rs Resolved
max-sixty and others added 2 commits July 23, 2026 17:32
Reaping happens inside the wait the guard outlives, so a freed PID is
briefly still listed and a sweep in that window could signal whatever
reused the number. Inherent to signalling by PID; deregistering before
the wait would remove cancellation entirely rather than fix it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Covers the run/pipe_into refusals and the mid-flight signal, which
codecov/patch flagged as the only untested lines in the change.

Its own binary, not another module under `integration`: cancellation
latches process-wide state and signals every background PID in the
process, so beside other tests it takes them out — TestRepo's helpers
drive git through the same Cmd path. Alone in its process it has nothing
to collide with, and the test is deterministic rather than timing-based.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@max-sixty
max-sixty marked this pull request as ready for review July 24, 2026 01:50

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One concern on the data-safety surface, flagged inline at the cancel_background_commands() call — the sweep can SIGTERM an in-flight alt-x worktree/branch removal, not just the read-only preview diffs the comment assumes. Not approving pending a call on whether to scope the cancellation (or join the removal threads first).

The latch/registry mechanics themselves read well, and the prior PID-reuse thread is addressed.

Comment thread src/commands/picker/mod.rs Resolved
An `alt-x` removal is dispatched to its own thread so the picker stays
live, so pressing Enter straight after can leave a `git worktree remove`
in flight when the sweep fires. Signalling it mid-run risks stranding a
half-removed worktree — and unlike a preview, its effects aren't
discardable even though its result is.

`shell_exec::uninterruptible` marks a thread's commands exempt from both
halves of cancellation: the sweep skips its PIDs, and the latch doesn't
refuse the calls it makes afterwards (a removal is several git calls, not
one). The two removal dispatches opt in.

Reported by the automated reviewer; my own comment had asserted that
everything cancelled here was read-only, which was false.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The uninterruptible latch resolves the alt-x concern cleanly — routing exemption through a thread-local that both track_if_background and background_cancelled consult closes both halves (the sweep skips the PID, and the post-sweep git calls of a multi-step removal aren't refused), and do_removal runs its git work synchronously on that thread so the whole git worktree remove → git branch -D sequence is covered. The exemption is scoped to the sweep only, so a real SIGINT still forwards through the signal handler, and removals go back to running to completion the way they did before this PR rather than being interrupted mid-op. The test exercising both directions plus the after-sweep spawn is a good pin.

One note, no change requested: "finishes what it started" holds against the sweep, but not against process exit — the foreground thread doesn't join these detached threads before wt goes on to the switch and exits, so a removal can still be cut short if the process tears down first (same race as the pre-PR orphaned thread, just now un-signalled). That's an inherent limitation of the optimistic-UI design, not something to fix here.

Not posting an approval: this lands on the worktree/branch removal surface, which per the repo's data-safety convention I leave for a human merge call rather than auto-approving — the flagged concern is resolved, so nothing is outstanding on my end.

max-sixty and others added 3 commits July 24, 2026 07:37
`test_background_command_registers_while_running` polled `BACKGROUND_PIDS`
for non-emptiness, but the registry is process-global. Under a shared-process
runner — which is what the coverage job's `cargo test` is — the loop can exit
on another test's PID, so the test passes without its own command ever
registering. A test that can be satisfied by unrelated work isn't pinning the
property it names.

`tests/cancel_background.rs` already pins it, and more strongly: the sweep
reaches a running command only if that command registered, so if registration
regressed the signal never lands and its `sleep` runs to completion. Note that
on the test rather than leave the guarantee looking untested.

Also clears three `codecov/patch` misses, which is how the unsoundness
surfaced: the poll loop's body only executes when the spawned thread hasn't
registered yet, so it read as dead on CI.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
An older `cargo-llvm-cov` leaks `--cfg=coverage` into every dependency, and
skim gates a nightly feature on it, so the run dies at E0554 before measuring
anything. Left undiagnosed that reads as "local coverage is broken here" and
pushes the next reader onto codecov's API, which answers a narrower question.

Also names the compare API field that actually reproduces the patch
percentage, since the two diff totals it returns disagree.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- track_if_background → track_if_cancellable: the gate is cancellability,
  and an uninterruptible background thread is deliberately not tracked
- inline the single-caller sweep loop into cancel_background_commands
- name both registration exemptions on BACKGROUND_PIDS
- CLAUDE.md: the picker cancels unfinished network work on exit rather
  than merely abandoning it

Co-Authored-By: Claude Fable 5 <[email protected]>
Route both alt-x removal dispatches through spawn_removal, which owns
the thread naming and the uninterruptible wrap, so the cancellation
exemption is carried by the spawn path itself rather than remembered at
each call site.

Re-indenting the dispatch closures pulls the (untestable) morph-failure
backstop lines into the codecov patch; accepted deliberately — coverage
doesn't outrank the better structure.

Co-Authored-By: Claude Fable 5 <[email protected]>
max-sixty added a commit that referenced this pull request Jul 24, 2026
## The failure this fixes

A session working on the picker found a structural improvement: routing
both removal dispatches through a `spawn_removal` helper, so the
uninterruptible-cancellation exemption lives in one place instead of
being remembered at each spawn site. It declined to make the change,
because the helper re-indents the morph closure's body and pulls two
pre-existing uncovered lines (a failure-path warn and a `revert_morph`
call) into the patch. Projected `codecov/patch`: ~97.3% against an
`auto` target of ~97.8%. Red. The improvement was shelved.

The section it was reading said "NEVER merge a PR with failing
`codecov/patch` without explicit user approval," then "on failure,
investigate and fix the gap," then "if you believe it's a false
positive, ask." Every route treats a red patch as a defect in the
change. The cheapest way to satisfy all three is to not make the change.

## What changed

The Coverage section now separates the two decisions it was conflating.
The check gates the merge; it never gates the design. A predicted red
patch is not a reason to shelve or water down an improvement, and
neither the code nor the tests get contorted to move the number. The
merge rule is unchanged: still never merge red without approval. What is
new is the route through it when the gap isn't real (misses that predate
the change, or a path with no deterministic trigger): push the change
and ask, handing over which lines, why they can't be covered, and what
the patch percentage comes to.

Two smaller corrections ride along:

- "Remove unused code" to green the number now excludes a rarely-reached
backstop that's load-bearing. The picker lines in question guard a
TOCTOU window during rename-based removal, and the repo's Data Safety
rules would rather keep them.
- `tests/CLAUDE.md`'s note on rename false positives now covers the
mechanism that caused this. Codecov counts any line the diff relocates
as a patch line, re-indentation included, not just a `git mv`.

The `spawn_removal` refactor itself is not in this PR: it touches picker
code mid-flight on #3560.

> _This was written by Claude Code on behalf of @max-sixty_

Co-authored-by: Claude Opus 5 <[email protected]>
@max-sixty
max-sixty merged commit bb43011 into main Jul 24, 2026
38 of 39 checks passed
@max-sixty
max-sixty deleted the picker-cancel-previews branch July 24, 2026 23:36
max-sixty added a commit that referenced this pull request Jul 25, 2026
…3583)

Documents three user-facing fixes that landed on `main` after the
v0.69.1 release branch was cut. They shipped in the v0.69.1 binary (the
release squash-merged onto the current `main` tip) but weren't yet in
the `## 0.69.1` changelog section, so this adds them under 0.69.1 where
they belong — no version change.

- **#3567** — `wt -C` honoured by `wt list statusline`
- **#3579** — `wt step squash`/`wt step commit` refuse to commit
unresolved conflicts; unified `wt list` operation gutter symbol
- **#3560** — `wt switch` picker cancels its orphaned background preview
processes on exit

Each was independently reviewed for the data-loss surface as part of the
release (all clean; #3579 is safety-positive).

> _This was written by Claude Code on behalf of max_

Co-authored-by: Claude Sonnet 5 <[email protected]>
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.

2 participants