Skip to content

refactor(claude): immutable pipeline + session-orchestrated rebuild (C9) - #326270

Draft
TylerLeonhardt wants to merge 3 commits into
claude-agent-host-consolidationfrom
claude-agent-host-consolidation-c9
Draft

TylerLeonhardt wants to merge 3 commits into
claude-agent-host-consolidationfrom
claude-agent-host-consolidation-c9

Conversation

@TylerLeonhardt

Copy link
Copy Markdown
Member

Stacked on #326256 (Tier 0 + C1). Review that first; this PR's diff is the single commit on top. Base will retarget to main once #326256 lands.

What

C9 — remove the rematerializer. Today one SDK session is split across two objects: ClaudeSdkPipeline owns the WarmQuery lifetime, ClaudeAgentSession owns Query construction (Options). Because the SDK bakes startup-only Options into the subprocess, any tool/customization/agent change — or crash recovery — needed a fresh WarmQuery, which the pipeline obtained by calling a rematerializer closure 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:

  • ClaudeSdkPipeline owns exactly ONE WarmQuery for its whole life. _query is bound eagerly in the constructor and never re-bound (the prompt iterable parks between turns rather than ending). The pipeline reports a terminal isDead (set synchronously by abort() and when the consumer loop ends abnormally) and never self-heals.
  • ClaudeAgentSession orchestrates rebuild. _installPipeline(isResume, freshController) builds+installs a pipeline into a MutableDisposable, with a per-pipeline signal-wiring DisposableStore. 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.
  • Config (folds in C2): desired lives on the session (_provisionalModel / _provisionalAgent; permissionMode read live) and seeds each build's Options; 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)

  1. shutdownAndWait before 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).
  2. Bijective model/effort survives a rebuild via Options, not runtime replay. The rebuilt Query gets model/effort from Options (baked from _provisionalModel), not a Query.setModel replay pass.

Also fixes a shared-controller idempotency bug surfaced while writing the tests: since the session now shares its AbortController with the live pipeline and aborts it before calling pipeline.abort(), the pipeline's old if (signal.aborted) return guard skipped failAll and stranded the in-flight send deferred. abort() now guards on its own terminal _dead flag.

Validation

  • typecheck-client / eslint / valid-layers-check clean.

  • All agent-host node suites pass — claudeAgent 194, plus claudeSdkPipeline / claudePromptQueue / claudeSdkMessageRouter green.

  • Live E2E (authenticated Agents window, watching agenthost.log):

    Time Event C9 behavior
    t0 startup isResume=false materialize (1 startup)
    t1–t3 3 results multi-turn reuse — no new startup
    t4 turnCancelled → consumer loop dies abort → isDead
    t5 startup isResume=true recover-rebuild
    t6 result rebuilt pipeline works

    Confirmed: no orphan subprocesses, single clean abort, clean recovery.

Follow-up (not in this PR)

  • Agent as a live setter (empirical gate): verify 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

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]>
@TylerLeonhardt

Copy link
Copy Markdown
Member Author

Copilot can you help me visualize this PR? I want diagrams that give me confidence that the diff makes sense

Copilot AI commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

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 after

flowchart 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
Loading

The key simplification is that the old split ownership is gone:

  • session owns when to build/rebuild
  • pipeline owns one Query lifetime
  • there is no pipeline→session rematerializer callback anymore

2) Send pre-flight decision

flowchart 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]
Loading

That’s the behavior change I’d look for in the diff: all rebuild causes funnel through one pre-flight branch.

3) Lifecycle / replacement model

sequenceDiagram
    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
Loading

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 refactor

flowchart 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
Loading

The important invariant is: desired state survives rebuild on the session; applied state dies with the pipeline. That’s why _current* can disappear.

If it helps, I can also turn this into a shorter “PR description ready” version with just 2 diagrams and 4 bullets.

TylerLeonhardt and others added 2 commits July 18, 2026 13:19
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]>

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.

2 participants