Skip to content

perf(sessions): publish entry writer postimages without rereading - #169090

Merged
steipete merged 19 commits into
mainfrom
dbasync/t1entry-postimages
Oct 11, 2026
Merged

steipete merged 19 commits into
mainfrom
dbasync/t1entry-postimages

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session entry writes reload window provenance, participant projections, membership, and committed metadata for publication even though the synchronous writer already owns their final values.

User Impact

Reduce SQLite work in ordinary session patches, turn commits, and lifecycle changes while preserving the exact persisted entry and its final side-table facts.

Why This Change Was Made

The existing entry writer returns a detached persisted entry and fills a transaction-local postimage map with its window, participant, membership, and Board facts. Patch/turn/lifecycle publication consumes that map. Owner assignment, alias transfer, archival, and deletion update or remove the same facts as they write, so publication sees the final values. Window postimages preserve retained creation/ownership columns and consume the transcript owner's staged watermark. Small window facts use a prefixed scalar LEFT JOIN in the existing read and are assembled in TypeScript. Existing size-limiting SQL JSON projections stay in SQL.

The callback patch path reads its current commit input once and retains the real compare-and-swap across awaited callback code. Closed reducers still read their current input. The old raw-row fast-check, implicit WeakMap, repeated participant/publication reads, and transaction-wide mutation-revision checks are removed. An actual no-op is reported by the writer's effect facts, not a freshness query.

Removed checks and accepted edges:

  • Raw-row comparison before hydrated callback CAS: one current hydrated read now owns comparison and publication facts; participant changes during the callback remain accepted and published.
  • Window/entry postimage revision checks: the synchronous transaction's owner facts are authoritative. Arbitrary raw SQL or a serializer callback mutating the same facts between selection and publication is unsupported; real owner writes update their facts.
  • Re-reading final metadata, participants, membership and Board state: final receipts replace these queries; subsequent independent operations receive their own current input.
  • Revalidating removals after internal lifecycle callbacks: the selected removal is authoritative through the synchronous commit; an internal callback that mutates a separately selected removal is no longer re-detected.
  • Global mutation checks that force cold snapshot rewrites: unrelated writes no longer trigger rewrites; explicit changed snapshots still persist exactly.

The generic publication read remains for owners that do not supply a complete postimage map (for example recovery and manual compaction). This removes the superseded implicit writer cache while retaining their current final-read contract. No schema, durability, retention, permission, SDK, dependency, update, plugin-loading, or service-lifecycle change. Migration test edits only remove assertions for the deleted raw-row helper; migration behavior is unchanged.

Evidence

Measured base ebdc7d54c0842d96c4bb2fb2bb4be4758f07f255 against head 53e5c9c1b8b38da79b286d74df90470da7a5157c on one remote host, with three alternating pairs (M,C,M,C,M,C). Both exact refs were rebuilt (base 79.550 seconds, candidate 80.525 seconds). The main integration was conflict-free and changed none of this PR's 42 files.

Scope Base statements Candidate statements Base requests Candidate requests MAIN statements
Warmed turn, median [min–max] 338.7 [336.5–339.8] 326.1 [324.8–328.1] 90.5 [89.7–90.5] 90.9 [90.6–91.4] 0 → 0
First turn, median [min–max] 1253 [1141–1257] 1213 [1020–1226] 210 [207–211] 202 [191–205] 61 [61–61] → 61 [52–61]
Entire workload, median [min–max] 9846 [9841–9851] 9593 [9555–9599] 1740 [1731–1741] 1740 [1729–1742] 2054 [2048–2054] → 2054 [2054–2054]

This removes 12.6 warmed statements per turn (3.72%). Warmed duration ratio is 0.995. First-turn statements and requests fall; whole-workload statements fall by 253 and requests are unchanged. The +0.4 warmed requests (+0.442%) pass the noise-floor rule: unchanged background indexing families rise 9.1 → 9.9 requests while other families fall 81.1 → 81.0 (medians are not additive). Whole-workload background requests remain 166 → 166, and total requests remain 1740 → 1740. The unchanged facts-worker entry-read operation rises only +0.1 warm and falls by one over the whole workload. This is timing redistribution, not a new request path. No extra pair was needed.

Other phase, median Statements, base → candidate Requests, base → candidate
Boot 2032 → 2032 66 → 66
Connect 872 → 868 42 → 41
Second session / spawn 1401 → 1352 332 → 333
Control plane 36 → 22 11 → 7
Cron 574 → 570 128 → 134
Compaction 180 → 175 33 → 33
Shutdown 102 → 102 14 → 14
Startup through first turn 4161 → 4111 318 → 307
Control + cron 612 → 592 141 → 141

Cron's request increase is offset in the adjacent control window; all other phase increases satisfy the campaign tolerance. Both first-turn totals and entire-workload totals pass the raw-turn rules.

Removed SQL family Statements saved per warmed turn
Window provenance 7
Entry snapshots 3
Committed entry query 4
Participant projection 1
Direct owner total 15

By operation, session.entry.patch.commit falls 55 → 43 statements per warmed turn (12 saved) (provenance 6, snapshot 3, committed query 3); session.lifecycle.project falls 18 → 15 (provenance, query and participant projection: 1 each). Whole-workload session.entries.replace falls 93 → 77 statements.

All six accounting and dual-isolate calibration validations pass. A copied harness retains the previously diagnosed spawn-parent terminal adapter, but none of these six samples used it: all parents and children completed normally, with zero warmed SQL errors. The adapter never skips child completion, remaining phases, shutdown or accounting. Original/copied runner SHA-256: 1de5109a7b89eaf8c10ef943bde724a89bd44772b7d70419bd344caf18d92cd1 / b7766246f79c02eb445e3194b47488ba5cd1a39d6c8282211b7643ce17fbd47e. The shared harness is unchanged.

T1 inventory call sites (not per-turn counts): changed owners 48 → 47, all session files 371 → 370, repository 616 → 615. The removed site is the superseded raw snapshot read. T1 is not zero: synchronous SDK/opaque callback contracts, inactive incognito paths, cross-store native atomicity, and durable Gateway creation/delivery/subagent/sharing lookups remain migration debt. Sharing authorization remains a real authority boundary. Doctor/migration artifact copies are offline exceptions; this PR does not relabel runtime modules as worker-only.

Owner proof covers writes, participants, exact/canonical replacement, deletion, maintenance, ACP resume, atomic initialization, incognito registry state, and turn commits. The final changed regression/turn run passes 5 files/37 tests (pnpm test <files> --maxWorkers=1, 65.517 seconds command time / 62.36 seconds Vitest). The complete six-case replacement-publication file passes after the batch repairs. Earlier unchanged-owner coverage includes 16 files/155 tests and 12 files/107 infrastructure tests, plus the affected owner reruns. Proof is reused only where source inputs are unchanged. Changed tests and tests mocking changed exports are covered; CI seconds were not separately benchmarked.

The two batch regressions were red on the prior implementation and green after repair: repeated exact-key replacements restore the old prompt in both publication and reopened storage; different keys sharing a physical window preserve Gmail exclusion provenance in the final history projection. Each replacement advances transaction-local entry and physical-window facts from the preceding writer receipt. Serialized snapshot strings are reused rather than parsing/serializing retained prompt bodies again.

Final remote changed-file static proof: core types, type-aware lint over all 39 changed TypeScript files, formatting, line/T1/dialect ratchets, export-name collisions and Madge pass apart from the inherited entry-store max-lines rule (733 versus base 739; limit 700). Knip is clean. Root-tooling types pass (67.294 seconds). The root-scripts check reports byte-identical baseline/candidate TS2339 diagnostics in test/scripts/managed-child-process.windows.test.ts:83 for the removed stopGatewayProcess helper (75.015 / 70.504 seconds); neither file nor owner is changed by this PR. No PR-caused static failure is bypassed. The remote check:changed plan also covers assertion safety, mock-export contracts, plugin boundaries and source-contract guards. No SDK API diff or published-driver update cell applies: this PR does not change the SDK surface, schema/migration behavior, update, Doctor, plugin loading or service lifecycle.

Integrated-head CI retains two known chat admission-authority failures, an unrelated Windows process-helper test type failure, and a UI chat-panel layout timeout. Admission failures reproduce on the baseline and preserve the real security checks; the UI layout timeout is outside this PR and no fix is claimed. The Windows helper failure is independently compared on both refs below. These are disclosed under the authorized relaxed landing policy. The previous UI type/Knip and canonical/Gateway fixture failures were resolved by integrating main. The missing authored Evidence heading is corrected here. No green overall CI claim is made.

Independent Codex autoreview ran twice. The cold-cache receipt finding was fixed; subsequent real batch-data issues and static repairs were inspected and covered by focused proof within the two-round limit. No extra review round was run.

Final diff: 42 files, +1139/-987; production +805/-630, tests +333/-356, other +1/-1. Transcript initialization moved into its own worker module to keep the dispatcher within its line limit. The mock-isolation baseline shrinks by one resolved factory.

Release-note context: reduce redundant session-entry SQLite reads while preserving exact committed publication values.

@clawsweeper

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

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR publishes committed session entries and side-table facts directly from the SQLite writer instead of rereading them.

Example: Change agent:main:entry-postimage to label "patched" while retaining its saved skills and participant history.

  • Before: Publication rereads committed entry, window, membership, and participant facts.
  • After: Publication consumes detached facts captured and updated by the committing writer.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The earlier code defects are resolved, but required authority evidence and stable-to-candidate storage compatibility remain unestablished.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary session updates perform redundant SQLite work before committed facts reach consumers.
Reason: The established feature owner proposes a focused optimization and explicitly records the accepted implementation tradeoffs.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this maintainer-authored PR open: it provides a distinct session-writer optimization absent from current main, and the earlier concrete findings are resolved.

Priority: P2
Reviewed head: 53e5c9c1b8b38da79b286d74df90470da7a5157c

Before merge

  • Add real behavior proof - Authority-chain proof required: demonstrate shared-window replacements through production memory ingestion with ordinary content admitted and policy-excluded Gmail content rejected before corpus or index writes; demonstrate sharing publication with an allowed viewer and a revoked member rejected before disclosure, including an operation retained across revocation. The complete submitted body contains superseded measurements and prior-head tests rather than these repaired consuming flows; supply redacted logs or live output, removing IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve security concern: Validate policy facts at consuming effects - The shared-window regression stops at history metadata, and sharing assertions stop at published facts; neither demonstrates exclusion before memory writes or rejection of a retained viewer operation after membership revocation.
  • Resolve merge risk - Replacing final provenance and membership reads with retained writer facts leaves material uncertainty about policy exclusions and revocation at the consuming effects.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [medium] Validate policy facts at consuming effects — src/config/sessions/session-accessor.sqlite-replacement-state.ts:70

Tests

  • Missing end-to-end proof: Missing current-candidate final-effect evidence for excluded sources and revoked viewers, a v2026.10.1 upgrade/write/reopen preserving saved snapshots, and demonstrated base-fail/head-pass execution of the added regressions.
Agent review details

How this fits together

Session patches, replacements, turns, and lifecycle operations enter the agent database writer; committed receipts supply Gateway projections and metadata consumed by sharing and memory policy.

flowchart TD
A[Session operations] --> B[Agent database writer]
B --> C[SQLite transaction]
C --> D[Entry and side table postimages]
D --> E[Committed receipt]
E --> F[Gateway session projections]
C --> G[Transcript provenance]
G --> H[Memory admission policy]
Loading

Technical review

Best possible solution:

Keep the existing writer as the sole postimage owner while preserving stored snapshots, final sharing facts, and memory exclusions.

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

Current-main source shows publication rereading facts already acquired by the writer; prior-head measurements support that cost, but this review ran no workload.

Is this the best way to solve the issue?

Explicit transaction-local postimages fit the existing ownership model, and the repaired batch progression and append-only row capture address the earlier concrete defects.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4f4741bfe2b6.

Merge-risk options

Maintainer options:

  1. Hold for consuming-boundary evidence (recommended)
    Keep this PR open until the authority scenarios recorded in the proof assessment are demonstrated through the real consumers.

Provenance checked

  • Implicit writer cache and publication reads keeps the original intent (da965e0: Reduce repeated SQLite work by reusing writer-owned entry facts.)
  • Raw-row callback comparison changes intended behavior with a stated reason (10f9b5a: Decode saved entries once while preserving complete commit-boundary revalidation and conflict rejection.)
  • Window facts and unchanged-write suppression keeps the original intent (38ced6e: Reuse authoritative transaction facts and suppress unchanged entry, window, and snapshot writes: perf(sessions): reduce turn completion database work #168592.)
  • Committed publication and authority keeps the original intent (7a82a47: Publish complete committed facts before observers while preserving newer assignments and revocation: fix(sessions): keep authority current after committed session changes #167875.)
  • Lifecycle removal revalidation changes intended behavior with a stated reason (26dffe7: Preserve selected cleanup inputs and lifecycle ownership while moving retention work off the Gateway thread; this PR explicitly accepts not detecting later mutations by internal callbacks.)
  • Transcript operation registration keeps the original intent (78ed04b: Keep typed lazy dispatch and native initialization/publication ownership together: refactor(state): register agent database worker operations #162776.)

Testing

Proof path: in-process harness.

Security

Needs attention: No reachable security violation was established, but the changed policy-fact publication needs final-effect validation.

Evidence

Security concerns:

  • [medium] Validate policy facts at consuming effects — src/config/sessions/session-accessor.sqlite-replacement-state.ts:70
    The shared-window regression stops at history metadata, and sharing assertions stop at published facts; neither demonstrates exclusion before memory writes or rejection of a retained viewer operation after membership revocation.
    Confidence: 0.93

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit cf8b57e adds src/config/sessions/session-accessor.sqlite-provenance.ts:63 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cf8b57e7d03a; files: src/config/sessions/session-accessor.sqlite-provenance.ts)
  • Vincent Koc: Raw commit 388f57a adds src/config/sessions/session-accessor.sqlite-provenance.ts:54 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 388f57a05b97; files: src/config/sessions/session-accessor.sqlite-provenance.ts)

PR surface

Source +175, Tests -23, Other 0. Total +152 across 42 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 27 805 630 +175
Tests 13 333 356 -23
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 1 0
Total 42 1139 987 +152

Review metrics

Metric Value Why it matters
Production versus test delta Production +805/−630; tests and support +333/−356. Production growth carries explicit postimages through existing owners; test changes replace raw-mutation expectations with persistence and publication contracts.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is an internal performance improvement without a demonstrated urgent user regression.
  • merge-risk: 🚨 security-boundary: The changed provenance and membership facts feed memory admission and session disclosure decisions.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Prove allowed and excluded memory ingestion plus allowed and revoked session disclosure through the real consuming owners.
  • Demonstrate saved snapshots surviving a v2026.10.1 upgrade, candidate writes, and reopen.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-11T12:22:58.719Z sha 58faaa5 :: needs real behavior proof before merge. :: [P1] Refresh shared-window facts after each replacement | [P1] Refresh entry preimages for repeated exact replacement keys
  • reviewed 2026-10-11T12:48:40.407Z sha 492319c :: needs real behavior proof before merge. :: [P1] Refresh shared-window facts after each replacement | [P1] Refresh entry preimages for repeated exact replacement keys
  • reviewed 2026-10-11T13:12:59.381Z sha 867b11c :: needs real behavior proof before merge. :: [P1] Refresh shared-window facts after each replacement | [P1] Refresh entry preimages for repeated exact replacement keys
  • reviewed 2026-10-11T14:11:50.043Z sha 7b2dae2 :: needs real behavior proof before merge. :: [P2] Supply the raw row for append-only turn postimages
  • reviewed 2026-10-11T14:28:08.038Z sha 3ecf7d3 :: needs real behavior proof before merge. :: none

Reviewed October 11, 2026, 10:58 AM ET / 14:58 UTC (Revision 6).

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Oct 11, 2026
@steipete
steipete merged commit 8fe6ac8 into main Oct 11, 2026
175 of 181 checks passed
@steipete
steipete deleted the dbasync/t1entry-postimages branch October 11, 2026 15:16
@steipete

Copy link
Copy Markdown
Contributor Author

Landed as 8fe6ac8. Verified MERGED on GitHub and ancestry on origin/main.

Used the authorized relaxed-landing v4 fallback after two identical native pre-dispatch refusals on the failed CI gate. Both attempts submitted no merge request; their stale operation locks were recovered after verifying no tools remained. The REST squash was pinned to reviewed head 53e5c9c and preserved GitHub's native squash title/body.

The PR body records the final three alternating measurement pairs, all changed-owner static proof, the identical baseline/candidate Windows helper type error, and the remaining admission-test/UI-layout CI failures. No PR-caused static failure was bypassed. Warmed all-thread statements: 338.7 → 326.1; requests: 90.5 → 90.9 with attributed background timing noise; full-workload requests: 1740 → 1740; warmed MAIN: 0 → 0.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…enclaw#169090)

* perf(sessions): publish exact entry writer postimages

* fix(sessions): publish cold-cache writes and preserve entry postimages

* chore(sessions): document projection and test isolation invariants

* chore(sessions): attach safety invariant to the projection assertion

* refactor(sessions): project window postimages with a portable join

* refactor(sessions): isolate window facts from provenance writes

* fix(sessions): carry postimages through ACP and incognito writers

* test(sessions): assert persisted initialization state

* fix(sessions): advance postimages across replacement batches

* perf(sessions): reuse serialized snapshot postimages

* test(sessions): exercise repeated exact replacements

* refactor(sessions): keep postimage row assembly with its owner

* fix(sessions): retain row facts for append-only turn receipts
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
First-parent upstream 19fe879..0bc7491 (100 commits, including
openclaw#169090 entry-writer postimages, openclaw#169201 transcript projection facts,
openclaw#169113/openclaw#169107/openclaw#169125 session-actor admission, openclaw#169110 bounded worker
heaps, openclaw#169130 inter-session provenance, openclaw#168931 Solid session UI).

Conflicts:
- session-accessor.sqlite-entry-mutation.ts: openclaw#169090 moved postimage
  publication into writeSessionEntry and replaced the revision-equality
  no-op check with postimages.changed. Took upstream's form; kept our
  recipient-authority advance on visibility narrowing (same transaction,
  after the write, before the no-op return).
- session-accessor.sqlite-entry-store.ts: import union (upstream dropped
  withProjectedParticipants/SessionEntryWindowFacts imports; ours adds the
  recipient-authority advance). Overlay vs upstream is now 2 lines.
- openclaw-tools.types.ts: import union (our RequestCompactionToolOpts,
  upstream's SessionsYieldRuntimeClaim).
- plugin-sdk-surface-report.mts: upstream raised the budgets to 3672/2133;
  ours stays +11/+4 on top (3683/2137).
- worker-access-inventory.md: regenerated on the merged tree.

Auto-merged files that carry continuation overlay (21) keep the overlay
byte-for-byte (interdiff of the +/- lines vs upstream before and after).

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant