Skip to content

perf(trajectory): scope write receipts and use the database worker - #170133

Closed
steipete wants to merge 5 commits into
mainfrom
dbasync/anchorreuse
Closed

steipete wants to merge 5 commits into
mainfrom
dbasync/anchorreuse

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Trajectory inserts, rolling trims and retention deletes advanced an unscoped SQLite write token even though they do not change session rows or transcript events. This discarded the actor's retained session/transcript facts and added worker reads on ordinary turns. Durable trajectory recording also retained a synchronous production fallback.

Certify trajectory-only DML with an empty session/transcript write scope and publish append receipts with the affected session, appended sequence range and removed-through sequence. Durable sinks now always use the existing worker; the synchronous fixture implementation lives in test support. A complete, current actor transcript can supply activity-summary batches using the same byte/message/omission policy as the worker. Cold, invalidated, truncated, admission-fenced and non-linear contexts retain the canonical worker read. No schema, retention policy, public SDK signature or update behavior changes.

This is the measured prerequisite, not completion of anchor/summary reuse. The live trace found a separate user-message rewrite after hydration on every warmed turn. That write correctly invalidates the replica because it does not yet publish an actor rewrite receipt. Standalone anchor and summary reads therefore remain at one each per turn. Follow-up #170199 carries the committed rewrite through the existing actor owner; this PR does not weaken invalidation to conceal that gap.

SQL and main-thread impact

One unchanged shared-harness v2 baseline/candidate pair, ten warmed turns each, through the campaign CPU gate. Baseline 1c12d0c8e6cc8154feea661a3bb3fec8058699c6; candidate b2bf9f9c01683a3b7b33446fd96010e5af0e9824. The measured production delta is unchanged; subsequent commits register a test pool and merge main at 22d6c639c169ea8d4f77126c03dd5281a4720e18. The sole merge conflict combined both lanes’ database-worker inventory classifications. These are turn-caused all-thread counts, excluding separately attributed background work.

Per warmed turn Base Candidate
Statements, median [min–max] 221.5 [215–232] 206 [206–211]
Requests, median [min–max] 52.5 [50–55] 46 [46–47]
Statements, mean 222.5 207.0
Requests, mean 52.5 46.2
MAIN statements 0 [0–0] 0 [0–0]
Standalone anchors, SQL / requests 10 / 1 10 / 1
Summary source, SQL / requests 7 / 1 7 / 1
Transcript hydration, SQL / requests 14 / 1.2 12 / 1

Observed mean reduction: 15.5 statements (7.0%) and 6.3 requests (12.0%) per warmed turn. Of that, auth-profile helper admission scheduling accounts for 8.5 statements and 1.7 requests per turn; excluding that unrelated variation leaves 7.0 statements and 4.6 requests per turn saved in session operations. Trajectory INSERT shapes and counts are unchanged (two per warmed turn). Trajectory inventory T1: 6 → 0 (three append operations and three retention operations); global inventory 481 → 475 against the original base, or 476 → 475 against CI's newer merge base.

Shared causal SELECT family, per turn Base Candidate
Exact-entry facts 6.0 4.0
Actor hydration 4.9 2.0
Entry-cache snapshot loads 0 0
Row facts 0 0
Watermark reads 1 1

Whole workload including startup/shutdown: statements 8,212 → 7,337; requests 1,561 → 1,259; MAIN 1,103 → 1,096. No shared causal family rises. Background SQL/min was 713.26 → 441.89; legacy-window SQL/turn was 290.9 → 238.6, with warmed windows lasting 57.539 → 42.907 seconds. Those wall-window/background numbers vary with host load; no latency claim. Both runs passed all 13 turns, native child, RPCs, cron, compaction and shutdown, with matching main/worker native calibration. Baseline logged a background skill-workshop read-fence error and two failed shutdown audit-prune lock attempts, outside warmed work; candidate had zero failed native calls.

Removed checks and accepted edges

  • Removed blanket session/transcript invalidation after trajectory-only DML. A trajectory append or trim no longer forces a transcript reread; a writer changing session/transcript tables must publish those scopes.
  • Removed the synchronous durable-sink fallback. Worker failure is surfaced through the existing worker settlement path.
  • Removed unconditional summary-source SQL when a complete current actor context is available. Eviction or invalidation still falls back to the worker; no new freshness probe or cross-thread handshake.

Retention's live data checks and existing execution-authority checks remain because an incorrect delete or unauthorized write affects real user data. Transcript append, rewrite, correlation changes, replacement, trim, rewind, compaction, reset/deletion and archive/restore retain their invalidation behavior.

Evidence

Basic changed-file oxlint, formatting and git diff --check passed. Codex review completed in the two allowed rounds; the final round had no actionable findings. The first round's sole byte-boundary finding was declined after verifying that SQL payloadBytes >= cap equals replica serializedBytes > cap including the JSONL newline; cap/cap+1 regression coverage compares both readers.

Added/extended regressions cover scoped trajectory append/trim/retention; nonactor transcript writer classes; archive/restore; actor append/accounting; summary byte limits, multibyte payloads, previous-summary invalidation, role-aware omission, 64-message batches and mutation isolation. Existing runtime proof checks zero main-thread trajectory SQL.

CI run 38297191033 passed production/test types, all core type stripes, type-aware lint, source contracts, Madge, Kysely, T1/dialect ratchets and build. Changed tests passed: transcript residency (3, 0.803 s summed test time), summary retry (28, 23.869 s), summary source (1 integrated case, 0.400 s), retention (21, 4.555 s), store (29, 5.276 s). Related writer (14), command export (6), actor replica (11), runtime (23) and tool-definition (7) tests passed. These are CI test durations, not isolated local per-file wall times; the relaxed workflow uses CI for broad proof.

CI exposed fixture assumptions after removal of the synchronous writer path. Summary, command-export and Codex trajectory fixtures now use the existing host-owned database fork pools; retention keeps its handle while advancing fake time. No assertions, timeouts or retries were weakened. The final one-line Codex pool registration passed the focused local file: 4/4 tests, 534.92 s command wall time (500.52 s Vitest, predominantly transformation); individual cases took 0.214, 9.649, 0.011 and 60.159 seconds. Exact-head CI 38299287921 passes production and test types, every lint stripe, source contracts, Madge/Kysely, T1/dialect ratchets, guards, docs, extension boundaries and build artifacts. The aggregate test gate is not claimed green: downloaded failures in untouched files reproduce the prior run's errors but are not all attributed to main. The authorized relaxed landing policy applies after the small fixture repair and passing focused proof.

Knip's initial parallel run passed the script scan but hit the unchanged 600-second timeout on larger scans. Running those same scans sequentially completed production in 482.545 s and full-tree in 514.797 s. Production found 34 unrelated UI export/type findings, exactly matched by rule/file/symbol in scheduled main dependencies, head c66da3d764b0b; no changed-owner finding. Full-tree found 22 symbols: 17 exact main diagnostic matches; the other five settings exports have identical source blobs on that main and were already removed by the newer main UI repair. The final merged-tree rerun at c1ea403ded45c486db723da5a98f3aa73c00481c (main 2b285c584aafc95f7d2f2dddb067e27691a656c0 plus candidate 9b5ecde) is clean: production 207.409 s, full-tree 336.633 s, both exit 0 with no unused-export entries. Inherited failures are handed to the campaign's red-main repair owner. The broader prior run also had unclassified failures in untouched files; they are not claimed to be proven inherited or green.

No update cell or SDK API diff is needed: update, Doctor, schema migration, plugin loading, service lifecycle and public SDK surfaces are unchanged. Landing follows the explicitly authorized relaxed CI policy, with mandatory static gates retained.

Aggregate change: 21 files, +730/−250 lines, including regressions, inventory and docs.

@clawsweeper

clawsweeper Bot commented Oct 12, 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 gateway Gateway runtime scripts Repository scripts size: L labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR scopes trajectory writes, routes durable recording through the database worker, and reuses complete actor transcripts for Activity recap batches.

Example: Session session-1 records two trajectory events after transcript hydration.

  • Before: Trajectory-only writes invalidate retained session and transcript facts.
  • After: Those facts remain reusable until a relevant session or transcript mutation invalidates them.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful measured performance work with meaningful owner-boundary coverage and no identified introduced defect; the reported conflict is a workflow blocker.
Proof confidence 🐚 platinum hermit (4/6) The supplied MEMBER classification exempts this maintainer-authored PR from the ordinary contributor proof gate; its full body reports Gateway baseline/candidate runs exercising worker trajectory persistence and explicitly discloses unchanged anchor and recap reads.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary chat turns repeat session and transcript database reads after unrelated trajectory recording.
Reason: The maintainer-authored direction addresses measured cost through existing owners and accurately limits its claims to the prerequisite delivered here.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored PR retains useful performance work beyond current main, with no introduced defect identified; GitHub still reports a merge conflict.

Priority: P2
Reviewed head: 3085ca481bf3df5def68c00f5756604e3d8d1b8b

Before merge

  • Complete next step - Resolve GitHub's reported merge conflict with main, preserving both append-scoping implementations' intent and main's projection receipts, then validate the affected resolution.

Findings

None.

Tests

  • Missing end-to-end proof: Base-fail/head-pass execution of the new regressions and shipped-flow use of the resident recap fast path are not established by the supplied measurements.
Agent review details

How this fits together

The Gateway retains committed session facts in its bounded actor replica; trajectory workers persist events, while Activity obtains recap inputs from complete resident context or the canonical transcript worker.

flowchart TD
  A[Chat turn] --> B[Session actor replica]
  A --> C[Trajectory worker]
  C --> D[Agent SQLite database]
  B --> E[Activity recap source]
  E --> F[Transcript worker fallback]
  F --> D
Loading

Technical review

Best possible solution:

Trajectory-only writes preserve actor facts through the existing receipt owner, while incomplete or invalidated recap context uses the canonical worker.

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

The introduced base leaves trajectory DML unscoped while actor validity depends on scoped write tokens; fetched main fixes append scoping but retains the other paths addressed here.

Is this the best way to solve the issue?

The patch repairs invalidation at its producer and shares recap selection policy without adding another cache owner or weakening transcript mutation checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 92f2a8c27337.

Provenance checked

  • Trajectory-driven replica invalidation keeps the original intent (perf(sessions): reuse committed transcript context during chat turns #169960: The predecessor conservatively invalidated retained facts and explicitly identified trajectory scoping as follow-up work.)
  • Activity recap selection keeps the original intent (0bc7491: Recap metadata, ancestry, and bounded pages share one snapshot; the extracted selector preserves that worker policy for resident reuse.)
  • Synchronous durable trajectory fallback changes intended behavior with a stated reason (5cf0047: The earlier worker migration retained native paths; this PR explicitly accepts worker-only durable sinks while retaining actor and fixture implementations.)
  • Trajectory retention keeps the original intent (fe43e10: Committed mutation reconciliation and candidate revalidation allow cleanup during sustained writes; those checks and retention policies remain intact.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Distinct work remains: Fetched main includes append scoping from perf(sessions): reuse actor projection receipts for history reads #170127 but retains the synchronous durable-sink fallback, unscoped retention deletion, and worker-only recap source. (src/trajectory/runtime-store.sqlite.ts:164, 92f2a8c27337)
  • Producer-owned invalidation: Append and trim certify an empty session/transcript write scope and return the affected session, appended sequence range, and removal boundary; the execution worker publishes that receipt. (src/trajectory/runtime-store.sqlite.ts:107, 3085ca481bf3)
  • Resident read and fallback: Resident recap reads require complete linear context, matching session identity, current physical identity and scoped token, and no transcript admission fence; other contexts retain the canonical worker reader. (src/gateway/session-activity-summary-source.ts:65, 3085ca481bf3)
  • Independent boundary expectations: Added coverage compares both recap readers against fixed byte-limit, multibyte, omission, stale-summary, batch-size, and mutation-isolation expectations; existing residency coverage extends transcript mutation and archive/restore invalidation. (src/gateway/session-activity-summary-source.test.ts:55, 3085ca481bf3)
  • Accepted worker cutover and measurement: The maintainer-authored body explicitly accepts worker-only durable sinks and reports a Gateway baseline/candidate comparison saving 7.0 session-operation statements and 4.6 requests per warmed turn after excluding unrelated auth variation; unchanged anchor and recap reads are disclosed. (3085ca481bf3)
  • Current merge blocker: GitHub reports mergeable=false and mergeable_state=dirty for the reviewed head, so the previous review's conflict-resolution action remains applicable. (3085ca481bf3)

Likely related people:

  • Peter Steinberger: Raw commit 09242dc adds src/trajectory/runtime-store.sqlite.ts:147 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-store.sqlite.ts)

PR surface

Source +53, Tests +407, Docs +16, Other +7. Total +483 across 21 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 10 279 226 +53
Tests 8 412 5 +407
Docs 2 88 72 +16
Config 0 0 0 0
Generated 0 0 0 0
Other 1 8 1 +7
Total 21 787 304 +483

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This reduces repeated database work during ordinary chat turns without evidence of an urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-12T19:11:36.478Z sha 93098f6 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T19:29:03.974Z sha b2bf9f9 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T20:20:52.454Z sha ed573c1 :: needs changes before merge. :: none
  • reviewed 2026-10-12T20:51:33.311Z sha 3085ca4 :: needs changes before merge. :: none

Reviewed October 12, 2026, 5:49 PM ET / 21:49 UTC (Revision 5).

@steipete steipete changed the title perf(sessions): reuse transcript anchors and activity-summary sources perf(trajectory): scope write receipts and use the database worker Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 12, 2026
steipete added a commit that referenced this pull request Oct 12, 2026
…170199)

Scope trajectory receipts to the affected session and sequence range, and run durable trajectory writes through the database worker. Preserve bounded actor transcript context after committed metadata rewrites so anchors, hydration, and activity summaries can reuse authoritative resident facts.

Keep canonical reads for cold, invalidated, incomplete, or changed transcript context. Cover committed and rolled-back rewrites, writer invalidation, summary batching, and trajectory retention.

Includes the trajectory prerequisite from #170133.
@steipete

Copy link
Copy Markdown
Contributor Author

Included in #170199, which combines the scoped trajectory receipts and worker-only durable writes with committed transcript rewrite reuse. Closing this prerequisite after verifying that the combined PR is merged.

@steipete steipete closed this Oct 12, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…penclaw#170199)

Scope trajectory receipts to the affected session and sequence range, and run durable trajectory writes through the database worker. Preserve bounded actor transcript context after committed metadata rewrites so anchors, hydration, and activity summaries can reuse authoritative resident facts.

Keep canonical reads for cold, invalidated, incomplete, or changed transcript context. Cover committed and rolled-back rewrites, writer invalidation, summary batching, and trajectory retention.

Includes the trajectory prerequisite from openclaw#170133.
@RomneyDa
RomneyDa deleted the dbasync/anchorreuse branch October 22, 2026 05:32
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 gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant