Repository navigation
perf(agents): reuse prepared initial session context - #170262
Conversation
Consume the complete sanitized history cohort directly while its receipt and manager view remain current. Avoid repeated history admission and detached manager construction, preserving attempt-scoped writer authority and receipt invalidation.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs changes before merge. What this changesThis PR builds initial model context directly from an unchanged prepared transcript instead of repeating history admission and constructing another SessionManager. Example: A complete transcript contains “question” and “answer,” with no intervening committed write.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep this PR open: it provides a focused, maintainer-directed simplification that current main does not contain, and review found no definite introduced bug; CI attribution remains incomplete. Priority: P2 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherAgent runtime preparation receives bounded transcript history from the database owner; SessionManager turns that history into sanitized messages and model metadata consumed by createAgentSession. flowchart TD
A[Runtime preparation] --> B[History cohort]
B --> C[Prepared SessionManager snapshot]
C --> D[Receipt and authority checks]
D --> E[Build initial context]
D --> F[Worker reader fallback]
F --> E
E --> G[Agent session]
Technical reviewBest possible solution: Keep prepared-context reuse in SessionManager with receipt invalidation, sanitized projection, current authority checks, and the existing worker fallback. Do we have a high-confidence way to reproduce the issue? Current-main source shows complete prepared history repeating admission and detached-manager construction; this read-only review ran no target code. Is this the best way to solve the issue? The change removes redundant work at its existing owner and deletes the superseded handoff without introducing another cache or configuration surface. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e4f463159d0a. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -4, Tests +122, Docs +7. Total +125 across 6 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (3 earlier review cycles)Reviewed October 12, 2026, 7:46 PM ET / 23:46 UTC (Revision 4). |
Reuse the complete sanitized history snapshot while its manager view and receipt-owned write revision remain unchanged. Remove duplicate history admission, worker-owner acquisition, FIFO handoff, and detached manager construction. Preserve original writer and selected-reader authority. Completed writes, reset, compaction, branch/fork, and retargeting invalidate through existing receipts or manager state. Keep writable managers and transport callbacks scoped to the attempt. Add coverage for write invalidation and navigation while preserving truncation and private-field behavior.
What Problem This Solves
Runtime preparation already receives a complete, sanitized transcript branch from its history cohort, but initial agent context sends those bytes back through history admission and the writer queue, then constructs another SessionManager. Reuse the accepted snapshot directly while its manager view and receipt-owned write revision remain unchanged. This removes the second admission, source/physical-identity capture, worker-owner acquisition, FIFO handoff, and detached-manager construction. Delete the superseded prepared-context parameter from the lower reader.
The Gateway remains the database owner. Completed native and worker writes invalidate through existing receipts; reset, compaction, branch/fork, and retargeting invalidate through receipts or the manager view. Truncated or admission-fenced contexts keep the existing worker reader. Original writer and selected reader authority still apply.
Writable managers, callbacks, resource extensions, and transport authority remain attempt-scoped because they retain attempt-specific writer, run, cancellation, and credential state. The history replica and provider connection already have persistent owners. No schema, storage format, public SDK, updater, or lifecycle change.
Removed checks and accepted edges
Measurement
Baseline:
529b4d75b7030592d7e0718fa63fb9db16ce8ec3; candidate:d3a722cc134da26511c24584a2c28128a50c0cb7. Shared harness, ten warmed turns per revision per pair, three alternating baseline/candidate pairs plus the one allowed extra pair because the direction reversed. Same isolated Linux host, 4 vCPU AMD EPYC, Node 24.19.0, SQLite 3.53.3. Paired latency runs used the lightweight collector without runtime-preparation wrappers or CPU profiling.No end-to-end latency improvement or SQL reduction was established. The −12 ms p50 aim was not met. Later candidate runs slowed across ACK, completion, process CPU, and event-loop delay. Runtime preparation starts 105–161 ms after ACK, so the slowdown is not isolated to this path; external contention is not proven and these measurements do not absolve the candidate. This PR removes redundant preparation work with existing owner invalidation; it does not claim a whole-turn speedup.
SQL figures below are medians [min–max] of four run-level results, normalized per warmed turn where indicated. Turn-caused counts exclude unrelated maintenance; window counts include it.
Shared-family attribution is from the preserved, separately instrumented baseline/candidate diagnostic windows (ten warmed turns each), not from the paired SQL archives. The remote host reached its allocation lifetime before that final raw archive downloaded; all eight paired causal summaries and latency results survived. No additional measurement pairs were run.
Observed requests per diagnostic warmed window: sessions writer 21→21; transcripts writer 5→5; domain publication 6→6; placement 2→2; audit 2→2; session-transcript reader 9.5→9.3; auth reader 1→1; state execute/ACP sessions/subagents 2/2/1→2/2/1; prompt state 1→1. The watermark/transcript differences are background-window overlap, not claimed runtime-preparation savings. The removed in-process admission/manager handoff produces no measured turn-caused statement or request reduction; prepared-context reuse is observed on 10/10 warmed diagnostic turns.
The candidate diagnostic raw capture covers Gateway and worker threads but lacks five read-only helper-process statements per turn. The baseline identifies those five as schema version, user version, encoding, schema inventory, and the auth-profile union read. Candidate diagnostics record exactly one completed
sqlite_read:auth_profilesrequest per turn and no other read-only child request class; the unchanged auth-reader owner supports excluding this missing work from the five session families above. Per-shape equivalence for the missing child capture is not claimed. Complete all-thread totals remain available in the paired causal summaries.Static T1 inventory is 0→0 in the four touched production files and the runtime-preparation entry point. The broader transitive legacy scope remains 9→9, comprising six sites in
session-accessor.sqlite-active-context.tsand three insession-accessor.sqlite-model-context.ts. Those inventory entries are labeled runtime/mixed and still require reachability tracing; this is not a claim of transitive or repository-wide zero. Measured warmed MAIN remains zero.Separate instrumented diagnostics show runtime-preparation p50 16.977→13.259 ms, initial-context p50 0.874→0.221 ms, and
createAgentSessionp50 1.141→0.423 ms. These were collected on different leases and are supporting attribution, not paired causal speedup proof. The candidate reused prepared context on all ten warmed turns. Baseline mean subcalls: history/manager 8.881 ms, trajectory 5.243 ms, agent-session preparation 2.022 ms, transport 0.938 ms, replay/persistence boundary 0.411 ms, resource-loader reload 0.127 ms. Nested timings overlap. CPU profiling identifies repeated trajectory metadata/tool-schema projection as a larger remaining cost; it includes idle/inspector time and is not used as latency proof.All eight paired latency and SQL runs completed successfully, including restart/shutdown, with no surviving fixture children. The separate diagnostic recorded one failed shutdown-maintenance
BEGIN IMMEDIATEinaudit.writer.prune; its retry completed 29 ms later, outside warmed work, followed by clean shutdown. No SQLite error code is inferred from the collector's missing error string.Evidence
git diff --check: passed.e3e7711c532b02b11df964050dc53d01ed9f5df5(main11a12460482f7790aca049243de04cb9193e87c2plus this head): production passed in 699.940 s; all-exports completed in 1020.491 s with only the same three unused exports/types inui/src/test-helpers/control-ui-team-scale-fixture.ts(TEAM_SCALE_COUNTS,TEAM_SCALE_CATALOG_PROGRESS_ID,TeamScaleEvent) independently verified in main job 115017223014. These are inherited, not a green all-exports result. The candidate all-exports scan passed before those main changes. Local scans used Node 26.11.1 with host load about 104.6; no runtime performance claim is drawn from their durations.SessionManager.inMemory(src/worker/embedded-agent.runtime.ts:149), so initial-context loading takes the unchanged nonpersistent return (session-manager.ts:138–139); the sibling placement rejection occurs atworker.runtime.ts:220, before runtime loading at line 245. The only other applicable SDK change removes a duplicate assertion with no intervening await or session mutation. All seven Codex-history errors occur in unchanged fixture batch append throughprepareTranscriptTurnTarget(session-accessor.transcript-turn.ts:428), before history capture or any changed runtimeprep path. Cached final-head logs establish these paths; they do not establish the causes of the three native timeouts.Release-note context: avoid repeating history admission and rebuilding a second manager during agent runtime preparation when the accepted transcript snapshot is unchanged.