Skip to content

perf(sessions): bound transcript source reads - #165221

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-history-source-messages-paged-20260919
Oct 5, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-history-source-messages-paged-20260919

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large sessions.history.source-messages reads decoded the complete transcript in one SQLite transaction and copied a 100+ MB result into the Gateway, delaying other work on the reader worker and causing heap spikes.

User Impact

Attachment cleanup and context reports consume bounded pages without retaining complete message arrays. Each source call admits at most 128 physical events and 8 MiB of stored payload. Oversized individual records fail explicitly; cleanup never treats an incomplete scan as proof that an attachment is unused.

The public before_reset hook, legacy model-context estimation, and unlimited HTTP history still require complete results and collect these same pages. Their total-result memory cost remains. Transcript bytes, schemas, retention, configuration, and update behavior are unchanged.

Why This Change Was Made

One source-page reader replaces the eager active-path/off-path readers. It walks indexed physical positions, preserving reset-kept messages, visible markers, and retained branches. The captured indexed sequence, generation, physical active tail (including hidden controls), and reset window exclude later appends and reject incompatible history changes. Shared exact-payload and coordinate readers also serve existing history/tail operations; the SQLite main-thread call-count ratchet remains flat.

Cold archives incrementally prepare the existing identity/LRU navigation index before returning bounded payload pages. The cache retains navigation metadata, not message payloads, and file identity invalidates partial and completed preparation. Ordinary exact archive reads retain oversized-image recovery. Context classification carries only its cross-page lookback counter.

Production delta is +455 lines (792 additions, 337 deletions, excluding *.test.ts, test-support, and docs). Growth is required to preserve the existing reset/branch/archive fidelity and whole-array consumer contracts while releasing each transaction: the cursor, snapshot fence, byte admission, and resumable archive preparation replace eager operations. The old whole-source readers, redundant recent branch, and test-only array methods are removed; there is no competing eager fast path. Legacy model-context estimation cannot simply sum page estimates because it plans tool-result truncation across the whole context.

Evidence

Pre-publication builds, test suites, and static gates ran on Blacksmith Testbox, profile openclaw-check; no local suites, typechecks, or builds. Final fixture and focused-test lease: tbx_01m44enevryb0s7dcqme0ke4y6, Node v24.19.0. Baseline a2697c13548d1a5cac96af77508e54b6dc496b8c and candidate ran sequentially on the same lease in disposable copies with source hashes checked. Each fixture verifies all 50,000 ordered IDs through the public source-reader facade.

Measurement Before After
Plain transcript largest request, cold / warm 877.55 / 827.49 ms 16.02 / 40.25 ms
50% visible-marker transcript largest request, cold / warm 990.87 / 998.01 ms 75.09 / 55.35 ms
Cold reset archive largest request 648.50 ms 57.79 ms
Largest serialized result, plain / markers / archive 107.43 / 108.36 / 107.83 MB 275,592 / 277,960 / 276,822 bytes
Largest caller heap delta per request across fixtures 127.39 MB 1.27 MB
SQLite worker transaction hold, plain 657–690 ms 1–5 ms; p95 2 ms across 782 reads
Plain complete scan, cold / warm 1,009.84 / 949.61 ms 1,103.33 / 1,056.27 ms
Cold archive complete scan 781.32 ms 1,185.48 ms

Full scans trade some throughput for bounded requests and worker availability. Observed caller peak heap growth during an entire paged scan was 82–85 MB across garbage-collection cycles; the per-request delta is the smaller figure above. SQLite scans used 391 requests; cold archive scans used 391 preparation continuations plus 391 payload requests. Worker-hold diagnostics lowered only the logging threshold in disposable copies and verified isMainThread=false; production instrumentation is unchanged. The benchmark command was node --expose-gc --import ./scripts/tsx.mjs <inline 50k fixture>; eight baseline/candidate runs completed successfully in 171.25 seconds.

365 distinct tests across 24 files passed on Testbox, comprising the 322-test history/session/attachment/context run, 40 additional archive tests, and three managed-image end-to-end cases.

node scripts/run-vitest.mjs <21 focused history/session/attachment/context files>: 322 tests passed, five shards, 244.74 seconds. Coverage includes byte limits, ordered pages, append exclusion, reset/branch/marker fidelity, archive preparation/cache behavior, bounded-tail readers, incognito/history siblings, and incremental consumers. On earlier Testbox tbx_01m448g4p9bm9w194s3khtggsd, the source-page regressions fail on the original eager implementation (260 messages instead of 128; three 3 MiB records instead of two). A separate pinned negative control proved the earlier visible-anchor fence deleted one retained attachment after an in-place hidden-tail branch change; the current physical-tail fence rejects the scan and preserves it. Both negative/positive runs completed as expected in 63.85 seconds.

Single-worker cost, command pnpm test <file> --maxWorkers=1 on the same CI-class lease:

File (under src/) Tests Command wall Vitest seconds
agents/compaction-real-conversation.test.ts 16 1.31 s 0.27 s
auto-reply/reply/commands-context-report.test.ts 20 8.76 s 6.93 s
gateway/managed-image-attachments.branch-retention.test.ts 3 19.80 s 17.97 s
gateway/managed-image-attachments.sqlite-visibility.test.ts 25 34.56 s 32.79 s
gateway/session-history.subagent-visibility.test.ts 12 18.95 s 14.46 s
gateway/session-transcript-index.fs.test.ts 7 6.92 s 4.64 s
gateway/session-transcript-readers.test.ts 18 14.10 s 9.63 s
gateway/managed-image-actions.e2e.test.ts 3 608.73 s including runtime build 49.55 s
gateway/session-utils.fs.test.ts 34 23.38 s 21.15 s
gateway/session-utils.fs.display-position.test.ts 6 6.46 s 4.24 s

Final test cutover on Testbox tbx_01m44h8bjafdyjh46pa2pt31y5: five focused files passed 81 tests in 39.83 seconds, including the two archive suites; their exact input hashes matched the applied test migration. The archive suites also passed individually with the explicit byte limit shown in the cost table.

Independent Codex reviews completed with no actionable P0–P2 findings for the production change and the final test cutover. Static checks also identified and removed two unused imports and a retired type re-export, required an explicit byte limit matching the existing default in one test fixture, and tightened method binding and fixed-shape cursor construction.

Managed-image E2E passed all three cases; its long command cost above is dominated by the fresh runtime build. Rebased onto 42ebb9d73483 with no production or test changes from the rebase; the only conflict combined independent documentation additions.

Final Testbox tbx_01m44n807vqf0jvk4gmpvv5x0f: node scripts/check-changed.mjs --base 42ebb9d73483b2d0d55178709b960af363cdd07d and the eight affected history/archive/attachment files (126 tests) both passed in one uninterrupted run (gate_result=0, test_result=0, total command 1,528.80 seconds; runtime tests 149.91 seconds). This includes all 27 core test-typecheck partitions, production types, structural guards, all three dead-export scans, core/script lint, and schema/storage/cycle/webhook/pairing guards. Source hashes verified the complete candidate before execution.

Measurements precede mechanical import/type-export/lint cleanup and test-only corrections; the paging bounds and selection behavior are unchanged. No production Gateway or real customer state was used. Final independent review of the lint-driven corrections also completed with no actionable P0–P2 findings.

CI follow-up: the first GitHub run found a type-only cycle between the reader contracts and page iterator, which the runtime-value cycle check does not cover. The source-page contracts now live with the existing reader types, and all consumers import them there. It also exposed an inherited declaration-fixture omission after 76922aba447e: the fixture copied scripts/lib but omitted its new root-level runtime-postbuild-shared.mjs dependency. The fixture now copies that existing helper; no assertion was weakened. The branch was rebased onto c5012333049e without changing lane-owned runtime source.

Testbox tbx_01m44s8k6z1pbavnn5x6f07m35 verified the CI repairs: pnpm check:architecture (including both cycle scanners, Kysely checks, and storage guards), production and gateway-test types, affected core/root-test lint, and 25 reader/archive tests passed. The exact failing declaration case, pnpm test test/scripts/write-unified-entry-dts.test.ts --maxWorkers=1 -t 'reuses unaffected canonical groups while rebuilding runtime after input edits', passed unchanged (11.31 s test time, 13.09 s command wall). A remaining test-only type import was migrated to the new contract owner and its gateway typecheck/lint passed separately. Independent review of the CI repair completed with no actionable P0–P2 findings. The final test-only import migration was typechecked and linted, then formatted into canonical import order.

Final GitHub CI passed on 8d45f399a8104e0868adda20581097643b2fb18d, including openclaw/ci-gate. The PR merged as 12785be2ff02a11e6587399ea3a0ac6ea2a4be36. The final CI plan skipped its Windows matrix; the declaration-fixture regression was verified on Linux Testbox as recorded above.

@clawsweeper

clawsweeper Bot commented Oct 5, 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 gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 5, 2026
@steipete
steipete marked this pull request as ready for review October 5, 2026 00:41
@steipete
steipete enabled auto-merge (squash) October 5, 2026 00:46
@clawsweeper

clawsweeper Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 4, 2026, 8:47 PM ET / October 5, 2026, 00:47 UTC.

ClawSweeper review

What this changes

The PR pages transcript source reads and incrementally consumes them for attachment cleanup and context reports while preserving callers that require complete results.

Merge readiness

✅ Ready for maintainer review

This remains useful: current main still materializes complete source transcripts. The pinned patch has no actionable correctness findings, and the supplied measurements support its performance benefit.

Priority: P2
Reviewed head: 3b78476b82a3aea2aa0c33e8a2734c58e84c949b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent performance patch with strong measured production-path evidence and no actionable findings from source review.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied Testbox measurements exercise the public source-reader facade against real SQLite and archive files, verify ordered results, and show reduced request size and worker holds. Tests provide supplemental snapshot and cleanup coverage. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Testbox measurements exercise the public source-reader facade against real SQLite and archive files, verify ordered results, and show reduced request size and worker holds. Tests provide supplemental snapshot and cleanup coverage. No stored-data contract changes require migration proof.
Evidence reviewed 8 items Pinned introduction: Reviewed the merge-base-to-head delta, including production readers, consumers, archive indexing, and changed tests. Base-branch drift was not attributed to this PR.
Still necessary on main: Fetched main's source selection still calls the complete visible-history reader and optionally the complete off-path reader; it does not implement this bounded source-page path. The bounded GitHub search found no verified replacement fixing PR.
Snapshot and cleanup safety: Continuation reads check generation, indexed sequence, physical active tail, and reset boundary. Attachment cleanup installs its reference index only after every page completes, so a rejected scan does not establish that an attachment is unused.
Findings None None.
Security None None.

How this fits together

Transcript readers turn stored SQLite events and retained archive files into session messages. Gateway history, context reports, and attachment cleanup consume those messages.

flowchart TD
  A[SQLite transcript events] --> C[Bounded source reader]
  B[Retained archive files] --> D[Incremental archive index]
  D --> C
  C --> E[Snapshot and byte checks]
  E --> F[Context reports and attachment cleanup]
  E --> G[Complete-result collector]
  G --> H[History and existing array consumers]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +455, Tests +340, Docs +22, Other 0. Total +817 across 30 files.

View PR surface stats
Area Files Added Removed Net
Source 17 791 336 +455
Tests 11 418 78 +340
Docs 1 22 0 +22
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 30 1232 415 +817

Review metrics

Metric Value Why it matters
Source request bounds 128 physical events; 8 MiB stored payload These limits constrain worker transaction and transport costs independently of total transcript size.
Production versus test growth Production net +455 lines; tests and support net +340 lines The PR explains the production growth needed for cursor fencing, archive preparation, and preserved complete-result contracts.

Technical review

Best possible solution:

Use one bounded source-page owner with snapshot fencing, incremental consumers, and explicit collection for existing complete-result contracts.

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

Yes, source inspection establishes the eager whole-transcript selection on current main, and the supplied 50,000-event runs quantify its cost. The reviewer did not execute a reproduction.

Is this the best way to solve the issue?

Yes, the patch replaces the eager owner and migrates its consumers while preserving reset, branch, archive, and complete-result contracts.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded performance improvement for large transcript reads, supported by substantial before/after measurements.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied Testbox measurements exercise the public source-reader facade against real SQLite and archive files, verify ordered results, and show reduced request size and worker holds. Tests provide supplemental snapshot and cleanup coverage. No stored-data contract changes require migration proof.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.

Label justifications:

  • P2: This is a bounded performance improvement for large transcript reads, supported by substantial before/after measurements.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Testbox measurements exercise the public source-reader facade against real SQLite and archive files, verify ordered results, and show reduced request size and worker holds. Tests provide supplemental snapshot and cleanup coverage. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction: Reviewed the merge-base-to-head delta, including production readers, consumers, archive indexing, and changed tests. Base-branch drift was not attributed to this PR. (3b78476b82a3)
  • Still necessary on main: Fetched main's source selection still calls the complete visible-history reader and optionally the complete off-path reader; it does not implement this bounded source-page path. The bounded GitHub search found no verified replacement fixing PR. (src/gateway/session-transcript-read-kernel.ts:254, 869657375d2d)
  • Snapshot and cleanup safety: Continuation reads check generation, indexed sequence, physical active tail, and reset boundary. Attachment cleanup installs its reference index only after every page completes, so a rejected scan does not establish that an attachment is unused. (src/config/sessions/session-accessor.sqlite-history-source.ts:55, 3b78476b82a3)
  • Archive and complete-result contracts: Cold archive preparation advances incrementally under file-identity checks. Complete-result consumers collect the same pages; exact archive reads retain oversized-image recovery. The diff changes queries and runtime navigation state, without changing durable schemas or serialized transcript formats. (src/gateway/session-transcript-index.fs.ts:397, 3b78476b82a3)
  • Production-path performance evidence: The captured PR body reports sequential baseline/candidate runs on a disposable Blacksmith Testbox using the public source-reader facade and checking all 50,000 ordered IDs. Plain SQLite transaction holds fell from 657–690 ms to 1–5 ms, and maximum per-request caller heap growth fell from 127.39 MB to 1.27 MB. These are supplied observations, not reviewer-executed results; complete scans became slower and complete-result consumers retain their total memory cost. (3b78476b82a3)
  • Regression coverage: Changed tests exercise event and byte bounds, append exclusion, transcript replacement, cross-page classification, cold archive selection, oversized-image recovery, and hidden-tail branch changes during cleanup. The supplied body records failing original-implementation controls and successful candidate runs; no tests were executed during this read-only review. (src/gateway/session-transcript-readers.test.ts:165, 3b78476b82a3)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • chelsealong: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

Bound source worker reads to 128 physical events and 8 MiB, fence the captured indexed history, and stream attachment cleanup and context reports. Prepare archive navigation incrementally while preserving reset, retained-branch, and full-result caller contracts.
Migrate remaining archive fixtures to bounded source and recent readers, preserve generation-change race coverage on file-window reads, keep fixture types concrete, and remove the retired full-reader type export.
Bind the history reader to its owner, construct the fixed-shape source cursor explicitly, and keep the archive index guard outside the bounded loop. Complete import, wire-key, and deferred-fixture lint cleanup.
Keep source-page contracts with the existing reader types and migrate every type consumer. Include the runtime postbuild helper in declaration fixtures to repair the missing fixture dependency exposed by Windows CI after the upstream build change.
@steipete
steipete force-pushed the steipete/perf-micro-history-source-messages-paged-20260919 branch from 3b78476 to 8d45f39 Compare October 5, 2026 01:42
@steipete
steipete merged commit 12785be into main Oct 5, 2026
132 checks passed
@steipete
steipete deleted the steipete/perf-micro-history-source-messages-paged-20260919 branch October 5, 2026 01:49
steipete added a commit that referenced this pull request Oct 5, 2026
Integrate the landed declaration-fixture dependency fix in #165221 without rebasing. Scoped integration proof passed 75 tests. The review's Talk-policy concern was rejected after source inspection and two real worker-authority probes confirmed current-policy revocation and fail-closed missing targets; no additional production change was needed.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
* perf(sessions): page transcript source reads

Bound source worker reads to 128 physical events and 8 MiB, fence the captured indexed history, and stream attachment cleanup and context reports. Prepare archive navigation incrementally while preserving reset, retained-branch, and full-result caller contracts.

* fix(sessions): complete paged reader cutover

Migrate remaining archive fixtures to bounded source and recent readers, preserve generation-change race coverage on file-window reads, keep fixture types concrete, and remove the retired full-reader type export.

* fix(sessions): preserve reader binding and explicit page state

Bind the history reader to its owner, construct the fixed-shape source cursor explicitly, and keep the archive index guard outside the bounded loop. Complete import, wire-key, and deferred-fixture lint cleanup.

* fix(sessions): keep source page contracts acyclic

Keep source-page contracts with the existing reader types and migrate every type consumer. Include the runtime postbuild helper in declaration fixtures to repair the missing fixture dependency exposed by Windows CI after the upstream build change.
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 gateway Gateway runtime size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant