Skip to content

🤖 fix: gate keep-mode unarchive and Coder stop/delete archives across backends - #4904

Merged
ThomasK33 merged 3 commits into
mainfrom
fix/4871-gate-unarchive-coder-archive
Sep 27, 2026
Merged

ThomasK33 merged 3 commits into
mainfrom
fix/4871-gate-unarchive-coder-archive

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes the two cross-backend gaps left by #4866: a keep-mode (non-snapshot) unarchive can no longer mark a workspace active while the other backend deletes its worktree, and an archive that stops or deletes a dedicated Coder workspace now takes the structural mutation gate like a checkout-deleting archive.

Fixes #4871

Background

Two backends (the desktop app and xum server) may use one workspace on one Xum root at the same time. #4866 added the cross-process mutation gate for rename, remove, checkout-deleting archive, snapshot-restoring unarchive and worktree deletion. It left out:

  1. A keep-mode unarchive: deleteWorktree in one backend passes its archived check under the gate, then an unarchive in the other backend commits unarchivedAt, leaving a visible workspace without a checkout.
  2. Coder archive policies Stop/Delete for dedicated (Xum-created) Coder workspaces: archiveDeletesManagedWorktree is false for SSH runtimes, so runBeforeArchive could stop or delete the remote workspace under the other backend's turn or terminal.

Implementation

  • Unarchive. The issue suggested probing the gate before the unarchivedAt edit. A bare probe still races: the mutator can take the gate after the probe and read "archived" before the edit lands. Instead, a keep-mode unarchive holds a short-lived use lease (new kind unarchive) across the commit only. The existing Dekker ordering in workspaceUseLeases.ts then guarantees that either the unarchive sees the live gate and refuses, or the mutator's lease scan sees the unarchive and refuses. An unarchive of a workspace that is already active returns before taking any lease or gate. Holding a lease never checks other leases, so ordinary activity of the other backend (a turn, a terminal) does not make unarchive fail. The lease is held from before the commit until the unarchive finishes, including lifecycle startup (for example starting a dedicated Coder workspace), so the other backend cannot stop-and-archive the workspace under that startup. After the lease is taken, the snapshot state is read again: a snapshot archive that the other backend finished before the lease is visible then (and no new one can start while the lease is held), so the unarchive drops the lease and takes the gate to restore it. The snapshot-restoring path otherwise keeps its gate unchanged.
  • Coder archive. The archive gate condition is extended to stopsDedicatedCoderWorkspace (Stop or Delete), with the same own-activity policy as the checkout-deleting archive: this backend's own turn, terminals, editors, MCP servers and one-off commands are still stopped by the archive itself.
  • Docs: removed the 🤖 Gate keep-mode unarchive against worktree deletion, and Coder stop/delete archives, across backends #4871 entry from the known-gaps Note in docs/config/server-access.mdx and described the new refusals.

Decision (conservative): a hold failure other than a live gate (for example a lock-file I/O error) also refuses the unarchive, matching the editor-open path.

Validation

New tests in workspaceService.mutationGate.test.ts, written from the other backend's perspective, fail on origin/main (4bd92ab38b):

(fail) structural workspace mutations across two backends on one root > a keep-mode unarchive refuses while the other backend deletes the worktree, but not on its turn
(fail) structural workspace mutations across two backends on one root > worktree deletion refuses while the other backend commits a keep-mode unarchive
(fail) structural workspace mutations across two backends on one root > an archive that stops or deletes a dedicated Coder workspace refuses while the other backend uses it
 18 pass
 3 fail

Two more tests were added for review round 1 (snapshot appearing before the lease; the other backend stopping and archiving a Coder workspace while this backend starts it on unarchive). Both failed on the first PR head fe3cd7f960:

(fail) structural workspace mutations across two backends on one root > a keep-mode unarchive restores a snapshot the other backend captured before it only under the gate
(fail) structural workspace mutations across two backends on one root > the other backend cannot stop and archive a Coder workspace while this backend starts it on unarchive

All of these failed with expect(received).toBe(expected) Expected: false Received: true (the operation succeeded). With the fix: 24 pass (round 2 added a test that a repeated unarchive of an already active workspace is a no-op that takes no lease, so it neither refuses nor blocks the other backend's mutation). Every unit test file that mentions unarchive or coderWorkspaceArchiveBehavior (31 files) passes, plus tests/ipc/tasks/unrelatedMissingCheckout.test.ts and tests/ui/workspaces/lifecycle.test.ts.

Risks

Low. Unarchive gains one lease-file publish and gate probe per call. While another backend renames, removes or archives the workspace, or deletes its worktree, unarchive now refuses with the gate holder named (try again). A Coder archive with Stop/Delete now refuses while the other backend uses the workspace, as checkout-deleting archives already do.


Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high

@mintlify

mintlify Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
Mux 🟢 Ready View Preview Sep 27, 2026, 6:54 PM

💡 Tip: Enable Automations to automatically generate PRs for you.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-27T19:41:01.867513Z 6c9644d New commits
🔒 Security Review ✅ Completed 2026-09-27T19:43:08.497595Z 6c9644d New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fe3cd7f960

ℹ️ 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".

Comment thread src/node/services/workspaceService.ts Resolved
Comment thread src/node/services/workspaceService.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1031704321

ℹ️ 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".

Comment thread src/node/services/workspaceService.ts Resolved
@ThomasK33

Copy link
Copy Markdown
Member Author

Readiness record

  • Final head: 6c9644d461ee67499f72c51f4f78977cda74bd49
  • Checks: all required CI checks pass on this head (only the non-required Pixel / Review is pending). Local: make static-check, make fmt-sync-docs-check and 181 targeted tests green.
  • Codex: 6 completed assessments (3 automatic normal/security pairs). Round 1: 2 P1 fixed; round 2: 1 P2 fixed; round 3: clean on both lanes. All threads resolved.
  • Budget: the final independent check is the 7th assessment, using 1 of the +2 extension (the overrun comes from automatic runs, and findings shrank 2 → 1 → 0).
  • Independent clean-context check: READY, with tracked follow-up 🤖 feat: cross-backend evidence for background processes in SSH, Docker, dev container and multi-project workspaces #4889 (background commands in remote/multi-project workspaces, already listed in the docs).
  • Stopping reason: acceptance criteria met, reviews clean.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high

@ThomasK33
ThomasK33 added this pull request to the merge queue Sep 27, 2026
Merged via the queue into main with commit 25faf8f Sep 27, 2026
31 of 32 checks passed
@ThomasK33
ThomasK33 deleted the fix/4871-gate-unarchive-coder-archive branch September 27, 2026 20:17
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 28, 2026
…ackends (coder#4908)

## Summary

This PR finishes the cross-process removal work tracked in coder#4782: the
other backend can no longer create a child task under a workspace that
is being removed (or was removed), a removal now checks for descendants
after it claims its marker, and a removal marker with an empty identity
field is dropped at load instead of blocking the workspace. Item 1 (a
send into a live attempt) is already closed by the use leases and
mutation gate that landed in coder#4861 and coder#4866; see below.

Fixes coder#4782

## Background

coder#4776 added the durable `pendingRemoval` marker. The issue lists what it
left open:

1. **A send into a live attempt is admitted by a config read.** Backend
B could pass the `pendingRemoval` read and start a turn while backend A
commits the marker and deletes the checkout.
2. **Child creation does not check the parent's marker.**
`removeUnlocked` checked for descendants before its claim, and no
task-creation config write looked at the parent's marker, so B could
commit `TaskService.create` under a parent that A was removing and leave
an orphaned child row (and possibly an unmanaged checkout).
3. (comment) `PendingRemovalSchema` accepted empty identity strings.
`parseProcessIdentity()` turns `""` into `null`, and `judgeHolder()` on
Linux then treats the holder as an unknown PID domain that never dies,
so such a marker blocked admission and removal until someone edited
config.json.
4. (comment) Reactivation's marker check before it unarchives is a read,
so a removal could race the unarchive's checkout restore.

## Implementation

- **Item 2.** A shared `assertParentAdmitsChild` runs inside every
task-creation config write (`commitReservations` for `createMany`, and
both the queued and the direct write in `create`). It refuses while the
parent row carries `pendingRemoval`. `create` also refuses when the
parent row it found by id during preparation is gone at write time (the
direct path materializes a checkout in between, so a whole removal can
fit in that gap). `createMany` does the same with the parent row it
found by id when it revalidated the reservation (its checkpoint callback
runs before the commit, so a whole removal can fit there too). A parent
that was not found by id (an upgraded, id-less row that resolves only
through its session metadata) is not required. `removeUnlocked` now
checks for descendants after `claimPendingRemoval` instead of before the
gate. Config writes are serialized, so either the child's write sees the
marker and refuses, or the removal's post-claim read sees the child and
refuses (its `finally` releases the marker, as for any other refusal
after the claim). A refused direct create rolls its checkout back
through the existing launch-failure path.
- **Item 3.** The identity fields of `PendingRemovalSchema` are
`z.string().min(1).nullable()`, so `normalizePersistedWorkspace` drops
such a marker as malformed.
- **Item 1: no code change.** `removeUnlocked` takes the structural
mutation gate before it claims the marker and holds it until removal
settles (coder#4866), and every turn holds a `turn` use lease from
preparation and confirms it before the provider starts (coder#4861). By the
Dekker ordering in `workspaceUseLeases.ts`, either B's turn sees A's
gate and fails as a settled preparation failure, or A's lease scan sees
B's turn and the removal refuses before any effect. This also covers a
turn B started before A's claim. Covered by
`agentSession.useLease.test.ts` ("B's send while A's mutation runs fails
as a settled preparation failure", "a turn in B holds its lease from
preparation until it settles") and
`workspaceService.mutationGate.test.ts` (other-backend leases refuse
rename and remove before any effect).
- **Item 4: no code change.** Since coder#4904, a keep-mode unarchive holds
an `unarchive` use lease from before its commit to the end, and a
snapshot-restoring unarchive takes the mutation gate. Either one refuses
while a removal holds the gate, and a removal refuses while the
unarchive holds its lease.

## Out of scope

The removal marker and this fence find the row by id. An upgraded
workspace whose config row is still id-less gets no marker (as before
this PR), so creation under it is not fenced; tracked in coder#4914.

## Validation

New tests in `workspaceService.pendingRemoval.test.ts` (two backends on
one root) fail on `origin/main` (`25faf8f1c4`):

```
(fail) workspace removal across two backends on one root > a malformed removal marker (an empty identity field) is dropped instead of blocking the task
(fail) workspace removal across two backends on one root > a removal refuses when the other backend created a child just before it closed admission
(fail) workspace removal across two backends on one root > the other backend cannot create a child task under a workspace being removed
```

Review round 1 added a test that a batch creation under a parent
resolved only through metadata (legacy, no config row by id) still
commits; it failed on the first PR head `b6d58bcb49` (`parent workspace
legacy-parent was removed`).

Review round 2 added a test that a batch creation refuses when the other
backend finished removing the parent during the reservation checkpoint;
it failed on `9ed0343a94` (`Received: "created"`).

Before the fix, B's `create` under the parent being removed succeeded,
A's removal deleted a parent whose child had been committed just before
its claim, and the empty-identity marker refused the reawaken. With the
fix all pass, and so do every `taskService*`/`workspaceService*` unit
test file (1851 tests) and the 21 test files that mention
`pendingRemoval`, `createMany` or descendant checks (935 tests).

## Risks

Low to medium. `create` and `createMany` now refuse when the parent row
they found by id is missing at write time; before, such a child was
written as an orphan. A removal of a workspace with descendants now
takes the gate and briefly claims its marker before it refuses (the
marker is released in the same call), so another backend's task
admission can see a short refusal during that window.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 28, 2026
…end is using (coder#4929)

## Summary

Startup recovery no longer re-drives a sub-agent task that another live
backend on the same Xum root is using. Before any recovery pass, it
probes the task workspace for another backend's live use lease (turn,
init, MCP, command, terminal, editor). A task with such a lease is left
alone in every pass: the starting→queued flip, the workflow prepass, the
stopped-state settle, and the `awaiting_report` and `running` re-drives
(including guidance replay). Each skip is logged with the holder and the
lease kind.

Refs coder#4801 (item 1)

## Background

With two backends on one root (the desktop app beside a `xum server`
that started first, or `XUM_ALLOW_MULTIPLE_INSTANCES=1`), a backend that
starts ran `TaskService.recoverInterruptedTasks` against rows the other
backend was still executing. Its liveness guards
(`aiService.isStreaming`, `workspaceService.isBusyForMessage`) are
process-local. So it rotated the attempt and sent the restart nudge or
completion prompt (a duplicate execution), relaunched a reservation that
was still starting, or stopped a task whose auto-retry was off. The docs
told users to start the second app only when no sub-agent tasks were
active.

The use leases from coder#4861, coder#4890, coder#4900, coder#4904 and coder#4907 already make
"another backend is working in this workspace" visible across processes.
This PR reads them with the same read-only probe coder#4917 introduced, and
adds no new lock, directory, lease kind, schema field or release rule.
That was the coordinator's scoping decision: the per-attempt lock from
the coder#4801 plan is deferred until dogfooding shows the remaining windows
matter.

## Implementation

- `WorkspaceUseLeases.findForeignUse(workspaceId)`: scans the
workspace's lease directory like the mutation gate does, skips this
backend's own files (its instance token), and returns the first live
foreign lease's kind and holder. An unreadable lease directory counts as
in use (fail closed); a dead holder's file does not.
- `recoverInterruptedTasks`: right after the workspace-turn reconcile,
collects the `starting`/`running`/`awaiting_report` tasks with a foreign
lease and filters them out of the stale-starting list and the
running/awaiting-report candidate list. The completion log reports
`skippedInUseElsewhereCount`. For those tasks the AgentSession startup
probe and history reads no longer run at all.
- Contract comment (`processLiveness.ts`) and
`docs/config/server-access.mdx`: the recovery note now states the
residual. The stale "Known gaps" sentence is corrected: MCP, init and
exec leases, background-name claims and the keep-mode unarchive gate
landed in coder#4890, coder#4891, coder#4892 and coder#4904; coder#4889 remains.

**Residual (documented):** a task the other backend runs but is idle in
at that moment holds no lease: while it is being set up (reservation),
between turns, or while it waits on its own descendants. The starting
backend can still take it over by rotation. The attempt-bound CAS
fencing then treats the other backend's execution as superseded: its
report and state writes are refused, while its stream keeps running
until it ends or is stopped there. Recovery already skips parents that
have blocking active descendants.

## Verification requested before this PR: child→parent reports after a
parent rotation

Scenario: backend B rotates an idle PARENT task while a child that
backend A runs is still working, then the child reports. Result: **the
report is neither refused nor lost.**
- The child's report CAS (`publishAgentTaskReport`, `taskService.ts`
~18432) edits the CHILD's row. The coder#4754/coder#4545 refusal
(`taskAttemptRetiredBy`) and the supersede check look only at the
child's own attempt; a parent rotation sets
`taskAttemptId`/`taskAttemptUnproven` on the parent row, never
`taskAttemptRetiredBy`.
- The report artifact (`upsertSubagentReportArtifact`) and the delivery
(`deliverReportToParentUnlocked`, ~19259-19396: finalize a pending
`task` tool call in the parent's partial, or append a synthetic report
message to the parent's history) are keyed by the child task id and have
no parent-attempt check.
- What does change: A's in-memory continuation of the parent under its
old attempt is fenced (superseded), so the parent's next turn runs under
B's attempt and reads the report from history. That is the documented
supersede behavior, not a loss.
- Workflow-owned children skip the generic parent delivery; the workflow
reads the child's own outcome (report artifact first), which a parent
rotation does not affect.

## Validation

New `taskService.startupRecovery.foreignLease.test.ts`: backend A is a
second `Config` on the root holding a real `WorkspaceUseLeases` lease;
backend B is a real `TaskService` running `recoverInterruptedTasks`.
Before the product change:

```
(fail) … a running task whose workspace backend A holds a turn lease on is left alone
Expected to not contain: "task-in-use"
Received: [ "task-in-use" ]
(fail) … a running task whose workspace backend A holds a mcp lease on is left alone
(fail) … a awaiting_report task whose workspace backend A holds a turn lease on is left alone
(fail) … a starting task whose workspace backend A holds a init lease on is left alone
Received: true   (the row was marked taskAttemptUnproven / flipped)
```

After the change, B sends nothing to the task and the row keeps A's
attempt id, has no unproven mark, and keeps its status. A control test
(passes before and after) shows that a task whose lease holder died is
re-driven as after a restart: new attempt, unproven mark, nudge sent.

`bun test src/node/services/taskService*` (1035 pass),
`workspaceUseLeases*` and `workspaceService.mutationGate*` (44 pass).

## Risks

Low. The only behavior change is that a task whose workspace another
live backend holds a lease on is not recovered at this startup.
- Terminal and editor leases last until the other backend archives or
removes the workspace, so a task with such a lease is skipped for as
long as that backend lives. This is the fail-closed direction: that
backend is alive, and the task can be stopped and resumed by hand.
- On macOS and Windows, a crashed backend whose pid got reused reads as
live (the lock kit's death rule, coder#4480), so its tasks are skipped until
that pid exits. The skip log names the holder.
- The probe is one directory read per active task at startup, plus one
lock-file read per foreign lease file.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high` • Cost: `$26.11`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=26.11 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant