Repository navigation
perf(trajectory): sweep retention from a covering index instead of regrouping every event - #165074
Conversation
Replace the partial canonical run index with a covering expression index and remove materialized event-size staging. Preserve retention, byte accounting, cadence, and atomic append behavior; document same-version admission and rollback and prove populated index repair.
|
🦞👀 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: needs maintainer review before merge. Reviewed October 4, 2026, 4:41 PM ET / 20:41 UTC (Revision 2). ClawSweeper reviewWhat this changesTrajectory, OpenClaw’s session flight recorder, replaces a partial SQLite index with a covering index to shorten retention sweeps and adds query-equivalence and populated-database repair coverage. Merge readiness✅ Ready for maintainer review The optimization remains useful: current main retains the materialized aggregate and partial index. No actionable introduced defect was found, and the latest test repair covers both supported query-execution methods. Likely related people: steipete (high-confidence routing candidate) and SunnyShu0925 (medium-confidence adjacent-area candidate). Priority: P2 Review scores
Verification
How this fits togetherAgent runs feed runtime events into the per-agent SQLite trajectory store. Its append transaction trims session history and periodically evicts older runs before those events are read for diagnostic exports. flowchart TD
A[Agent runtime events] --> B[Database writer]
B --> C[Append and session trim]
C --> D{Retention sweep due}
D -->|Yes| E[Covering index aggregate]
E --> F[Existing retention policy]
F --> G[Retained diagnostic events]
D -->|No| G
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource -11, Tests +81, Docs +45. Total +115 across 7 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep retention policy with its existing owner and use the admitted covering index to avoid temporary regrouping while preserving event bytes and upgrade behavior. Do we have a high-confidence way to reproduce the issue? Yes: current-main source identifies the materialized aggregate, and the captured regression reports temporary grouping before the change. This review inspected that path but did not execute it. Is this the best way to solve the issue? Yes: replacing the existing derived index avoids a second persistence owner, and the query preserves the previous grouping and byte calculation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against f98ca0d0a1fa. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
Capture both all() and iterate() so the retention query regression remains effective on Node 24.19 as well as newer Node runtimes. Keep equivalence, covering-index, and retained-event assertions unchanged. The original observer failed locally on Node 24.19; all 30 trajectory tests now pass on Node 24.19 and Node 26.10. Changed-file checks and independent review passed.
|
Merged via squash.
|
Doctor's v17 memory repair failed when the trajectory covering-index change triggered a whole-schema assertion before the supported inline recall metadata and provenance-trigger migrations. Keep the v17 physical-integrity gate, then let the existing migration finalizer repair indexes and validate the complete target schema inside the same transaction. Preserve the covering retention index and aggregate, all current-schema admission checks, and migration rollback. Clarify v17 ordering in the database versioning notes. The existing frozen Doctor fixture retains the old partial index and supplies the regression: red before this change, green afterward. Validation: 156 tests passed across Doctor memory, agent database, canonical index, and trajectory suites (two existing skips); 13 participant migration and rollback tests passed. Changed-file formatting and oxlint, assertion safety, max-lines, line-cap, database-worker ratchets, and docs links passed. Repairs the regression introduced by 97a770b (#165074).
…grouping every event (openclaw#165074) * perf(trajectory): sweep retention through a covering index Replace the partial canonical run index with a covering expression index and remove materialized event-size staging. Preserve retention, byte accounting, cadence, and atomic append behavior; document same-version admission and rollback and prove populated index repair. * test(trajectory): observe retention aggregates on older Node Capture both all() and iterate() so the retention query regression remains effective on Node 24.19 as well as newer Node runtimes. Keep equivalence, covering-index, and retained-event assertions unchanged. The original observer failed locally on Node 24.19; all 30 trajectory tests now pass on Node 24.19 and Node 26.10. Changed-file checks and independent review passed.
Doctor's v17 memory repair failed when the trajectory covering-index change triggered a whole-schema assertion before the supported inline recall metadata and provenance-trigger migrations. Keep the v17 physical-integrity gate, then let the existing migration finalizer repair indexes and validate the complete target schema inside the same transaction. Preserve the covering retention index and aggregate, all current-schema admission checks, and migration rollback. Clarify v17 ordering in the database versioning notes. The existing frozen Doctor fixture retains the old partial index and supplies the regression: red before this change, green afterward. Validation: 156 tests passed across Doctor memory, agent database, canonical index, and trajectory suites (two existing skips); 13 participant migration and rollback tests passed. Changed-file formatting and oxlint, assertion safety, max-lines, line-cap, database-worker ratchets, and docs links passed. Repairs the regression introduced by 5736753 (openclaw#165074).
What Problem This Solves
Trajectory appends that perform global retention hold the agent database writer while regrouping every retained event through a temporary B-tree.
User Impact
Sweep-bearing appends can spend less time holding the writer, with unchanged event retention and byte limits. The first database open rebuilds the index and needs temporary disk; later writes maintain a slightly larger expression index.
Why This Change Was Made
Replace the existing partial
idx_agent_trajectory_runtime_runindex with(session_id, run_id, created_at, octet_length(event_json)), including null run IDs. Aggregate directly from the covering index and remove the materialized CTE. The previous CTE avoided sorting large event bodies; the new plan avoids that sort entirely. Run selection, ordering, and deletion remain with the existing retention owner.Storage design: The coordinator accepted this index-only design in the trajectory-retention-index work order. Canonical events remain in the per-agent trajectory store; the index is derived and replaces the old definition under the same canonical name. Writable admission atomically repairs definition drift at agent schema 24, using the existing integrity checks and probe/replacement lifecycle. Construction reads retained trajectory history and temporarily holds a probe and replacement index. Same-version older writable owners can rebuild their old partial definition on downgrade or rollback without changing rows; strict read-only admission can require writable repair first. No schema-version bump, counter, trigger, summary table, second retained index, config option, or new owner is introduced. The 14-day age rule, current-session exemption, 512 MiB default global limit, JSONL separators, existing encoding semantics, per-session UTF-8 cap, hourly handle-local cadence, postcommit publication, and atomic outcome are preserved. The repository storage design and versioning notes record this decision.
Evidence
team.openclaw.aion 2026-10-04 recordedtrajectory.runtime.append: 38 slow immediate/write holds, average 2.243 s, maximum 3.174 s, with 241,697 trajectory events. The samples do not identify which appends swept; this change targets sweep-bearing appends and does not explain every slow hold.MATERIALIZE event_sizesandUSE TEMP B-TREE FOR GROUP BY. The same append fixture compares every grouped result with the previous query, includes null and named runs in one session and shared run IDs across sessions, and checks exact retained event-type sequences at the byte boundary. Existing UTF-8/UTF-16 cases remain. The existing canonical-index repair test opens populated old-index data and verifies canonical shape, unchanged rows, and unchangeduser_version; its setup moved to the existing drift helper to keep the over-cap test file smaller.origin/mainhas advanced, so unrelated changes on main are excluded from these task counts. Schema artifacts were regenerated throughdb:kysely:genandsqlite:sessions-schema:gen; neither produced a tracked artifact delta.pnpm check:assertion-safety,pnpm check:max-lines-ratchet,pnpm check:line-cap-ratchet, andpnpm check:database-worker-ratchet. No ratchet baseline or environment-variable budget changed.git diff --checkpassed.scoped-clean, patch correct, no accepted/actionable P0–P2 findings.Focused validation (Node 26.10.0 / SQLite 3.53.4):
TMPDIR=/private/tmp/oc-sqlite2/tmp-trajectory-retention-index pnpm test src/trajectory/runtime-store.sqlite.test.ts --maxWorkers=1TMPDIR=/private/tmp/oc-sqlite2/tmp-trajectory-retention-index pnpm test src/state/openclaw-agent-db.test.ts --maxWorkers=1Wall times include worker compilation, input verification, and cleanup on the shared host. The two extended trajectory cases took 135 ms and 200 ms; the populated canonical-index repair case took 506 ms. The full database suite exceeds 30 seconds because it exercises real database admission, migrations, integrity failures, rollback, and lifecycle boundaries; this change reuses its existing fixture instead of adding another bootstrap. CI job seconds are pending at PR creation.
node scripts/worktree-setup.mjs gatewaypassed with frozen inputs, and both generated-schema verification commands passed. An initial preparation attempt overlapped test edits/asset generation and was rejected by build/compiler input guards before tests ran; settled-input preparation succeeded. The intentional pre-fix regression then failed on materialization/temp grouping, and both final full suites passed. No tests use performance thresholds.Landing CI repair: Exact-head CI run 37230944768 failed both new global byte-budget cases because the regression observer captured only
StatementSync.all(). CI used Node 24.19, whose existing executor consumesiterate(); the original local proof used Node 26.10. The same failure reproduced locally on Node 24.19. The test-only repair observes both methods while retaining aggregate-count, previous-query equivalence, covering-index plan, and exact retained-event assertions. No production behavior changed and no CI rerun was requested. The fullpnpm test src/trajectory/runtime-store.sqlite.test.ts --maxWorkers=1file then passed 30 tests on Node 24.19 (85.40 s wall time) and Node 26.10 (141.74 s), using the same isolated TMPDIR as above. The original CI file ran for 10.97 s and failed; new-head CI is pending after publishing the repair. A fresh independent autoreview of the repair was scoped-clean with no actionable P0–P2 findings.