Skip to content

perf(doctor): batch first transcript header reads - #188789

Merged
steipete merged 3 commits into
mainfrom
dbasync/doctorconfig-b
Oct 30, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/doctorconfig-b

Conversation

@steipete

@steipete steipete commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Doctor checks the first transcript event separately for every session, even when every session already has a valid header. Group the minimum sequence per session in one read per database, stream and parse the complete first events, and retain only candidate session IDs before opening any repair writer.

Full JSON parsing preserves last-duplicate-key semantics, nonzero minimum sequences, malformed-first skipping and pre-compression schemas. Corrupt compressed payloads remain isolated to their session. Positive repairs still read their full exact snapshot and use the existing maintenance authority, identity, backup, transaction and snapshot guards. No schema, cache, generation or receipt change.

Acceptance rule (registered before measurement)

Flow: the compiled Doctor invoked by runPackageUpdateDoctor, with an adopted native update executor, original recovery capture and stopped database backup. Workload: generated four-agent, 4,096-session state of at least 1 GiB; independent fresh fixture copies for baseline and candidate, same macOS/arm64 host and Node runtime. Filesystem cache is warm from generation/copy; this is not a cold-disk claim.

Primary acceptance is work counts: clean first-header detection falls from 4,100 SQL statements to four across four databases, with no additional worker requests or runtime Gateway-main SQL. Compare whole Doctor and attributed header-owner SQL/requests/MAIN. One matched baseline/candidate count/profile pair is required by the lane order. Verify the frozen observer and collect CPU profiles per process/thread. Any timing claim requires the timing lock, load1 below 24, at least five alternating samples per variant, and median/p95/spread with cold and warm separate. A 20% adverse cell stops the change. Loaded-host diagnostic timings are not a latency or CPU speedup claim.

Behavior acceptance: same candidate identities and repair results, byte-preserving original backup, unchanged malformed/corrupt-row handling, no cursor across repair writes, and normal compiled-finalizer completion and receipts. Peak process RSS will be observed alongside counts; it is not additive across threads or simultaneous process peaks.

Evidence

The production-path regression is red on the unmodified reader (two transcript reads instead of one) and green with grouping. Reader, header-repair and unchanged label suites pass all 23 tests. Cases cover nonzero sequence starts, duplicate JSON keys, malformed first events, legacy schemas, corrupt compressed payloads, exact snapshots and recovery copies, timestamp changes, duplicate event identities, and logical workspace selection. Test consolidation retains these behaviors with net zero test-source lines.

The generated 4,096-session fixture returns identical first rows through the grouped and original readers. SQLite uses the existing covering (session_id, seq) index plus keyed payload lookups, with no temporary B-tree or sorter. Underlying payload retrieval still occurs once per session; the removed work is statement/native-call overhead and separate enumeration.

Two isolated Codex reviews, a delta-only review of the test placement correction, and a CI-forced delta review of the final ordering correction are scoped-clean. The change adds 57 production lines and one RSS diagnostic line, and has zero net test-source growth; the extra code replaces per-session lookups with a portable streaming selection at the existing reader owner. Required PR CI, all three actual PostgreSQL shards, and the published-driver update cell have passed at 8969d086ab1d35869edd810ad53768fab95e8990 (PR CI, main-tier qualification). No latency or CPU speedup is claimed.

Indexed open-PR overlap proof compares the base and candidate against #188397 at f243711f0384, #187268 at f03a5086ef0a0, and #158723 at 69dc6bf27a16. No new conflict paths or blocks: 0→0, 1,853→1,853, and 32→32 conflicted paths respectively. The prior indexed #188397 head eda006e04e97 also had 0→0 conflicts. All nine existing test-conflict regions are unchanged. The existing scanner-versus-inline-loop production conflict in #158723 gains only the selector line (20→21 current-side lines, unchanged boundaries and 118-line peer side); retaining the existing shared scanner requires no additional resolution choice.

Matched compiled Doctor evidence

One matched, warm-filesystem 1 GiB count/profile pair on macOS/arm64, Node 26.12.1: base cf83a69f74eed57a3467bba3963d433e25d20743 versus production code at c3b4e6ef408e2c9f7d719b05e32873f5e3d41efd. Both use the same sourcePerformance build profile. The measured candidate runtime was built from the production sources at c3b4e6ef; that head differed from its predecessor only in tests. Canonical build-info was regenerated for that measured head. The later final-head toSorted correction is described below and was not included in this runtime measurement. Frozen observer verification: 37/37 hashes.

Command: node --import ./scripts/tsx.mjs scripts/perf/doctor-config-measure.mts run --repo <built-repo> --fixture <fresh-synthetic-copy> --output <fresh-output> --observer-root <frozen-v3.1.5> --profile, serialized through the campaign proof slot. Each independent fixture has 4,096 sessions, 1,408 messages and 1,087,377,408 database bytes. Both real compiled finalizers completed with accepted exit/receipts, six stopped backup records and no backup warning. Both original recovery captures had the same one existing plugin backup-inventory warning.

Work per Doctor pass Base Candidate Delta
First-header detection SQL 4,100 4 −4,096
Whole Doctor SQL 50,922 46,826 −4,096
CLI-main SQL 50,279 46,183 −4,096
Worker SQL 643 643 0
Worker requests 251 251 0

The exact changes are 4,096 ORDER BY seq LIMIT 1 statements removed, four header session-ID enumeration queries removed, and four grouped statements added. Label enumeration is retained. All other SQL shapes and all original-capture, backup, parent-startup and receipt-verification phase counts are identical. This exercises the update finalizer, not a complete launchctl outage or Gateway turn; no Gateway-runtime measurement is claimed. No work moved to another thread.

Timing qualification failed: load1 was 32.46 and 24.44 (required below 24), and this is one count/profile pair, not five alternating timing samples. Diagnostic only: Doctor process elapsed 70.647→75.941 s; main-thread OS CPU 24.351→25.439 s; observed process-tree CPU 80.803→84.426 s; Doctor-process peak RSS 1,181,904→1,254,368 KiB. No cell increased 20%; these values do not establish latency, CPU or memory improvement. Median/p95/spread are not claimed from one ineligible pair. Native Node profiles cover 104 of 171 observed Doctor-tree threads in each run; missing worker exits make total CPU incomplete. The one invalid baseline Inspector profile belongs to the parent harness, outside the Doctor tree; all native profiles validate.

PostgreSQL semantic approval is recorded for exact final head 8969d086ab1d35869edd810ad53768fab95e8990. The final one-line correction uses toSorted instead of sort with the same UTF-8 comparator to satisfy unicorn/no-array-sort; it changes neither the SQL nor the ordering result. The final reader suite passes 6/6 tests, basic lint/format pass, and its isolated CI-delta review is scoped-clean. The matched compiled measurement above remains evidence for its named earlier head; it is not relabeled as a final-head runtime measurement. Final-head compiled integration is covered by CI and the published-driver update cell. Local type-aware lint could not start because the mandated external checkout/internal virtual store violates declaration custody; exact-head CI supplies type-aware/static proof, without a local guard bypass.

Static baseline attribution: the earlier candidate check-dependencies failure reports only src/gateway/plugin-node-capability.ts: prepareClientPluginNodeCapabilities. Scheduled main run 41138060956 reports the identical unused-export failure. That owner is untouched. Final-head qualification job 124356495499 repeats exactly that failure. Perf-driver unused-file, script-export and full-tree export scans passed; all five final-head type-aware core lint shards passed. No static failure caused by this PR is being waived.

Broader nonrequired qualification also reports the untouched Talk browser-disconnect case (cancels a public provider that resolves after its browser disconnects without creating a chat, cancellation spy zero versus one), job 124356496165. The selected scheduled-main large-15 shard passed, so this is disclosed without claiming a matching inherited failure. Required PR CI is green.

Final-head required PR CI: 41141353923 succeeded. Actual PostgreSQL shards 1, 2, and 3, plus the published-driver update, all succeeded. Source contracts, architecture, test/type ratchets and type-aware lint passed.

Additional broad-qualification failures are the untouched CLI group-help test (exit 2 versus 0, job 124356501255) and the test runner retaining a temporary namespace because nested-writer completion was unverified (jobs 124356496321 and 124356496359). Along with the Talk case and baseline Knip export above, these mean the optional main-tier matrix is not green; they are not claimed as repaired by this PR or all matched to main.

Coordinator acceptance (2026-10-30): counts-only, no speedup claim. The loaded-host timing pair is ineligible. The existing SQL decode function is itself a JavaScript callback using the same zstd codec, so moving first-payload decoding into the streaming reader adds no decode work. The accepted result is 4,096 fewer statements per Doctor pass with unchanged requests. No latency, CPU or memory improvement is claimed.

@clawsweeper

clawsweeper Bot commented Oct 30, 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 scripts Repository scripts commands Command implementations labels Oct 30, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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-30T22:46:17.479441Z c3b4e6e New commits
ℹ️ 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.

@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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 30, 2026
@clawsweeper

clawsweeper Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR batches first-event header detection into one streaming query per database instead of querying every session separately.

Example: Doctor checks 4,096 sessions across four agent databases.

  • Before: First-header detection executes 4,100 SQL statements.
  • After: First-header detection executes four SQL statements, with unchanged worker request counts.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused and source-consistent, with real compiled work-count evidence and green PR CI; required upgrade validation is unfinished.
Proof confidence 🦐 gold shrimp (3/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: Doctor performs thousands of unnecessary statement invocations while checking already healthy session histories during updates.
Reason: The maintainer-authored direction removes measured redundant work within the existing owner and preserves the documented repair contract.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes measured Doctor query overhead while preserving repair safeguards, and no concrete correctness or security regression was found.

Priority: P2
Reviewed head: 8969d086ab1d35869edd810ad53768fab95e8990

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The PR owner still needs a completed latest-stable published-driver upgrade result showing settings and transcript data survive candidate Doctor finalization.
Agent review details

How this fits together

Doctor reads stored transcript events, identifies headerless candidates, and passes their exact snapshots to the existing guarded backup and repair owner.

flowchart TD
  A[Doctor command or update finalizer] --> B[Read-only transcript scanner]
  B --> C[Grouped first-event query]
  C --> D[Candidate session IDs]
  D --> E[Exact snapshot validation]
  E --> F[Existing backup and repair transaction]
Loading

Technical review

Best possible solution:

Retain batching in the existing reader while preserving full candidate snapshots and the established repair owner.

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

Current main enumerates session IDs and performs a first-event query for each session; the supplied compiled baseline records that overhead, but this read-only review executed no target code.

Is this the best way to solve the issue?

Batching at the existing reader is a focused solution: it preserves full JSON semantics, session-local decoder errors, deterministic candidate order, and guarded repair snapshots without introducing a cache or competing owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • First-header detection keeps the original intent (cd7b282: Avoid materializing healthy long histories while honoring nonzero first sequences and exact positive-repair snapshots.)
  • Reader and scanner lifecycle keeps the original intent (348ad76: Reuse statements within a read-only pass without retaining a cursor across repairs or allowing iterator errors to poison later sessions.)
  • Early rejection and repair coverage keeps the original intent (3164188: Reject ineligible prefixes before retaining large histories while keeping complete exact snapshots for valid repairs.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Galin Iliev: Raw commit 8aa6763 adds src/commands/doctor-session-transcript-headers.ts:201 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8aa67634ca03; files: src/commands/doctor-session-transcript-headers.ts)

PR surface

Source +57, Tests 0, Other +1. Total +58 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 80 23 +57
Tests 2 93 93 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 6 174 116 +58

Review metrics

Metric Value Why it matters
Production versus test growth Runtime production +80/-23; tests +93/-93; measurement tooling +1/-0. The 57-line runtime increase implements streaming batch selection at the existing owner; distinct repair and decoder contracts remain covered without net test growth.

Labels

Label changes:

  • add P2: This is a bounded maintenance performance improvement with measured query reduction and no demonstrated urgent user-facing outage.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a bounded maintenance performance improvement with measured query reduction and no demonstrated urgent user-facing outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Complete the published-driver upgrade scenario from v2026.10.9 and record preserved settings, transcript data, and successful Doctor finalization.

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 30, 2026, 7:13 PM ET / 23:13 UTC.

@steipete
steipete merged commit fca4dc4 into main Oct 30, 2026
306 of 317 checks passed
@steipete
steipete deleted the dbasync/doctorconfig-b branch October 30, 2026 23:35
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 31, 2026
Read the first transcript event for all sessions in one streaming query per database, retaining only repair candidate IDs before any writes. Preserve full JSON parsing, minimum sequence selection, legacy schemas, repair authority, snapshots and receipts. The matched synthetic 1 GiB Doctor pass removes 4,096 SQL statements with unchanged worker requests. No timing speedup is claimed.
maplel pushed a commit to maplel/openclaw that referenced this pull request Nov 24, 2026
Backport the bounded runtime fix for LOCAL11.8; preserve unrelated baseline behavior.

(cherry picked from commit fca4dc4)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 324bcbf6511a70c5835a0c8f2a7c2a578ed0e276)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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