Skip to content

improve(sessions): avoid full transcript scans during session checks - #148725

Merged
vincentkoc merged 2 commits into
mainfrom
fix/session-transcript-small-reads-cpu-20260915
Sep 15, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
fix/session-transcript-small-reads-cpu-20260915

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Cron persistence, failed-session recovery, and terminal-session freshness checks scan an entire transcript even when they only need its presence or mutation timestamps.

User Impact

These checks use narrow database reads while preserving recovery decisions, physical transcript presence, and terminal-session freshness. No schema, configuration, retention, or permission change is included.

The synthetic warm-database comparison below shows a substantial improvement for 4,096-event transcripts, with a small-transcript cost: presence checks at 0–10 events took roughly 4–10 µs more wall time per call. This is a bounded aggregate-work optimization, not a measured production Gateway speedup.

Why This Change Was Made

The canonical transcript metadata reader checks hot events and current cold descriptors in one statement for presence, and exposes the existing paired session-window mutation facts for freshness. Callers retain their error handling and operation order. The full statistics reader remains available where statistics are needed. The new queries compile per call; the baseline statistics query already caches compilation and avoids payload decoding.

Evidence

  • Exact head: c0cbc69, based on 5b1d6e0.
  • Independent source review and refreshed native autoreview through P2 found no actionable defects in the complete candidate. Pinned oxfmt 0.66.0, diff checks, and targeted typed lint passed.
  • 57 focused real-SQLite, lifecycle, and cron tests passed on this head.
  • Exact-head Gateway CI job: the complete agent.test.ts is included in agentic-gateway-methods-hosted-2; 3 files / 340 tests passed, including the final cached-accepted/in-flight dedupe case. The CI merge has this exact PR head as its parent. Linux Node 24, existing 8 GiB heap policy, 2 workers. The earlier local 330-pass-then-OOM run was not a suite pass.
  • Both original caller tests failed exactly at the added aggregate-read budget assertion (one read instead of zero); the restored candidate operator paths passed. The first original lifecycle failure was reused once after correcting the proof controller's Vitest-output parser; it was not rerun.
  • Separate real-SQLite proof passed empty → hot → cold archive → restored → same-millisecond observation → later mutation → delete, with presence and paired timestamps matching the existing statistics API at every phase.
  • Full exact-head CI, attempt 1, completed successfully.
  • Production: +82/-38 lines (net +44), including the coherent metadata-read owner and caller migration. Tests/support: +92/-42 (net +50).

CPU comparison and tradeoff

2026-09-15, Node 26.7.0 / ABI 147, macOS arm64, one shared host. The baseline uses the unchanged full statistics implementation; the candidate uses the new presence/paired-freshness readers. Four physical-event counts (header first, then custom rows with 256-character payloads), 3 warmup pairs, 10 alternating baseline/candidate rounds, 100 calls per sample: 160 raw samples total.

Counters and lifecycle proof run in separate processes. Timed code uses native JSON.parse; no spies, assertions, RSS capture, setup, or restoration are inside the CPU/wall intervals. Results and authoritative state are checked outside each sample. Process CPU includes background runtime work; overlapping ranges and host noise limit small-difference conclusions.

Values are median [min, max] µs per call:

Events Read Baseline CPU Candidate CPU Baseline wall Candidate wall
0 presence 56.65 [35.77, 96.01] 63.00 [49.70, 97.42] 29.79 [23.19, 35.10] 33.75 [27.76, 36.51]
0 freshness 51.50 [32.22, 90.91] 59.61 [33.04, 101.32] 30.54 [23.19, 41.34] 32.88 [28.10, 47.98]
1 presence 44.88 [30.29, 100.37] 56.33 [44.59, 67.27] 25.45 [22.94, 32.55] 35.45 [30.55, 43.30]
1 freshness 42.53 [33.78, 54.71] 46.66 [30.71, 70.80] 25.43 [20.35, 27.65] 29.01 [22.87, 34.43]
10 presence 56.03 [36.24, 76.02] 76.02 [41.11, 126.14] 27.01 [20.76, 29.80] 32.09 [28.06, 37.62]
10 freshness 40.17 [34.80, 54.55] 37.70 [25.00, 83.12] 25.88 [20.19, 32.93] 24.92 [22.75, 28.85]
4096 presence 601.28 [440.63, 1648.50] 39.17 [28.79, 79.00] 481.06 [455.56, 510.88] 32.30 [29.71, 36.63]
4096 freshness 424.85 [370.68, 438.07] 25.38 [18.81, 36.54] 434.07 [377.19, 524.87] 25.29 [18.78, 30.77]

At 4,096 events, median wall time fell from 481.06 to 32.30 µs for presence and 434.07 to 25.29 µs for freshness. At small counts, per-call compilation can cost more than the avoided scan; no speculative cache was added. These measurements establish bounded reader work and the observed tradeoff, not end-to-end latency or fleet CPU savings.

Proof completed with all 13 source hashes and 194 install inputs unchanged, a clean exact-head tree, and temporary source fixture removed. Completed raw receipt SHA256: f6701f4c9bc03cf5c81744419a4351acbaa579ffffbaa6272707621200059fab. The retained initial parser-failure receipt is linked from it; its failed/restoration-pending status was preserved.

Review resolution and follow-up

The three pending-evidence items in the exact-head ClawSweeper review, and its rank-up suggestion, are addressed by the corrected-head parity and measured small-to-large comparison above. The measured small-transcript overhead is accepted in exchange for removing transcript-length work at these session boundaries. No source changed after that review.

Named follow-up: reuse prepared metadata query compilation through the existing prepareSqliteQueryTakeFirstSync / database-owned WeakMap pattern, then compare the same empty, 1-row, and 10-row cases. That follow-up should remove repeated compilation without adding a separate metadata cache or changing freshness semantics; it is outside this PR.

Read physical transcript presence from hot events and current cold descriptors in one statement. Reuse the paired session-window mutation facts for terminal freshness checks while preserving observed timestamps, error handling, and caller order.

Formatting and independent source reviews through P2 passed. Focused runtime and performance proof follows in the native PR checkout; no measured Gateway speedup is claimed.
@vincentkoc vincentkoc self-assigned this Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@vincentkoc
vincentkoc marked this pull request as ready for review September 15, 2026 03:23
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Sep 15, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 14, 2026, 11:43 PM ET / September 15, 2026, 03:43 UTC (Revision 2).

ClawSweeper review

What this changes

Replace full transcript statistics queries with narrow presence and timestamp reads for cron persistence, failed-session recovery, and terminal-session freshness checks.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: current main still performs the aggregate reads, and this focused optimization remains useful. No actionable correctness defect was found; the declared performance and parity validation remains unfinished.

Priority: P2
Reviewed head: c0cbc6925360c8eff8aa0669d0f310e5999c345f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-consistent optimization with meaningful regression coverage and clearly disclosed validation gaps.
Proof confidence 🌊 off-meta tidepool Not applicable: This member-authored internal SQLite optimization is exempt from the external-contributor proof gate and introduces no material authority change; the reported older-head tests do not establish the pending CPU and full parity results.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This member-authored internal SQLite optimization is exempt from the external-contributor proof gate and introduces no material authority change; the reported older-head tests do not establish the pending CPU and full parity results.
Evidence reviewed 9 items Introduced scope and review continuity: The host-pinned merge-base delta contains the metadata reader, three caller migrations, exports, and supporting tests. GitHub's exact-head commit patch confirms the follow-up moves the same queries into a separate module and replaces the test switch with a lazy reader map. The previous review reported no findings.
Current-main optimization remains necessary: Current main still computes COUNT, MAX, and byte-size aggregates through the cached statistics reader. Its lifecycle, cron persistence, and failed-session recovery callers still request those statistics for narrower decisions.
Release baseline: The supplied latest release, v2026.9.4, also uses readTranscriptStatsSync for terminal-session freshness; no released implementation of this replacement was established.
Findings None None.
Security None None.

How this fits together

OpenClaw stores session transcripts and lifecycle metadata in agent-scoped SQLite databases. Gateway and cron session checks consult this storage to decide whether to reuse a session and preserve its resume information.

flowchart TD
  A[Gateway session checks] --> C[Session storage accessor]
  B[Cron persistence] --> C
  C --> D[Hot events and cold archive descriptors]
  C --> E[Session mutation timestamps]
  D --> F[Transcript present or absent]
  E --> G[Transcript freshness]
  F --> H[Preserve existing session decisions]
  G --> H
Loading

Before merge

  • Resolve merge risk (P1) - The new readers compile their queries on each call, whereas the statistics reader caches compilation; CPU benefit for empty and small transcripts remains unmeasured.
  • Resolve merge risk (P1) - The captured evidence does not yet complete archive/restore/delete parity validation on the corrected head.
  • Complete next step (P2) - Complete and record the already-declared SQLite archive/restore/delete parity and CPU comparisons, including empty and small transcripts.
Agent review details

Security

None.

PR surface

Source +44, Tests +50. Total +94 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 82 38 +44
Tests 6 92 42 +50
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 174 80 +94

Review metrics

Metric Value Why it matters
Production versus test growth Production net +44 lines; tests/support net +50 lines Production growth introduces one focused metadata owner and migrates its callers; the PR explicitly explains that scope.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep session reuse and resume semantics unchanged while making metadata-only checks scale independently of transcript length, supported by workload-specific measurements.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep session reuse and resume semantics unchanged while making metadata-only checks scale independently of transcript length, supported by workload-specific measurements.

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

Yes for the unnecessary aggregate work: current-main callers reach transcript-wide statistics queries for presence or timestamps. An end-to-end performance penalty was not measured in this review.

Is this the best way to solve the issue?

Yes at the source level: the patch preserves the storage owner and existing decisions, and the message-presence API has different semantics. Performance value still needs the declared comparisons.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded session-check performance improvement without an established urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored internal SQLite optimization is exempt from the external-contributor proof gate and introduces no material authority change; the reported older-head tests do not establish the pending CPU and full parity results.

Evidence

What I checked:

  • Introduced scope and review continuity: The host-pinned merge-base delta contains the metadata reader, three caller migrations, exports, and supporting tests. GitHub's exact-head commit patch confirms the follow-up moves the same queries into a separate module and replaces the test switch with a lazy reader map. The previous review reported no findings. (src/config/sessions/session-accessor.sqlite-metadata-read.ts:13, c0cbc6925360)
  • Current-main optimization remains necessary: Current main still computes COUNT, MAX, and byte-size aggregates through the cached statistics reader. Its lifecycle, cron persistence, and failed-session recovery callers still request those statistics for narrower decisions. (src/config/sessions/session-accessor.sqlite-read.ts:405, cae155c7e75d)
  • Release baseline: The supplied latest release, v2026.9.4, also uses readTranscriptStatsSync for terminal-session freshness; no released implementation of this replacement was established. (src/config/sessions/lifecycle.ts, 3a9d69db306c)
  • Physical-presence invariant: Cold descriptors require event_count >= 1 and reference session_windows with cascading deletion. The existing cold-storage writer atomically exchanges hot rows and cold descriptors, supporting the new single-statement presence query, including header-only transcripts. (src/state/openclaw-agent-schema.sql:433, c0cbc6925360)
  • Timestamp semantics and ownership: The new metadata reader reuses the existing paired session-window mutation reader and deferred transaction. Lifecycle comparisons retain the observed timestamp fallback and error handling. This path uses OpenClaw's own SQLite storage contract; no changed behavior depends on the Codex harness. (src/config/sessions/session-accessor.sqlite-metadata-read.ts:38, c0cbc6925360)
  • Focused regression coverage and remaining evidence: Inspected tests cover header-at-sequence-zero presence, concurrent archival, physical mutation timestamps, and avoidance of aggregate reads. The captured PR body reports 57 focused tests passing before the module move, an incomplete Gateway run after heap exhaustion, and pending CPU plus archive/restore/delete parity validation. No target code or tests were executed during this review. (src/config/sessions/session-accessor.sqlite-cold-read.test.ts:299, c0cbc6925360)

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the declared archive/restore/delete parity and small-to-large transcript CPU comparisons, recording results without an unmeasured speedup claim.

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 (1 earlier review cycle)
  • reviewed 2026-09-15T03:29:39.781Z sha 56d6571 :: blocked before merge. :: none

Keep scoped physical presence and mutation readers in one metadata module, preserving their queries and transaction boundaries. Use a lazy reader map in the cold-storage race test.
@vincentkoc
vincentkoc merged commit 9453702 into main Sep 15, 2026
212 of 213 checks passed
@vincentkoc
vincentkoc deleted the fix/session-transcript-small-reads-cpu-20260915 branch September 15, 2026 04:01
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 15, 2026
…penclaw#148725)

* improve(sessions): avoid full transcript scans during session checks

Read physical transcript presence from hot events and current cold descriptors in one statement. Reuse the paired session-window mutation facts for terminal freshness checks while preserving observed timestamps, error handling, and caller order.

Formatting and independent source reviews through P2 passed. Focused runtime and performance proof follows in the native PR checkout; no measured Gateway speedup is claimed.

* refactor(sessions): isolate transcript metadata reads

Keep scoped physical presence and mutation readers in one metadata module, preserving their queries and transaction boundaries. Use a lazy reader map in the cold-storage race test.
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. 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.

1 participant