Repository navigation
fix(orchestration): record the created remote worktree before the attach can fail - #20805
brennanb2025 wants to merge 1 commit into
Conversation
…ach can fail A federated `--worktree new-top-level` start creates the worktree on the worker host, but the attachment row only learned about it at `terminal_readying`. Any throw in between settled the attachment with `residual_resources` still at its `'[]'` default, so the coordinator was told nothing was left behind while a real worktree stayed on the remote peer. Record the worktree the moment it exists, and route federated stage writes through one function that derives the residual set from the effects it records. Extract the federated create path into `federation-worktree-creation.ts`, the remote counterpart of the local path's `worker-worktree-creation.ts`, so the two creation paths have the same shape. `setup` is filled in place because the caller reports it from its own catch block.
There was a problem hiding this comment.
Important
The worker-side record is now correct, but the home-side outcome_unknown receipt still prints Residual resources: [] for the transport-shaped failure this PR is aimed at. The core fix is sound and well-tested; this is the one gap between what the PR now writes and what the operator is shown.
Reviewed changes
- Federated worktree creation extracted — new
federation-worktree-creation.tsholdscreateFederatedWorkerWorktree, the remote counterpart ofworker-worktree-creation.ts;federation.tsnow calls it instead of inlining the path. - Worktree recorded before the attach can fail — a new
persistFederatedWorktreeCreationwritesstage: 'worktree_created'with theworktreeIdand residual, immediately after thecreated_top_leveleffect is pushed and before the no-terminal throw andlistTerminals. - Single stage writer — all federated stage writes route through one private
writeStage, which derivesresidualResourcesfrom the effects being recorded viaisFederationResidualEffect. - Coverage — a new test mocks
listTerminalsrejection and asserts the worktree appears in both the response and the worker attachment; the PR body's ablation shows it fails on the merge-base.
⚠️ The transport-shaped case still reports no residual to the coordinator
The PR body states the fix makes a failed attach name what the host was left holding, and calls out worktree_create transport-shaped errors — which isFederationEffectUnknown classifies as outcome_unknown — as "exactly the case where an operator most needs to know something may have been left behind." On the home side, that path still discards the newly-populated residual: startFederatedWorker sends remote.state === 'outcome_unknown' to federatedUnknownReceipt, which hardcodes effects: [] and residualResources: [], while the parallel non-transport failed path forwards remote.residualResources. The immediate worker-start output the PR quotes as the defect therefore still reads Residual resources: [] for the highlighted case; the value survives on the remote row and worker-show reconciles it home, but the receipt itself is unchanged.
The new test uses a message (the worker host dropped the terminal listing) that does not match the transport regex, so it settles as failed and exercises the forwarding branch — it cannot catch this. A federated test with a connection-shaped error at listTerminals would.
Technical details
# Home-side `outcome_unknown` receipt drops the remote residual
## Affected sites
- `src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts:241` — the
`remote.state === 'outcome_unknown'` branch calls `markWorkerStartUnknown(started.dispatch.id,
remote.failedStage ?? 'remote_attach', remote.lastError ?? ...)` without the `effects` argument the
function accepts, then returns `federatedUnknownReceipt(...)`.
- `src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start-receipts.ts:43-44` —
`federatedUnknownReceipt` hardcodes `effects: []` and `residualResources: []`, ignoring
`remote.effects` / `remote.residualResources`.
- `src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-outcome.ts:114` —
`markWorkerStartUnknown` already accepts an optional `effects` array that is persisted into the
worker projection; nothing passes it from the federated path.
- For contrast, the sibling `failed` path at `federated-worker-start.ts:249-267` does forward
`remote.residualResources` (line 266).
## Why it is in scope
Before this PR the federated worker's `residual_resources` was always `[]` at `worktree_create`, so
the home discard was moot. This PR makes that field carry the stranded worktree, and the very next
call on the home side throws it away for `outcome_unknown` — the state `isFederationEffectUnknown`
produces for transport-shaped errors at `worktree_create`.
## Required outcome
A federated `worker-start` that fails transport-shaped after the worktree exists should surface the
worktree in its `residualResources` (and, consistently, in `effects`), matching the non-transport
`failed` path. The remote row's value is durable and trustworthy — it was read back from the
worker's own attachment via `failFederatedAttachmentWithReceipt` — so there is no reason to prefer
the hardcoded empty arrays.
## Suggested approach (optional)
Thread `remote.effects` and `remote.residualResources` into `markWorkerStartUnknown` and give
`federatedUnknownReceipt` optional `effects` / `residualResources` parameters that replace the
hardcoded arrays. Keep the catch path at `federated-worker-start.ts:286` at `[]` — there is no
receipt when the transport itself failed.
## Open questions for the human
Is the empty `outcome_unknown` receipt deliberate (i.e. the design wants unknown outcomes to be
settled only through the `worker-show` / `worker-abandon` `nextCommands`, and never to assert a
possibly-stale remote resource)? If so, that rationale should be recorded, because it contradicts
this PR's stated user-facing goal.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe change centralizes federation stage persistence and derives residual resources from recorded effects. A new helper now creates federated worker worktrees and handles setup, terminal validation, and effect recording. The federation path delegates to this helper. A test verifies that a created remote worktree remains recorded as a residual resource when terminal listing fails. Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🟡 Moderate · up to If terminal discovery fails after a terminal starts, cleanup cannot identify that live terminal, leaving resources on the worker host. This should be fixed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed and relevant explanation of the failure, fix, scope, testing, and remaining risks. However, it omits required template sections, including the mandatory linked issue, Visual Proof, explicit Testing checklist, Agent skill upstream boundary, Notes, and Checklist. Resolution Add the missing template sections. Include a valid
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 1814f871-16ec-4dfd-bab0-ae01e61bc23c
📒 Files selected for processing (4)
src/main/runtime/rpc/methods/orchestration/federation/federation-setup.tssrc/main/runtime/rpc/methods/orchestration/federation/federation-worktree-creation.tssrc/main/runtime/rpc/methods/orchestration/federation/federation.test.tssrc/main/runtime/rpc/methods/orchestration/federation/federation.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| }) | ||
| setup.requested = setupDecision | ||
| setup.effective = setupDecision | ||
| setup.hookFound = created.setupReceipt?.hookFound ?? false | ||
| setup.startupPolicy = created.setupReceipt?.startupPolicy ?? 'start-immediately' | ||
| setup.state = created.setupReceipt?.state ?? 'not_configured' | ||
| const terminalHandle = created.startupTerminal?.handle | ||
| if (!terminalHandle) { | ||
| throw new Error(created.warning ?? 'Agent-first worktree creation returned no terminal.') | ||
| } | ||
| const listed = await runtime.listTerminals(`id:${created.worktree.id}`, undefined, { | ||
| includeVisualLayouts: false | ||
| }) | ||
| appendFederationTerminalEffects( | ||
| effects, | ||
| listed.terminals, | ||
| terminalHandle, |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Persist the spawned startup terminal before listing terminals. createManagedWorktree sets startupTerminal.handle only after createTerminal succeeds. If runtime.listTerminals then rejects, the persisted failure state retains only the worktree effect. The federation release path therefore lacks the terminal identity needed to call closeTerminal, so the spawned terminal can remain unreclaimed. Record the known handle as a created terminal residual before the fallible listing, while avoiding a duplicate when listing succeeds.

Failure mechanism
A federated worker started with
--worktree new-top-levelcreates a real worktree on the worker host, insideorchestration.federationAttachStart.The handler recorded
stage: 'worktree_creating'beforecreateManagedWorktree, and the next durable write of that attachment's resources waspersistFederatedReadinessStage(terminal_readying), which happens only after the terminal listing and setup receipt are assembled. Between those two points the worktree exists on the remote peer but no row records it.Every failure in that window settles through
failFederatedAttachmentWithReceipt, which reportsresidualResourcesby readingattachment.residual_resources— still at the'[]'column default. Two reachable throws sit inside it: the no-startup-terminal check, and theruntime.listTerminalscall.The result reaches the user.
src/cli/handlers/orchestration/worker-output.tsprints aResidual resources:line whenever the state isoutcome_unknownor the list is non-empty, so the coordinator was toldResidual resources: []while a worktree — and whatever terminals came with it — stayed behind on the remote host with nothing naming it.This is also the
worktree_createstage, whichisFederationEffectUnknownclassifies asstart_unknownfor transport-shaped errors — exactly the case where an operator most needs to know something may have been left behind.The fix
persistFederatedWorktreeCreationwritesstage: 'worktree_created'with theworktreeIdand the residual set, immediately after thecreated_top_leveleffect is pushed and before anything downstream can throw.writeStageinfederation-setup.ts, which derivesresidualResourcesfrom the effects being recorded via the existingisFederationResidualEffect. No caller can persist a residual set narrower than the effects it just wrote.federation-worktree-creation.ts.This removes the bug class rather than guarding one throw site. The gap existed because the residual rule was applied at some stage writes while the create path hand-rolled its own
recordRemoteAttachmentStagecall that skipped it; there is now one writer.Scope: this makes the resource reported, not reclaimed
Stated plainly, because it changes what an operator must do. This PR makes a failed federated attach tell the truth about what it left on the worker host. It does not delete anything. No code here reclaims the stranded worktree, and
federated-worker-release-host.tsreads no residual resources today, so nothing else in the system will clean it up either.So when a receipt now reads
Residual resources: [{ kind: 'worktree', id: 'repo::…' }], that is an action item for a human: a worktree exists on the remote peer and will persist until someone removes it. Previously the same situation printedResidual resources: [], which read as "nothing to do" — the reason this was worth fixing is precisely that it was silently wrong at the moment an operator was deciding whether to act.Automatic reclamation is deliberately out of scope. It needs a decision about ownership and timing on the worker host that this defect does not settle, and bolting it on here would widen a reporting fix into a lifecycle change.
Precedent matched, and the deviations
In-repo precedent is the local worker create path,
createWorkerWorktreeinworker-worktree-creation.ts. It already does exactly this: push the worktree effect, thenrecordWorkerStage({ stage: 'worktree_created', worktreeId, effects, residualResources }), and only then list terminals. The federated path had the same sequence minus that write.The extraction makes the match structural rather than incidental:
federation-worktree-creation.tsis now the remote counterpart ofworker-worktree-creation.ts, with the same responsibility and the same ordering. It also broughtfederation.tsback under the 300-line limit without a lint disable.Material deviations, named:
recordWorkerStageonworker_dispatches; federated writesrecordRemoteAttachmentStageonremote_dispatch_attachments. I did not unify them — they carry different identity (home run/dispatch vs. remote attachment + protocol version + home peer fingerprint) and different lineage, and collapsing them is a cross-boundary refactor beyond this defect. The match is on when and by whom the resource is recorded, not on the persistence call.effectsarray; the federated writer filters throughisFederationResidualEffect. I kept the federated filter, because that is the rule the other federated stage writes already use and changing it would alter unrelated receipts.setupis filled in place, not returned. The original code assignedsetupbefore the no-terminal throw so the handler'scatchreports the created receipt. Returning it would have silently regressed that. Mutating matchesapplyWaitForSetupOutcome, which already mutates the same object in this subsystem.Also removed two
as TuiAgentassertions that moved with the code:startupAgentandcreatedWithAgentare optional inworktree-create-params.ts, so the casts were never needed.Ablation evidence
Run at the final head, after the extraction and the de-cast — not at an earlier one. The three implementation files were backed up by file copy,
federation.tsandfederation-setup.tsreverted to merge-base775a932651fa, andfederation-worktree-creation.tsmoved aside; absence of the fix was verified during the run, and the restore was verified by a green re-run.Command:
Ablated — exit
1:Restored — exit
0. The test fails for the stated reason, not an incidental one.Validation
Totals with non-passing counts stated explicitly:
pnpm test src/main/runtime/rpc/methods/orchestration/federation/— exit 0. 17 test files total, 0 failed. 114 tests total, 0 failed. Ran the whole federation directory becausefederation-setup.tsis shared.pnpm tc— exit 0,error TSoccurrences in output: 0.pnpm run check:code-quality:changed— exit 0. 6 sub-checks, 0 new findings each, across 4 changed files.oxlinton the federation directory — exit 0, including themax-linesrule that the extraction resolved (federation.ts311 → 259 lines).Note on reading CI here: a pending count of zero is not by itself a green — checks that have not been created yet also report as zero pending.
What remains unverified
OrchestrationDbinstances with a real dispatcher on both sides, not against two paired peers. The stranded-worktree consequence is inferred from the CLI rendering path, not observed on a real remote host.createTerminaland the readiness write contains noawait, so I judged it unreachable. That is reasoning, not a test.residualResourcesis an existing optional field already passed through byparseRemoteFederatedWorkerStartReceipt, so an old coordinator sees a populated array where it previously saw an empty one. I did not run a mixed-version pairing.Note on the originally-reported defect
I was pointed at
startupAgent: agent as TuiAgentbeing passed unconditionally, on the theory that it makes the structured (native-chat) branch unreachable for federated workers. I could not reproduce that as a defect, and I believe the premise is wrong. Stated as an explicit claim, verified against currentmain:resolveStructuredNativeChatSupportreturns{ supported: false, blocker: 'remote-execution-host' }for anyexecutionHostId !== 'local'.decideWorkerStartModemapsparams.ontoruntime:<peer>, so a federated dispatch never resolves to structured in the first place.workers.tssays so at theparams.onbranch — "A remote worker is always a terminal agent; the mode receipt rides along so the coordinator still learns why its structured default did not apply."['a remote --on', { on: 'server-1' }, 'remote_execution_host']case, and one assertingcreateStructuredWorkerSessionForWorktreeis not called for a remote dispatch.FederationAttachStartParamscarries no mode field, so the wire cannot express a structured request.So the unconditional
startupAgentis the correct implementation of a deliberate decision, andworker-start-agent-placement.tsis the wrong precedent for this file — itswithAgentTerminalsplit exists to serve a structured mode the federated path never reaches. Making federation create structured sessions would be building remote structured chat, not fixing a bug. I left that code untouched and fixed the defect I could actually demonstrate.