Skip to content

perf(agents): reuse prepared context across unrelated session writes - #178602

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-session-reopen-latency-20260919
Oct 20, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-session-reopen-latency-20260919

Conversation

@steipete

@steipete steipete commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Reopening a session can repeat transcript preparation when another session writes to the same database between hydration and model-context construction.

Related: #178536.

User Impact

Concurrent sessions can reuse their already-prepared context without rereading unchanged transcript data. Transcript contents, authority checks, and idle-worker retirement remain unchanged. No migration or configuration change is needed.

Why This Change Was Made

The prepared context used a database-wide write receipt even though its readers select one physical session ID. It now uses the existing session-scoped receipt, which still invalidates on same-session writes, unknown writes, schema changes, and database replacement. No new cache or retention policy is introduced.

The benchmark now separates provider arrival, synthetic cohort-barrier wait, and first assistant text. It can seed 655-entry measured histories through the transcript owner and paginate integrity verification after reopening, avoiding pre-reopen history reads that warmed the workers. The original workload created fresh measured sessions regardless of the background roster's history size.

Evidence

  • Regression: the unrelated-session-write case fails on the original code with one extra context read; all 31 focused model-context tests pass with the fix. Existing same-session, reader authority, and detached-clone cases remain covered.
  • Diagnostics aggregation: 3 tests passed. Targeted core typecheck passed using the repository's native checker. Changed-file format/lint and independent review through P2 completed.
  • Production change: +6 lines in SessionManager. The growth is the precise existing receipt contract; it removes redundant runtime work without another cache, owner, or compatibility path.
  • Broad validation runs in PR CI. No remote test leases were allocated.

Paired measurements

The isolated real Gateway uses a deterministic loopback SSE provider and the real read tool: 100 sessions in cohorts of 10, 128 KiB prompts, 655 seeded transcript entries, then six minutes idle. Two concurrent baseline/candidate pairs ran on separate 16-core halves under the shared exclusive measurement lock, swapping halves for pair 2. Fixtures and instrumentation match; states and ports are independent. These isolate the receipt change on the same source base.

There is no consistent median speedup: pair 1 improves by 0.8%, while pair 2 is 5.7% slower. Both tails improve slightly. This is a small work-elimination step, not a fix for the dominant latency or a claim of a material end-to-end gain.

Metric Pair 1 baseline Pair 1 scoped B − A Pair 2 baseline Pair 2 scoped B − A
Reopen p50 3393 ms 3366 ms -27 ms 3456 ms 3654 ms +198 ms
Reopen p95 13720 ms 13576 ms -144 ms 13906 ms 13509 ms -396 ms
Provider arrival p50 2142 ms 2107 ms -35 ms 2168 ms 2444 ms +276 ms
Provider arrival p95 12570 ms 12422 ms -148 ms 12709 ms 12339 ms -369 ms
First assistant text p50 2753 ms 2739 ms -14 ms 2876 ms 3155 ms +279 ms
First assistant text p95 13153 ms 12980 ms -173 ms 13315 ms 12920 ms -395 ms
Reopen main-thread CPU 29209 ms 29303 ms +94 ms 29233 ms 33068 ms +3835 ms
Reopen process CPU 94993 ms 93587 ms -1406 ms 93991 ms 100926 ms +6935 ms
Minor GC 612 / 2554 ms 628 / 2572 ms +16 / +18 ms 598 / 2511 ms 674 / 2590 ms +76 / +79 ms
Major GC 7 / 411 ms 6 / 435 ms -1 / +24 ms 7 / 438 ms 8 / 554 ms +1 / +115 ms
Reopen promoted bytes 4.121 GB 4.104 GB -0.017 GB 4.073 GB 4.267 GB +0.193 GB
Idle heap growth 32.59% 32.48% -0.11 pp 33.36% 32.78% -0.57 pp

Each side captured 100 first-text samples and passed all 100 transcript-prefix/answer checks. The long-history absolute idle-heap target of 110% of baseline is not met by either version in either pair. The patch adds no retained cache; its demonstrated benefit is avoiding the redundant read in the regression. Pair 2 also uses 13% more main-thread CPU and promotes 193 MB more; the small sample does not establish a CPU/GC improvement.

A separate source-Gateway attribution probe with the same 100 long histories, but a smaller background roster, found zero live SessionManager, AgentSession, and Agent instances after idle. Invoking existing cleanup owners only in that synthetic probe released 118.50 MiB of JavaScript heap from prompt-cache observations. Fork snapshots released another 1.10 MiB of heap and 65.03 MiB of array-buffer storage. This attributes retained memory; it is not a proposed production cleanup policy or a passing memory acceptance run.

The original short-history diagnostic reproduces 2839 ms p50 / 14362 ms p95. The first cold cohort owns the tail. Checkpoint p95 deltas are 4001 ms for the region ending at session-resource-loader, 2603 ms for AgentSession construction, 198 ms for history-window selection, 478 ms for model dispatch, 7 ms for tool catalog, and 2 ms for system prompt. The resource-loader checkpoint includes lifecycle and transcript hydration; these are not isolated function timings. Transcript-worker aggregate queue time rises from 2.44 s during touch to 97.02 s during reopen. Source workers restart through the TypeScript loader after idle; a bundled-runtime comparison remains necessary before attributing all of this tail to production JavaScript workers.

These synthetic SSE runs do not measure real provider WebSocket reconnects, prompt-cache hits, or network inference latency. First text is timestamped inside the Gateway and excludes later client delivery. Sessions were already rebuilt/disposed per attempt before #178536; that fix removed references pinning disposed objects.

CI attribution

The only failing test job is checks-node-changed, in test/gateway-openai-compaction-replay.e2e.test.ts. The aggregate CI gate reflects that failure; the other completed test/type/lint/security jobs passed.

The failing CI checkout is merge 6d2eaa81543d9d3d6d405da6d5c70559a41da25d, with main parent 051bf6fa4d05e0870d0f360aee7ac1643cbb787d and PR head 75c2531b9e825da1b494bb0ccb213d4b936416f8. In an isolated sandbox, both exact source trees passed pnpm build qaRuntime; both then reproduced the same assertion under the pinned Bun runtime with:

node scripts/run-vitest.mjs test/gateway-openai-compaction-replay.e2e.test.ts --maxWorkers=1
main parent: expected array length 2, received 3
CI merge:    expected array length 2, received 3

The continuation instruction appears twice in the third provider request. The retry-persistence path and failing assertion are unchanged by this PR. The reproduction changes only the fixture's loopback ports to avoid other processes; the initial baseline attempt hit a port collision and was discarded as setup failure, then repeated on a free port above the ephemeral range. No CI reruns were requested. This is an attributed inherited failure, not a passing test.

@clawsweeper

clawsweeper Bot commented Oct 20, 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.

@steipete
steipete marked this pull request as ready for review October 20, 2026 17:27
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T17:33:03.660497Z 75c2531 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: M labels Oct 20, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR scopes prepared-context invalidation to the physical session and extends the existing reopen benchmark with seeded histories and preparation timings.

Example: After hydrating session hydrated-model-context, unrelated-session appends a message to the same database.

  • Before: Building the first model context performs another context read despite unchanged session history.
  • After: The prepared context is reused while same-session changes still invalidate it.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is focused and source-consistent, but the required performance evidence is unfinished and a failing behavioral check remains unattributed.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Concurrent sessions can repeat transcript preparation even though the session being reopened has not changed.
Reason: The maintainer-authored direction removes source-verifiable redundant work through an existing receipt contract without adding a competing owner.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this maintainer-authored PR open: it addresses source-verifiable redundant context reads with a focused runtime change, and inspection found no definite introduced correctness defect.

Priority: P2
Reviewed head: 75c2531b9e825da1b494bb0ccb213d4b936416f8

Before merge

  • Complete next step - Establish whether the compaction-replay failure at test/gateway-openai-compaction-replay.e2e.test.ts:102 is caused by this diff or also occurs on the base; repair it only if diff-caused.

Findings

None.

Tests

  • Missing end-to-end proof: Completed paired Gateway runs must show scoped-context reuse, preserved seeded history, and the declared latency, heap, and GC acceptance results.
Agent review details

How this fits together

SessionManager receives bounded transcript snapshots from the history owner and supplies detached conversation context to agent creation; existing database receipts determine whether prepared bytes remain reusable.

flowchart LR
  A[History owner] --> B[Bounded transcript hydration]
  B --> C[SessionManager prepared context]
  D[Session scoped write receipt] --> C
  C --> E[Current writer and reader checks]
  E --> F[Agent model context]
Loading

Technical review

Best possible solution:

Use the existing physical-session receipt at both prepared-context boundaries while retaining live authority checks and conservative invalidation.

Do we have a high-confidence way to reproduce the issue?

The base compares a database-wide write token, so an unrelated committed session write forces the fallback context reader; the added interleaved regression exercises that path, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

The runtime fix uses the existing freshness owner and changes both token boundaries together; benchmark additions support measuring the affected concurrent reopen flow without introducing another runtime cache.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against fc374815c3e8.

Provenance checked

  • Prepared initial model context changes intended behavior with a stated reason (1efc0b4: Reuse accepted immutable history while preserving completed-write invalidation and original writer and reader authority.)
  • Idle/reopen history verification changes intended behavior with a stated reason (5c1432f: Verify retained history and append-only reopening while measuring completed-session retention; this PR defers the idle check until after reopening to avoid warming workers and paginates long histories.)
  • Benchmark diagnostics aggregation keeps the original intent (214275f: Collect bounded, content-free Gateway work summaries; the new reservation grouping preserves those bounds and numeric-only output.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 1efc0b4 adds src/agents/sessions/session-manager.ts:158 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1efc0b40276e; files: src/agents/sessions/session-manager.ts)

PR surface

Source +6, Tests +33, Docs +29, Other +202. Total +270 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 13 7 +6
Tests 2 33 0 +33
Docs 1 31 2 +29
Config 0 0 0 0
Generated 0 0 0 0
Other 3 222 20 +202
Total 7 299 29 +270

Review metrics

Metric Value Why it matters
Benchmark controls 3 new benchmark flags and 1 benchmark-only environment switch Adds --prep-trace, --history-turns, --seed-history, and OPENCLAW_BENCH_FIRST_TEXT; no persisted product setting or schema migration.

Labels

Label changes:

  • add P2: Avoidable repeated preparation affects concurrent-session efficiency without establishing message loss, an outage, or an urgent user regression.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Avoidable repeated preparation affects concurrent-session efficiency without establishing message loss, an outage, or an urgent user regression.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab 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.

Reviewed October 20, 2026, 1:44 PM ET / 17:44 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

The remaining compaction-replay failure is inherited. CI run 39466279051 tested merge 6d2eaa81543d9d3d6d405da6d5c70559a41da25d, whose main parent is 051bf6fa4d05e0870d0f360aee7ac1643cbb787d. Both exact trees passed the isolated QA runtime build, then failed the same single test with the same assertion: expected length 2, received 3 for Continue from the compacted transcript. The initial baseline launch hit a port collision; after moving both fixtures to checked-free loopback ports, the baseline reproduced the assertion too. No CI rerun was requested.

Both concurrent, swapped-core Gateway pairs are complete, with 100 first-text samples and 100 append-only transcript checks per side. The body now records all latency, CPU, promotion, GC, and heap results. There is no consistent median latency gain, and both baseline and candidate miss the long-history 10% heap-growth goal. This first step removes the independently reproduced false invalidation; it does not claim to solve the remaining cold-worker or retained-fingerprint costs.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit f5bd31e into main Oct 20, 2026
254 of 259 checks passed
@steipete
steipete deleted the steipete/perf-micro-session-reopen-latency-20260919 branch October 20, 2026 18:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts 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