Skip to content

perf(trajectory): sweep retention from a covering index instead of regrouping every event - #165074

Merged
steipete merged 2 commits into
mainfrom
steipete/sqlite-trajectory-retention-index
Oct 4, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/sqlite-trajectory-retention-index

Conversation

@steipete

@steipete steipete commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

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_run index 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

  • Production: Read-only measurements from team.openclaw.ai on 2026-10-04 recorded trajectory.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.
  • Component benchmark supplied by the audit: 241,697 synthetic events across about 964 sessions, 1% null run IDs, 2,034-byte JSON bodies, about 469 MiB logical payload / 946 MiB table storage. Four aggregate runs measured 407–453 ms before, 31–40 ms after (about 10–15×); all 3,836 groups were equal. This is a component measurement, not end-to-end production throughput. Actual run distribution, payloads, storage locality, and first-run outliers matter.
  • Write/storage tradeoff: Replacement index 7,712,768 bytes versus 6,598,656 bytes, about +1.06 MiB / +17% for this index. It replaces the old index. A warm 320-row insert/rollback probe was roughly 0.7 ms for both shapes, excluding commit, eviction, and checkpoint amplification.
  • Statements per append: One retention aggregate per sweep before and after; zero on ordinary appends inside the cadence window. Sequence lookup, inserts in batches of 32, suffix trimming, and deletes in batches of 100 runs are unchanged. The regression captures exactly one aggregate and requires a single covering-index scan, without temporary grouping or table-body access.
  • Regression proof: The new plan assertion failed against the original implementation with MATERIALIZE event_sizes and USE 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 unchanged user_version; its setup moved to the existing drift helper to keep the over-cap test file smaller.
  • LOC (task delta from the branch merge base): production +5 / −16 = −11; tests and test support +104 / −23 = +81; docs +45. Current origin/main has advanced, so unrelated changes on main are excluded from these task counts. Schema artifacts were regenerated through db:kysely:gen and sqlite:sessions-schema:gen; neither produced a tracked artifact delta.
  • Checks: Targeted oxfmt and oxlint passed, as did pnpm check:assertion-safety, pnpm check:max-lines-ratchet, pnpm check:line-cap-ratchet, and pnpm check:database-worker-ratchet. No ratchet baseline or environment-variable budget changed. git diff --check passed.
  • Autoreview: scoped-clean, patch correct, no accepted/actionable P0–P2 findings.

Focused validation (Node 26.10.0 / SQLite 3.53.4):

Command Result Wall time
TMPDIR=/private/tmp/oc-sqlite2/tmp-trajectory-retention-index pnpm test src/trajectory/runtime-store.sqlite.test.ts --maxWorkers=1 30 passed 170.28 s
TMPDIR=/private/tmp/oc-sqlite2/tmp-trajectory-retention-index pnpm test src/state/openclaw-agent-db.test.ts --maxWorkers=1 93 passed, 2 skipped 157.48 s

Wall 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 gateway passed 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 consumes iterate(); 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 full pnpm test src/trajectory/runtime-store.sqlite.test.ts --maxWorkers=1 file 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.

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.
@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 4, 2026
@steipete
steipete marked this pull request as ready for review October 4, 2026 20:08
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 4, 2026, 4:41 PM ET / 20:41 UTC (Revision 2).

ClawSweeper review

What this changes

Trajectory, 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
Reviewed head: 27bd4d82bb78c8101427b0a8e7e048836a85d805

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with meaningful equivalence, retention, and upgrade coverage and no concrete correctness finding.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository State identifies a MEMBER-authored internal optimization, so ordinary external-contributor proof is exempt. Reported SQLite benchmarks and append regressions support the changed aggregate; populated old-index admission verifies compatible repair without row conversion or a version bump.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies a MEMBER-authored internal optimization, so ordinary external-contributor proof is exempt. Reported SQLite benchmarks and append regressions support the changed aggregate; populated old-index admission verifies compatible repair without row conversion or a version bump.
Evidence reviewed 9 items Pinned introduced changes: Reviewed the merge-base-to-head delta. Production changes replace the canonical run index and remove aggregate staging; retention selection, deletion, cadence, transaction boundaries, and authority checks remain unchanged.
Still necessary on current main: Fetched main still materializes event_sizes before grouping; its canonical trajectory index remains partial on session_id, run_id, and seq. The requested covering-index optimization is absent.
Latest release retains the old index: The latest supplied release, v2026.9.8, defines the old partial trajectory index; it does not contain this index replacement.
Findings None None.
Security None None.

How this fits together

Agent 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
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -11, Tests +81, Docs +45. Total +115 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 2 5 16 -11
Tests 3 104 23 +81
Docs 2 45 0 +45
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 154 39 +115

Review metrics

Metric Value Why it matters
Aggregate performance 407–453 ms before; 31–40 ms after; 3,836 groups equal The reported component benchmark supports the optimization without claiming an end-to-end production speedup.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded database performance improvement with measured aggregate savings and preserved retention semantics.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository State identifies a MEMBER-authored internal optimization, so ordinary external-contributor proof is exempt. Reported SQLite benchmarks and append regressions support the changed aggregate; populated old-index admission verifies compatible repair without row conversion or a version bump.

Evidence

What I checked:

  • Pinned introduced changes: Reviewed the merge-base-to-head delta. Production changes replace the canonical run index and remove aggregate staging; retention selection, deletion, cadence, transaction boundaries, and authority checks remain unchanged. (src/trajectory/runtime-store.sqlite.ts:279, 27bd4d82bb78)
  • Still necessary on current main: Fetched main still materializes event_sizes before grouping; its canonical trajectory index remains partial on session_id, run_id, and seq. The requested covering-index optimization is absent. (src/trajectory/runtime-store.sqlite.ts:279, f98ca0d0a1fa)
  • Latest release retains the old index: The latest supplied release, v2026.9.8, defines the old partial trajectory index; it does not contain this index replacement. (src/state/openclaw-agent-schema.sql:652, fc23bc864e45)
  • Existing atomic admission owner: Same-version writable admission invokes canonical index repair. That owner constructs a probe and replacement inside a savepoint, validates integrity and schema, and rolls back failed repair without rewriting event rows. (src/infra/sqlite-index-schema.ts:146, 27bd4d82bb78)
  • Existing-state compatibility coverage: The extended admission regression seeds the previous partial index with null and named runs, reopens through the real database owner, and verifies canonical shape, unchanged user_version, and unchanged event rows. The captured body reports the full database suite passing. (src/state/openclaw-agent-db.test.ts:2946, 27bd4d82bb78)
  • Retention regression and Node compatibility: The append fixture compares every aggregate group with the previous query, requires covering access without temporary grouping, and checks exact retained events at two byte boundaries. Observing both all() and iterate() matches the existing executor’s Node-version branches. The captured body reports all 30 trajectory tests passing on Node 24.19 and 26.10 after the observer repair. (src/trajectory/runtime-store.sqlite.test.ts:341, 27bd4d82bb78)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • SunnyShu0925: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-04T20:13:54.359Z sha a4725bb :: needs maintainer review before merge. :: none

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.
@steipete
steipete merged commit 97a770b into main Oct 4, 2026
135 of 136 checks passed
@steipete
steipete deleted the steipete/sqlite-trajectory-retention-index branch October 4, 2026 20:53
@steipete

steipete commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Oct 4, 2026
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).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
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).
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 P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant