Repository navigation
refactor(claude): immutable pipeline + session-orchestrated rebuild (C9) - #326270
TylerLeonhardt wants to merge 3 commits into
Conversation
Removes the rematerializer entirely. ClaudeSdkPipeline now owns ONE WarmQuery
for its whole life (bound eagerly in the ctor, never re-bound); a rebuild is the
session disposing the pipeline and building a fresh one via _installPipeline. The
pipeline reports terminal `isDead` (set synchronously on abort and when the
consumer loop ends abnormally) and never self-heals.
Session orchestrates rebuild:
- _installPipeline(isResume, freshController) builds+installs a pipeline into a
MutableDisposable, with a per-pipeline signal-wiring DisposableStore.
- send() pre-flight is the single reuse-vs-rebuild decision (isDead / tool diff /
customization diff / resume anchor); _rebuildPipeline shutdownAndWaits the old
subprocess before the resume spawn (closes the two-writer window on <id>.jsonl).
- session owns the AbortController, reassigned per build and shared with the live
pipeline, so session.abortController === pipeline._abortController always.
Config (folds in C2): desired-on-session (_provisionalModel/_provisionalAgent;
permissionMode read live) seeds each build's Options; applied-on-pipeline
(_applied{Model,Effort,PermissionMode}) is an ephemeral dedup seeded once at ctor.
Bijective model/effort survives a rebuild via Options, not runtime replay.
Also fixes a shared-controller idempotency bug surfaced by the abort test:
pipeline abort() now guards on its own terminal _dead flag, not the shared signal
(the session aborts the controller before calling abort(), which would otherwise
skip failAll and strand the in-flight send deferred).
Net -366 lines. typecheck-client / eslint / valid-layers clean; all agentHost
node suites pass (claudeAgent 194, pipeline/queue/router green).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Copilot can you help me visualize this PR? I want diagrams that give me confidence that the diff makes sense |
Here are the diagrams I’d use to reason about the refactor. 1) Ownership before vs afterflowchart LR
subgraph Before
S1[ClaudeAgentSession]
P1[ClaudeSdkPipeline]
Q1[WarmQuery / Query]
S1 -- builds Options --> Q1
P1 -- owns lifetime --> Q1
P1 -- rematerializer callback --> S1
S1 -- seed/replay desired config --> P1
end
subgraph After
S2[ClaudeAgentSession]
P2[ClaudeSdkPipeline]
Q2[WarmQuery / Query]
S2 -- _installPipeline builds Options --> P2
P2 -- owns exactly one --> Q2
S2 -- rebuild decision + replace whole pipeline --> P2
P2 -- emits signals / isDead --> S2
end
The key simplification is that the old split ownership is gone:
2) Send pre-flight decisionflowchart TD
A[send(prompt)] --> B{pipeline.isDead
or tool diff
or customization diff
or resume anchor?}
B -- no --> C[forward live permissionMode]
C --> D[pipeline.send]
B -- yes --> E[reject parked client-tool calls]
E --> F[old pipeline.shutdownAndWait]
F --> G[_installPipeline isResume=true freshController=true]
G --> H[new pipeline installed into MutableDisposable]
H --> I[pipeline.send]
That’s the behavior change I’d look for in the diff: all rebuild causes funnel through one pre-flight branch. 3) Lifecycle / replacement modelsequenceDiagram
participant Session
participant OldPipeline
participant OldSDK
participant NewPipeline
participant NewSDK
Session->>OldPipeline: send()
OldPipeline->>OldSDK: use parked Query across turns
Note over OldPipeline,OldSDK: reuse between turns; no rebinding
Session->>OldPipeline: detect rebuild needed
Session->>OldPipeline: shutdownAndWait()
OldPipeline->>OldSDK: abort + await real exit
Note over OldSDK: releases <id>.jsonl
Session->>NewSDK: startup(resume)
Session->>NewPipeline: install fresh pipeline
NewPipeline->>NewSDK: own one new Query for rest of life
This is the confidence point for me: the PR changes rebuild from "swap internals in place" to "wait for old process to die, then replace the whole pipeline object". 4) Config ownership after the refactorflowchart LR
subgraph Session
DM[desired model / effort]
DA[desired agent]
PM[live permissionMode read]
end
subgraph Pipeline
AM[applied model]
AE[applied effort]
AP[applied permissionMode]
end
DM -->|seed Options at build| Pipeline
DA -->|seed Options at build| Pipeline
PM -->|seed Options at build / live setter between turns| Pipeline
AM -->|dedup runtime setter| Query[(Query)]
AE -->|dedup runtime setter| Query
AP -->|dedup runtime setter| Query
The important invariant is: desired state survives rebuild on the session; applied state dies with the pipeline. That’s why If it helps, I can also turn this into a shorter “PR description ready” version with just 2 diagrams and 4 bullets. |
Adds deterministic coverage for the immutable-pipeline / session-orchestrated rebuild races that a happy-path live E2E can't hold open. Driven against the real ClaudeAgentSession + ClaudeSdkPipeline via the controllable SDK fake (park a turn or park inside startup, then fire a concurrent abort): - Double abort back-to-back is idempotent, rejects the in-flight turn once, and the session still recover-rebuilds on the next send (regression guard for the shared-controller `_dead`-vs-signal abort guard). - Abort landing inside a rebuild's startup() await is caught by _installPipeline's post-await gate on the REBUILD path: the half-built WarmQuery is async-disposed and the send rejects, with no dead pipeline installed. - Abort→resend churn (x4): every retired WarmQuery is disposed (no leaked subprocess handle) and there is exactly one SDK startup per cycle — the deterministic analog of the live "no orphan subprocess accumulates" check. 197 passing. typecheck-client / eslint clean. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Captures the manual C9 validation as a repeatable, assertion-driven script. Drives a REAL authenticated Agents window (via the launch skill) + a real Claude SDK subprocess and asserts on ground truth (agenthost.log + `ps`), covering what the node fakes can't: that the OS subprocess is actually reaped and that rapid abort->rebuild churn never leaks a process or hits an <id>.jsonl two-writer conflict. Scenarios: materialize (isResume=false, 1 subprocess) - warm reuse - recover-rebuild (abort -> isResume=true) - abort-churn x N (subprocess count <=1 in-flight and post-abort, peak <=1, zero conflict/leak errors, session still usable). Auth-required and GUI-driven, so there is no CI slot yet - it is a run-by-hand regression check for now (see test/agent-host-e2e/README.md). The assertions are structured to graduate into a gated smoke suite once an authed headless runner exists. Robust to live-product variance: eval-clicks Send/Cancel (no snapshot-ref churn), reads truth from log+ps, retries sends/aborts, tolerates background workbench tool-syncs (a legitimate rebuild trigger) and prior-run subprocesses (baseline exclusion). Green end-to-end: 19/19 assertions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
What
C9 — remove the rematerializer. Today one SDK session is split across two objects:
ClaudeSdkPipelineowns theWarmQuerylifetime,ClaudeAgentSessionowns Query construction (Options). Because the SDK bakes startup-onlyOptionsinto the subprocess, any tool/customization/agent change — or crash recovery — needed a freshWarmQuery, which the pipeline obtained by calling arematerializerclosure back up into the session and rebinding in place, carrying a large amount of swap machinery and a_current*config duplicate.This PR makes the pipeline immutable and moves rebuild orchestration to the session:
ClaudeSdkPipelineowns exactly ONEWarmQueryfor its whole life._queryis bound eagerly in the constructor and never re-bound (the prompt iterable parks between turns rather than ending). The pipeline reports a terminalisDead(set synchronously byabort()and when the consumer loop ends abnormally) and never self-heals.ClaudeAgentSessionorchestrates rebuild._installPipeline(isResume, freshController)builds+installs a pipeline into aMutableDisposable, with a per-pipeline signal-wiringDisposableStore.send()'s pre-flight is the single reuse-vs-rebuild decision (isDead/ tool diff / customization diff / resume anchor). A rebuild = dispose the old pipeline + build a fresh one; there is no in-place swap._provisionalModel/_provisionalAgent;permissionModeread live) and seeds each build'sOptions; applied lives on the pipeline (_applied{Model,Effort,PermissionMode}) purely to dedup runtime setters, seeded once at construction. The_current*desired-state duplicate is gone.Net −366 lines.
Behavior changes (not a pure refactor)
shutdownAndWaitbefore a rebuild's resume spawn. The tool/customization restart path now awaits the old subprocess's real exit before the resume spawn (matches_removeAllTurns' existing discipline; closes a latent two-writer window on<id>.jsonl).Options, not runtime replay. The rebuilt Query gets model/effort fromOptions(baked from_provisionalModel), not aQuery.setModelreplay pass.Also fixes a shared-controller idempotency bug surfaced while writing the tests: since the session now shares its
AbortControllerwith the live pipeline and aborts it before callingpipeline.abort(), the pipeline's oldif (signal.aborted) returnguard skippedfailAlland stranded the in-flightsenddeferred.abort()now guards on its own terminal_deadflag.Validation
typecheck-client/eslint/valid-layers-checkclean.All agent-host node suites pass —
claudeAgent194, plusclaudeSdkPipeline/claudePromptQueue/claudeSdkMessageRoutergreen.Live E2E (authenticated Agents window, watching
agenthost.log):startup isResume=falseisDeadstartup isResume=trueConfirmed: no orphan subprocesses, single clean abort, clean recovery.
Follow-up (not in this PR)
applyFlagSettings({ agent })swaps the live agent; if confirmed, drop agent from the rebuild triggers. Gated on a ~15-min live E2E; kept as a rebuild trigger for now.🤖 Generated with Claude Code