Skip to content

fix(orchestration): record the created remote worktree before the attach can fail - #20805

Open
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/federated-worktree-residual
Open

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/federated-worktree-residual

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Failure mechanism

A federated worker started with --worktree new-top-level creates a real worktree on the worker host, inside orchestration.federationAttachStart.

The handler recorded stage: 'worktree_creating' before createManagedWorktree, and the next durable write of that attachment's resources was persistFederatedReadinessStage (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 reports residualResources by reading attachment.residual_resources — still at the '[]' column default. Two reachable throws sit inside it: the no-startup-terminal check, and the runtime.listTerminals call.

The result reaches the user. src/cli/handlers/orchestration/worker-output.ts prints a Residual resources: line whenever the state is outcome_unknown or the list is non-empty, so the coordinator was told Residual 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_create stage, which isFederationEffectUnknown classifies as start_unknown for transport-shaped errors — exactly the case where an operator most needs to know something may have been left behind.

The fix

  • persistFederatedWorktreeCreation writes stage: 'worktree_created' with the worktreeId and the residual set, immediately after the created_top_level effect is pushed and before anything downstream can throw.
  • All federated stage writes now go through one private writeStage in federation-setup.ts, which derives residualResources from the effects being recorded via the existing isFederationResidualEffect. No caller can persist a residual set narrower than the effects it just wrote.
  • The federated create path moved out of the RPC handler into 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 recordRemoteAttachmentStage call 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.ts reads 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 printed Residual 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, createWorkerWorktree in worker-worktree-creation.ts. It already does exactly this: push the worktree effect, then recordWorkerStage({ 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.ts is now the remote counterpart of worker-worktree-creation.ts, with the same responsibility and the same ordering. It also brought federation.ts back under the 300-line limit without a lint disable.

Material deviations, named:

  1. Different store. Local writes recordWorkerStage on worker_dispatches; federated writes recordRemoteAttachmentStage on remote_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.
  2. Different residual derivation. The local path passes the whole effects array; the federated writer filters through isFederationResidualEffect. I kept the federated filter, because that is the rule the other federated stage writes already use and changing it would alter unrelated receipts.
  3. setup is filled in place, not returned. The original code assigned setup before the no-terminal throw so the handler's catch reports the created receipt. Returning it would have silently regressed that. Mutating matches applyWaitForSetupOutcome, which already mutates the same object in this subsystem.

Also removed two as TuiAgent assertions that moved with the code: startupAgent and createdWithAgent are optional in worktree-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.ts and federation-setup.ts reverted to merge-base 775a932651fa, and federation-worktree-creation.ts moved aside; absence of the fix was verified during the run, and the restore was verified by a green re-run.

Command:

pnpm test src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts

Ablated — exit 1:

Test Files  1 failed (1)
     Tests  1 failed | 19 passed (20)

 FAIL  ... > reports the created remote worktree as residual when the attach fails after creation

- Expected
+ Received
      "failedStage": "worktree_create",
-     "residualResources": [
-       ObjectContaining {
-         "action": "created_top_level",
-         "id": "repo::windows-worktree",
-         "kind": "worktree",
-       },
-     ],
+     "residualResources": [],
      "state": "failed",

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 because federation-setup.ts is shared.
  • pnpm tc — exit 0, error TS occurrences in output: 0.
  • pnpm run check:code-quality:changed — exit 0. 6 sub-checks, 0 new findings each, across 4 changed files.
  • oxlint on the federation directory — exit 0, including the max-lines rule that the extraction resolved (federation.ts 311 → 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

  • No live federated run. Proven at the RPC-handler level against two in-memory OrchestrationDb instances 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.
  • Reclamation is not attempted — see "Scope: this makes the resource reported, not reclaimed" above. Listed here too so it is not mistaken for an oversight: it is a deliberate boundary, and the operator, not the system, closes it.
  • The existing-worktree branch was left alone. When a terminal is created in an already-existing remote worktree, the window between createTerminal and the readiness write contains no await, so I judged it unreachable. That is reasoning, not a test.
  • Wire compatibility is argued, not tested. No RPC params or stream opcodes changed; residualResources is an existing optional field already passed through by parseRemoteFederatedWorkerStartReceipt, 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 TuiAgent being 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 current main:

  • resolveStructuredNativeChatSupport returns { supported: false, blocker: 'remote-execution-host' } for any executionHostId !== 'local'.
  • decideWorkerStartMode maps params.on to runtime:<peer>, so a federated dispatch never resolves to structured in the first place.
  • workers.ts says so at the params.on branch — "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."
  • Two tests pin it: a ['a remote --on', { on: 'server-1' }, 'remote_execution_host'] case, and one asserting createStructuredWorkerSessionForWorktree is not called for a remote dispatch.
  • FederationAttachStartParams carries no mode field, so the wire cannot express a structured request.

So the unconditional startupAgent is the correct implementation of a deliberate decision, and worker-start-agent-placement.ts is the wrong precedent for this file — its withAgentTerminal split 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.

…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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.ts holds createFederatedWorkerWorktree, the remote counterpart of worker-worktree-creation.ts; federation.ts now calls it instead of inlining the path.
  • Worktree recorded before the attach can fail — a new persistFederatedWorktreeCreation writes stage: 'worktree_created' with the worktreeId and residual, immediately after the created_top_level effect is pushed and before the no-terminal throw and listTerminals.
  • Single stage writer — all federated stage writes route through one private writeStage, which derives residualResources from the effects being recorded via isFederationResidualEffect.
  • Coverage — a new test mocks listTerminals rejection 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The 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 fd9ad

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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, … Add the missing template sections. Include a valid Fixes #<issue> reference, add Visual Proof with N/A and a reason if applicable, complete the Testing checkboxes, address AI Disclosure if applicable, complete Review, Agent skill upst…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: recording a created remote worktree before later attachment operations can fail.
Full details: Description check

Explanation

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 Fixes #&lt;issue&gt; reference, add Visual Proof with N/A and a reason if applicable, complete the Testing checkboxes, address AI Disclosure if applicable, complete Review, Agent skill upstream boundary, Notes, and Checklist sections. Retain the existing technical explanation under ELI5, What Changed, Why, and Testing.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1814f871-16ec-4dfd-bab0-ae01e61bc23c

📥 Commits

Reviewing files that changed from the base of the PR and between 22ce8d6 and fd9ad55.

📒 Files selected for processing (4)
  • src/main/runtime/rpc/methods/orchestration/federation/federation-setup.ts
  • src/main/runtime/rpc/methods/orchestration/federation/federation-worktree-creation.ts
  • src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts
  • src/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.

Comment on lines +65 to +81
})
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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

This branch has not been deployed

No deployments
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.

1 participant