Skip to content

perf(sessions): backfill historical transcript facts after readiness - #194519

Merged
steipete merged 14 commits into
mainfrom
steipete/perf-active-event-facts-backfill-20261107
Nov 14, 2026
Merged

steipete merged 14 commits into
mainfrom
steipete/perf-active-event-facts-backfill-20261107

Conversation

@steipete

@steipete steipete commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Approved by Peter (2026-11-07, question tool): "Approve + merge". Ships in the next Team build after landing.

Refreshed onto 51c2f42a8e029f667829c753d7098af911dd7f70. New cron-model measurements and refreshed validation are identified first under Evidence. All other runtime measurements below remain historical evidence from fe435de371195768a35f26bfe9f4875c8482ef50 or their explicitly named earlier head. The previously reported multi-second shutdown tail remains unresolved; this refresh does not claim to resolve it. The TS session merges after validation.

What Problem This Solves

Schema 41 (#193682) accelerates transcript hydration through active-event facts, but ordinary appends populate only a recent window. Long sessions written before the upgrade retain uncovered historical rows and miss the full benefit. This adds the separately requested paced backfill within the existing database worker and post-ready maintenance owners.

User Impact

Backfill starts after the existing startup-methods barrier and restart recovery, never inside database opening, migration or readiness. It processes recently updated sessions first (seven days), largest paths first within that group, then older paths by size. Each session stays selected until covered or skipped. Live runs and unrelated Background/root work do not require global idleness; background writer admission waits outside the foreground FIFO until existing work drains. The supplied Team observations found full idleness in only 0.97% of samples (median 14 active items). That factor no longer multiplies completion time: after recovery, eligibility depends on foreground writer admission and pacing, not active-run count. Measured busy-workload rates remain conditional; continuous foreground writes can still delay background admission.

One Gateway-lifetime callback deduplicates canonical physical database paths across normal and deferred startup. Each pass retains one V2 client and closes it on completion, failure or shutdown abort. Progress reports include filled/skipped rows, visited/remaining sessions, payload bytes, maximum batch time and contention pauses. Restart derives coverage from the existing facts primary key; there is no durable cursor or sidecar.

Transactions use the writers' existing derivation helpers and recheck current active-row identity/payload together. They skip cold, rebuilding, ineligible, changed and malformed rows; missing remains unknown, while {} remains a known non-candidate. The identity query finishes before inserts, retaining at most 512 small identities. Payload work targets 10 ms, at most 16 rows and 128 KiB before yielding. An indivisible payload read or commit can exceed those soft limits.

Cadence charges the larger of native transaction duration and complete admitted publication execution, including preparation and reply delivery but excluding foreground FIFO wait. The next delay is at least 250 ms and twenty times that cost; lock-contention backoff reaches five seconds. A foreground arrival can still wait behind one admitted publication. These are pacing controls, not a hard transaction or shutdown deadline.

The backfill uses the existing empty derived-cache write scope: equivalent facts preserve semantic actor/replica tokens, while native mutation witnesses and database-wide write tracking remain intact. Ordinary transcript mutations still invalidate. There is no schema, index, stored-shape, configuration or retention change. This background pass is SQLite-only; PostgreSQL retains ordinary writer population and reader fallback pending a separately measured locking protocol.

Why This Change Was Made

Existing readers substitute these facts for the same payload-derived byte counts and dependency navigation. Filling them therefore removes repeated historical payload work without changing hydration results. The implementation reuses existing scheduling, admission, transaction and invalidation contracts rather than introducing another maintenance manager.

Qualification found two consequential boundaries. Native batch timing omitted admitted preparation/reply cost, so pacing now charges the complete publication. Facts-only inserts also unnecessarily invalidated semantic session state. Merely declaring an empty scope was insufficient while a native identity iterator remained open: the observer correctly treated nested writes conservatively. Finishing that bounded query before inserts preserves the intended derived-cache contract without weakening any observer or reader. This changes batch work and requires fresh final-head measurements.

Runtime production growth is +532 lines (+536/−4), necessary for the requested maintenance operation, lifecycle integration and observability. The requested broader non-test/non-doc filter is +2,774 lines (+2,825/−51), including reproducible performance tooling; the exact regression allocation is 558 lines.

Evidence

2026-11-13 refresh — current-head proof.

Rebase replayed the existing twelve lane commits cleanly. Main is now agent schema 42 (the opt-in tool-usage table); active-facts storage and semantics are unchanged, and the backfill has no schema-41 equality assumption. Auditing every active-row mutation owner found no new writer: append callsites now add mention membership and tool-usage side effects, and cold restore changed its execution custody, but all preserve the same facts derivation/invalidation owner. Existing append/rewrite/branch/delete and cold/archive/restore interleaving tests cover those transitions.

The backfill kernel, pacing wrapper, worker-store addition and startup-session scheduler are byte-identical to the approved head. Background FIFO admission and post-ready/RestartRecovery gates remain compatible with main's lifecycle changes. No selection, schema, stored-shape, or pacing change was needed; the conditional direct-owner contention rerun was therefore not triggered. Earlier foreground/Gateway/shutdown numbers are retained below, not presented as remeasured.

Refreshed cron-model facts evidence

Production source was rebased onto 51c2f42a8e029f667829c753d7098af911dd7f70 before these runs (refreshed production head 091dc56a38a55e19f62a70b2a55f8bb8ed392f8c; final head 129b947470a5fc282eb9bca554c5257613625bb1 adds only the proof tools). The backfill kernel and pacing were unchanged. Node 26.12.1; source/probe hashes, each raw sample, process receipts and host loads are retained beside this report. The final inspect mode was added after comparative measurement. A subsequent script-only typing fix uses a static import for the cohort unique symbol and binds the first result before comparison callbacks; neither changes the measured workload or production code.

These fixtures use real persistSessionTranscriptTurn writes and SessionManager.appendCompactionAsync, then copy the closed synthetic database on SF1 and delete facts outside the last 512 active rows. They contain alternating ordinary user messages and excluded assistant dashboard posts in historical rows, with an ordinary final tail. This is a declared synthetic composition, not an inference about Team’s excluded-row fraction. There are no unresolved pending automation results, custom/reset/branch-summary events, malformed rows, cold archives or off-path branches.

Shape Stored rows UTF-8 bytes zstd bytes Compactions Final retained tail Excluded historical rows / UTF-8 bytes
frv 48,111 624,353,820 220,095,076 15 726 rows / 9,165,745 B 23,685 / 307,983,172 B
shellbench 13,971 136,515,581 48,025,825 18 181 rows / 1,791,835 B 6,886 / 67,473,136 B

Tail counts include one compaction summary: FRV has 725 retained messages plus summary; ShellBench has 180 plus summary. The header is additional. The production default cron limits are 1,024,000 bytes and 10,000 events, so the open deliberately returns less than the whole tail.

The measured entry point is SessionManager[sessionManagerOpenTranscriptCohort] with caller cron-model, the production limits and an empty-ID/message-presence cohort. This matches the owned-reader branch of attempt-session-prepare, without an initial user-turn entry lookup. It dispatches the real readSessionTranscriptHydrationRequest worker and readSessionTranscriptBoundedActiveContextCore owner. The alternate SessionManager.openAsync smoke produced exactly equal entry hashes, model-message hashes, VFS bytes and facts counts in all three states.

Five fresh-native-reader opens per state ran in ABC/CBA order, serially. Closing the DB owner between opens also includes worker preparation in CPU/wall. All first samples are retained; no OS cache eviction is claimed. Exact-target VFS xRead bytes are logical SQLite I/O, not physical disk reads; repeated reads count. The opt-in probe forces xFetch misses so mmap cannot bypass counters. Atomic counters capture worker reads. Physical process counter deltas are separate and include code/supporting activity.

Shape/state VFS logical bytes/open, median SQLite read spans CPU ms, median [min–max] Wall ms, median [min–max] Hydrated events / manager entries / model messages
frv / before 204,197,496 49,873 2095.0 [1915.5–6424.6] 2507.3 [2173.5–9209.1] 82 / 81 / 81
frv / after 19,000,952 4,659 1867.0 [1696.2–2261.0] 2180.9 [1934.4–2852.5] 82 / 81 / 81
frv / natural 19,000,952 4,659 1903.2 [1782.2–1916.3] 2239.1 [2075.4–2472.8] 82 / 81 / 81
shellbench / before 38,778,652 9,495 2003.1 [1821.2–5627.6] 2316.1 [2157.8–7285.8] 104 / 103 / 103
shellbench / after 6,784,796 1,684 1852.1 [1787.2–2226.4] 2200.5 [2114.1–2548.5] 104 / 103 / 103
shellbench / natural 6,813,468 1,691 1933.4 [1896.9–2105.5] 2385.7 [2248.1–2557.2] 104 / 103 / 103

Before means 512 natural-window facts. After means completed production backfill. Natural means all facts left by real writers. Every returned entry and final model message is hash-identical across states. All first before/after reads had 77,824 extra VFS bytes (19 spans) versus subsequent reads; these are retained. The FRV natural control is exactly equal to backfilled steady I/O; ShellBench natural differs by 28,672 B (seven spans), consistent with different fact-table page packing rather than missing semantics.

FRV VFS reduction is 90.69%; ShellBench 82.50%. CPU/wall include worker preparation and other fresh-open work; those components were not independently timed. The byte reduction is the decisive result, not a claim of equivalent production latency reduction.

Residual reads and selection

The completed reads do not collapse to only the post-compaction tail: FRV still reads 19.00 MB versus a 9.17 MB complete tail; ShellBench 6.78 MB versus 1.79 MB. They do eliminate the historical payload fallback. This is already the natural-writer result, not rows missed by the backfill.

Inspection repeats the real cohort open and asserts its entry and model hashes against all recorded samples. It finds:

  • frv: header plus latest summary at raw seq 47,393 plus 80 messages at raw seq 48,031–48,110. All 48,110 active rows have facts; 47,598 were filled, zero skipped. There are zero off-path identities, pending automation-result facts, cold archives, custom/reset/branch-summary events or unknown facts. Full backfilled facts equal natural writer facts row-for-row. Relevant metadata tables and indexes occupy 29,745,152 B; the facts table alone occupies 10,698,752 B.
  • shellbench: header plus latest summary at raw seq 13,798 plus 102 messages at raw seq 13,869–13,970. All 13,970 active rows have facts; 13,458 were filled, zero skipped. There are zero off-path identities, pending automation-result facts, cold archives, custom/reset/branch-summary events or unknown facts. Full backfilled facts equal natural writer facts row-for-row. Relevant metadata tables and indexes occupy 9,469,952 B; the facts table alone occupies 3,080,192 B.

session-accessor.sqlite-active-context.ts still builds the dependency CTE over excluded active rows (23,685 / 6,886), irrespective of compaction boundaries. With facts present, the CASE reads companion navigation and byte counts; its correlated transcript payload subqueries are not evaluated. Ordinary eligible identities are excluded from that candidate set. All generated excluded posts are non-pending, so there are zero materialized dependency payloads. The reader separately loads the selected header/latest summary/newest messages, gets logical parents and retention ranges from identities, and probes custom/reset cache-TTL metadata (none in these fixtures). Off-path and cold-storage reads do not occur.

This source-backed row attribution distinguishes selected payloads from history-sized metadata scans. The dbstat values are storage footprints, not an exact allocation of the 19.00/6.78 MB VFS reads to individual statements or objects. No per-object I/O trace was claimed. No backfill selection change or new stored shape is needed for this case; further shrinking the metadata scan belongs to the bounded reader.

Ordinary-history control and Team implication

A separate real-writer 2,001-row, three-compaction control with no excluded history returns 104 hydrated events / 103 manager entries / 26 model messages. Its VFS median is exactly 1,384,702 B and 365 spans before, after and natural. This explains the earlier neutral cron result: ordinary indexed history is already filtered before dependency payload reads. Missing facts matter for excluded history, not every old compacted transcript.

Conditional workload at 30 opens/hour Before After backfill Natural control
frv synthetic mix 6.126 GB/h 0.570 GB/h 0.570 GB/h
shellbench synthetic mix 1.163 GB/h 0.204 GB/h 0.204 GB/h

These are bytes/open × 30, in decimal GB. The synthetic FRV baseline is below the reported 11–16 GB/h on Team; this does not prove Team’s exact excluded-row mix, fragmentation, context budget, pending-result retention or physical I/O rate. If Team’s excess reads arise from this same missing-fact dependency fallback, covering those rows should remove that payload traffic. The remaining metadata and selected-context reads persist. Unresolved pending automation results intentionally retain their payloads and were not modeled here.

Entry loads were FRV 23.86–27.05, ShellBench 19.24–24.65, ordinary control 28.96–38.12; no measured post-open load exceeded 40. A later non-timing FRV inventory attempt refused load 48.48 before opening and is preserved; a fresh inventory retry passed and joined. All comparative and inventory workers joined. Cleanup completed: 36 exact synthetic DB/WAL/SHM files removed (5,077,254,144 logical bytes; physical reclaim not measured). All JSON/Markdown reports, probes, scripts, raw logs and process receipts remain. cron-cleanup-receipt.json verifies every target absent.

Refreshed validation: 146 focused tests passed with one pre-existing skipped test across the worker/admission, native and real-worker facts/interleaving, cold restoration, scheduler/startup and restart-recovery files. Strict agents-sessions, state-logging, gateway-server and gateway-root test graphs passed, as did all four strict root partitions (pnpm tsgo:test:root) and the fixed-protocol export guard. The first refreshed CI found a proof-script typing error in its separate tsconfig.scripts.json graph: dynamic destructuring widened a unique symbol, and the result array was captured before inference. Both were fixed without casts or behavior changes; that exact scripts graph now passes locally, along with the repeated four root partitions. Changed-file formatting and script lint passed. Scoped production lint has only size-limit observations: startup-finish 701 lines (main 688 plus the approved integration) and worker manifest 706 (main already 703 plus the approved registration), against 700. The repository's existing GitHub policy makes these size rules advisory; no lint config, suppression, baseline or environment was changed. Main CI 43540256697 for the rebased base is green; these are local size observations, not an invented inherited failed-CI claim. No production code changed after the clean rebase.

Local Codex P0–P2 reviews of the proof tools and subsequent typing fix returned no accepted findings. An independent evidence review reconciled all 45 main/control opens and cleanup. Exact requested branch command python3 ~/.agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main --engine codex completed clean on 129b947470a5fc282eb9bca554c5257613625bb1 (helper default P0 scope), with no provider/model overrides or inherited AUTOREVIEW_/CODEX_ overrides. The final new proof tools also passed the local P0–P2 review. Exact-head CI 43545292660 completed successfully on 129b947470a5fc282eb9bca554c5257613625bb1 (53 successful jobs, 25 skipped), including check-test-types and all PostgreSQL conformance jobs. The TS session owns merging; this lane has not merged the PR.

Cleanup verified 36 task-owned DB/WAL/SHM files absent, 5,077,254,144 logical bytes removed (physical reclaim not measured). All 17 fixture/probe commands settled; the one inventory load refusal is retained separately. Reports, raw samples, source/probe hashes and receipts remain under .local/buf706/revision6/. No Team access, writes, load, deployment or database copies were used for this refresh.

Historical qualification below. These are the retained November 7 measurements, not new runs on the refreshed head.

November 7 source and validation. The previous handoff used head fe435de371195768a35f26bfe9f4875c8482ef50. Fresh Codex P0–P2 review and the exact requested branch review are scoped-clean. Five backfill cases pass on the final head, with strict session types and changed lint/format. The 28 projection/replica consumer cases passed before the final cursor correction; that correction does not execute in those cases, so this is reused earlier-head consumer evidence. Earlier admitted-timing validation passed 38 focused cases, relevant strict state/session configurations and all four strict root typecheck shards. Exact-head CI 42391976242 completed successfully on this exact head. That November 7 CI gate passed; the older cancelled PR-context run was superseded by a successful same-head run. At that handoff, the separate harness PR had a documented inherited test-line-ratchet failure; no CI was rerun to chase green.

Regressions cover historical coverage, restart, writer interleavings, cold transitions, malformed data, readiness/recovery ordering, live-work progress and shared-physical-store deduplication. The original post-ready regression fails on the schema-41 base. Timing regressions distinguish 1,000 ms of FIFO wait from 100 ms of admitted work and preserve publication success/original failure if observation throws. Final native and real-V2 regressions prove facts growth with an unchanged semantic token and advancing database revision; an actual transcript rewrite still invalidates. The token regression fails on the preceding implementation.

November 7 Gateway qualification. Baseline is 4f132c9f661b714cb2786da748294cd30dfd972f. Separate tooling uses the canonical harness plus #194563, bf33a13ead512afb903ca191dfece9b6accd2bef, for bounded retryable startup-sidecar refusal handling; that repair is not part of this branch. All proof is synthetic and isolated on SF1. Entry load must be ≤40; pauses/outliers are retained.

Final native-owner measurement fe435de3 result
49k-path missing facts filled; transaction count 48,488; 6,208
Paced wall / CPU; native hold p50/p99/max, n, holds >50 ms 27.515 min / 54.536 s; 10.447 / 16.688 / 148.116 ms, n=6,208; 3 holds >50 ms
Logical reads/writes; process physical reads/writes 1,739,554,816 / 72,905,624 B; 1,476,481,024 / 282,144,768 B
WAL peak / checkpoint snapshots; RSS / heap; host load 523,272 B; both complete, zero consecutive blocks/no warning at capture; 323.44 / 94.03 MiB; 4.23–35.77
Restart covered-prefix work; completed-path rescan wall/CPU 20 batches, 10,240 identities, zero payload/fills; 48.248 ms native / 57.295 ms CPU. Full rescan: 96 batches, 24.308 s paced / 345.167 ms CPU, zero payload/fills/logical writes
Native-model rows/hour and conditional missing-row durations 105,734/hour; 49k path's 48,488 missing rows: 27.515 min; 1M: 9.46 h; 6.27M: 59.30 h. Not a Team forecast or host cadence

The native fixture has 10M active rows, 40,236 sessions, fragmented overflow chains, four 20k–49k paths and a 21.75 GB file. Only selected paths are filled. Final runs use production NORMAL synchronization and disabled automatic checkpoints, with a fresh process at the predeclared restart. Native modeled cadence is distinct from the real host's admitted-publication cadence. Materialized-but-unconsumed identity rows count toward measured CPU/I/O even when excluded from rowsVisited. No hydration warmup ran; OS cache state was uncontrolled, so this is not a paired comparison with the earlier warmed native campaign. All 6,208 sampled loads were ≤40. Native holds over 50 ms were 55.916, 86.480 and 148.116 ms; the largest used 10.686 ms CPU and 10.764 ms kernel time, with the remaining elapsed time unattributed. Mean batch CPU was 7.763 ms and mean modeled delay 253.328 ms (max 2,962.315 ms). Process physical writes include diagnostics; checkpoint snapshots are not cumulative blocked-attempt counts. WAL was zero after both native closes. Only this selected path was filled, not all 10M rows. Scaling this native shape to 6.27M missing rows implies about 117.5 CPU minutes, 224.94 GB logical reads and 9.43 GB logical writes. These are conditional estimates, not Team physical I/O measurements. Tiny paced transactions and repeated identity/current-row checks cost substantially more CPU and page writes than the earlier coarse 512-row proposal; that prototype is not an equivalent production algorithm.

Final foreground proof: four A/A pairs + AB/BA + one predeclared extra pair, 1,000 append/read samples per arm Idle → backfill / signed paired delta
Append request p50/p99; writer execution p99; queue p99/max 7.090→7.557 / 26.213→44.144 ms; 26→39 ms; 0→10 ms paired queue p99; candidate queue maxima 257/110/257 ms
Nonresident read p50/p99; writer execution/queue p99 5.956→6.297 / 22.060→42.172 ms; execution 22.333→38 ms; queue 0→10 ms, candidate maxima 111/159/108 ms
A/A request-p99 delta ranges; load Append −12.100…+16.292 ms; read −16.164…+6.837 ms. All gates qualified; in-window load 9.89–35.45
Actual host-paced rows/hour; conditional missing-row durations Mean 49,983/hour; 49k path with 512 facts: 58.21 min; 1M: 20.01 h; 6.27M: 125.44 h. Direct-actor shape, not a Team forecast

Queue-p99 target ≤15 ms passes on the signed three-pair mean; individual append queue p99 values were 7/15/8 ms and read values 7/16/7 ms. The 16 ms read arm remains included. Initial request baselines differed by >6×, triggering exactly one predeclared extra pair. All three request-tail differences were positive: append +22.314/+29.709/+1.768 ms; read +17.070/+38.595/+4.672 ms. The observed mean request increases (+68.4%/+91.2%) exceed numeric adverse thresholds, with noisy A/A controls limiting causal precision. This is not a neutral result. The queue target passed, so no slower pacing curve was triggered and runtime pacing stayed unchanged.

Host-paced candidate arm Midpoint / measured fills Returned delay mean / max Rows/hour
AB 100 / 372 465.155 / 5,154.416 ms 43,743
BA 286 / 596 424.248 / 3,190.603 ms 42,990
Extra 99 / 413 425.168 / 5,158.898 ms 63,217

Delay medians were 250 ms. Arm BA added three more facts during drain, excluded from its measured rate. All arms started with 512 facts and remained unfinished. The backfill's domain reservation explicitly blocked all six maximum-queue observations; maximum batch publication occupancy was 258/110/258 ms, distinct from native transaction timing. Cadence includes that occupancy, but does not bound an individual foreground wait. Seven sparse 49k reads per arm were context-only: median 171.270/180.245/171.503→179.177/195.630/176.388 ms, with initial/max reads up to 22.481 s retained. The 600-row foreground append tails are not long-session append tails. All fourteen children joined and their copies were deleted.

Final whole-Gateway result. All eight ≥10-minute arms completed: timing AB/BA and separate allocation AB/BA, with 320 primary turns/tool calls/results and 80 distinct completed native children total. Every arm retained all four long transcript paths and completed 40 primary turns/tools plus 10 native children. Candidate backfill progressed strictly inside every measured interval and remained unfinished at shutdown.

Timing CPU was 8.256→8.133% with opposite pair signs; this is not a verified CPU win. GC was 0.214587→0.179349 s/min. Append queue p95 was 32.5→27.5 ms; p99 rose 235→280.5 ms but is context at 660 samples/arm. Endpoint RSS/main heap rose 77.018/39.098 MiB; old-generation growth rose 26.059 MiB and settled old generation rose 3.335 MiB. These are distinct observations, not interchangeable memory statistics.

Allocation was 29.861974→31.171270 and 30.554461→30.199522 MiB/s: mean 30.208217→30.685396 MiB/s (+1.58%), with opposite signs, so inconclusive. Host imbalance limits causal interpretation of apparent timing improvements. The final allocation baseline had two sampled minutes over load 40 (maximum 42.06), after passing its premeasurement gate at 11.20; they remain included under the predeclared entry-gate/no-mid-window-filtering protocol. Traced latency/GC is context only. No predeclared extra GC/pause A/A condition triggered; per-kind totals, counts and both maxima are retained below.

Strict timing fills of 20,250/26,636 over actual 600.013/600.007-second intervals imply 121,497/159,814 rows/hour, mean 140,656/hour. At that compact, bursty Gateway rate: 20.68 minutes for a 49k path's 48,488 missing rows, 7.11 hours for 1M, and 44.58 hours for 6.27M. These are conditional estimates, not measured Team physical-I/O throughput or continuous 99%-busy occupancy. The direct-actor proof's 49,983/hour (58.21 min / 20.01 h / 125.44 h) and fragmented-native proof's 105,735/hour are different workload models, not a confidence interval. Allocation arms do not qualify throughput estimates.

Primary measurements

Arm Main CPU % Allocation MiB/s GC s/min Loop p99 ms (n) Client list p99 ms (n) RSS/main heap/worker heap MiB Host load min–max
timing-1-base 7.830 — 0.181 29.032 (27846) 29.946 (1202) 2743.940/538.040/1122.993 3.594–8.219
timing-1-candidate 8.260 — 0.173 28.606 (27922) 30.151 (1204) 2762.269/560.303/1125.350 4.060–5.714
timing-2-candidate 8.005 — 0.186 28.541 (27951) 29.834 (1204) 2830.071/581.560/1129.763 5.663–16.771
timing-2-base 8.681 — 0.248 34.406 (27742) 53.010 (1198) 2694.364/525.628/1124.527 9.809–24.990
allocation-1-base 9.179 29.862 0.370 36.930 (27531) 89.928 (1191) 2751.536/543.033/1101.712 7.198–36.884
allocation-1-candidate 8.647 31.171 0.289 29.360 (28194) 31.053 (1193) 2821.807/543.336/1129.728 4.597–9.977
allocation-2-candidate 8.769 30.200 0.273 29.311 (27947) 39.863 (1193) 2620.413/554.587/1130.789 5.319–17.957
allocation-2-base 11.022 30.554 0.619 77.726 (24845) 331.639 (1195) 2706.831/542.679/1121.267 20.514–42.057

Server and foreground latency

Server handler tails are first-to-last measured Prometheus histogram deltas, not exact event samples. Upper bucket bounds and sample counts are retained. Append reservation samples require enqueue and completion inside the measurement. Per-arm counts determine eligibility: p95 requires at least200 samples and p99 requires at least1,000. A p99 sample shortfall does not dismiss a qualified p95 cost. The isolated continuous owner probe and this concurrent whole-Gateway workload use the same outer reservation metric, but their budgets and observed distributions are not interchangeable. Reservation execution includes broader owner work/hydration and is not native BEGIN-through-COMMIT hold.

Arm Handler mean / interpolated p99 / upper bound ms (n) Append hold p50/p95/p99/max ms Append queue p50/p95/p99/max ms Append samples
timing-1-base 8.110/28.067/30.000 (1173) 5.000/320.000/616.000/1024.000 0.000/26.000/226.000/487.000 660
timing-1-candidate 8.011/28.896/30.000 (1173) 5.000/284.000/559.000/746.000 0.000/25.000/234.000/499.000 660
timing-2-candidate 7.445/27.395/30.000 (1173) 6.000/298.000/590.000/905.000 0.000/30.000/327.000/579.000 660
timing-2-base 7.809/41.814/50.000 (1173) 6.000/355.000/865.000/1418.000 0.000/39.000/244.000/649.000 660
allocation-1-base 8.052/40.450/50.000 (1173) 7.000/300.000/985.000/1317.000 0.000/56.000/454.000/1332.000 660
allocation-1-candidate 6.948/24.932/25.000 (1173) 6.000/280.000/688.000/900.000 0.000/39.000/454.000/553.000 660
allocation-2-candidate 7.236/27.135/30.000 (1173) 6.000/292.000/714.000/1303.000 1.000/43.000/487.000/813.000 660
allocation-2-base 15.285/172.700/200.000 (1173) 11.000/393.000/1214.000/1928.000 0.000/251.000/727.000/1206.000 660

GC samples and maxima

Major pause tails are context below 50 collections. Minor p95 can gate above 200 collections; minor p99 is context below 1,000. Total paired GC rises below 50 ms/min remain context. All pauses and maintenance intervals are retained. GC p95/p99 are approximate RecordableHistogram quantiles: canonical team-shape-stress-telemetry.ts:47–70 rounds each duration to integer microseconds before recording it, then uses histogram.percentile. Raw maxima and totals retain the original PerformanceEntry duration. Histogram quantization can therefore place an approximate p99 slightly above the raw maximum; no exact-sample ordering is claimed.

Arm Kind Count Total ms Approx histogram p95/p99 / raw max ms
timing-1-base minor 708 1036.718 2.289/3.603/5.818
timing-1-base incremental 39 30.162 1.603/2.589/2.588
timing-1-base major 39 747.597 28.671/31.903/31.890
timing-1-candidate minor 731 1054.841 2.335/3.091/4.053
timing-1-candidate incremental 34 28.886 1.729/2.733/2.732
timing-1-candidate major 34 644.587 29.055/37.823/37.812
timing-2-candidate minor 724 1066.683 2.127/3.375/5.666
timing-2-candidate incremental 38 26.529 0.959/1.565/1.565
timing-2-candidate major 38 765.504 33.791/34.815/34.811
timing-2-base minor 770 1431.332 3.189/9.551/39.872
timing-2-base incremental 44 35.178 1.228/1.502/1.502
timing-2-base major 44 1010.831 38.271/60.831/60.809
allocation-1-base minor 754 1643.940 4.679/12.775/63.328
allocation-1-base incremental 41 30.071 0.951/1.260/1.260
allocation-1-base major 52 2031.066 93.375/123.519/128.347
allocation-1-candidate minor 800 1226.248 2.575/4.263/5.690
allocation-1-candidate incremental 41 28.959 0.964/1.050/1.050
allocation-1-candidate major 52 1632.917 77.503/82.303/86.755
allocation-2-candidate minor 733 1142.555 2.463/4.239/13.930
allocation-2-candidate incremental 36 25.551 1.037/1.474/1.474
allocation-2-candidate major 46 1561.205 84.415/92.031/92.022
allocation-2-base minor 710 3120.980 14.399/50.623/114.649
allocation-2-base incremental 35 32.897 1.487/1.812/1.812
allocation-2-base major 46 3043.066 217.087/298.495/298.396

Work and eligibility

Arm Primary turns / tool calls Native children completed / accepted Strict in-window backfill rows Historical rows still missing at SIGTERM Backfill native/admitted max ms (cumulative reports) Graceful shutdown ms Eligible
timing-1-base 40/40 10/10 — 141105 —/— 129 True
timing-1-candidate 40/40 10/10 20250 116057 13.500/192.000 178 True
timing-2-candidate 40/40 10/10 26636 108852 55.800/255.300 147 True
timing-2-base 40/40 10/10 — 141105 —/— 144 True
allocation-1-base 40/40 10/10 — 141105 —/— 141 True
allocation-1-candidate 40/40 10/10 27284 107380 61.400/219.700 136 True
allocation-2-candidate 40/40 10/10 26975 109081 29.600/99.400 141 True
allocation-2-base 40/40 10/10 — 141105 —/— 287 True

Native child receipts come from each measured round’s canonical child completion and parent yield/result/continuation checks. Native/admitted maxima are cumulative only through the available progress reports; a missing admitted field in older logs is unknown, not zero. Candidate fill is the conservative difference between cumulative progress reports both strictly inside the measured window; boundary snapshot deltas are recorded separately in appendix.json. Each live path appended during every qualified arm. Canonical activity scrapes occur during cohort polling, so they do not establish 97% continuous occupancy. The continuous foreground owner proof remains the primary queue-budget experiment.

Paired deltas

Values below use canonical paired means and retain A/A controls separately. Missing pairs stay incomplete. Client list/loop tails alone do not reject a change. Background CPU/allocation and latency costs are real work costs even when a control makes a specific gate inconclusive.

Mode Comparison Metric Base Candidate Absolute delta Relative % Pairs
timing A/B mainThreadCpuPercent 8.256 8.133 -0.123 -1.487 2
timing A/B gcSecondsPerMinute 0.215 0.179 -0.035 -16.421 2
timing A/B eventLoopP95Ms 23.511 22.643 -0.868 -3.693 2
timing A/B eventLoopP99Ms 31.719 28.574 -3.146 -9.917 2
timing A/B sessionsListP99Ms 41.478 29.992 -11.486 -27.691 2
timing A/B rssMiB 2719.152 2796.170 77.018 2.832 2
timing A/B heapMiB 531.834 570.932 39.098 7.351 2
allocation A/B mainThreadCpuPercent 10.100 8.708 -1.392 -13.782 2
allocation A/B allocationMiBPerSecond 30.208 30.685 0.477 1.580 2
allocation A/B gcSecondsPerMinute 0.495 0.281 -0.214 -43.248 2
allocation A/B eventLoopP95Ms 29.909 22.602 -7.307 -24.432 2
allocation A/B eventLoopP99Ms 57.328 29.336 -27.992 -48.828 2
allocation A/B sessionsListP99Ms 210.784 35.458 -175.326 -83.178 2
allocation A/B rssMiB 2729.183 2721.110 -8.073 -0.296 2
allocation A/B heapMiB 542.856 548.962 6.105 1.125 2

Memory statistics

All values below are MiB. RSS and main live heap are the telemetry sample at measurement stop, not peaks or time averages. Worker heap is the aggregate at the last non-forced-GC resource sample. Growth is last minus initial old-generation telemetry heap spaces; native after-GC is the last scraped major-GC epilogue; settled old generation follows explicit GC outside timing. Paired means average these per-arm observations, not their sample streams.

Arm End RSS / live heap Initial oldgen / growth Native after-GC / settled oldgen Worker heap
timing-1-base 2743.940/538.040 402.070/35.774 443.892/425.164 1122.993
timing-1-candidate 2762.269/560.303 405.059/55.642 429.957/428.497 1125.350
timing-2-candidate 2830.071/581.560 405.120/59.218 429.257/427.589 1129.763
timing-2-base 2694.364/525.628 401.372/26.967 442.288/424.252 1124.527
allocation-1-base 2751.536/543.033 408.640/20.082 435.505/427.989 1101.712
allocation-1-candidate 2821.807/543.336 404.986/24.018 446.159/428.237 1129.728
allocation-2-candidate 2620.413/554.587 405.611/36.196 431.962/430.798 1130.789
allocation-2-base 2706.831/542.679 401.648/25.727 427.499/426.371 1121.267

Reused baseline A/A controls

These four arms are reused from ../stress-v1, with baseline4f running under both labels. They are historical controls, not contemporaneous final-candidate observations. The unchanged fixture, measured canonical workload, duration, warmup, instrumentation mode and load gates permit the predeclared reuse. No old candidate A/B results are pooled with the final comparison. Allocation-mode GC and latency are traced context, not substitutes for untraced timing controls.

Control arm (both baseline) Measured UTC window Host load min–max Loop p99 ms (n) Client list p99 ms (n) Handler interp p99 / upper ms (n)
timing-aa-1-base 2026-11-07T13:45:40.025+00:00 → 2026-11-07T13:55:40.032+00:00 6.326–26.730 31.752 (27609) 50.589 (1202) 36.100/40.000 (1173)
timing-aa-1-candidate 2026-11-07T13:58:27.602+00:00 → 2026-11-07T14:08:27.610+00:00 5.789–15.091 29.295 (28208) 41.855 (1193) 29.479/30.000 (1173)
allocation-aa-1-base 2026-11-07T15:00:36.766+00:00 → 2026-11-07T15:10:37.032+00:00 3.892–4.990 29.147 (27778) 39.475 (1193) 27.796/30.000 (1173)
allocation-aa-1-candidate 2026-11-07T15:12:56.748+00:00 → 2026-11-07T15:22:57.022+00:00 4.092–6.062 29.508 (27758) 31.701 (1202) 28.598/30.000 (1173)
Control arm Main CPU % Allocation MiB/s GC s/min Append hold p95/p99 ms Append queue p95/p99 ms (n)
timing-aa-1-base 7.617 — 0.212 295.000/661.000 32.000/370.000 (660)
timing-aa-1-candidate 7.524 — 0.176 316.000/714.000 32.000/367.000 (660)
allocation-aa-1-base 8.116 29.170 0.272 292.000/601.000 24.000/280.000 (660)
allocation-aa-1-candidate 8.178 29.384 0.270 318.000/605.000 26.000/331.000 (660)

Every kind and both sides’ raw maxima are retained below. p95/p99 are approximate histogram quantiles; raw maxima retain PerformanceEntry durations. Major tails are context below50 collections; append p99 is context below1,000 samples.

Control arm GC kind Count Total ms Approx p95/p99 ms Raw maximum ms
timing-aa-1-base minor 710 1314.398 2.743/5.099 199.277
timing-aa-1-base incremental 35 26.192 0.963/1.220 1.220
timing-aa-1-base major 35 777.931 33.791/60.351 60.346
timing-aa-1-candidate minor 704 1061.794 2.183/3.335 13.005
timing-aa-1-candidate incremental 33 24.924 1.117/1.207 1.207
timing-aa-1-candidate major 33 676.980 29.311/33.087 33.079
allocation-aa-1-base minor 751 1109.822 2.685/3.959 7.786
allocation-aa-1-base incremental 35 25.067 0.954/1.917 1.917
allocation-aa-1-base major 46 1589.640 83.391/97.983 97.922
allocation-aa-1-candidate minor 725 1095.736 2.765/4.037 4.769
allocation-aa-1-candidate incremental 38 28.882 1.444/2.333 2.332
allocation-aa-1-candidate major 49 1579.428 81.215/88.255 88.238

Memory statistic definitions: RSS and main live heap are the telemetry sample at measurement stop, not peaks or time averages. Worker heap is the aggregate at the last non-forced-GC resource sample. Old-generation growth is last minus initial telemetry heap-space bytes. Native after-GC old generation is the last scraped native major-GC epilogue. Settled old generation is measured after explicit GC outside the timed interval. These distinct observations are not interchangeable.

Control arm End RSS / live heap MiB Initial oldgen / growth MiB Native after-GC / settled oldgen MiB Worker heap MiB
timing-aa-1-base 2786.348/554.701 405.448/40.317 432.515/428.237 1110.075
timing-aa-1-candidate 2798.037/551.639 404.751/46.687 435.119/428.974 1139.258
allocation-aa-1-base 2759.050/543.502 404.363/25.790 441.509/428.708 1098.693
allocation-aa-1-candidate 2776.225/542.709 407.016/21.410 439.571/426.907 1111.987

Each control arm completed40 primary turns/tools and10 native children. Full progress, ownership, cleanup and source receipts remain in the original campaign; reused-controls.json preserves the selected raw numeric rows and source path.

The Gateway template has 10,800 sessions, 40 plugins, 65 WebSocket clients, four concurrent primary turns, native subagents, mock tool calls and sidebar/list/search churn. Each ten-minute arm has ten measured rounds at 60-second intervals: 40 primary turns/tool calls and 10 native children. This is bursty mixed load, not proof of continuous 99% live-run occupancy. Its four actual live paths contain 34,153/20,000/49,000/40,000 events. The compact 210 MiB database models contention/cardinality, not cold 70 GB storage. All final-head measurement campaigns are complete. No historical path finished backfill during a Gateway arm; the separate owner proof establishes the eventual hydration benefit. Shutdown remains inconclusive, not proven unchanged.

Reusable component proof, measured before the final correction. Reader semantics, client lifecycle and discovery selection are unchanged; these are not final-head end-to-end measurements.

Component and sample scope Before → after
Fresh-reader partial/full coverage, 5 untraced lifecycles/side CPU 188.381→34.218 ms; wall 181.494→34.400 ms; equal outputs
Same hydration logical work 502,243,328→12,898,304 bytes; 122,618→3,149 spans (−97.43%)
Hydration allocation, AB/BA, 100 complete lifecycles/arm 2,214,970→2,157,804 sampled bytes (−2.58%)
Retained versus reopened client, AB/BA, 1,000 calls/arm 208,206→157,585 sampled host bytes/command (−24.31%)
Client timing, AB/BA after four A/A pairs, 10,000 calls/arm Host CPU 0.324126→0.324125 ms; no demonstrated CPU win
Same client timing, process CPU / wall per command 0.681244→0.719933 ms / 0.617575→0.675573 ms; variability in A/A controls
Discovery over 40,236 index-state rows, 100 scans/timing arm Size-first→recent-first: wall 27.500→28.103 ms; CPU 32.071→32.393 ms

Hydration A/A CPU was 175.692→176.514 ms (four controls); timed physical reads were zero, so this is fresh-reader/nonresident proof, not OS-cold storage. Client process CPU rose 5.68% with large A/A variability (−1.30% to −14.28%); allocation is the demonstrated client benefit. Discovery reads index-state/cold metadata, not historical payloads. Prior native resume traversed 15,360 covered identities without payload reads/writes; a completed 49k rescan still cost 24.125 s paced. Final resume and completed-path rescan costs are reported in the native table above.

Prior adverse results retained; not final-head claims. At f8cdb81, Gateway append queue p95 was 29→299 and 29→282 ms (660 samples/arm; A/A 32→32). Main CPU was 7.497→8.858%, allocation 29.1655→30.4661 MiB/s, GC 0.179148→0.227509 s/min, loop p99 28.172→32.686 ms and client-list p99 29.804→47.390 ms. Server-handler p99 was 27.445→37.515 ms, n=1,173/arm. Loads were 4.04–30.32. This supported foreground cost cannot be dismissed by the p99 sample limit. The 48.36 ms/min GC rise is below the material floor; adverse pause conclusions require additional matched controls. List/loop tails alone do not reject the change.

At admitted-pacing head 138650d4, forced-nonresident foreground AB/BA met the ≤15 ms queue-p99 target (append 7/5 ms, read 7/7 ms) but raised request p99 by +3.949 ms append and +5.340 ms read, with four comparatively tight A/A controls. The 76,436 rows/hour conditional rate implied 38.46 min / 13.08 h / 82.03 h for 49k / 1M / 6.27M rows; it is neither a final rate nor a Team forecast. Rare queue maxima were 121/120 ms append and 98/104 ms read. Final materialization/residency changes prevent reusing those costs as final acceptance evidence.

Final-head untraced short shutdown N5. Same external-volume fixture, with backfill unfinished at SIGTERM. Pairs 1–3 are from the initial final-head campaign; pairs 4–5 are fresh complete pairs from recovery. Pair 4 replaces the whole load-refused pair; its earlier slow candidate remains separately reported below.

Pair Base ms Candidate ms Paired delta ms
1 155 165 +10
2 133 121 −12
3 141 195 +54
4, fresh BA 641 132 −509
5, fresh AB 132 853 +721

Means are 240.4→293.2 ms (+52.8 ms, +22.0%); medians 141→165 ms and maxima 641→853 ms. All five pairs exited gracefully and joined. Candidate rows filled per bracket were 1,056/1,298/1,217/1,110/1,408, with 139,115–139,494 historical rows still missing at SIGTERM; all four long paths appended in every arm. Entry/signal loads were 5.05–10.38. The +52.8 ms paired-mean change has mixed signs and does not establish unchanged shutdown or a causal regression. Four identical-base A/A pairs were 174/140, 121/127, 128/622 and 138/131 ms: means 140.25→255.00 (+114.75 ms), medians 133→135.5, maxima 174→622; original loads/timestamps remain separate.

The original fourth candidate took 6,276 ms, including 5,378 ms in plugin-service cleanup. Its following baseline was refused at load 50.14, making that whole pair invalid; the slow candidate remains a standalone observation. The baseline's 902 ms cleanup is not a measurement. A fresh whole pair replaced it, without erasing or re-pairing that tail.

Five symmetric diagnostic pairs on exact base/final head were 165/159, 130/637, 122/640, 184/285 and 134/129 ms (means 147→370, +223 ms; maxima 184→640). All expected spans completed without drops. Facts-client closes were approximately 7 ms, and native closes approximately 18–57 ms; these spans overlap and are not additive. Two candidate runs had unexplained 531/533 ms gaps between native close and first plugin service. A later untraced baseline also had a roughly half-second delay. Normal logs omit individual steps below one second. No diagnostic run reproduced the multi-second plugin-service stall, so its cause is unresolved and no causal fix is claimed. Instrumented runs are not pooled with untraced qualification. All diagnostic and shutdown children joined and private temporary state was removed.

Earlier dedicated shutdown pairs included a 9.4-second candidate tail: base/candidate means 1,115.8/2,978.4 ms. Four quieter A/A pairs and a 533→256 ms diagnostic pair did not explain it; plugin-service cleanup was the aggregate location, not a proven backfill cause. Later 138650d4 N5 pairs were 656/174, 662/653, 646/127, 124/125 and 639/713 ms (means 545.4/358.4 ms), all graceful/joined, without a plugin-services stage over one second. Those results predate the final correction and do not establish unchanged final shutdown or a causal fix for the old outliers.

No Team writes, load, deployment or database copies occurred. All final Gateway children joined and private temporary state returned to zero. The five 21.75 GB native fixture databases and ten sidecars have been deleted (108.736 GB logical size, with APFS sharing; physical reclaim not measured). Cleanup also removed 470 arm fixture directories, six template fixture directories and eight task-owned runtime build archives (35.063 GB logical files; physical reclaim not measured). All targets are verified absent. Reports, raw evidence and ten allocation profiles remain; shared dependencies and UI attribution evidence were preserved. Peter approved this PR on 2026-11-07; the unresolved shutdown observation remains an explicit gap retained for the TS session's merge review.

@clawsweeper

clawsweeper Bot commented Nov 7, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T02:06:54.448708Z 6a55bbd 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts size: XL labels Nov 7, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 7, 2026
@clawsweeper

clawsweeper Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR gradually fills missing historical transcript facts through background SQLite transactions after Gateway readiness.

Example: An existing SQLite session has 34,153 active events with missing facts.

  • Before: Historical hydration continues reading payload-backed metadata despite recent appends.
  • After: Idle batches populate historical facts, allowing cheaper hydration while preserving the existing fallback.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, appropriately scoped maintenance with meaningful owner measurements, one concrete guard defect, and incomplete Gateway and upgrade validation.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long existing conversations retain expensive historical hydration after recent writes have covered only their newest events.
Reason: This maintainer-authored PR implements the explicitly planned follow-up and supplies measured hydration savings with equal outputs and clearly stated pacing tradeoffs.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open: it delivers the planned historical backfill, but introduces a concrete Kysely guard failure that needs a focused repair.

Priority: P2
Reviewed head: 97b2aee59e25299f21c3559e4879acbea82ee7a2

Before merge

  • Use a typed reference in the backfill navigation expression (P2) - The newly added sql.ref("active.context_eligible") is independently checked by the Kysely guard. Its line has no allowance, and the comment attached to the enclosing SQL template is not a leading comment on this nested call, so this PR fails lint:kysely. Exact-head CI confirms a Kysely failure. Change the select to use an expression-builder callback and pass eb.ref("active.context_eligible") to the shared navigation helper; this preserves behavior and restores literal-reference checking.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Use a typed reference in the backfill navigation expression — src/config/sessions/session-transcript-active-facts-backfill.worker.ts:159

Tests

  • Missing end-to-end proof: Supply the pending built-Gateway base/candidate run showing after-ready filling, foreground append responsiveness, and drain/shutdown, plus a latest-stable upgrade preserving settings and transcripts.
Agent review details

How this fits together

Gateway startup hands admitted databases to idle maintenance, which sends bounded backfill commands through the existing database worker and stores derived facts consumed by transcript hydration.

flowchart LR
  A[Gateway readiness and recovery] --> B[Idle maintenance scheduler]
  B --> C[Background writer admission]
  C --> D[Database worker]
  D --> E[Canonical transcript rows]
  D --> F[Derived transcript facts]
  F --> G[Transcript hydration]
  E --> G
Loading

Technical review

Best possible solution:

Retain the existing scheduler and worker design, replace the raw identifier reference with a typed Kysely reference, and complete the recorded integration validation.

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

Source confirms that existing historical facts can remain missing, and the supplied synthetic owner measurements demonstrate the resulting hydration cost; no target code was executed during this review.

Is this the best way to solve the issue?

The design addresses historical coverage at the existing maintenance and writer owners, preserves canonical payloads and fallback behavior, and needs no additional manager or persisted cursor.

Full review comments:

  • [P2] Use a typed reference in the backfill navigation expression — src/config/sessions/session-transcript-active-facts-backfill.worker.ts:159
    The newly added sql.ref("active.context_eligible") is independently checked by the Kysely guard. Its line has no allowance, and the comment attached to the enclosing SQL template is not a leading comment on this nested call, so this PR fails lint:kysely. Exact-head CI confirms a Kysely failure. Change the select to use an expression-builder callback and pass eb.ref("active.context_eligible") to the shared navigation helper; this preserves behavior and restores literal-reference checking.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Historical facts coverage keeps the original intent (b6ed907: The prerequisite intentionally introduced an empty derived table with exact fallback behavior and reserved paced historical backfill for a separate reviewed change.)
  • Post-ready scheduling and shutdown keeps the original intent (ddf95b6: Optional transcript maintenance was moved beyond readiness while retaining admitted database identities and tracked cleanup.)
  • Foreground-priority maintenance checks keeps the original intent (d0cd39e: Optional startup maintenance waits for readiness and idleness so recovery and interactive work retain capacity.)
  • Synthetic fixture generation keeps the original intent (b6ed907: The existing fixture models fragmented historical transcript storage; the extension preserves predecessor defaults and adds schema-41 backfill workloads.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm lint:kysely
  • pnpm test src/config/sessions/session-transcript-active-facts-backfill.test.ts --maxWorkers=1
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b6ed907 adds src/config/sessions/session-transcript-active-facts.ts:55 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b6ed90743ed7; files: src/config/sessions/session-transcript-active-facts.ts)

PR surface

Source +444, Tests +322, Docs +88, Other +666. Total +1520 across 23 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 9 454 10 +444
Tests 6 322 0 +322
Docs 2 93 5 +88
Config 0 0 0 0
Generated 0 0 0 0
Other 6 681 15 +666
Total 23 1550 30 +1520

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime versus test growth Runtime +454/-10; tests/support +322/-0 Runtime growth implements bounded discovery, transactional backfill, and lifecycle integration; the tests cover distinct historical, mutation, cold-storage, and cancellation boundaries.

Labels

Label changes:

  • add P2: Historical hydration performance improves without removing the existing fallback; the identified repair is a localized CI guard defect.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Historical hydration performance improves without removing the existing fallback; the identified repair is a localized CI guard defect.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 November 7, 2026, 1:50 AM ET / 06:50 UTC.

@steipete
steipete force-pushed the steipete/perf-active-event-facts-backfill-20261107 branch from 97b2aee to b2ba6a8 Compare November 7, 2026 06:52
@clawsweeper

clawsweeper Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: applying reviewed decision.

I am applying the reviewed decision for this pull request: perf(sessions): backfill historical transcript facts after readiness This is item 1/1 in the current shard. Shard 1/1.

This transient lease prevents a newer review from overlapping label, comment, or close mutations.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 7, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 05086c6c7e

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +58 to +60
backfill = createSessionTranscriptFactsBackfill({
database,
assertCurrent,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use in-memory authority checks for recurring backfill batches

During a historical backfill, this passes the startup database guard into every worker operation. That guard calls assertExistingDatabaseIdentity() (server-startup-session-migration.ts:94–97), which performs statSync() on the Gateway main thread; the worker client also invokes the guard during admission. Consequently, the new recurring pass repeatedly performs blocking filesystem I/O while serving live traffic, outside the worker's transaction budget. Use the retained owner's in-memory admission/generation checks here and preserve physical replacement detection at the worker admission boundary. This also violates the scoped Gateway rule that authority revalidation use the owner's in-memory revision rather than disk.

AGENTS.md reference: src/gateway/AGENTS.md:L12-L12

Useful? React with 👍 / 👎.

Fill existing schema-41 active-event facts through paced background worker transactions after recovery. Reuse writer derivation and foreground admission; resume from facts without new stored shape. Historical sessions regain cheaper non-resident hydration once covered. SQLite only; PostgreSQL retains its current fallback.

Regression coverage requires 322 net test/support lines for historical coverage, invalidation interleavings, cold restoration, post-ready scheduling, and drain; allocate exactly those lines. Requires Peter approval before merge or deployment.
Keep the writer-derived facts query unchanged while using the owning Kysely expression builder for the active-row eligibility reference. This satisfies the raw-identifier guard without another allowance.
Start normal database backfill from the existing post-ready task without waiting for global idleness. Keep restart recovery and drain gates, use background writer admission, cap duty cycle and back off on lock contention. Prioritize recently active paths and retain one worker client for each pass.

Regression proof covers progress during live work, post-ready registration during background work, recent-path ordering and worker-client reuse. No schema or stored-shape changes.
@steipete
steipete force-pushed the steipete/perf-active-event-facts-backfill-20261107 branch from fe435de to 6a55bbd Compare November 14, 2026 02:04
@steipete
steipete merged commit 72f90dd into main Nov 14, 2026
153 of 155 checks passed
@steipete
steipete deleted the steipete/perf-active-event-facts-backfill-20261107 branch November 14, 2026 02:51
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
…penclaw#194519)

* perf(sessions): backfill historical transcript facts after readiness

Fill existing schema-41 active-event facts through paced background worker transactions after recovery. Reuse writer derivation and foreground admission; resume from facts without new stored shape. Historical sessions regain cheaper non-resident hydration once covered. SQLite only; PostgreSQL retains its current fallback.

Regression coverage requires 322 net test/support lines for historical coverage, invalidation interleavings, cold restoration, post-ready scheduling, and drain; allocate exactly those lines. Requires Peter approval before merge or deployment.

* perf(sessions): use the typed backfill query reference

Keep the writer-derived facts query unchanged while using the owning Kysely expression builder for the active-row eligibility reference. This satisfies the raw-identifier guard without another allowance.

* perf(sessions): pace facts backfill during foreground work

Start normal database backfill from the existing post-ready task without waiting for global idleness. Keep restart recovery and drain gates, use background writer admission, cap duty cycle and back off on lock contention. Prioritize recently active paths and retain one worker client for each pass.

Regression proof covers progress during live work, post-ready registration during background work, recent-path ordering and worker-client reuse. No schema or stored-shape changes.

* perf(sessions): wait for restart input admission before backfill

* perf(sessions): qualify paced backfill under foreground load

* perf(sessions): preserve recent facts in hydration baseline

* perf(sessions): align backfill test allocation with ratchet

* perf(sessions): share facts backfill registration across startup paths

* perf(sessions): remove obsolete startup test schedulers

* perf(sessions): match backfill probe durability to worker

* perf(sessions): pace facts backfill by admitted execution

* perf(sessions): preserve snapshots during facts backfill

* perf(sessions): measure compacted cron facts hydration

* perf(sessions): preserve cron proof types
roboclaw-bot added a commit that referenced this pull request Nov 14, 2026
* fix(perf): invoke cron-model probe compiler through xcrun

Resolve the Knip unlisted binary clang finding from #194519. xcrun is already modeled by the repository.

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>

* Publish openclaw/faint-krill

Worked on by:
- @obviyus
- @steipete

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
OpenClaw-Publication: 66f51bf9-966c-89ba-b447-89c4f8268fbb

---------

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…98694)

* fix(perf): invoke cron-model probe compiler through xcrun

Resolve the Knip unlisted binary clang finding from openclaw#194519. xcrun is already modeled by the repository.

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>

* Publish openclaw/faint-krill

Worked on by:
- @obviyus
- @steipete

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
OpenClaw-Publication: 66f51bf9-966c-89ba-b447-89c4f8268fbb

---------

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

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant