Skip to content

fix(worktrees): delete a worktree outside the store's ownership lock - #2133

Merged
yyhhyyyyyy merged 21 commits into
mainfrom
hui/worktree-delete-lock-scope-2
Nov 24, 2026
Merged

yyhhyyyyyy merged 21 commits into
mainfrom
hui/worktree-delete-lock-scope-2

Conversation

@yyhhyyyyyy

@yyhhyyyyyy yyhhyyyyyy commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

A managed worktree removal held SessionStore's ownership lock from its checks through the Git or filesystem deletion, so every unrelated Session creation, fork and deletion in the daemon waited for it, and the non-force removal of an unregistered task directory followed a symlink swapped in after its content check and deleted a same-named empty directory outside the managed root.

Fixes #2124. Refs #1981, #1986.

The removal now registers the resolved path in an in-memory set under the ownership lock, releases the lock and runs the deletion in the removal's own task, which clears the path only when the deletion returns. The directory record is deleted after the physical removal succeeds; a failed removal reports its error to its caller and leaves no registration, and dropping the caller stops neither the deletion nor the registration. A Session creation or fork whose workspace, and a worktree association whose root, is at, under or above a registered path is refused with the existing invalid / is being removed error while it runs, and a repeated worktree.remove of that path is refused with worktree_in_use. A managed worktree creation compares the directory it chose against the same set under the same lock and moves to another task id while a removal covers that path, and it registers that directory in the same lock until its Session row exists, or until its failed creation's rollback hands that registration over to the path's deletion, so a removal that starts while the worktree is built is refused instead of deleting it. Every removal path follows the same two steps, and each edge of the scheme is handled explicitly:

  • The lock-scope change reaches every removal path: store.removeWorktree (the Git removal and cleanup_unregistered_root), store.removeUnregisteredDirectory, the prune candidates that call the same removal, and a failed creation's discard.
  • Session creation, fork and association canonicalize under the ownership lock and compare both directions, so a route through a symlink and the directory it names overlap, and a create at the removed path's parent is refused too because its content is being deleted.
  • A worktree creation that would pick the task id of a registered path does not wait and is not refused there: the path may be free again as soon as the deletion returns, and the creation has nothing to keep at the old one, so the allocation moves to another task id and reports worktree_in_use only when three attempts all meet a registration.
  • A creation registers the directory it chose under the ownership lock before it builds there and holds that registration until its Session row is written, or until its failed creation's rollback takes that registration over as the path's deletion registration in the same lock hold. A removal that registers that path, a path above it or a path below it in between is refused with worktree_in_use and is being created, so the window between the creation's directory check and its Session row cannot hand the worktree to a deletion; the hand-over leaves no moment in which neither registration covers the path, so a creation that found the path free before the failure cannot register it between the two, and a failed creation still removes its worktree and branch.
  • A second removal, or a removal of an overlapping path, meets the registration and returns worktree_in_use instead of racing the first deletion.
  • store.removeWorktreeDirectory meets the same registration and refuses to delete the record of a path that is being removed, so a plugin cannot remove it under the deletion.
  • A stored fork configuration that names no workspace has nothing to compare: an empty cwd is skipped instead of matching every registered path.
  • The registration ends in the same task as the deletion, so a dropped caller cannot clear it early; the two tests below park the deletion and observe the refusal.
  • The set is memory only: a crash leaves a partly deleted directory, which the same removal deletes again; there is no tombstone on disk.
  • worktree.list keeps its behavior; a creation never builds at a path a removal registered, so the deleted path keeps no directory and a removal that already deleted the files cannot hand the same path to a new worktree.

On Unix, the non-force unregistered removal opens the task directory and its parent and deletes each recorded empty child and then the task directory by name with unlinkat, so a symlink that replaces the task directory or one of its children after the check refuses the removal with the existing in-use error instead of redirecting it outside the managed root. Windows has no ready-made deletion that removes only an empty directory relative to an open directory handle, so the non-force removal of an unregistered directory now fails closed with the existing worktree_in_use error and asks for --force; --force removes the tree with std::fs::remove_dir_all, which walks it through directory handles and does not follow a reparse point inside it. Registered worktree removals and --force removals are unchanged.

The Send + 'static bound on the removal callback is Rust's requirement for the task that now runs the deletion: store.removeWorktree's data-face shape is unchanged, npm/plugin.d.ts still declares remove: (path: string) => Promise<void>, npm/branch-services.d.ts does not name the method, and no Rust caller outside this crate uses it.

Tests. Against 6e86d48 with this change removed, these fail, and each passes after it:

  • worktrees::an_unregistered_removal_refuses_its_path_without_holding_the_lock and worktrees::a_recorded_removal_refuses_its_path_without_holding_the_lock: with the deletion parked, an unrelated creation completes, and a creation at, under or above the removed path, an association and a repeated removal are refused.
  • worktrees::a_failed_removal_reports_the_error_and_keeps_no_registration: the deletion's error reaches the caller and the workspace is usable again.
  • worktrees::tests::a_swapped_task_directory_does_not_redirect_the_removal and worktrees::tests::a_swapped_child_does_not_redirect_the_removal: the directory a symlink names outside the managed root is left alone; the existing content checks still refuse content that appears after the check.

Two tests added while this change was in review fail on 0b714f8, the head before their fixes, and pass after them:

  • worktrees::dropping_the_caller_keeps_the_removal_and_its_path_refused: dropping the caller of a recorded removal keeps the spawned deletion running, the path refused and its record undeletable until it ends.
  • worktrees::a_fork_without_a_workspace_is_not_refused_by_an_unrelated_removal: a stored configuration with an empty cwd is not refused while another path is being removed; an empty path matched every registered path before the empty-workspace check, and on 6e86d48 the same fork has no check of its own and waits on the ownership lock the removal holds.

worktrees::a_creation_does_not_build_at_a_path_a_removal_is_deleting fails on b2efafa, the commit that adds the test on the head before the creation check: with the removal's directory already deleted and its registration still held, a creation that picks that task id builds there and its Session creation is then refused with is being removed. With the check the creation moves to another task id, no directory appears at the removed path, and the removal still deletes its record.

worktrees::a_removal_does_not_delete_a_path_a_creation_is_building fails on 91fc8a9 and on ee9a566, the head of that test alone: with the creation parked after its directory check, worktree.remove of the task directory deletes it and answers removed: true. With the creation's registration the same call is refused with worktree_in_use and is being created, the creation builds in the directory it registered, and the path is removable again once it finishes. worktrees::a_failed_creation_removes_the_worktree_it_registered keeps the rollback working: a creation whose base does not carry its workspace's subtree removes the worktree and the branch it added, and a later creation reuses the same task id, so the registration neither blocks the cleanup nor outlives the creation.

worktrees::a_creation_cannot_take_the_path_a_failed_creation_rolls_back fails on a1f2e7c, the commit that adds the test and the holds it parks on, before the hand-over, and the same test applied to ba1430f fails the same way: a failed creation ended its own registration, and a second creation parked after its directory check registered that path before the rollback's removal did, so the rollback was refused as meeting a path being created and the worktree with its .git entry and the branch stayed behind. With the hand-over the path is registered as being created or as being deleted at every moment, the second creation moves to another task id, and the failed creation removes its worktree and its branch. worktrees::a_second_creation_moves_off_the_path_a_creation_registered covers the refusal of a second creation that meets a registered path and passes before the hand-over as well; the hand-over is what the other test needs.

worktrees::tests::a_path_based_removal_refuses_an_unregistered_directory is compiled only on platforms without unix, where the non-force removal refuses with worktree_in_use and --force still removes the tree. It compiles for x86_64-pc-windows-gnu with cargo check -p dim-app-server --all-targets, and no CI job runs the dim-app-server unit tests on Windows, so the assertion has not executed anywhere.

Three tests on main asserted the old semantics, where a creation at a removed path waited for the deletion and then failed its workspace check. They now assert the refusal the registration produces, and each waits for the creation before releasing the parked deletion, so no assertion depends on which of the two runs first. In worktrees::session_creation_after_an_unregistered_removal_fails_its_workspace_check the refused creation is InvalidInput with is being removed, and a creation after the removal completes still fails with no longer exists. worktrees::dropping_the_caller_keeps_the_removal_until_the_deletion_finishes (renamed from ..._keeps_the_removal_lock_until_the_deletion_finishes) waits for a completion signal from the deletion before it asserts the directory is gone. process_typescript::node_store_preserves_repository_results_and_worktree_removal_exclusion replaces its 50 ms "still blocked" check with the same bounded InvalidInput refusal before it releases the foreign store. Three phrases in main tests still named the ownership lock; the comment in worktrees::unregistered_remove_refuses_a_git_entry_added_after_the_content_check and the expect messages in worktrees::session_creation_after_an_unregistered_removal_fails_its_workspace_check and the renamed test now name the removal's deletion step, with no assertion, timeout, wait or test name changed. Two more tests on main pin the non-force empty-directory deletion, worktrees::tests::content_that_appears_after_the_check_is_not_deleted and worktrees::tests::content_that_appears_in_a_checked_child_is_not_deleted; they now carry #[cfg(unix)] because that deletion no longer exists on Windows, and their function bodies and assertions are unchanged.

Known limits: the deletion itself has no time limit, as the Git call has 30 seconds and the recursive paths follow the tree size; and both sets are lost on a crash, so a removal or a creation the process died in leaves the directory it was working on, which the next removal or worktree.list handles.

A worktree removal held SessionStore's ownership lock from its checks through the Git or filesystem deletion, so every unrelated Session creation, fork and deletion in the daemon waited for it, with no time limit on the recursive paths.

The removal now registers the resolved path in an in-memory deleting set under the ownership lock, releases the lock for the deletion and runs it in the removal's own task, which clears the path only when the deletion returns. A Session creation or fork whose workspace, and a worktree association whose root, is at, under or above a registered path is refused while it runs, and so is a repeated removal of it; operations on other paths no longer wait. The record is deleted after the physical removal succeeds, and a failed removal reports its error and leaves no registration.
The non-force removal of an unregistered task directory deleted the empty children its content check recorded, one path at a time. Directory removal follows a symlink in an intermediate component, so replacing the task directory with a symlink after the check made the removal delete a same-named empty directory outside the managed root.

The removal now opens the task directory and its parent and deletes each recorded name in them with unlinkat, which never resolves the name it deletes. A task directory or child swapped for a symlink refuses the removal with the existing in-use error. A platform without handle-relative directory removal keeps the path-based removal and re-checks each directory before it deletes it.
The design documents said a worktree removal holds the session store's ownership lock through the deletion and that Session creation, fork, deletion and association wait for it. They now state the two steps: checks and registration under the lock, the deletion outside it, and the paths that stay refused while it runs.

They also state the non-force removal's name-based deletion, the platform limit on it and the unchanged absence of a time limit on the deletion itself.
The store tests that pinned the old lock semantics awaited a creation after they released a parked deletion: the creation queued on the ownership lock, failed its workspace check, and only then did the deletion run. They now await the creation first, assert the refusal the registration produces and release the deletion afterwards; the caller-drop tests wait for a completion signal from the deletion instead of a 50 ms window or a polling loop.

New tests cover a record deletion while its path is being removed, a recorded removal whose caller is dropped, and a stored configuration whose workspace is empty.
The database-only directory-record deletion checked only Session associations. A plugin could delete the record of a path whose worktree removal was already registered and still running, leaving the removal to delete an already-forgotten row and the path unrecorded if its deletion then failed.

It now meets the same in-memory registration as the other worktree operations under the ownership lock and refuses a path that is being removed.
A fork's stored configuration text was compared against the paths a removal is deleting as it was read, and an empty path is a prefix of every path, so a configuration with an empty cwd was refused with the in-use error during any removal. Such a configuration names no workspace and is now skipped like text without one.
The storage and resource documents still said a worktree removal holds the session store's ownership lock through the deletion, that its callback must not await other store operations, and that creation, fork and association wait for it. They now state the two steps, the paths refused while the deletion runs, and the record deletion that meets the same registration.

The plugin binding drops the callback's lock restriction, and the worktree design lists the record deletion among the refused operations.
Session deletion takes the ownership lock but does not compare its Session against the paths a removal registered, so listing it among the operations refused during a deletion was wrong.
Name the task id the next managed worktree creation tries and park a recorded removal after it deletes its directory: a creation that would pick that task id must build elsewhere and leave nothing at the removed path.
A creation picks its task id and builds its directory outside the ownership lock, so a removal that registered the path and already deleted its files could hand the same path to a new worktree. Compare the chosen directory with the store's deleting set under the ownership lock, the same lock and set the removal registers under, and move to another task id when they overlap.
The module and entry-check comments, the design document and the storage page still said a removal runs its checks under the ownership lock; a removal registers its path there and deletes outside it, and a creation compares its task directory with that registration. Two test comments and expect messages name the deletion step instead of the lock.
A creation checks its directory against the store's deleting set, releases the ownership lock and builds that directory later, so a removal that registers the same path in between deletes the worktree the creation is building. Park the next creation after that check and remove the task directory it is about to build in: the removal deletes it and answers that it removed it, where a creation holding its directory must refuse it.
A creation checked its directory under the ownership lock and built it after releasing that lock, so a removal that registered the same path in between deleted the worktree the creation was building, or its Session row then failed its workspace check. Register the chosen directory in a creating set under the same lock, hold it until the Session row is written or the failed creation's rollback returns, and refuse a removal that registers an overlapping path with the existing in-use error. The rollback ends its own creation's registration first, so its removal is not refused by the registration it holds.
The design section on the deleting set and the storage page described a creation only as a reader of that set; a creation also registers the directory it chose under the same lock until its Session row or its rollback, and a removal that meets that registration is refused. State the creating set, its lifetime, the refusal a removal gets, and that the rollback ends it first.
A creation that fails after it built its worktree removes that worktree and its branch under the ownership exclusion, and a second creation that found the path free before the failure registers it once the rollback has ended its own registration and before the removal registers the path. Park a creation between its directory check and its registration and a failed creation before its rollback removes the worktree: the second creation takes the path while the first one rolls back, and the first one leaves the worktree it built. Also cover two creations that reach the same task id, where the second one meets the registration of the first and builds elsewhere.
A failed creation ended its own registration before its rollback registered the path as being deleted, so a creation that had already found the path free registered it in between: the rollback was refused as meeting a path being created, its error was dropped, and the worktree with its `.git` entry and the branch stayed behind. Take the creation's own registration over as the path's deletion registration in the same ownership lock hold that re-checks the removal, so the path is registered as being created or as being deleted at every moment, and keep the deletion guard in the removal's task so a dropped caller cannot clear it early.
…tration

The creation step, the section on the two sets and the storage page said a failed creation ends its own registration first and then runs the deletion, and that the registration lives until the rollback returns. The rollback now takes that registration over as the path's deletion registration in the same lock hold, so the path is registered as being created or as being deleted at every moment and another creation cannot register it in between.
Format the two new tests as `cargo fmt` lays out their calls.
The module summary said a creation holds its registration until its Session row is written; a failed creation hands that registration to the removal before then, so it ends at either point.

@eric8810 eric8810 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.

Reviewed at head f8c3162.

Two defects, and the fix addresses the shape of each rather than the symptom.

The lock was held from the checks through the Git or filesystem deletion, so every unrelated Session creation, fork and deletion in the daemon waited on a removal. Registering the resolved path in an in-memory set under the ownership lock, releasing it, and running the deletion in the removal's own task is the right pattern: the set is the mutual-exclusion point and it costs a map insert, while the slow work happens outside. Refusing a Session creation or fork whose workspace, and an association whose root, is at, under or above a registered path covers overlap in every direction — the refusal cannot be dodged by naming a parent or a child. Clearing the registration only when the deletion returns, and leaving none on failure, keeps the set honest in both outcomes; that "dropping the caller stops neither the deletion nor the registration" is the lifecycle rule applied properly, since the work belongs to the task that started it, not to the caller's future. Deleting the directory record after the physical removal succeeds puts the durable fact last.

The second defect is the one worth the care: a symlink swapped in after the content check let a non-force removal delete a same-named empty directory outside the managed root. The deletion now re-canonicalizes the checked path immediately before acting and refuses when it differs — "never follow it" — and the primitives help: remove_dir and remove_dir_all do not follow a symlink, so the canonical check is the belt to their braces rather than the only guard.

Blocking: none.

Checks are green at this head. I read the removal path, the canonical re-check and the surrounding refusal logic in worktrees.rs, and the PR body; I did not read the 348 lines of storage/timeline.rs, the 837 lines of worktrees.rs flow tests, the lib.rs and face.rs changes, or the storage document delta, and ran nothing.

Non-blocking: none.

@zerob13 zerob13 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 ownership reservation and detached deletion work are an improvement: unrelated Session operations no longer wait for the filesystem deletion, and the reservation and durable record have clear failure semantics.

[P2] Preserve managed-root containment on Windows too. The Windows empty-directory fallback in crates/dim-app-server/src/worktrees.rs does not provide the same containment guarantee as the Unix implementation, as its source comment notes. #2124 does not specify a Windows exception. Please provide a Windows deletion primitive that preserves containment, or fail closed on that path until it can guarantee the boundary. The Windows job passing does not establish this invariant. Static defensive review only; no reproduction attempted.

…red directory

Windows deletes a directory by path, so a reparse point swapped into a path component after the check could redirect the non-force removal outside the managed root. That path now returns the existing in-use error and asks for --force; --force still removes the tree with std::fs::remove_dir_all, which walks it through directory handles and does not follow a reparse point inside it.
The two tests on main that pin the non-force empty-directory deletion are Unix-only now, with their function bodies and assertions unchanged, and a new non-Unix unit test pins the refusal and that --force removes the tree.
The removal section now states that an unregistered directory is not removed without --force off Unix and that --force removes the tree through std::fs::remove_dir_all, which does not follow a reparse point inside it.
@yyhhyyyyyy

Copy link
Copy Markdown
Collaborator Author

Fixed in a292d92.

The Windows empty-directory fallback is gone. Removing an unregistered directory without --force now fails closed with worktree_in_use and asks for --force, and the design document records the platform exception. --force removes the tree through std::fs::remove_dir_all, whose Windows implementation opens each directory with FILE_FLAG_OPEN_REPARSE_POINT and removes entries relative to the open directory handle, so it does not follow a reparse point inside the tree it removes.

The non-Unix path is covered by a #[cfg(not(unix))] unit test, a_path_based_removal_refuses_an_unregistered_directory: it pins the refusal and that --force still removes the tree. It compiles for x86_64-pc-windows-gnu with cargo check -p dim-app-server --all-targets, and the Windows job of this pull request compiles the production code through cargo test -p dim-app-server --test app_server_flow, but no CI job runs the dim-app-server unit tests on Windows, so the assertion has not executed. Two unit tests on main that pinned the removed non-force deletion are #[cfg(unix)] now, with their bodies unchanged.

@yyhhyyyyyy
yyhhyyyyyy requested a review from zerob13 November 24, 2026 08:50

@eric8810 eric8810 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.

Reviewed at head a292d92.

Approving, citing my review at f8c31626. The two commits address the part of that fix that was Unix-only and say so plainly rather than leaving it as an assumption: the handle-relative empty-directory deletion is what closes the swap window, and a target without it was still deleting by path after a check. Refusing the non-force removal there — with --force kept, since remove_dir_all walks through directory handles and does not follow a reparse point inside the tree — is the right trade: an operator on such a platform who needs the directory gone is told to say --force, instead of the daemon deleting something outside the managed root when the platform cannot prove it is safe.

The doc comments now carry the distinction at the two places a reader will meet it, which is where it belongs: the reason the non-force path exists at all, and why --force does not share its limit.

Blocking: none.

Checks are green at this head. I read the worktrees.rs delta's comments and the removed non-Unix helper, and the file list; I did not read the 43 added lines in full, the design delta, or any Windows-side test, and ran nothing.

Non-blocking:

  • The new refusal has no test: the change touches only worktrees.rs and the design document, and the repository's Windows job runs the app-server worktree flow only when its path list selects it. A refusal that only exists on a platform whose CI may not reach it is the kind of branch that rots — either a cfg(not(unix)) unit test for the refusal, or a line in the doc saying where it is exercised.

@zerob13 zerob13 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.

Re-reviewed a292d928. Windows now refuses the non-force fallback for an unregistered task directory before deletion, resolving my containment blocker. Unix keeps handle-relative removal. The reservation remains owned by the deletion task until settlement while the slow work runs outside the store lock.

Hosted retry 45359444312 passed Linux, Windows CLI, selected macOS native checks and ci-ok on synthetic 603d7281, based on 7a0e3d46. The Windows-only refusal assertion was compiled, not run by the Windows job. A source-only merge into current main eacc672d was clean; #2126’s TUI changes and this App Server patch retained their contents without interaction found. No hosted run on that newer base is claimed.

@yyhhyyyyyy

Copy link
Copy Markdown
Collaborator Author

The cfg(not(unix)) unit test for the refusal is at crates/dim-app-server/src/worktrees.rs:1865-1882.

a_path_based_removal_refuses_an_unregistered_directory builds a task directory with one empty child and calls remove_checked_entry without --force: it asserts the worktree_in_use error code, a message that names --force, and that the child directory is still there.

It then calls remove_checked_entry with --force and asserts the task directory is gone.

The test compiles for x86_64-pc-windows-gnu with cargo check -p dim-app-server --all-targets --target x86_64-pc-windows-gnu --locked, which builds the lib test target.

The production code around it is compiled natively on Windows by the windows-cli job of this pull request through cargo test -p dim-app-server --test app_server_flow.

No CI job builds the dim-app-server lib test target on Windows, and on Unix the test is compiled out, so its assertions have not executed; cargo test -p dim-app-server --lib on Windows runs it.

The design document already records the platform limit in the remove description (docs/design/worktree-management.md:100) and in the non-force removal paragraph that gives the reason (docs/design/worktree-management.md:132-135).

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.

Worktrees: a removal holds the session store's ownership mutex, so unrelated Sessions wait, and a non-force removal follows a swapped symlink

3 participants