Skip to content

fix(doctor): avoid excessive work on large transcript histories - #147464

Merged
steipete merged 1 commit into
openclaw:mainfrom
VACInc:perf/doctor-header-scan
Sep 13, 2026
Merged

steipete merged 1 commit into
openclaw:mainfrom
VACInc:perf/doctor-header-scan

Conversation

@VACInc

@VACInc VACInc commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

Doctor can spend substantial time and memory examining large SQLite transcripts that cannot need repair. Stop header detection as soon as the existing validator rejects a prefix, and avoid JSON decoding rows that cannot contain a frozen legacy label.

What Problem This Solves

Fixes excessive Doctor work when an existing session header follows another transcript event, and unnecessary JSON decoding of label-free history during update finalization.

User Impact

Large existing histories require less detection time and memory. Repair eligibility, exact transcript bytes, guarded writes, derived projections, and Unicode label support remain unchanged. No configuration or schema migration is required.

Why This Change Was Made

Root Cause

The read-only header reader previously materialized every storage row before the existing validator rejected any later session header. A valid indexed first event followed by a header at row two therefore caused the entire remaining history to be retained needlessly. The new constrained-memory regression fails on the original implementation with a heap OOM.

Label detection also decoded every serialized event before discovering whether it contained any legacy label. Every frozen rewrite requires decoded untrusted or Untrusted. A conservative raw-text check rejects only rows containing neither spelling nor any Unicode escape; escaped candidates still use the existing decoder and normalization rules.

The header reader now streams through the same validator used by writer revalidation. Positive candidates still retain complete exact snapshots. No write transaction, binding check, authority, retention, or projection-update policy changes.

Evidence

Verification

  • 39 focused tests passed across the read-only transcript reader, header repair, and label migration suites, including the 256 MiB heap regression, opaque first-row preservation, Unicode escapes, malformed siblings, metadata preservation, and idempotence.
  • Final autoreview: no actionable P0–P2 findings; separate readiness review confirmed the shared validation and guarded-write contracts.
  • Full changed-file checks passed, including production/test typechecking, lint, formatting, export checks, schema and database guards, and runtime import-cycle checks. The initial run identified two lint errors; both were fixed before this passing run.
  • Full build and package integrity validation passed.
  • Published-driver × packed-candidate SQLite-volume upgrade passed: installed updater from [email protected] upgraded to the exact PR package, automatic migration/finalization passed before any standalone Doctor pass, and persisted history survived subsequent Doctor and Gateway restart.
  • Exact-head CI passed, including the Docker seed owner lanes.

Real behavior proof

The constrained-memory regression uses the actual Doctor header owner with a valid event, an existing header, and a large payload tail. Original code exhausts the constrained heap; the candidate reports {found: 0, repaired: 0} and leaves the database content hash unchanged. Positive repair tests also exercise the actual owner and session reader.

node scripts/run-vitest.mjs run \
  src/commands/doctor-session-sqlite-transcript-readers.test.ts \
  src/commands/doctor-session-transcript-headers.test.ts \
  src/commands/doctor-session-transcript-labels.test.ts

Copied result: 5 passed in the reader shard and 34 passed in the commands shard; both shards passed.

A synthetic 676,098,048-byte SQLite fixture with 8,194 events was measured at the Doctor owner boundary using Node 24.19.0, fresh processes, one warmup per variant, and five interleaved measured samples. Header results were always zero repairs; fixture SHA-256 stayed 0879e89c13eae3e258cafba6e6ebde324f016a35f02625e7f523e6e971771b3a.

Detection check Baseline median Candidate median
Header after initial event 307.90 ms 4.99 ms
Label-free transcript 307.11 ms 111.88 ms
Header process peak RSS 856.96 MiB 135.23 MiB

These are isolated owner benchmarks, not full Doctor or deployment timings. The candidate is exact commit b92319c442977a1336d4c7259637aadc5b104e57, compared with base 98101871f29fcb29d65cb8d916089aa2f14ad64b. Header samples ranged 296.25–313.22 ms before and 4.86–5.43 ms after; label samples ranged 271.43–312.66 ms before and 107.41–116.70 ms after.

Published-driver upgrade proof

Upgrade compatibility was tested and verified for existing data. Existing data was preserved through the published updater, candidate finalization, Doctor idempotence, and Gateway restart, as shown by the completed scenario below. No data migration is required by this patch.

Completed on an isolated Linux Docker runner using the repository's published upgrade-survivor sqlite-volume scenario, with the baseline updater performing the upgrade (candidateInstallMode: updater, updateOutcome: success). The candidate package embeds commit b92319c442977a1336d4c7259637aadc5b104e57; its SHA-256 is bf7c6d56ecc195319607530d9ee6dbed426bde31fd8f9bcba9a4ee9d54208271.

node scripts/package-openclaw-for-docker.mjs \
  --output-dir /tmp/doctor-proof-package \
  --output-name openclaw-doctor-b92319c4429.tgz
OPENCLAW_UPGRADE_SURVIVOR_PUBLISHED_BASELINE=1 \
[email protected] \
OPENCLAW_UPGRADE_SURVIVOR_SCENARIO=sqlite-volume \
OPENCLAW_CURRENT_PACKAGE_TGZ=/tmp/doctor-proof-package/openclaw-doctor-b92319c4429.tgz \
  bash scripts/e2e/upgrade-survivor-docker.sh

The run reused a Docker runner freshly built from this checkout's scripts/e2e/Dockerfile (bare target); artifact paths above are portable equivalents of the isolated test paths.

Copied output:

sqlite-volume sessions=4800 events=23890 cronJobs=2200
sqlite-volume Gateway RPC verified 8 conversations across 2 agents
SQLite volume idempotence doctor completed in 17s (budget 60s).
sqlite-volume sessions=4800 events=23890 cronJobs=2200
sqlite-volume Gateway RPC verified 8 conversations across 2 agents
sqlite-volume sessions=4800 events=23890 cronJobs=2200
Upgrade survivor Docker E2E passed [email protected] scenario=sqlite-volume candidate=2026.9.4 updateRestartMode=manual idempotence=17s startup=20s updateRestart=manuals healthz=1s readyz=1s status=1s.

Automatic migration and survival assertions passed immediately after the installed updater finished; this scenario intentionally omits an intervening standalone Doctor. History RPC, health/readiness, and persisted-state assertions then passed again after restart. The 17-second Doctor result is the synthetic fixture's idempotence pass, not a production performance claim.

What was not tested

No live production rollout or whole-Doctor performance comparison has been measured. The Docker proof uses the harness's manual restart mode; it does not claim a real host systemd restart or live channel delivery. This PR does not change startup integrity checks.

ClawSweeper review

The review at b92319c442977a1336d4c7259637aadc5b104e57 reports no actionable findings and accepts the published 2026.9.3 updater compatibility proof above. Its remaining generated “Add data-model compatibility proof” checklist item repeats that accepted evidence; no additional code change is needed. The existing upgrade proof covers automatic finalization, persisted history, Doctor idempotence, and restart. No re-review was requested during landing because the code is unchanged.

Maintainer validation and release-note context

The header-after-event regression was independently rerun with all three production files restored to the pre-fix implementation: it failed with FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory (1 failed, 14 skipped). Restoring the reviewed head and running the reader, header, and label suites passed all 39 tests, including the constrained-heap case and unchanged history checks.

openclaw doctor and the update-time candidate Doctor no longer scan and retain whole transcript histories for ineligible headers, so large installs avoid stalling in Doctor on those histories. Thanks @VACInc (#147464).

@clawsweeper

clawsweeper Bot commented Sep 13, 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 commands Command implementations size: M maintainer Maintainer-authored PR labels Sep 13, 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 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 13, 2026, 6:11 PM ET / 22:11 UTC (Revision 2).

ClawSweeper review

What this changes

Doctor’s SQLite transcript checks stop reading ineligible header histories earlier and skip unnecessary JSON decoding, with regression coverage for memory use and preserved history.

Merge readiness

⛔ Blocked before merge - 1 item remains

The PR remains useful and has no actionable findings. The newly supplied published-updater proof resolves the previous review blocker; current main and the latest release still have the original detection behavior.

Priority: P2
Reviewed head: b92319c442977a1336d4c7259637aadc5b104e57

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-supported repair with no actionable findings and the previous upgrade-proof gap resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Exact-head Doctor-owner measurements demonstrate lower time and memory with unchanged history, and the supplied Linux Docker trace shows the published 2026.9.3 updater completing candidate finalization with persisted history surviving Doctor and Gateway restart. The inspected harness confirms that automatic migration is checked before standalone repair; production rollout and systemd behavior are outside this proof's claims.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Exact-head Doctor-owner measurements demonstrate lower time and memory with unchanged history, and the supplied Linux Docker trace shows the published 2026.9.3 updater completing candidate finalization with persisted history surviving Doctor and Gateway restart. The inspected harness confirms that automatic migration is checked before standalone repair; production rollout and systemd behavior are outside this proof's claims.
Evidence reviewed 9 items Pinned introduction boundary: The host verifies the introduced delta from 9810187 to b92319c. Its verified test merge contains only the same seven changed paths relative to its main parent; unrelated endpoint drift was excluded.
Current main still needs the optimization: The current-main reader still materializes the complete header snapshot after a non-header first row and decodes each label-detection row. The three production modules are unchanged between the pinned merge base and fetched main.
Latest-release comparison: The v2026.9.4 reader also contains the original full-snapshot header detection and unconditional JSON decoding; this PR's optimization is not present in that release.
Findings None None.
Security None None.

How this fits together

Doctor checks stored conversation transcripts during maintenance and update finalization. Its detection readers identify repair candidates, which existing guarded transactions revalidate before changing stored history.

flowchart TD
  A[Doctor or update finalization] --> B[Stored SQLite transcripts]
  B --> C[Header and legacy label detection]
  C --> D{Repair candidate?}
  D -->|No| E[Leave history unchanged]
  D -->|Yes| F[Complete exact snapshot]
  F --> G[Revalidate and repair transaction]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +37, Tests +74. Total +111 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 3 77 40 +37
Tests 4 87 13 +74
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 164 53 +111

Review metrics

Metric Value Why it matters
Reported owner benchmark Header median 307.90 → 4.99 ms; peak RSS 856.96 → 135.23 MiB Five interleaved samples on a synthetic SQLite fixture demonstrate the targeted improvement; these are not whole-Doctor timings.
Production versus test growth Production net +37 lines; tests and test support net +74 lines Production growth shares streaming validation with writer revalidation and adds a conservative prefilter; tests cover memory and preservation contracts.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-session-sqlite-transcript-readers.ts, migration/backfill/repair: src/commands/doctor-session-transcript-headers.ts, serialized state: src/commands/doctor-session-transcript-headers.ts, unknown-data-model-change: src/commands/doctor-session-transcript-headers.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep detection cheap for ineligible histories while preserving complete snapshots, canonical validation, and existing transaction safeguards for actual repairs.

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

Yes: current main buffers the remaining history when a valid first event precedes an existing header, and the supplied constrained-heap regression reports an original-code OOM. This review verified the source path without executing it.

Is this the best way to solve the issue?

Yes: reusing the existing validator for early rejection and conservatively filtering label-free JSON narrows detection work without introducing another repair owner or changing eligibility.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. Exact-head Doctor-owner measurements demonstrate lower time and memory with unchanged history, and the supplied Linux Docker trace shows the published 2026.9.3 updater completing candidate finalization with persisted history surviving Doctor and Gateway restart. The inspected harness confirms that automatic migration is checked before standalone repair; production rollout and systemd behavior are outside this proof's claims.

Label justifications:

  • P2: This is a bounded performance repair for Doctor and update finalization on large transcript histories.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Exact-head Doctor-owner measurements demonstrate lower time and memory with unchanged history, and the supplied Linux Docker trace shows the published 2026.9.3 updater completing candidate finalization with persisted history surviving Doctor and Gateway restart. The inspected harness confirms that automatic migration is checked before standalone repair; production rollout and systemd behavior are outside this proof's claims.
  • proof: sufficient: Contributor real behavior proof is sufficient. Exact-head Doctor-owner measurements demonstrate lower time and memory with unchanged history, and the supplied Linux Docker trace shows the published 2026.9.3 updater completing candidate finalization with persisted history surviving Doctor and Gateway restart. The inspected harness confirms that automatic migration is checked before standalone repair; production rollout and systemd behavior are outside this proof's claims.

Evidence

What I checked:

  • Pinned introduction boundary: The host verifies the introduced delta from 9810187 to b92319c. Its verified test merge contains only the same seven changed paths relative to its main parent; unrelated endpoint drift was excluded. (b92319c44297)
  • Current main still needs the optimization: The current-main reader still materializes the complete header snapshot after a non-header first row and decodes each label-detection row. The three production modules are unchanged between the pinned merge base and fetched main. (src/commands/doctor-session-sqlite-transcript-readers.ts:40, f6f241952b0e)
  • Latest-release comparison: The v2026.9.4 reader also contains the original full-snapshot header detection and unconditional JSON decoding; this PR's optimization is not present in that release. (src/commands/doctor-session-sqlite-transcript-readers.ts:40, 3a9d69db306c)
  • Repair invariants preserved: Detection and writer revalidation use the same headerless-event parser. Positive candidates retain exact rows; the transaction still compares snapshots, checks the current session binding, and uses the existing replacement owner. The label prefilter admits either required spelling and every Unicode-escaped candidate, leaving canonical normalization and surgical writes unchanged. (src/commands/doctor-session-transcript-headers.ts:44, b92319c44297)
  • Meaningful regression coverage: Read the complete changed tests and memory helpers plus the existing label suite. Coverage includes a header after an initial event under a 256 MiB heap, unchanged storage hashes, opaque first-row preservation, released native cursors, Unicode labels, malformed siblings, and repair idempotence. Tests were not executed during this read-only review. (src/commands/doctor-session-transcript-headers.test.ts:87, b92319c44297)
  • After-fix behavior and previous blocker resolved: The complete supplied body at sourceRevision 55a7d1f7c66679e20b0f1bd531c4b1910b0870b9aab6ff908c15cfef3ad0f221 records exact-head owner benchmarks with unchanged fixture hashes and a completed Linux Docker upgrade from [email protected] using the installed updater. Copied output reports 4,800 sessions, 23,890 events, successful history RPC checks across two agents, and survival after Doctor and Gateway restart. This supplies the packaged-upgrade result requested by the previous review at fix(doctor): avoid excessive work on large transcript histories #147464 (comment). (b92319c44297)

Likely related people:

  • Peter Steinberger: 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 (1 earlier review cycle)
  • reviewed 2026-09-13T21:59:47.458Z sha b92319c :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 13, 2026
@VACInc

VACInc commented Sep 13, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper Please re-review the remaining data-model compatibility gate for this exact head. Your latest review accepts the published-updater proof and says the previous blocker is resolved, but its generated checklist still asks for that same proof.

Upgrade compatibility was tested and verified for existing data. The installed [email protected] updater successfully finalized the packed candidate at b92319c442977a1336d4c7259637aadc5b104e57. Existing fixture data was preserved: 4,800 sessions, 23,890 events, and 2,200 cron jobs survived automatic migration, a subsequent Doctor pass, and Gateway restart. History RPC checks passed across both agents before and after restart. The complete command, package hash, copied output, and limits are in the PR body's Published-driver upgrade proof section. Exact-head CI is now green: https://github.com/openclaw/openclaw/actions/runs/34785030305

Please reconcile the structured stored-data compatibility assessment and generated checklist with this accepted evidence. If any concrete compatibility case remains unproven, identify that case. No gate bypass, repair, or merge is requested.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper assist is taking a look at your question.

I queued a lightweight read-only assist pass. It will post a separate answer comment and will not edit the durable ClawSweeper review comment or trigger close, merge, repair, label, or branch changes.

Request: Please re-review the remaining data-model compatibility gate for this exact head. Your latest review accepts the published-updater proof and says the previous blocker is resolved, but its generated checklist still asks for that same proof. Upgrade compatibility was tested and verified for existing data. The installed [email protected] updater successfully finalized the packed candidate at b92319c442977a1336d4c7259637aadc5b104e57. Existing fixture data was preserved: 4,800 sessions, 23,890 ev...

@steipete
steipete merged commit 3164188 into openclaw:main Sep 13, 2026
254 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
`openclaw doctor` and the update-time candidate Doctor no longer scan and retain whole transcript histories for ineligible headers, so large installs avoid stalling in Doctor on those histories. Shared validation rejects ineligible prefixes early; eligible repairs still retain complete exact snapshots and guarded writer revalidation. Label-free rows skip unnecessary decoding while Unicode-escaped candidates retain canonical handling.

The constrained-heap regression fails on the original implementation with a heap OOM and passes on this head; all 39 reader, header, and label tests pass. Exact-head CI is green. Contributor-supplied published 2026.9.3 updater proof preserves existing history through candidate finalization, Doctor, and restart.

Thanks @VACInc (openclaw#147464).

Co-authored-by: VACInc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations 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.

2 participants