Skip to content

fix(remove): drain the trash with one background process per repository - #4516

Merged
max-sixty merged 5 commits into
mainfrom
rm
Oct 20, 2026
Merged

max-sixty merged 5 commits into
mainfrom
rm

Conversation

@max-sixty

@max-sixty max-sixty commented Oct 20, 2026 •

Copy link
Copy Markdown
Owner

A prune of many worktrees started one rm -rf per staged worktree. On a 193-worktree prune those processes competed for the disk: together they deleted about 1,500 files/s on 3 cores, while a single rm alone managed 3,000–5,400 files/s on under one core. Read-only directories (dr-xr-xr-x, as installers leave them) also made rm -rf fail, so those entries stayed in .git/wt/trash/ and every later sweep retried them.

Removal now starts a hidden wt _drain-trash, which holds .git/wt/trash.lock and deletes every staged entry, including entries staged while it runs. A removal or sweep that finds the lock held starts nothing, so a prune runs about one deleter. The sweep after wt remove drains leftovers immediately rather than waiting 24 hours. Priority is unchanged (taskpolicy -b on macOS).

The drain uses wt's own walker (src/remove_dir.rs), which wt remove --foreground and wt config state clear also use:

  • On Unix it opens each directory relative to its parent's descriptor with O_NOFOLLOW and unlinks relative to the holding directory. The old path-based walker could follow a directory swapped for a symlink mid-walk and delete outside the tree; a swap-race script reproduced that, and the new walker lost nothing in 20 runs.
  • It grants the owner rwx on each directory it enters, so read-only and unreadable trees are deleted, never changing a symlink's target. Linux's fchmodat has no AT_SYMLINK_NOFOLLOW, so there it opens the directory with O_PATH | O_NOFOLLOW and changes the mode through /proc/self/fd.
  • Subdirectories are removed sequentially, so open descriptors stay bounded by depth. On a 199k-entry pnpm node_modules it deleted about twice as fast as rm -rf.
  • On Windows it uses std::fs::remove_dir_all, which removes junctions without following them.

This was written by Claude Code on behalf of max-sixty

max-sixty and others added 2 commits October 19, 2026 18:24
A prune of many worktrees started one `rm -rf` per staged worktree. On a
193-worktree prune these competed for the disk and together deleted about
1,500 files/s on 3 cores, while a single deleter managed 3,000-5,400 files/s
on under one core. Read-only directories (`dr-xr-xr-x`, as installers leave
them) also made `rm -rf` fail, so those entries stayed in the trash and every
later sweep retried them.

Removal now starts a hidden `wt _drain-trash`, which holds
`.git/wt/trash.lock` and deletes every staged entry, including ones staged
while it runs. A removal or sweep starts no second drain while one holds the
lock. The sweep after `wt remove` drains leftovers immediately rather than
after 24 hours.

The drain uses wt's own removal walker. On Unix it now opens each directory
relative to its parent's descriptor with O_NOFOLLOW and unlinks relative to
the holding directory, so a directory swapped for a symlink mid-walk can no
longer redirect deletion outside the tree (the path-based walker could, and
`wt remove --foreground` used it). It grants the owner rwx on directories it
enters, removes subdirectories sequentially so open descriptors stay bounded
by depth, and deletes about twice as fast as `rm -rf` on a pnpm
node_modules. Elsewhere it uses `std::fs::remove_dir_all`, which removes
junctions without following them.

A `wt` binary inside the removed worktree still starts the drain: its path
is captured before staging and remapped into the staged directory.

Co-Authored-By: Claude Opus 5.5 (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.

This PR changes what worktrunk deletes, so I'm holding it for a maintainer's decision rather than approving, per the data-loss rule in .claude/skills/running-tend/references/review-pr.md. It widens deletion in two places:

  • The sweep no longer waits 24 hours. sweep_trash and drain_trash now delete every <name>-<digits> entry in .git/wt/trash/ as soon as any removal runs, where collect_stale_trash_entries used to skip fresh entries so concurrent removals wouldn't race. On the current tree that is safe: rename_into_trash prunes the registration right after the rename and never restores a staged entry. But this PR now relies on a rule that nothing else writes there: any entry in the trash may be deleted at once.
  • The new walker changes permissions before deleting. remove_dir_with_progress adds owner rwx to every directory it enters, so it can now delete read-only trees that rm -rf and the old walker left behind. All of its callers (drain_trash, cleanup_staged_with_progress, clear_trash) pass paths under the trash, so its reach is still limited to staged entries.

Conflict with #4459 (and #4463). #4459 redesigns the same sweep: it keeps collect_stale_trash_entries with the 24-hour threshold, and it keeps checkouts whose registration move hasn't finished, stating "Containers without a committed registration are preserved". If that design lands, an immediate drain of every timestamped entry could delete a checkout #4459 means to keep recoverable. Whichever lands second has to decide which trash entries the drain may delete; this is more than a textual merge conflict.

On Linux, `fchmodat` has no `AT_SYMLINK_NOFOLLOW`, so the walker left
directories their owner can't read (mode 000) in the trash. It now opens such
a directory with `O_PATH | O_NOFOLLOW`, which needs no permission on it, and
changes the mode through the descriptor's `/proc/self/fd` link.

`remove_dir_with_progress` now reports whether the path is gone, which the
drain and `wt config state clear` used to check separately. The walker opens
the root relative to the working directory, dropping the parent lookup.

The cleanup-spawn-failure test no longer expects the staged entry to stay:
`wt remove`'s sweep starts a drain that deletes it.

Co-Authored-By: Claude Opus 5.5 (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.

Folding remove_path into remove_entry(CWD, path) dropped its early return for paths with no final name. Before, remove_dir_with_progress did nothing for /, ., .., or x/.., because path.parent()/file_name() returned None. Now openat(CWD, path, DIR_FLAGS) opens that directory and empty_dir deletes everything in it. Today's callers only pass entries under .git/wt/trash/, so nothing reaches this yet. Still, this is the public deletion helper, and a caller bug that passes such a path would now empty the working directory or / when it used to do nothing. A one-line guard keeps the old behaviour.

Comment thread src/remove_dir.rs Resolved
max-sixty and others added 2 commits October 19, 2026 19:50
Opening the root relative to the working directory dropped the parent and
name lookup that refused `/`, `.`, and `x/..`; such a path would now be
emptied. The public helper refuses it, as `rm -rf` does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ed worktree

Only a dev build run from the worktree it removes has its binary moved into
the trash. There the drain fails to start and the next removal drains the
entry, so the remapping isn't worth its code. Its test also failed with
ETXTBSY on Linux: a copied binary's write descriptor leaked into a child
forked by a concurrent test.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@max-sixty
max-sixty merged commit 25d0c44 into main Oct 20, 2026
42 checks passed
@max-sixty
max-sixty deleted the rm branch October 20, 2026 05:12
max-sixty pushed a commit that referenced this pull request Oct 20, 2026
…sh lock (#4530)

The nightly `feature-powerset` job
[failed](https://github.com/max-sixty/worktrunk/actions/runs/39376521570)
in
`git::remove::tests::drain_trash_deletes_staged_entries_once_the_lock_is_free`
(added in #4516) with `assertion failed:
staged_trash_entries(&trash).is_empty()`. This is a race in the test,
not a bug in the drain. After the test drops its lock holder, it expects
the next `drain_trash` to get the lock. But another test in the same
process can fork a child while the holder is open. That child inherits
the descriptor, and the flock stays held until it execs. The drain sees
`WouldBlock` and exits, leaving the deletion to the holder, as designed.
`test_configure_shell_opens_rc_with_exclusive_lock` has the same race on
the rc-file lock.

Both tests now wait for the release through the shared
`testing::wait_for` helper. It polls with a bounded timeout and stops at
the first success, so on Windows the test never asks a handle that
already holds the lock to take it again.

Verification: I reproduced the race with a scratch test that ran the
same lock/release/drain sequence 2000 times while four threads spawned
`true` in a loop. The first drain left the entry behind in 17–20 of the
2000 iterations. With the retry, no iteration left it. Both tests pass
locally, and clippy is clean.

The same window exists in production, but it only delays cleanup: a
staged entry waits in the trash until the next removal's drain. The doc
comment on `trash_drain_running` already accepts a similar window, so
this PR doesn't change the drain itself.

Refs #4509

---------

Co-authored-by: worktrunk-bot <[email protected]>
max-sixty pushed a commit that referenced this pull request Oct 26, 2026
… picker tabs (#4529)

This PR fixes comments, user docs, and maintainer skills that no longer
match the code. There are no behavior changes. #4516 replaced the trash
sweep, and several references still describe the old one. A few other
docs were wrong before that.

- **Troubleshooting, `wt list` timeout example**: the warning prints
`TaskKind::display_name()` labels (`working-tree diff, working-tree
conflict check`), not the kebab-case names the example showed. The
snapshot in `format_drain_timeout_diag`'s tests uses the same labels.
- **Troubleshooting, config checklist**: dropped "path must be relative,
not absolute". No such validation exists, and `worktree-path` accepts
absolute paths.
- **`drain_trash` doc** (`src/git/remove.rs`): dropped "Every staged
removal starts a drain". That describes the behavior #4516 replaced.
Removals now skip spawning when a drain is already running.
- **State module doc**: the default-branch override key is
`worktrunk.default-branch`, not `worktrunk.default_branch.*`.
- **Summary tab number**: `PreviewMode::Summary = 6`, so the `[list]
summary` doc comment and a test comment now say tab 6 instead of 5.
- **`release` skill**: the safety-scan note named "the trash sweep in
`src/commands/process.rs`" as the densest destructive code outside
`src/git/`. That sweep now only spawns a drain; the deletion walk is in
`src/remove_dir.rs`, so the note points there. `unlinkat`, the walk's
primitive, is added to the keyword regex, which would otherwise miss
changes to it.
- **`writing-user-outputs` skill**: `sweep_stale_trash` is now
`run_internal_sweep`.

The plugin skills mirror was regenerated, and `test_docs_are_in_sync`
and the `switch_picker_dry_run` tests pass. No regression test is needed
because no behavior changed.

Co-authored-by: worktrunk-bot <[email protected]>
max-sixty pushed a commit that referenced this pull request Oct 26, 2026
…#4527)

`test_switch_picker_abort_with_escape` failed on Windows in the
`affected` run on main ([run
39373658313](https://github.com/max-sixty/worktrunk/actions/runs/39373658313)).
Its list snapshot held only the prompt line `>`, with no header and no
`@ main` row. The commit that triggered the run (#4516, trash draining)
doesn't touch the picker, so this is a test timing race.

**Cause.** This is the only capture-before-abort test that passes no
inputs (`&[]`). So the only thing that gates its capture is
`boot_picker_pty`: it waits for the `> ` prompt, then for the screen to
sit unchanged for `STABLE_DURATION` (500ms). Items load asynchronously.
On a loaded Windows runner the prompt can stay quiet for 500ms before
the first row arrives, and the test captures that frame.

**Fix.** Gate the capture on `"has no file changes"`. That preview text
appears only after the list has a selected row, so it confirms both
panels before the capture. The sibling tests already gate the same way
(`&[("", Some("plain-branch"))]`, `&[("", Some("@ main"))]`). If the
preview never renders, the test now panics after 30s and shows the
screen, instead of producing a snapshot diff. The committed snapshots
don't change.

**Verification.** All 32 `switch_picker` tests pass locally with
`--features shell-integration-tests`. I couldn't reproduce the race on
Linux, even under CPU load (0/15 runs on the original code), so the
evidence is the code path above plus the failing frame from the run.

Co-authored-by: worktrunk-bot <[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