Skip to content

perf(agents): reuse prepared initial session context - #170262

Merged
steipete merged 2 commits into
mainfrom
dbasync/runtimeprep
Oct 13, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/runtimeprep

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

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

  • The second history admission, identity recapture, native witness, and writer-FIFO handoff are unnecessary for an already accepted immutable snapshot. Accepted edge: a later pending write may finish after this snapshot is materialized; completed writes invalidate it before reuse.
  • Remove the duplicate initial-session identity assertion in createAgentSession. No awaited work or external effect occurs between it and the preceding assertion.
  • Preserve original writer revocation and selected-reader authority: these protect real run ownership and context disclosure.

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.

Paired warmed latency Baseline Candidate
Pair 1 wall p50 334.472 ms 331.838 ms
Pair 2 wall p50 327.151 ms 267.944 ms
Pair 3 wall p50 277.746 ms 405.591 ms
Pair 4 wall p50 306.172 ms 479.391 ms
Primary three pairs, pooled wall p50 / p95 323.422 / 465.701 ms 331.838 / 529.175 ms
All four pairs, pooled wall p50 / p95 321.393 / 465.701 ms 377.466 / 591.261 ms
All four pairs, first-delta p50 / p95 223.142 / 350.822 ms 262.169 / 416.419 ms
All four pairs, ACK p50 31.736 ms 43.847 ms

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.

SQL metric Baseline Candidate
Warmed turn-caused all-thread statements 201 [201–201] 201 [201–201]
Warmed turn-caused requests 45 [45–45] 45 [45–45]
Warmed MAIN statements 0 0
Warmed window statements 213.85 [213.6–214.2] 214.15 [213.6–214.2]
Warmed window requests 55.3 [55.2–55.4] 55.4 [55.3–55.6]
Whole-workload statements 6670 [6666–6694] 6672 [6672–6674]
Whole-workload requests 1220.5 [1219–1225] 1219.5 [1219–1222]

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.

Shared read family, statements per diagnostic warmed window Baseline Candidate
Exact-entry facts 4 4
Actor hydration 2 2
Entry-cache snapshots 0 0
Row facts 0 0
Watermark reads 1.5 1.3

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_profiles request 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.ts and three in session-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 createAgentSession p50 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 IMMEDIATE in audit.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

  • Added regressions for receipt invalidation after reset and compaction, local reset/branch without durable mutation, fork, retargeting, and revoked original writer under a replacement run. Existing append, truncation, and private-field cases retained. Read-boundary budgets prove the removed handoff.
  • Formatting and git diff --check: passed.
  • Focused lint: passed. Codex autoreview: two scoped-clean rounds, no actionable findings.
  • Final-head CI 38311138056: production/test types, lint, source contracts/export collisions, Madge (0 cycles), and T1/dialect/worker ratchets passed. Knip on the pinned merge snapshot e3e7711c532b02b11df964050dc53d01ed9f5df5 (main 11a12460482f7790aca049243de04cb9193e87c2 plus this head): production passed in 699.940 s; all-exports completed in 1020.491 s with only the same three unused exports/types in ui/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.
  • Owner suites passed: model-context snapshot 35/35, model-context 45/45, incognito 22/22, transcript-context worker 13/13. Their summed case durations were 27.554 s, 29.251 s, 1.717 s, and 11.064 s respectively; these are CI case durations, not local command wall times. Local suites were not duplicated.
  • CI is not aggregate-green. Twelve unchanged behavioral cases match scheduled main exactly: model-context prefix (1), transaction rollback (7), code-mode source (1), and pending-input foreign rewrite (2), in main run 38305224828, jobs 114997828820/114997828704/114997828811/114997828524; prompt provenance (1) in main run 38298274614. They fail in runtime-config/profile-catalog preparation and have existing repair owners. The two preserved native-worker baseline case fragments also match the startup runtime-config error and unsupported-reasoning placement mismatch. The remaining eleven cases have source-level exclusion, not completed baseline assertion proof: three native timeout cases use 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 at worker.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 through prepareTranscriptTurnTarget (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.
  • Baseline diagnostic limitation: the local native retry on the pinned baseline, Node 26.11.1, initial host load 100.28, exited 143 after 462.681 s of command wall time with zero case outcomes. Compiled fixture generation took 278.241 s; the supported 300 s no-output watchdog then stopped the run, followed by verified cleanup. No assertion or per-case timeout was changed. After the source exclusions were verified, the marker-history diagnostic was explicitly canceled with no case outcomes (wrapper exit 143, no watchdog firing); its completed fixture took 280.127 s. The final settled-history stage was not started. Owned readers settled before checkout restoration. These canceled/unstarted runs are not claimed as test passes or baseline failures.
  • Landing uses the maintainer-authorized relaxed-v4 exception: no introduced product regression is established; static gates pass or have exact main attribution; the eleven cases above remain explicitly unproven as baseline reproductions. They are handed to the existing red-main repair queue. CI remains failed, not aggregate-green.
  • Published-driver update cell and SDK API diff: not applicable; the corresponding surfaces are unchanged.
  • LOC: production +39/−43, tests +141/−19, docs +11/−4.

Release-note context: avoid repeating history admission and rebuilding a second manager during agent runtime preparation when the accepted transcript snapshot is unchanged.

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.
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

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

  • Before: Initial context repeats history admission and constructs a detached manager.
  • After: SessionManager returns the same sanitized context after checking its view, write receipt, original writer, and selected reader.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, apparently correct simplification supported by production-owner coverage and reported Gateway measurements; the performance benefit remains limited to removed preparation work.
Proof confidence 🐚 platinum hermit (4/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its updated body reports pinned baseline/candidate Gateway workloads, successful runtime completion, and prepared-context reuse on ten diagnostic turns, without claiming demonstrated latency or SQL savings.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Agent runtime preparation repeats work for transcript history it already accepted.
Reason: The maintainer-directed change removes redundant preparation with a small production reduction; its body accurately withdraws any claim of demonstrated whole-turn speedup.

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
Reviewed head: d3a722cc134da26511c24584a2c28128a50c0cb7

Before merge

  • Complete next step - Finish attributing the eleven remaining native-worker and Codex-history cases using the pinned baseline results, and repair only failures shown to be introduced by this PR.

Findings

None.

Tests

  • Missing end-to-end proof: The added cases have reported head passes, but execution showing their intended failure on the base is not supplied.
Agent review details

How this fits together

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

Technical review

Best 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

  • Prepared initial-context admission changes intended behavior with a stated reason (da965e0: Reuse complete sanitized hydration while binding it to the selected physical reader and committed write revision; this PR explains why repeated admission and FIFO handoff can be removed.)
  • Immutable model-message sharing keeps the original intent (adcfdcd: Reduce duplicate retained payloads without restoring fields removed by model-context projection.)
  • SDK initial-session identity assertion changes intended behavior with a stated reason (fd578cb: Keep initialization bound to its original session across awaited persistence; the removed assertion duplicates the preceding check with no intervening await, and later post-await checks remain.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit da965e0 adds src/agents/sessions/session-manager.ts:577 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: da965e09656e; files: src/agents/sessions/session-manager.ts)
  • RoboClaw: Raw commit e95e7c1 adds src/agents/sessions/session-manager.ts:92 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: e95e7c1d7ecc; files: src/agents/sessions/session-manager.ts)

PR surface

Source -4, Tests +122, Docs +7. Total +125 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 39 43 -4
Tests 1 141 19 +122
Docs 1 11 4 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 191 66 +125

Review metrics

Metric Value Why it matters
Production versus test LOC Production +39/-43; tests +141/-19 Production shrinks overall; test growth extends the existing fixture to protect invalidation, navigation, sanitization, and original-writer rejection.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This is a focused runtime-preparation improvement without an established urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-12T21:29:16.944Z sha fd5ef64 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T21:45:08.217Z sha d3a722c :: needs changes before merge. :: none
  • reviewed 2026-10-12T22:03:20.899Z sha d3a722c :: needs changes before merge. :: none

Reviewed October 12, 2026, 7:46 PM ET / 23:46 UTC (Revision 4).

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@steipete
steipete merged commit 1efc0b4 into main Oct 13, 2026
156 of 165 checks passed
@steipete
steipete deleted the dbasync/runtimeprep branch October 13, 2026 00:31
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant