Repository navigation
perf(doctor): batch first transcript header reads - #188789
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherDoctor 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +57, Tests 0, Other +1. Total +58 across 6 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 30, 2026, 7:13 PM ET / 23:13 UTC. |
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.
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)
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 atf03a5086ef0a0, and #158723 at69dc6bf27a16. No new conflict paths or blocks: 0→0, 1,853→1,853, and 32→32 conflicted paths respectively. The prior indexed #188397 headeda006e04e97also 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
cf83a69f74eed57a3467bba3963d433e25d20743versus production code atc3b4e6ef408e2c9f7d719b05e32873f5e3d41efd. Both use the samesourcePerformancebuild profile. The measured candidate runtime was built from the production sources atc3b4e6ef; that head differed from its predecessor only in tests. Canonical build-info was regenerated for that measured head. The later final-headtoSortedcorrection 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.The exact changes are 4,096
ORDER BY seq LIMIT 1statements 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 usestoSortedinstead ofsortwith the same UTF-8 comparator to satisfyunicorn/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.