Skip to content

improve: reduce memory use for raw-trace diagnostics - #150754

Merged
steipete merged 1 commit into
mainfrom
codex/perf-raw-trace-usage-stream-7006
Sep 18, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf-raw-trace-usage-stream-7006

Conversation

@steipete

@steipete steipete commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #150724

What Problem This Solves

Raw-trace diagnostics retain all transcript message bodies while computing a small usage summary, adding memory pressure for long conversations.

User Impact

Authorized raw-trace completion no longer buffers the full transcript for usage aggregation. Reported usage and the bounded recent-usage reader keep their existing behavior. This does not establish a default-request or whole-Gateway speedup.

Why This Change Was Made

Feed the shared aggregation logic incrementally from the existing SQLite snapshot visitor and JSONL line reader. Keep forward ordering, source-specific usage rules, normalization, and cleanup. Each cold-storage retry starts a fresh accumulator. SQLite aggregation now runs inside the existing synchronous read snapshot; there are no schema, configuration, or persistence changes.

The reply tests also close their SQLite state through the existing cleanup helper before removing temporary directories. This repairs a Windows cleanup failure reproduced on the original production code and removes duplicate inline deletion paths.

Evidence

Windows / Node 26.8.2, base 4345deb5dbe89d2e56589f5bbed618a92da36ca0: 16 fresh-process reads in baseline/candidate/candidate/baseline order, covering SQLite and JSONL at 32 and 8,192 messages with 8 KiB of content each. All complete output objects matched, and source, dependency, fixture, and cleanup checks passed.

Long SQLite reads had 8.3% and 12.4% lower process peak RSS in the two fixed pairs, with mixed wall time. Long JSONL reads were 8.3% and 14.9% faster, while peak RSS was essentially unchanged. Short reads and CPU results were mixed; both pairs are retained below.

All fixed-pair changes; positive values are regressions
Case Pair Wall time Process CPU Process peak RSS
SQLite, 32 messages B1/C1 +17.75% -9.73% +1.26%
SQLite, 32 messages B2/C2 -6.68% -10.68% -7.01%
JSONL, 32 messages B1/C1 -71.12% undefined (baseline zero) +14.56%
JSONL, 32 messages B2/C2 +9.99% 0.00% +4.33%
SQLite, 8,192 messages B1/C1 -24.28% -19.47% -8.32%
SQLite, 8,192 messages B2/C2 +8.00% +0.10% -12.36%
JSONL, 8,192 messages B1/C1 -8.30% +27.35% +0.39%
JSONL, 8,192 messages B2/C2 -14.87% -11.35% -0.75%

Exactly two comparisons per case on one shared Windows host. Call timing excludes initial imports; process peak RSS includes them, and pre-read memory varies substantially. These are component observations, not GC-normalized retained-heap, cold-cache, or end-to-end guarantees. The initial misplaced JSONL fixture and a zero-measurement Windows Python-launcher rejection were corrected and preserved separately; neither is a performance result.

Original patch validation: 227 selected cases passed (108 Gateway reader cases, all 112 reply cases, three recent-usage cases, and four queued-trace cases). The repository changed-file checks passed, including core and test types, formatting, lint, unused exports, and import cycles. Fresh review of the final four-file patch and the exact-head ClawSweeper review found no actionable issues.

The branch is now at 0061248aeec63571418fe498bc4ab27796bee1dc, with an identical four-file patch after incorporating three landed repairs for inherited CI failures: #150655 (labeler and Doctor test expectations), #151372 (compact-planner worker assertion), and #151417 (duplicate UI test declaration). The prior CI run 35312679421 finished with 134 successful jobs, 17 skipped jobs, and three static-check failures from that same UI declaration plus the aggregate gate. All runtime jobs passed; specific test-case coverage is not inferred from those job results. Exact-head CI run 35315107780 passed with 138 successful jobs and 17 skipped jobs. The current ClawSweeper workflow also completed successfully; its durable published verdict remains attached to the patch-identical prior head, and the native workflow applies its review freshness policy.

The refreshed Windows changed-file checks passed the preceding guards, formatting and production typechecking, then failed test typechecking on the same inherited UI declaration. That repair is now included. The additional selected Windows run passed 226 cases and timed out one queued-trace case. Its direct children completed and the scoped process census was empty. The affected fixture supplies an unwritten synthetic transcript, so its artifact lookup normally returns before the changed usage accumulator; the run also showed substantial slowdown in other cases and build preparation. The failure remains recorded. The four-case diagnostic with temporary phase logging passed with the original assertions, order and timeouts. Accounting, including the raw-trace lookup, took 5–28 ms; follow-up delivery took 92.678, 15.020, 12.276 and 9.750 seconds. This locates the reproduced delay after the changed reader, but does not retroactively trace the original timeout. The diagnostic is separate from uninstrumented proof, and the exact original test bytes were restored after its children joined and scoped process checks cleared. All bound reader/caller/helper inputs and dependency metadata remain unchanged across these rebases.

The initial Windows reply run failed while deleting open SQLite files; a two-case control on the original production code reproduced the failure. The first cleanup fix left seven inline-deletion failures; the final patch removes those duplicate paths and passes the full reply file. The first changed-check invocation stopped because the isolated environment unnecessarily selected unavailable Corepack; the successful run used the normal local route with installed pnpm 12.4.0. These failures remain separate from the performance measurements.

@clawsweeper

clawsweeper Bot commented Sep 17, 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 self-assigned this Sep 17, 2026
@steipete
steipete marked this pull request as ready for review September 17, 2026 08:48
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Sep 17, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 17, 2026
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 18, 2026, 3:04 AM ET / 07:04 UTC (Revision 7).

ClawSweeper review

What this changes

The PR computes raw-trace usage incrementally instead of retaining transcript message arrays and closes test databases before deleting temporary directories.

Merge readiness

✅ Ready for maintainer review

Keep open: the optimization remains necessary on current main, and review found no actionable introduced defect. The supplied component measurements support the bounded performance claim.

Priority: P2
Reviewed head: 0061248aeec63571418fe498bc4ab27796bee1dc

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, behavior-preserving optimization with relevant component evidence and no actionable review findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Windows production-reader measurements exercise both changed SQLite and JSONL paths, report identical complete outputs, and show lower long-history SQLite peak RSS. The measured claim is appropriately limited to these components; tests and CI are supplemental.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Windows production-reader measurements exercise both changed SQLite and JSONL paths, report identical complete outputs, and show lower long-history SQLite peak RSS. The measured claim is appropriately limited to these components; tests and CI are supplemental.
Evidence reviewed 9 items Current main still buffers full transcripts: Fetched main retains the SQLite event and payload arrays and the JSONL normalized-message array. This PR therefore still addresses the mechanism described in #150724.
Latest release retains the artifact array: The releases endpoint identifies v2026.9.4 as latest; its artifact reader accumulates normalized messages at lines 529–562 before aggregation.
Aggregation and retry semantics preserved: The accumulator preserves source-specific normalization, ordered context replacement, model selection, cost summation, and artifact text estimates. Each cold-restore callback creates fresh state; the bounded recent reader still uses the same aggregation owner.
Findings None None.
Security None None.

How this fits together

Raw-trace diagnostics read session transcripts to summarize token usage and cost after an authorized agent run. These readers consume SQLite events or JSONL artifacts and supply the diagnostic reply.

flowchart TD
  A[Authorized raw-trace completion] --> B[Scoped transcript reader]
  B --> C[SQLite snapshot visitor]
  B --> D[JSONL line reader]
  C --> E[Incremental usage summary]
  D --> E
  E --> F[Diagnostic reply]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +17, Tests -7. Total +10 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 65 48 +17
Tests 1 93 100 -7
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 158 148 +10

Review metrics

Metric Value Why it matters
Long SQLite reader memory 8.32% and 12.36% lower peak RSS in two fixed pairs The reported Windows measurements support the scoped optimization without establishing a whole-Gateway speedup.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #150724
Summary: This PR is the explicit implementation candidate for the linked transcript-retention issue; that issue remains open pending merge.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Use the existing transcript iterators with one shared incremental aggregator while preserving diagnostic output and bounded recent reads.

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

Yes for the retention mechanism: current-main full-history readers visibly retain message arrays until aggregation finishes. This read-only review did not independently execute a memory benchmark.

Is this the best way to solve the issue?

Yes. Reusing the existing ordered iterators and aggregation rules removes the unnecessary retention without introducing a competing summarizer or changing stored data.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: Avoidable memory retention affects optional raw-trace diagnostics on long histories, with no demonstrated urgent outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied Windows production-reader measurements exercise both changed SQLite and JSONL paths, report identical complete outputs, and show lower long-history SQLite peak RSS. The measured claim is appropriately limited to these components; tests and CI are supplemental.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Windows production-reader measurements exercise both changed SQLite and JSONL paths, report identical complete outputs, and show lower long-history SQLite peak RSS. The measured claim is appropriately limited to these components; tests and CI are supplemental.

Evidence

What I checked:

  • Current main still buffers full transcripts: Fetched main retains the SQLite event and payload arrays and the JSONL normalized-message array. This PR therefore still addresses the mechanism described in Raw-trace usage diagnostics retain full transcript message arrays #150724. (src/gateway/session-transcript-usage.ts:46, b4894512c20c)
  • Latest release retains the artifact array: The releases endpoint identifies v2026.9.4 as latest; its artifact reader accumulates normalized messages at lines 529–562 before aggregation. (src/gateway/session-utils.fs.ts:529, 3a9d69db306c)
  • Aggregation and retry semantics preserved: The accumulator preserves source-specific normalization, ordered context replacement, model selection, cost summation, and artifact text estimates. Each cold-restore callback creates fresh state; the bounded recent reader still uses the same aggregation owner. (src/gateway/session-transcript-usage.ts:48, 0061248aeec6)
  • Existing iteration and authorization boundaries: The previous array reader already materializes iterateVisibleMessageRange; the replacement visitor consumes that same ordered iterator inside the existing snapshot. Raw-trace authorization remains in the unchanged diagnostic caller. No permissions, persisted formats, or dependency contracts change. (src/config/sessions/session-accessor.sqlite-reset-window.ts:545, 0061248aeec6)
  • Windows behavior evidence: The complete supplied PR body records 16 Windows/Node 26.8.2 production-reader runs covering SQLite and JSONL, short and long transcripts, and baseline/candidate/candidate/baseline ordering. Complete outputs matched; long SQLite peak RSS decreased 8.32% and 12.36%. JSONL memory and short-read timing were mixed. These support component behavior, not whole-Gateway or retained-heap guarantees. The body also retains the subsequent queued-trace timeout and distinguishes its diagnostic rerun from uninstrumented proof. (0061248aeec6)
  • Cleanup preserves existing test assertions: The changed teardown drains session writers and reconciliation, closes fixture databases through the existing helper, then removes tracked directories. Inline deletions move to this owner without weakening assertions. The supplied Windows evidence reports baseline cleanup reproduction and a passing complete reply-test file after repair. (src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts:468, 0061248aeec6)

Likely related people:

  • Peter Steinberger: Raw commit 6ac7eed adds src/gateway/session-transcript-usage.ts:25 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6ac7eed664b0; files: src/gateway/session-transcript-usage.ts)
  • vincentkoc: 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.

History

Review history (6 earlier review cycles)
  • reviewed 2026-09-17T08:55:00.770Z sha d918670 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-17T09:21:28.897Z sha d918670 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-18T05:30:01.910Z sha 22c7b99fe1454c52951e46e5618afcbd3a1baeb6 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-18T05:43:15.618Z sha 22c7b99fe1454c52951e46e5618afcbd3a1baeb6 :: blocked before merge. :: none
  • reviewed 2026-09-18T06:03:15.991Z sha 2c6799a22a6002b2dace0b4cee70e1947b6a9a25 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-18T06:20:37.430Z sha 2c6799a22a6002b2dace0b4cee70e1947b6a9a25 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/perf-raw-trace-usage-stream-7006 branch 2 times, most recently from 22c7b99 to 2c6799a Compare September 18, 2026 05:54
@steipete
steipete force-pushed the codex/perf-raw-trace-usage-stream-7006 branch from 2c6799a to 0061248 Compare September 18, 2026 06:29
@steipete
steipete merged commit a6611df into main Sep 18, 2026
215 checks passed
@steipete
steipete deleted the codex/perf-raw-trace-usage-stream-7006 branch September 18, 2026 07:04
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Raw-trace usage diagnostics retain full transcript message arrays

1 participant