Repository navigation
perf(trajectory): move global retention off the append writer - #165274
Conversation
Prepare serialized rows before writer admission, select bounded whole-run retention candidates outside the writer, and fence short delete batches with the native database revision. Preserve age and byte policies, active-session protection, and eviction ordering.
Use the canonical covering index for one grouped retention scan, preserve its plan regression, and defer synchronous maintenance while an enclosing transaction remains open. This keeps failed outer writes from suppressing the next retention pass.
Assign sequence numbers to private prepared rows inside the writer without allocating another object per event. Declare receiver-free authority callbacks and keep maintenance promise observation with its lifecycle owner.
|
🦞👀 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: blocked before merge. Reviewed October 4, 2026, 11:39 PM ET / October 5, 2026, 03:39 UTC (Revision 3). ClawSweeper reviewWhat this changesTrajectory event capture moves global cleanup outside append transactions into independent reads and short, revision-checked deletion batches. Merge readiness⛔ Blocked before merge - 3 items remain This remains a useful, measured improvement absent from current main. No discrete correctness defect was found, but retention progress under sustained writes remains unresolved from the previous review. Priority: P2 Review scores
Verification
How this fits togetherTrajectory records agent-run events in each agent’s SQLite database for diagnostic export. Its appends share the database writer with other agent state operations, so long cleanup transactions delay unrelated writes. flowchart TD
A[Agent runtime events] --> B[Prepare serialized rows]
B --> C[Append and trim session window]
C --> D[Independent retention read]
D --> E[Check authority and database revision]
E -->|Current| F[Delete bounded historical runs]
E -->|Changed| G[Defer until another append]
F --> D
Decision needed
Why: The latency benefit is demonstrated, but accepting potentially indefinite cleanup deferral requires explicit owner intent. Before merge
Agent review detailsSecurityNone. PR surfaceSource +416, Tests +468, Docs +14, Other +3. Total +901 across 14 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Preserve short append holds while ensuring retention makes progress under write pressure, with explicit documentation of any accepted quiet-period limitation. Do we have a high-confidence way to reproduce the issue? Yes: current main places the global scan inside append admission, and the captured production-boundary benchmark demonstrates long writer holds. This review did not execute code. Is this the best way to solve the issue? Unclear: independent reads and bounded deletion address writer latency cleanly, but sustained-write retention progress must be demonstrated or explicitly accepted as a limitation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 94f1e932eedc. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
Keep the trusted wrapper source inventory closed over the new read-only retention operation and its runtime imports.
|
Maintainer decision (post-merge, lead of the Team perf campaign): accepted with a follow-up. The latency half is proven on the paired Testbox run (max append writer hold 1,808 ms to 80 ms, deletions at most 15 ms, identical retained rows), and this landed as part of the Team round-48 deployment. The retention-progress question is real: under sustained writes the revalidation step can keep invalidating cleanup selections, so convergence to the default 512 MiB budget is unproven and settlement grew about eightfold on the synthetic run. Team's trajectory table is currently far under budget (0.63 GiB, every session under its per-session cap), so this is a contract risk rather than an active regression. Resolution: a dedicated follow-up lane is measuring convergence under a sustained-write workload (continuous appends across hundreds of sessions while the sweep runs) and, if it does not converge within one sweep cycle, will make revalidation reject only candidates whose own facts changed and carry sweep progress forward with a cursor, keeping the bounded deletion holds and the current-session protection. That work references this decision in its PR body. |
…aw#165274) * perf(trajectory): move retention reads off the append writer Prepare serialized rows before writer admission, select bounded whole-run retention candidates outside the writer, and fence short delete batches with the native database revision. Preserve age and byte policies, active-session protection, and eviction ordering. * fix(trajectory): preserve retention cadence across nested rollbacks Use the canonical covering index for one grouped retention scan, preserve its plan regression, and defer synchronous maintenance while an enclosing transaction remains open. This keeps failed outer writes from suppressing the next retention pass. * perf(trajectory): avoid copying prepared insert rows Assign sequence numbers to private prepared rows inside the writer without allocating another object per event. Declare receiver-free authority callbacks and keep maintenance promise observation with its lifecycle owner. * fix(trajectory): include retention worker in maintainer wrapper Keep the trusted wrapper source inventory closed over the new read-only retention operation and its runtime imports.
Move retention request and result types into a dependency-free leaf contract shared by the SQLite reader registry and worker. Keep the existing lazy worker loader and retention behavior unchanged. The type-only registry import introduced by 09242dc (#165274) pulled the agent database and SQLite reader back into the registry graph. Validated both import-cycle guards at zero, core and state/trajectory test types, focused SQLite/retention tests (36 passed), formatting, and lint.
|
Follow-up on the accepted post-merge finding (retention convergence under sustained writes): #165678 lands the fix. The global aggregate now runs outside the writer transaction with sweep-scoped in-memory receipts and a foreign-commit refresh; on the 20M-row fixture retention converges in 9.7 s with zero invalidations (previously no sweep completed in 30 minutes), and the deletion transaction's SQL hold is 3.7 ms (the remaining ~123 ms peak is a WAL checkpoint commit, tracked separately as "WAL checkpoint scheduling during retention deletes"). |
Move retention request and result types into a dependency-free leaf contract shared by the SQLite reader registry and worker. Keep the existing lazy worker loader and retention behavior unchanged. The type-only registry import introduced by b7ca379 (openclaw#165274) pulled the agent database and SQLite reader back into the registry graph. Validated both import-cycle guards at zero, core and state/trajectory test types, focused SQLite/retention tests (36 passed), formatting, and lint.
What Problem This Solves
Trajectory appends can block every other agent-database writer while performing global retention. A 24-hour production census recorded 12 append holds of 2.4–3.0 seconds, totaling 28.7 seconds, on an hourly cadence. The covering index landed in #165074 reduces scan cost, but the scan still holds the append writer.
User Impact
Global retention reads now run outside both the append transaction and its canonical writer reservation. Events are serialized before
BEGIN; the existing bounded per-session suffix trim remains in the append. The 14-day age policy, 512 MiB global target, protected current session, whole-run eviction, byte accounting, and tie ordering remain intact. No new schema, configuration, dependency, or migration is introduced.The tradeoff is more total maintenance work: in the final fixture, retention settlement took 31.44 seconds instead of 3.82 seconds. Concurrent changes reject a stale selection and defer remaining cleanup to a later append. Progress under continuous writes and full reclamation to the default 512 MiB budget remain unproven. Nested synchronous appends also defer cleanup until a later independent append, avoiding maintenance inside the caller's transaction and premature cadence publication after rollback.
Why This Change Was Made
One lifecycle-owned retention job reuses the existing read worker. SQL aggregates through the canonical covering index; a bounded accumulator keeps the oldest 100 candidate runs while preserving locale-sensitive and NULL/empty-ID ordering. Separate admitted transactions delete an oldest prefix capped at 100 runs and 10 MiB, allowing one oversized complete run. Native incarnation, local mutation revision, and foreign data version must still match before deletion. Committed results carry the revision to the next batch; only a complete sweep advances cadence.
The inline global scan and unbounded JavaScript run array/sort are removed. Private prepared rows receive their sequence numbers inside the writer without another object copy. One retention kernel serves synchronous and asynchronous callers. Cancellation, database borrowing, and cleanup remain attached to agent/shared-state lifecycles; failed cleanup stays visible to lifecycle joiners, and callbacks do not retain completed append batches.
LOC exception: +419 net (586 added, 167 removed; excluding tests, test support, and docs): +416 runtime lines and three wrapper-inventory entries, exceeding this lane's neutral-LOC target. The added code preserves the independent reader's cancellation/drainage and database borrow, admitted revision-fenced deletion, and exact eviction ordering. No alternate inline implementation or new persistence owner remains.
Evidence
The final comparison uses indexed main
c8b847edc7e4e5089cec4b01ca056727f24e279aand the final implementation, including the allocation cleanup. Both use the real schema, writer broker, admission, and read-worker boundaries with the same synthetic fixture shape: 20,067,216 rows, 200,001 runs, 156-byte event envelopes, 3,130,485,696 payload bytes, and a 5,725,073,408-byte database.Exact retention outcome: both retain 19,866,470 rows, with ordered identity SHA-256
db5b7c0a15f21c9c15610bcf38faf97b5b422ce0e165549a55e198d818515d78. Starting after the timing phase, 20,066,516 rows + 22 appended rows − 200,068 deleted rows = 19,866,470. Both delete the same 2,000 historical runs/200,000 rows and 68 rolling-prefix rows. Candidate cleanup uses 20 delete transactions: 11.67 ms median, 15.17 ms maximum, 235.40 ms total. Its 21 deferred reads total 27.925 seconds. Identity hashing takes 17.228 / 16.974 seconds separately; complete outcome runs take 21.045 / 48.413 seconds.The final pair ran on Blacksmith Testbox
tbx_01m44s37p4q078rvbd5hdxbybh, profileopenclaw-check, Linux, 4 guest-reported CPUs, Node 24.19.0, SQLite 3.53.3, and pnpm 12.5.1. Load samples ranged from approximately 0.01 to 1.68. Both revisions usednice -n 10 ionice -c3, isolated state/TMPDIR on disk, and enforced free-space reserves. The full paired driver exited 0 in 215.897 runner seconds; each completed synthetic database was removed after its evidence was recorded.Limits: 31 queued victims make nearest-rank burst p99 equal to the maximum; ordinary p99 has 300 samples. First-use exercises the hourly retention kernel without waiting an hour. The roughly 67k-row active suffix is a tiny-event stress case, not production payload distribution. Scan timing raises the existing internal byte cap to retain the large corpus; the outcome applies age/byte pressure for 2,000 run evictions. An earlier shared-rig run corroborated shorter writer holds but had worse ordinary p99, so these observations do not establish a general throughput improvement.
Validation, costs, and source identity
The benchmarked runtime implementation at
50bb65373eae93e3b2e5e5db9bb050bbf694efcdagainst the pinned base has full-index patch SHA-25612f668727e2f37847a42821ebb850dc37c434f55b7b6c5aa66277fba0f677574(abbreviated-index patch283f2ef88218ae5c7cc17386d9662b1dda941710a8d86a52dd5ee1dacf1571aa). It was verified before and after execution in an isolated Testbox checkout. The subsequent CI repair changes only the wrapper inventory; every runtime file remains byte-identical.node scripts/check-changed.mjs --stagedblacksmith-testbox,tbx_01m44s37p4q078rvbd5hdxbybhnode scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json <11 changed TS files> --threads=1node scripts/run-vitest.mjs src/trajectory/runtime-store.sqlite.test.ts --maxWorkers=1node scripts/run-vitest.mjs src/trajectory/runtime-store-writer.test.ts --maxWorkers=1src/infra/sqlite-readonly-worker.operations.test.tsblacksmith-testbox,tbx_01m44nsza4ybe4vwc7d1k8djtynode scripts/run-vitest.mjs src/trajectory/runtime-retention.test.ts --maxWorkers=1pnpm buildblacksmith-testbox,tbx_01m44gvd9k34v67pcszaz9pz2vCI repair: run 37255362137 passed every selected check except
checks-node-compact-small-2and its aggregate gate. The source-closure test found three newly reachable files absent from the maintainer wrapper inventory:src/trajectory/paths.ts,runtime-retention.sqlite.ts, andruntime-retention.worker.ts. The repair adds those exact entries; no assertion changed. Onblacksmith-testbox/openclaw-checkleasetbx_01m44z7cmar9nafr9cxhfv2k4a, the originalpr-wrapper-source-closure.test.tspassed all 3 cases in 3.136 s wall, the selectedeager-import-closure.test.ts“PR wrapper inventory” case passed in 3.804 s, andnode scripts/check-changed.mjs --stagedpassed for the manifest delta in 94.526 s. The repair also passed independent P0–P2 review. Repaired-head CI passed: run 37259893749, head7945005063dce5d57d64e623f2751cd1b147b77a: 59 successful jobs, 24 intentionally skipped jobs, 6m27s run elapsed, and 8,508 accumulated job wall seconds. The formerly failing compact-small-2 job passed in 110 job wall seconds (including setup).Original baseline
ae4ebd2cfailed the serialization, competing-writer, and bounded-delete regressions for their intended reasons (25.23 s focused invocation). The extended cadence regression also failed on the candidate's pre-fix synchronous implementation: after outer rollback, the next independent append incorrectly retained the old run (26.18 s invocation). It passes in the final full SQLite suite.Independent review found cleanup-failure propagation, append-payload capture, and nested-transaction cadence defects; each was repaired. The final source repairs are scoped-clean at P0–P2. The first complete rig gate passed its guards/typechecks/export scans but found three lint errors; those were fixed without suppressions before the final green Testbox gate. No assertions, baselines, budgets, or guard policies were weakened.
Queued/disappeared leases, checksum-sync failures, and mismatched sync-root Git metadata were infrastructure failures, not passing evidence. Validation used a pinned isolated checkout and full object IDs. Superseded/cancelled rig gates are not claimed as passing. The final pair moved to Testbox when safe cleanup could not restore the rig's required disk reserve. All owned leases and rig worktrees have been stopped or removed. Auto-merge completed as squash commit
09242dc32ae1182f72856721170524882051f0f8after repaired-head CI passed. The documented sustained-write/default-budget convergence gap remains; the automated review requested a maintainer decision on that operational tradeoff.No production database was queried or modified, and no Gateway was restarted.