Repository navigation
perf(infra): batch usage refresh maintenance - #174050
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 changes before merge. What this changesThis PR batches usage-cache prune transfers and monthly partition deletions while removing redundant refresh metadata checks. Example: A full usage refresh finds 97 small stale cache rows.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 1 item remains Keep this PR open: it provides a focused maintenance optimization, but the new partition rollback test runs in the wrong CI worker pool and fails before exercising deletion. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe usage refresh worker derives cost projections from transcripts, stages obsolete cache snapshots on the host, and commits maintenance through the existing agent database writer. flowchart LR
A[Transcript inventory] --> B[Usage refresh worker]
C[Stored usage checkpoints] --> B
B --> D[Host batch accumulator]
D --> E[Agent database writer]
E --> F[Usage checkpoints and monthly partitions]
Technical reviewBest possible solution: Keep the existing batching design and register the new rollback test in the fork-based database-worker lane. Do we have a high-confidence way to reproduce the issue? Exact-head CI records the new test's admission failure, and source inspection explains it through threaded unit-fast routing; no target code was executed during this review. Is this the best way to solve the issue? Batching within the existing refresh and writer owners is appropriate, and the explicit metadata-check tradeoff preserves final snapshot pruning and commit authority. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 6ce455bfed82. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
PR surfaceSource +9, Tests +74, Docs +9. Total +92 across 10 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
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 16, 2026, 5:26 AM ET / 09:26 UTC. |
* commit 'ac03ca0b6d26a7dc55d0d262e40d2549631b1ea7': (25 commits) fix: apply shared plugin model policy to decisions (#156621) perf: shortlist transcript relevance scores before metadata reads (#174058) fix: strip standalone trailing NO_REPLY from replies (#171990) fix(ci): avoid repeated discovery during changed-test planning (#174069) fix(sqlite): preserve transaction outcomes when warnings throw (#157151) fix(ai): native video handoff to chat-completions providers + preflight video cost (#170920) fix(litellm): image generation fails when the backend returns image URLs (#173508) test(memory,gateway,infra,subagents): remove low-value tests (batch d152) (#174034) perf(memory): bound derived worker snapshot and pricing retention (#174067) fix(test): reduce eager imports during test startup (#174056) refactor(codex): share lifecycle preflight fixtures (#174062) test(gateway,matrix,agents,ui): remove low-value tests (batch d150) (#174025) perf(infra): batch usage refresh maintenance (#174050) fix(gateway): revert cold session list worker regression (#174052) refactor(config): consolidate browser meeting configuration (#173947) fix(cron): keep global-session deliveries on the selected agent (#173855) test(compaction): assert structured stale-writer failure (#174064) fix(cli): local terminal chat sends model requests without the configured proxy (#173530) test(ui): restore bootstrap preference locale after each case (#174065) fix: download session files through the development proxy (#173973) ...
Batch stale usage-cache snapshot transfers and exact month deletions under their existing owners. Preserve ordered bounded payloads, the final snapshot-checked prune transaction, rollback, write-receipt invalidation, and effect-time lease checks. Remove repeated body metadata comparisons and per-row staging admission; targeted refresh no longer sends unused prune commands. No schema or public API change.
What Problem This Solves
Usage-cache refresh currently waits for one prune-staging reply per stale row, and month cleanup issues one DELETE per removed month. Batch those operations under their existing owners, and remove redundant body-metadata comparisons after refresh ownership and write-receipt validation.
Full refresh transfers ordered batches of at most 64 snapshots or 1 MiB of encoded metadata/key data; an oversized row travels alone. The host keeps its existing accumulator and performs one final snapshot-checked prune transaction. Targeted refresh sends no prune commands. Month cleanup deletes up to 100 exact keys per statement inside the existing rollup-write transaction, preserving rollback across batches. The old single-row command is deleted.
Both snapshot-prune implementations and their timestamp/value predicates remain unchanged. SQL-side payload limits, receipt invalidation, cancellation, settlement, and the final effect-time lease check remain. No schema, SDK, configuration, migration, Doctor, updater, service-lifecycle, or plugin-loading changes.
Measurements
Pinned comparison: baseline
80949b4ec75d2479ab8c35d746e2aa82a17f515fversus candidated69538dfaa2d0aa6c4e1cac566781daa722d2878. Three alternating M/C pairs used the shared v3 harness with the recorded runtime-only pin: Node 24.22.0 and both compiled/loaded SQLite 3.54.0;NODE_DISABLE_COMPILE_CACHE=1. Synthetic Gateway fixtures were on the internal disk. All six raw native SQL/request recounts and causal phase/window recounts match the saved analyses; all source/runtime pins, workload outcomes, and cleanup checks pass. No native execution or prepare errors occurred in the Gateway series. No latency claim is made on this busy host.The workload does not demonstrate a warmed SQL reduction: causal warm totals are identical. Pooled warm SQL/request medians do not increase, but raw warm-window sums and whole-workload totals do increase. Those real differences are retained below; this is not a blanket claim that every scenario improved.
Gateway workload
Each cell is median [min–max], baseline → candidate. Warm pooled rows contain 30 turns per arm; other rows contain three scenario measurements per arm. SQL means all-thread native executed statements, requests mean v3 actor/task wire requests, and MAIN is the Gateway main-thread subset.
Whole-workload median SQL rises 4,582→4,597 (+0.33%) and requests 1,144→1,146 (+0.17%). Whole sums rise by 46 SQL and five requests. Raw warm sums rise by 28 SQL and three requests, while causal sums remain exactly 2,275 SQL / 853 requests / 0 MAIN per arm. Raw warm MAIN rises 12→30; first-turn MAIN falls 27→9. The whole MAIN total falls 919→918. Scoped inventory evidence is T1 0→0, T1-compat 0→0, and worker API sites 13→13; raw MAIN in boot/lifecycle windows is not a new usage-owner T1 call.
Observed variation and coverage
Pairs 1 and 3 each execute 12 more lease-store SQL in the candidate warm windows and 12 fewer in its first-turn window. That explains 24 of the 28 extra raw warm SQL as a phase shift; the all-workload lease-store SQL is unchanged. Pair 3 also moves 268 maintenance SQL from the first-turn window into earlier boot/connect. These shifts are not optimization savings.
The restart preflight/sweep executes in baseline pairs 1 and 2 and all three candidate arms; it is absent from baseline pair 3. Each execution contributes 30 SQL directly attributed to session-transcript-index-status.worker.ts and four directly attributed to session-transcript-projection-publication.worker.ts, including first-handle TEMP tracking setup. The one additional execution accounts for 34 of the whole-workload +46 SQL; other observed module changes net to +12 SQL. This is an actual additional background execution, not evidence of transcript rebuilding and not discarded as noise. The retained usage-series evidence does not establish which scheduling trigger caused the extra execution, so its causal relationship to the usage change remains unresolved.
The remaining whole-workload changes include +8 agent DB admission SQL, +3 auth-profile SQL, +3 transcript-backfill SQL, +3 agent readonly-open SQL, +3 schema-read SQL, offset by -6 readonly-scope SQL, -4 session-entry-list SQL and other smaller differences. Per-module and per-scenario deltas are retained in the independent audit. Compaction SQL 96→98 shifts with idle-settle work; connected-idle SQL is identical in every pair while total idle requests rise 118→119. Spawn totals rise 1,639→1,643 SQL and 503→504 requests, with session-entry/read/projection and ACP metadata variation retained.
Usage-origin totals include admission/support SQL. The request at session-cost-usage-cache.sqlite.ts:89 prepares the owner/agent registration: it occurs in first turn for base-2/base-3 (18 SQL) and candidate-2 (19 SQL), but not the other first turns. Restart preparation is 36 SQL except base-3 at 35. Candidate-2/candidate-3 each execute one additional SQL statement under the metadata-read/admission path (session-cost-usage-worker.ts:198) and one under refresh-input lookup (session-cost-usage-refresh-inputs.worker.ts:114) in first turn. In pairs 2 and 3, the existing first-turn usage-worker task executes 7→9 SQL; each arm still has four usage-worker task requests across first turn, cron, connected idle and restart-first-turn. Thus these are two additional SQL executions within one existing task, not another task invocation. Both extra executions are single-row SELECTs in unchanged read/admission paths. Source order places metadata reading and transcript inventory before the changed prune/body branches within that refresh task; the separate writer preparation also finishes before task dispatch. Direct rollup-iterator and transcript-instance read counts remain unchanged, so this is not evidence of a second full inventory pass. The retained evidence does not establish why cache/admission work differs or the initial scheduling cause. Pair-2's remaining +1 usage-origin SQL is agent metadata in preparation. These cold changes are included, not subtracted. Across the three arms, usage-origin totals are 320→308 SQL and 26→25 requests.
Gateway traces observe inventory, refresh-input reads/admission, rollup INSERTs and partition replacement. They contain no executed removed-month deletion or changed body-snapshot SELECT path. Unchanged reads and INSERTs do not establish coverage of the batching change. Zero-SQL branch effects are not inferred from the SQL trace. The owner probes below establish the changed maintenance-path savings separately.
Owner operations
The kernel and actual-refresh series each contain three alternating M/C runs, with three measured repetitions of each ordinary operation inside each run. Counts below are the median per operation; all reported ordinary counts are invariant across the nine samples per arm. Fixture seeding, direct result reads and report verification are outside measured phases. The refresh entry point uses real durable reader/writer workers and includes its measured warm support work; cold fixture admission is not part of these warmed refresh samples.
The 97-row refresh replaces 97 per-row host commands plus one final prune command with two bounded batches plus one final prune command. These host commands are a separate instrumentation scope: do not add them to or relabel them as v3 wire requests. The final SQL prune work is unchanged. Monthly deletion independently uses bounded SQL batches and keeps the original transaction semantics.
The kernel control uses 8,407 synthetic rollups in one synthetic agent/DB, with artificial partition rows and small metadata. It is an unchanged control, not an actual full-refresh batching measurement. A separate actual-refresh M/C pair used the same 8,407 synthetic rollups, one synthetic partition per stale rollup and one live synthetic transcript, with one repetition per operation per arm:
The full-refresh command sequence changes from 8,407 per-row commands plus one final prune to 132 bounded batch commands plus one final prune. Executed SQL remains identical, including 8,411 SELECTs and 8,670 DELETEs; this is a worker→host command reduction, not a v3 wire-request or SQL reduction. The later-targeted difference is one baseline-only PRAGMA and is not claimed as a batching saving. MAIN and native/prepare errors are zero. Targeted refresh retains the stale rows, full refresh deletes only those rows, and a later update preserves exact expected monthly totals. Saved rows/statistics, 15 source-file hashes per arm, proof hashes, clean snapshots and runtime attestations all pass independent checks. Both supplemental raw arms had already been auto-cleaned, so this pair has no independent raw recount. This one-pair synthetic result makes no latency or live-deployment claim. Its small metadata exercises row-count batching; existing focused tests cover the byte cap and oversized single rows. Transfer bounds do not cap the host accumulator or total discovery memory.
Owner MAIN is zero throughout. Each kernel arm intentionally injects two late DELETE failures (rollup and partition), observes the expected execution error, verifies the full pre-transaction rows survive, and successfully retries; these expected errors are not hidden. Ordinary owner operations have no native/prepare errors. Actual refresh proves targeted refresh preserves stale rows, full refresh removes only stale rows, and a later write remains visible with exact monthly totals. Kernel proof also verifies retained unrelated rows and later rewrite visibility.
All saved owner statistics, exact source-file hashes, clean tracked snapshots and native runtime attestations were independently checked. Nine of twelve owner arms also have independent raw native recounts that exactly match their saved rows. Raw files for native-candidate-3, refresh-base-3 and refresh-candidate-3 had already been cleaned; those three are saved-evidence audits, without a claimed independent raw recount.
Evidence hashes
b5c7c7fcc7963563944759ffdff063dfb4c70d27c79be91f2f3f5c35ee064a8b9a40f4ac50bf3d64f543111e42492086ea0f95f9cc61624e119f414eeff2cbb1cc71ca2b64ea3ba4e989978697ced557252ba2adece86530290b234de4ee064d0000cf736deafc9a837920d56e2d165feee051170afde276ee3b345aeceaf8fb6920cf0b3d66ef48288523f3d9f26f93ee6af592e22a9850f8cf26e91b6eeefaSummary files: usage-safe-pairs-d69538dfaa2d/gateway-pairs-summary.json, usage-native-summary.json and usage-refresh-summary.json. Detailed independent evidence: independent-measurement-audit.json.
Area T1 is 0 → 0 across all five changed production files; the same 13 inventoried synchronous primitive call sites remain worker-owned. Exact source and worker callers are recorded in
usage-area-t1-evidence.json. Final CI reports global T1 222 → 222, deprecated-only 12 → 12, and all three dialect groups 0 → 0.Removed checks and accepted edges
Locations refer to the base above.
src/infra/session-cost-usage-cache.kernel.ts:259src/infra/session-cost-usage-partitions.worker.ts:167src/infra/session-cost-usage-worker.ts:225src/infra/session-cost-usage-worker-runtime.ts:389src/infra/session-cost-usage-worker.ts:505The test that injected a rewrite through the active refresh's own lease is removed. Tests for retained snapshot-prune checks remain.
Evidence
Two Codex autoreview rounds completed; the final scoped review is clean. Changed-file type-aware lint, format, and diff checks passed (
usage-lint-final.log); the inventory correction also passed focused format/lint checks. Prior-head CI source contracts, Madge (0 cycles), T1/dialect ratchets, production types, and all test types passed. Six focused files passed there (88 tests). Its only leaf failure was the new partitions regression, incorrectly assigned to unit-fast/threads; the final commit adds it to the existing database-worker inventory for isolated infra/forks. That regression now passes locally (1 file / 1 test) on the exact bytes committed in the final head. All seven focused test files are byte-identical across the inventory-only correction, giving 7 files / 89 passing cases with source provenance inusage-final-coverage.json. Final-head CI run 38881684862 passed ond69538dfaa2d0aa6c4e1cac566781daa722d2878, including the aggregate CI gate, production/test types, lint, source contracts, architecture checks, ratchets, and all executed test shards. Knip completed with inherited failures: four production / three full-tree unused exports in untouched UI files, and zero script findings. These exactly match observed maina9e85bfa0f2104543254675a1a950d3f2237714c(run 38875037669, job 116888078091); the complete UI source tree, relevant Knip configs/runners, lockfile, and deadcode commands match by Git object or exact value. Seeusage-knip-final-provenance.json; Knip is not claimed green. SDK diff and published-driver update proof are not triggered by this scope.New regressions use real owner writes to verify rollback/retry when the second month-deletion batch fails, preservation of unrelated rows, bounded full-refresh transfers including oversized metadata, targeted-refresh preservation, and later monthly totals. Existing admission, receipt-invalidation, payload-bound, snapshot, and memory-path suites passed as part of the seven-file focused proof; no required focused file remains uncovered.
A separate key-only prune proposal is deferred: usage partitions inherit NUL-containing PostgreSQL TEXT keys, and combining the prune would newly bind them for missing/non-current snapshots. This is a source finding, not a live PostgreSQL reproduction. The current change preserves the existing prune implementation and does not claim PostgreSQL usage-partition support. Key representation belongs to the storage migration owner.
Size: 11 files, +251/−158 (net +93). Production +60/−51 (net +9); tests/support +178/−103; docs +13/−4. Growth supplies bounded transfers while removing the per-row path. Release-note context: batch usage-cache maintenance without changing public APIs or refresh ownership.