Skip to content

🤖 feat: turns and terminals hold cross-process workspace use leases - #4861

Merged
ThomasK33 merged 5 commits into
mainfrom
fix/4476-turn-terminal-leases
Sep 27, 2026
Merged

ThomasK33 merged 5 commits into
mainfrom
fix/4476-turn-terminal-leases

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Agent turns and terminals now record cross-process use leases (#4476). While a turn or a terminal runs in a workspace, another backend on the same Xum root sees it, and its rename/remove gate (next PR) refuses. While another backend holds that gate, a new turn fails before the provider starts, and a terminal does not open; both show the holder's pid.

Background

Two backends can share one root (the desktop app beside a xum server, or XUM_ALLOW_MULTIPLE_INSTANCES), and by the user's decision both may use one workspace at once. #4844 added WorkspaceUseLeases and #4852 the mutation gate. This PR wires the two most common activities. MCP servers, init hooks and executeBash follow in #4857.

Implementation

  • workspaceUseLeasesFor(config) returns one WorkspaceUseLeases per backend, keyed by its Config instance (each ServiceContainer and each CLI run owns exactly one). No DI changes.
  • Turns (AgentSession):
    • completePreparation starts the lease without awaiting it. Awaiting there made queued dispatch asynchronous and broke 12 tests about synchronous queued startup.
    • streamWithHistory confirms it right before the provider request, the point from which tools can touch the checkout. A refusal fails the turn through the existing pre-start failure path (fail), so the turn settles normally. The user message is already in history; like other transient pre-stream errors, the retry policy retries it, and the retry succeeds once the mutation ends. The "×2" badge in the screenshot is that merged retry error.
    • Released when the turn is idle and no preparation is running: on the idle transition (before any idle listener runs), after a preparation that never left idle, and in dispose (which awaits in-flight releases). One lease spans streaming, handoff retries and background attempts.
  • Terminals (TerminalService): create holds the lease before spawning. Once the PTY has spawned, only its exit releases the lease: close paths just signal the shell, which can keep using the checkout until it exits. A throwing exit subscriber cannot skip the release. A create that fails before any spawn releases the lease at once. terminal.create now passes the refusal to the client as CONFLICT; transports masked the plain error as "Internal Server Error" (found in dogfooding).

Validation

Tests with two backends on one root (B's real AgentSession/TerminalService with a real Config and HistoryService; A is a second Config whose WorkspaceUseLeases runs the gate):

  • agentSession.useLease.test.ts: B's turn refuses A's gate while the provider request is pending; the lease is released on failure and after a completed stream, and A's gate then succeeds; B's send during A's mutation fails without reaching the provider and leaves B idle with a count of 0, and the next send is admitted; dispose mid-turn releases the lease.
  • terminalService.useLease.test.ts: an open terminal refuses A's gate until the shell exits; close and closeWorkspaceSessions release per session; no PTY spawns during A's mutation; a failed spawn leaves no lease.
  • router.test.ts: terminal.create maps the refusal to CONFLICT with its message.
  • Each new test fails without its production change. Existing suites pass: agentSession* (1136), terminalService*, and workspaceService*/taskService*/workspaceTurnManager*/workflows (2394).

Dogfood

The server ran as xum server and the desktop app (Electron) on the same root; Electron logged that it skipped its API server. A small script held the mutation gate for 20 s in place of the rename/remove call sites, which arrive in the next PR.

  1. During a desktop turn, <token>.turn.lock exists (Electron's pid) and is gone at idle. A terminal adds <token>.terminal.lock, and closing it removes the file.
  2. Gate held: the send fails naming the pid, and the terminal refuses with the same message. After release, the send works.
  3. SIGKILL the gate holder mid-hold: the next send works (a dead holder never blocks).

Send refused while the gate is held
Terminal refused with the real message
Send succeeds after the gate is released
Refusal at 390 px

Refusal → release → success:

step2-refusal-release-fixed.mp4

Perf check (both backends on one workspace, 25 MB history epoch, 10,966 rows; medians of 5)

Condition Chat open total (ms) History lock wait (ms) partial.json writes/s Max gap (ms) Turn lease files per turn
Server only 1362 0.3 (max 2.8) 7.9 190 1 created, 1 deleted
Desktop also subscribed 1283 0.5 (max 2.6) 8.0 201 1 created, 1 deleted
Both reopen at once server 1454 / desktop 1145 0.3 (max 9.0) – – –
Desktop reopens 3× mid-stream desktop 1142 0.0 8.1 142 1 created, 1 deleted

The median gap between partial writes was 121 ms in every stream. The lease code adds one lock file per turn and none per partial write; an in-process lease transition costs about 0.6 ms. Informational, and not from this PR: each partial write takes the cross-process history lock (93–114 times per 20 s stream), which caused at most a 9 ms wait with both backends opening the chat at once.

Risks

Medium-low. Turn start now awaits a local lock-file write (about 0.6 ms) before the provider request. A leaked lease would block other backends' renames/removals until this process exits; the release paths have refcount assertions and tests for success, failure, abort (dispose) and refused starts. Known limitation: on macOS/Windows a crashed backend's lease can read as live after pid reuse (#4849).

Refs #4476


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

@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-27T11:06:34.631163Z c94e027 New commits
🔒 Security Review ✅ Completed 2026-09-27T11:07:00.026749Z c94e027 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: 94a30d6b08

ℹ️ 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/terminalService.ts Resolved
Comment thread src/node/services/terminalService.ts Resolved
Comment thread src/node/services/terminalService.ts Resolved
Comment thread src/node/services/agentSession.ts Resolved
Comment thread src/node/services/agentSession.ts Resolved
@ThomasK33
ThomasK33 added this pull request to the merge queue Sep 27, 2026
Merged via the queue into main with commit d24920a Sep 27, 2026
31 checks passed
@ThomasK33
ThomasK33 deleted the fix/4476-turn-terminal-leases branch September 27, 2026 11:24
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 27, 2026
…ses the workspace (coder#4866)

## Summary

Rename, remove, an archive that deletes the checkout, unarchive with a
snapshot restore, and managed-worktree deletion now refuse right away
while **another backend on the same Xum root** has a turn, an open
terminal or a background process in the workspace or in a sub-agent that
shares its checkout. They never wait. Rename also refuses this backend's
own running turn or background process. This is the last step of the
use-lease plan.

Closes coder#4476
Closes coder#4478

## Background

The desktop app and `xum server` can share one Xum root, and the owner
decided that both may use one workspace at the same time. Each backend's
rename/remove guards are in-memory, so one backend could move or delete
a checkout under the other's live activity. The earlier steps built the
pieces:
- coder#4844: `inspectCrossProcessLock` and `WorkspaceUseLeases`.
- coder#4852: the per-workspace mutation gate.
- coder#4861: turns and terminals hold use leases.
- coder#4759, coder#4776: removal stops own users before deleting and closes
admission durably.

This PR makes the structural mutators take the gate.

## Implementation

- `WorkspaceUseLeases.acquireMutationGate(ids, options)` returns a
release function, and `withMutationGate` now wraps it. Rename and
archive already release their other locks in an existing `finally`, so
they need a release function rather than a callback. A partial
acquisition releases what it took. Release is idempotent and releases
every gate even if one fails.
- `WorkspaceService.acquireStructuralMutationGate(id, own)` gates the
workspace plus every `taskIsolation: "none"` row on the same checkout
path. It maps `WorkspaceBusyError` to `Err`. Other backends' leases, and
background processes this backend does not track, always refuse.
`ignoreOwnKinds` is per workspace: a mutator ignores its own activity
only in the workspace it mutates, so its own activity in a shared
sub-agent refuses too. How each mutator treats its own activity in the
mutated workspace:

| Mutator | Own kinds ignored | Own background processes | Where |
|---|---|---|---|
| rename | terminal (shells follow the moved dir) | refuse (coder#4478 item
1) | after validation, before the MCP-overrides lock and the move |
| remove | turn, terminal (removal stops them) | allowed (removal cleans
them up) | after the descendant check, before `claimPendingRemoval` |
| archive, only when `archiveDeletesManagedWorktree` | turn, terminal
(archive stops them) | allowed (unchanged) | before the untracked-files
confirmation (metadata is re-read under the gate), held through the
after-archive hook |
| unarchive with a snapshot row | none | refuse (nothing stops them) |
before `unarchivedAt` is written |
| deleteWorktree | none | refuse (nothing stops them) | before the
archived-state validation |

- `archiveDeletesManagedWorktree` moves the worktree archive hook's
deletion rule into one predicate. Archive gates exactly when the hook
would delete, so keep-mode archive is unaffected.
- Docs: `docs/config/server-access.mdx` gains the guarantee and its
limits. The one-app-per-workspace warning stays, because background
process IDs are reserved only in-process (see coder#4857). The
`processLiveness.ts` contract comment is updated to match.

## Validation

- `workspaceService.mutationGate.test.ts` uses two real service stacks
on one root. Without the gate, 7 of its 8 tests fail; the 8th guards the
"remove still ends its own turn and terminals" behavior. One test spawns
a real child process that holds a terminal lease: remove names its pid,
and after `SIGKILL` the retry succeeds with no lockout.
- Dogfood: `xum server` (B) and the desktop app (A) on one root, built
at b0e2650aa6. The head differs only in formatting, a test, and
releasing every gate on error. A's calls went through the renderer's
oRPC client because rename has no UI.
1. Rename was refused while B had a terminal open, then succeeded after
B closed it (recording below).
2. Remove was refused while B ran a background `sleep 300`, even with
`force`, then succeeded after B stopped it.
3. Archive was refused under Delete and Snapshot while B had a terminal
open. Keep succeeded, and unarchive worked.
4. After `kill -9` of B, the stale lease file stayed on disk, and A's
rename and remove succeeded at once.


https://github.com/user-attachments/assets/157eb15d-ad7f-4889-993a-cfbd1d69a9ff


![Rename refused while the server has a terminal
open](https://github.com/user-attachments/assets/4dc24875-cd0a-48bb-8b76-00bcca6cf536)
![Remove refused while the server runs a background process, even with
force](https://github.com/user-attachments/assets/6abbd3cd-68a0-4e77-96c0-2bc9c3eb4f64)
![Delete-mode archive refused while the server has a terminal
open](https://github.com/user-attachments/assets/4966e5c7-7e45-40ff-9d0d-25f437a01783)
![Rename succeeds right after the server is
SIGKILLed](https://github.com/user-attachments/assets/271f32f9-8734-495c-b799-403d3cd190d1)

<details>
<summary>Perf check: two backends on one 25 MB workspace (measurement,
not a gate)</summary>

Both backends ran in mock mode, the same method as coder#4861. The history
file is 25 MB with 10,966 rows. Values are medians over 5 opens, in ms.

| Condition | Chat open total | History-lock wait | partial.json
writes/s | Max gap |
|---|---|---|---|---|
| Server only | 1433 | 0.5 (max 1.7) | 8.0 | 141 |
| Desktop also subscribed | 1403 | 0.3 (max 1.4) | 8.0 | 181 |
| Both reopen at once | 1416 / 1242 | 0.3 / 0.2 (max 2.3) | – | – |
| Desktop reopens 3× mid-stream | 1142 | 0.0 | 8.1 | 161 |

- The median gap between partial writes was 121 ms in every run.
- Each turn creates and deletes one `turn.lock`. The mutation gate never
appears during turns: it is held about 5 ms for a refusal, 72 ms for a
rename and 208 ms for a remove.
- Not from this branch: the cross-process history lock is taken 101–121
times per 20 s stream.
</details>

## Risks

- Single-backend behavior changes only for rename: a rename during the
preparation phase of this backend's own turn, while its own background
process runs, or while a shared sub-agent is active now refuses with a
retry message. It used to run.
- The following are unchanged: remove and archive stopping their own
stream and terminals, keep-mode archive, and task clean-up. The broad
service suites pass (workspaceService, taskService, projectService,
leases, hooks).

## Follow-ups

- coder#4857: MCP, init and executeBash leases are not checked yet, and
neither are background commands in SSH or Docker workspaces, whose spawn
records are remote. The docs say so.
- coder#4871: gate a keep-mode unarchive against a concurrent worktree
deletion, and gate Coder Stop/Delete archives. Both predate this PR.
- coder#4865: the command palette's remove hides backend refusals. This
predates the PR; dogfood found it.
- Rename has no UI, so its refusal reaches only API callers.

---

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

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=23.07 -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 27, 2026
…r#4886)

## Summary

The docs and the `processLiveness.ts` CONCURRENT BACKENDS comment no
longer tell users to pick one app per workspace. Using one workspace
from the desktop app and `xum server` at the same time is supported, and
the known gaps are listed.

## Background

The owner decided that two backends on one data directory may use one
workspace at the same time. The structural-mutation gate (coder#4844, coder#4852,
coder#4861, coder#4866) makes rename, delete and checkout-removing archives refuse
while the other backend is busy, and coder#4874 gives same-named background
commands separate records. The old warning was kept only until coder#4874
landed.

## Implementation

- `docs/config/server-access.mdx`: adds the background-record guarantee
(for commands running at the same time) to "What stays consistent" and
replaces the Warning with a Note that lists the gaps: MCP servers, init
hooks, one-off commands and non-host background records (coder#4857),
migrated background commands (coder#4878), reuse of a settled record the
other app still tracks (coder#4882), keep-mode unarchive and Coder
stop/delete archives (coder#4871). The sub-agent recovery Note and the
mixed-version line are unchanged.
- `processLiveness.ts`: the same statement and gaps in the CONCURRENT
BACKENDS comment. The attempt-fence guarantees and "not guaranteed" list
are unchanged.
- `builtInSkillContent.generated.ts`: regenerated from the docs.

Refs coder#4857

---

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

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs= -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 27, 2026
…ash (coder#4890)

## Summary

Another backend on the same Xum root (the desktop app beside a `xum
server`) now sees three more kinds of activity through workspace use
leases, so its rename, remove, checkout-deleting archive, snapshot
restore and worktree deletion refuse while they run:

- **stdio MCP servers** (`mcp`): held from before the spawn until the
server process exits.
- **init hooks** (`init`): held inside `runBackgroundInit` for the whole
init; released before the returned settlement resolves.
- **one-off commands** (`exec`, the `executeBash` RPC): one lease per
call, until the command settles.

Refs coder#4857 (the background-process gaps from its comments moved to
coder#4889).

## Background

coder#4476 added `WorkspaceUseLeases` and the structural mutation gate; coder#4861
leased turns and terminals and coder#4866 made the mutators refuse. The kinds
`mcp`, `init` and `exec` were declared but never held, so another
backend could still move or delete the checkout under them.

## Implementation

Same rules as turns and terminals: a lease is taken before the activity
starts; `WorkspaceMutationInProgressError` makes the start fail (MCP:
the server counts as failed; init: it fails through the init logger like
any init failure; exec: `Err`), and it is never swallowed into a start.

- **MCP** (`startStdioInstance`): released when `execStream.exitCode`
resolves, like a terminal's PTY exit. A rejected exit observation proves
nothing, so it kills the process and keeps the lease until this backend
exits (fail closed); `MCPStdioTransport` now handles that rejection
instead of leaving it unhandled. `close()` and the idle sweep only ask
the process to exit, so tying the lease to the instance maps would miss
servers that outlive them (timeouts, retired generations). Remote
(HTTP/SSE) servers do not run in the checkout and take no lease.
- **init** (`withInitUseLease`, used by `runBackgroundInit` and by
multi-project creation's per-project init loop): `runBackgroundInit`
takes a new required `useLeases` parameter, so every caller (create,
deferred checkout, fork, the two task-service inits) passes this
backend's leases.
- **exec** (`WorkspaceService.executeBash`): taken right after the
in-process admission guards and before the metadata read, released with
`await using`.

This backend's own activity, per mutator ("does this mutator stop it?"):

| Mutator | own `mcp` | own `init` | own `exec` |
| --- | --- | --- | --- |
| remove | ignored (stops servers) | ignored (aborts and awaits it) |
ignored (today's handling; `removingWorkspaces` refuses new ones) |
| checkout-deleting archive | ignored (stops servers) | refuses (already
aborted and awaited before the gate) | ignored (today's handling;
model-facing archives refuse it themselves) |
| rename | ignored (processes follow the moved directory, like own
terminals) | refuses (nothing stops it) | ignored (today's handling) |
| unarchive restore, worktree deletion, creation rollback | refuse
(unchanged empty sets) | refuse | refuse |

Other backends' leases always refuse. The docs Note in
`server-access.mdx` now lists only the remaining background-command gap
(coder#4889).

## Review decisions

- Not changed: keeping an `exec` lease after an unconfirmed remote exit.
The lease is scoped to the call, the same contract as the turn lease;
changing it needs a bash-tool exit-contract change for every runtime.
- Not changed: taking the MCP lease before callers resolve the workspace
path. A rename in that sub-second gap makes the spawn target a path that
no longer exists (a failed server); moving the hold into every caller is
new mechanism.

## Deferred

The two comment gaps on coder#4857 (background records of SSH/Docker/dev
container workspaces invisible to the gate; no cross-backend name claim
for multi-project and remote runtimes) need `BackgroundProcessManager`
changes, which another workspace is changing now for coder#4878/coder#4882. Filed
as coder#4889.

## Validation

Red → green: the new tests fail on `origin/main` (10 failures) and pass
with this change.

<details>
<summary>Pre-fix failures (tests run against main's production
code)</summary>

```
(fail) MCPServerManager workspace use leases > a running server refuses the other backend's mutation until its process exits [21.00ms]
(fail) MCPServerManager workspace use leases > a server whose process exits on its own releases its lease [1.00ms]
(fail) MCPServerManager workspace use leases > no server starts while the other backend mutates the workspace [3.00ms]
(fail) structural workspace mutations across two backends on one root > a one-off command of the other backend refuses rename until it fails [19.00ms]
(fail) structural workspace mutations across two backends on one root > a one-off command releases its lease when it succeeds [16.00ms]
(fail) structural workspace mutations across two backends on one root > no one-off command runs while the other backend mutates the workspace [15.00ms]
(fail) structural workspace mutations across two backends on one root > an init hook of the other backend refuses rename until it ends [16.00ms]
(fail) structural workspace mutations across two backends on one root > an init hook releases its lease when it fails or is aborted [8.00ms]
(fail) structural workspace mutations across two backends on one root > no init hook runs while the other backend mutates the workspace [5.00ms]
(fail) structural workspace mutations across two backends on one root > own MCP servers, init hook and one-off commands follow what each mutator ends [16.00ms]
 11 pass
 10 fail
```

</details>

- `mcpServerManager.useLeases.test.ts`: a running server makes the other
backend's gate refuse ("mcp"); release on stop, on process exit, on
failed handshake and on a startup abandoned at its deadline; no spawn
while the other backend holds the gate.
- `workspaceService.mutationGate.test.ts`: the other backend's in-flight
`executeBash` and init hook make rename refuse and release on success,
failure and abort; neither runs while the gate is held; own-kind policy
for rename and remove.
- Targeted suites (`workspaceService*`, `taskService*`,
`mcpServerManager*`, `terminalService*`, `workspaceUseLeases`,
`serviceContainer`, `runtimeFactory*`) and `make static-check`.

## Risks

Moderate, in the checks that make rename/remove/archive refuse. The new
refusals are for other backends' activity (intended) and own init hooks
during rename (nothing stopped them before). An `executeBash` issued
while this backend's own mutation holds the gate now fails fast instead
of racing it. A hung SSH exec whose exit never settles keeps its MCP
lease (fail closed), like a terminal.

---

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

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=6.62 -->
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