Skip to content

perf(trajectory): converge retention during sustained appends - #165678

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-trajectory-retention-convergence-20260919
Oct 5, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-trajectory-retention-convergence-20260919

Conversation

@steipete

@steipete steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes global trajectory cleanup being starved by continued event appends. The database-wide revision handshake invalidated every historical selection, leaving expired events and bytes above the default budget. Related: #165274.

User Impact

Cleanup makes progress during managed event appends while preserving whole runs, current-session protection, oldest-first ordering, the 14-day age rule, and the default 512 MiB budget. No schema, stored counter, trigger, configuration, durability, or upgrade migration changes are introduced by this PR.

Why This Change Was Made

The read worker aggregates run summaries once per sweep. The retention owner reconciles committed session summaries and selects a bounded batch before writer admission. Each deletion transaction revalidates only its selected candidates: at most 16 runs / 10 MiB, preserving the existing oversized-whole-run exception.

Sweep-scoped mutation receipts account for appends and concurrent trims without double counting changes that overlap snapshot creation. Unknown foreign or unaccounted local mutations require a read-worker refresh; one refresh is allowed before deferring to the next append. Lease revocation and native close/replacement invalidate the receipts. Completion follows the deleting commit's remaining byte/age facts, without waiting for a quiet reader pass. Both callers use this owner; the global-revision handshake is removed. SQL-generated byte-order keys preserve SQLite BINARY ties in UTF-8 and UTF-16 stores.

Production LOC: +201 (437 additions, 236 deletions), excluding tests, test support, and docs. The approved schema-free freshness contract requires post-commit receipts, snapshot reconciliation, and lifecycle/freshness fencing. No parallel cleanup implementation or persisted counter is retained.

Measurement

Both final fixtures started with 700 MB of logical events across 450 sessions and ran sustained 50/100/200 events/s for 30 minutes. Every one of the 30 pressure sweeps at each scale completed under budget, with zero invalidations, zero freshness refreshes, and exact retained-row equality against a single-pass reference.

Fixture Prior v5 max deletion hold Final max deletion hold Prior v5 maximum settlement Final maximum settlement
200K × 3,500 bytes 82.554 ms 15.871 ms 1.333 s 0.276 s
20M × 35 bytes 5,023.059 ms 127.108 ms No completed sweep in 30 min 9.722 s

The full 20M maximum was 3.748 ms SQL + 123.360 ms COMMIT/checkpoint, with no overlapping GC. Deletion p99 was 7.023 ms. The maintainer accepted this result on 2026-10-05: the bounded SQL work meets the lane's intent; WAL checkpoint scheduling belongs to its existing owner. All hold measurements include COMMIT, and the measured 127.108 ms is not presented as below 100 ms.

Follow-up: WAL checkpoint scheduling during retention deletes.

These are recorded campaign results, not controlled same-host speedup claims. Final runs used Testbox / Node v24.19.0; prior v5 20M evidence used a shared Linux rig / Node 26.8.1. Maximum final append holds were 25.920 ms at 200K and 95.050 ms at 20M. The original starvation baseline's append maximum was 57.224 ms with a different arrival clock/host, so these measurements do not establish append-latency nonregression.

Resolved maintainer decision from #165274

ClawSweeper asked:

Must retention demonstrate sustained-write progress and convergence to the default 512 MiB target before merge, or may cleanup depend on quiet periods?

Its recommendation was:

Establish retention progress: Require production-boundary evidence of progress during sustained writes and convergence to the default budget before accepting the tradeoff.

Resolved: both final-source 30-minute campaigns demonstrate progress and convergence during continued writes. The original 20M starvation baseline invalidated all 1,100 selections, deleted no historical rows, and ended 208,369,770 bytes over budget.

Evidence

Provider for all final remote validation: blacksmith-testbox, profile openclaw-check.

Proof / command Lease Result
Four focused suites: node scripts/run-vitest.mjs src/trajectory/runtime-store.sqlite.test.ts src/trajectory/runtime-retention.sqlite.test.ts src/trajectory/runtime-store-writer.test.ts src/trajectory/runtime-retention.test.ts --maxWorkers=1 tbx_01m463bfs4m049dztkd491dtzb 56 passed, 79.93 s wrapper wall including cold worker compilation.
Touched suites rerun on rebased cd326f915580 with the same command tbx_01m46eksxb2eyb5eh7aw72fmtn 56 passed, 50.32 s wrapper wall; 75.786 s remote command, exit 0.
Targeted node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json <12 changed TS files> --threads=1 tbx_01m463bfs4m049dztkd491dtzb 0 warnings/errors.
node scripts/check-changed.mjs --staged Same validation lease Core and all 27 test type graphs passed; failed only on ten inherited unused exports reproduced identically on untouched base. 1,939.103 s command.
Baseline attribution and remaining native-schema/storage/import-cycle/webhook/pairing guards Same validation lease Identical baseline findings; all remaining guards passed. Candidate restored and hash-verified. 288.788 s command.
RIG_ROWS=200000 RIG_ROW_BYTES=3500 RIG_LIVE_EVENT_BYTES=3500 RIG_APPEND_INTERVAL_MS=5 RIG_RATE_CLOCK=elapsed RIG_DURATION_SECONDS=1800 bash .local/lane455/run-rig.sh candidate tbx_01m466anq8e314rm5m87x9g770 1,800.080 s pressure; 210,003 pressure events + 1 final-drain event; exact reference, 9,681 groups.
RIG_ROWS=20000000 RIG_ROW_BYTES=35 RIG_LIVE_EVENT_BYTES=0 RIG_APPEND_INTERVAL_MS=250 RIG_RATE_CLOCK=elapsed RIG_DURATION_SECONDS=1800 bash .local/lane455/run-rig.sh candidate tbx_01m4689bx64k729gst2dwvcbwc 1,800.099 s pressure; 209,988 pressure events + 16 final-drain events; exact reference, 77,674 groups.

A native-owner negative control records one full-store writer-held aggregate in v5 and zero in the candidate. Restoring the former JavaScript comparator makes the Unicode tie regression fail for the intended retained-row difference; the candidate passes. The original starvation and settlement regressions also failed on their preceding implementations. Independent detached P0–P2 review completed scoped-clean, with no actionable findings. The subsequent rebase changed no trajectory or relevant SQLite implementation source; its schema-file delta only adds unrelated voice-cache indexes.

The inherited export findings concern BranchSummaryResult, renderRootHelpText, stripEnvelopeFromMessage, and seven media-default constants. They were neither changed nor suppressed here.

Benchmarks were pinned to base 0043be77a33e; publication was rebased onto cd326f915580. Source and exact executed-driver hashes were verified. The rig exercises actual append/retention owners with a separate reader worker and canonical schema/index/WAL policy; it does not measure Gateway broker latency. Unknown mutations outside the receipt owner may conservatively refresh/defer. At pressure stop, subsequent writes had refilled 2,528,486 bytes above target on the 20M fixture; every pressure-sweep commit receipt met the budget, and the final quiet sweep reached 536,867,279 bytes with zero eligible expired runs. This preserves hourly retention semantics.

@clawsweeper

clawsweeper Bot commented Oct 5, 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: XL labels Oct 5, 2026
@steipete
steipete enabled auto-merge (squash) October 5, 2026 16:52
@clawsweeper

clawsweeper Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 12:55 PM ET / 16:55 UTC.

ClawSweeper review

What this changes

Trajectory cleanup reconciles committed appends with a sweep snapshot and revalidates small deletion batches so historical events can expire during continued writes.

Merge readiness

⛔ Blocked before merge - 3 items remain

This remains useful work: current main still has the retention starvation mechanism, and the recorded campaigns demonstrate convergence during sustained appends. One introduced lifecycle defect needs repair.

Priority: P2
Reviewed head: bf83c3d0eb42d9ee3514aa6978ac8d77ac3c32d6

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong production-boundary convergence evidence supports the repair, but completed sweep snapshots currently outlive their intended lifecycle.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The captured final-source Testbox campaigns exercise actual append, reader, and retention deletion owners on canonical SQLite stores under sustained writes, reporting under-budget completion and exact retained-row equality. The results cover convergence, while explicitly excluding Gateway broker latency and controlled append-latency nonregression. No stored-data contract changes require migration; the separate snapshot cleanup finding remains blocking.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured final-source Testbox campaigns exercise actual append, reader, and retention deletion owners on canonical SQLite stores under sustained writes, reporting under-budget completion and exact retained-row equality. The results cover convergence, while explicitly excluding Gateway broker latency and controlled append-latency nonregression. No stored-data contract changes require migration; the separate snapshot cleanup finding remains blocking.
Evidence reviewed 9 items Pinned introduction and merge ownership: Inspected the merge-base-to-head production changes. The raw test-merge commit records the fetched main parent followed by the exact PR head, and its retention delta preserves the introduced changes.
Current main still requires the fix: Fetched main rejects deletion when any captured database mutation revision or foreign data version changes. It does not contain the receipt reconciliation and sweep cursor introduced here.
Latest release comparison: The v2026.9.8 source invokes global retention during append processing; it does not already implement this sustained-write convergence repair.
Findings 1 actionable finding [P2] Release the sweep snapshot when its lease is revoked
Security None None.

How this fits together

Trajectory stores diagnostic events from agent runs in each agent’s SQLite database. Retention removes historical runs according to age and byte limits while sharing the database writer with other agent operations.

flowchart TD
 A[Agent run events] --> B[Append and trim session]
 B --> C[Committed session receipts]
 D[Reader snapshot] --> E[Retention sweep owner]
 C --> E
 E --> F[Revalidate bounded batch]
 F --> G[Delete historical runs]
 G --> E
Loading

Before merge

  • Release the sweep snapshot when its lease is revoked (P2) - After a sweep finishes, both callers only set the lease to zero. This WeakMap entry still owns queue, sessions, and receipts, and the queue retains even runs already deleted from SQLite. execution.release() can keep the native connection cached for 30 minutes, so a large sweep followed by no further trajectory append retains its entire snapshot throughout that interval; unrelated database activity can extend it. Explicitly retire the matching sweep on completion/cancellation in both paths instead of waiting for another append or native disposal.
  • Resolve merge risk (P1) - Large completed sweeps retain their run summaries until another trajectory append or native connection disposal, extending heap pressure across the connection’s 30-minute idle lifetime or longer while borrowed.
  • Complete next step (P2) - Release matching sweep state during synchronous and worker cleanup, including cancellation, and verify release without closing the native connection.

Findings

  • [P2] Release the sweep snapshot when its lease is revoked — src/trajectory/runtime-retention.sqlite.ts:145-146
Agent review details

Security

None.

PR surface

Source +201, Tests +437, Docs +18. Total +656 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 437 236 +201
Tests 5 872 435 +437
Docs 1 23 5 +18
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 1332 676 +656

Review metrics

Metric Value Why it matters
Sustained-write convergence 60/60 pressure sweeps under budget across two 30-minute campaigns The recorded production-owner campaigns directly address the convergence gap left by the merged predecessor.

Root-cause cluster

Relationship: canonical
Canonical: #165678
Summary: This PR owns the sustained-write convergence follow-up to the already-merged writer-latency optimization.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Retire completed sweep snapshots (recommended)
    Add owner-scoped sweep retirement to synchronous and worker cleanup, preserving cancellation and failed-cleanup custody while releasing the matching snapshot.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Release the matching retention sweep's in-memory queue, session maps, and receipts when synchronous or worker cleanup completes or cancels; guard retirement by sweep identity so older cleanup cannot remove a newer sweep, and preserve existing admission and failed-cleanup custody.

Technical review

Best possible solution:

Keep the receipt-based convergence design and explicitly retire each sweep’s in-memory state when either caller finishes or cancels it, without retiring a newer sweep.

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

Yes: current main’s database-wide revision check explains starvation during sustained writes, and the captured campaign records the failing baseline. The introduced snapshot-retention defect is source-proven; this read-only review executed no target code.

Is this the best way to solve the issue?

Yes, with the lifecycle repair: reconciling committed session summaries and revalidating bounded candidates addresses starvation through the existing owner without changing stored data or retention policy.

Full review comments:

  • [P2] Release the sweep snapshot when its lease is revoked — src/trajectory/runtime-retention.sqlite.ts:145-146
    After a sweep finishes, both callers only set the lease to zero. This WeakMap entry still owns queue, sessions, and receipts, and the queue retains even runs already deleted from SQLite. execution.release() can keep the native connection cached for 30 minutes, so a large sweep followed by no further trajectory append retains its entire snapshot throughout that interval; unrelated database activity can extend it. Explicitly retire the matching sweep on completion/cancellation in both paths instead of waiting for another append or native disposal.
    Confidence: 0.95

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 122967ae9f07.

Labels

Label changes:

  • add P2: This is a bounded retention reliability repair with demonstrated convergence benefits and no evidence of an urgent user outage.
  • add merge-risk: 🚨 availability: The introduced full-sweep snapshot survives cleanup on cached native connections, creating avoidable memory pressure that ordinary correctness checks may miss.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The captured final-source Testbox campaigns exercise actual append, reader, and retention deletion owners on canonical SQLite stores under sustained writes, reporting under-budget completion and exact retained-row equality. The results cover convergence, while explicitly excluding Gateway broker latency and controlled append-latency nonregression. No stored-data contract changes require migration; the separate snapshot cleanup finding remains blocking.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.

Label justifications:

  • P2: This is a bounded retention reliability repair with demonstrated convergence benefits and no evidence of an urgent user outage.
  • merge-risk: 🚨 availability: The introduced full-sweep snapshot survives cleanup on cached native connections, creating avoidable memory pressure that ordinary correctness checks may miss.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured final-source Testbox campaigns exercise actual append, reader, and retention deletion owners on canonical SQLite stores under sustained writes, reporting under-budget completion and exact retained-row equality. The results cover convergence, while explicitly excluding Gateway broker latency and controlled append-latency nonregression. No stored-data contract changes require migration; the separate snapshot cleanup finding remains blocking.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/trajectory/runtime-store.sqlite.test.ts src/trajectory/runtime-retention.sqlite.test.ts src/trajectory/runtime-store-writer.test.ts src/trajectory/runtime-retention.test.ts --maxWorkers=1.
  • [P1] git diff --check.
  • [P1] Verify through owner-boundary lifecycle evidence that completion and cancellation release the matching snapshot without native disposal and cannot retire a newer sweep.

What I checked:

  • Pinned introduction and merge ownership: Inspected the merge-base-to-head production changes. The raw test-merge commit records the fetched main parent followed by the exact PR head, and its retention delta preserves the introduced changes. (src/trajectory/runtime-retention.sqlite.ts:120, bf83c3d0eb42)
  • Current main still requires the fix: Fetched main rejects deletion when any captured database mutation revision or foreign data version changes. It does not contain the receipt reconciliation and sweep cursor introduced here. (src/trajectory/runtime-retention.sqlite.ts:184, 122967ae9f07)
  • Latest release comparison: The v2026.9.8 source invokes global retention during append processing; it does not already implement this sustained-write convergence repair. (src/trajectory/runtime-store.sqlite.ts:137, fc23bc864e45)
  • Production-boundary convergence evidence: The complete captured body, source revision 302049cfe28950fefa2de1632f209960b9c015f9e957abbbb58cffd9fba8961c, records two final-source Testbox campaigns using actual append and retention owners, a separate reader worker, and canonical SQLite schema/index/WAL policy. Both started with 700 MB across 450 sessions and exercised 50/100/200 events per second for 30 minutes; all 60 pressure sweeps finished under budget with exact reference row equality and no invalidations or refreshes. This proves the changed retention path, without claiming Gateway broker latency or controlled same-host append-latency nonregression. (src/trajectory/runtime-retention.sqlite.ts:213, bf83c3d0eb42)
  • Predecessor discussion supports this follow-up: The human post-merge comment on perf(trajectory): move global retention off the append writer #165274 explicitly recognizes the convergence gap and calls for sustained-write measurement and candidate-specific revalidation with carried sweep progress. The predecessor is merged and addresses writer latency; it does not supersede this repair.
  • Completed sweep state remains retained: The new sweeps WeakMap retains a full run queue and session maps. Both cleanup paths only revoke the shared lease; deletion of the WeakMap entry occurs on a later currentSweep call, replacement sweep, or native disposal. Deleted runs remain referenced by the queue. Consequently, finishing a sweep does not release its snapshot. (src/trajectory/runtime-retention.sqlite.ts:145, bf83c3d0eb42)

Likely related people:

  • Peter Steinberger: Raw commit 09242dc adds src/trajectory/runtime-retention.sqlite.ts:42 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 09242dc32ae1; files: src/trajectory/runtime-retention.sqlite.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Retire matching sweep state on completion and cancellation in both callers, and verify that cleanup releases the snapshot while the native connection remains open.

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.

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 size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant