Skip to content

perf(sessions): admit persisted-turn replays through the transcript readers - #165367

Merged
steipete merged 3 commits into
mainfrom
dbasync/replayadmit
Oct 5, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/replayadmit

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Persisted-turn replay admission repeatedly reads the exact session writer row and transcript context version on the Gateway thread. The sqlmeasure4 workload attributed 18 MAIN statements per warmed turn to these checks.

Why This Change Was Made

Validate the writer row and prepared context version together in the existing transcript anchor reader. Retain the physical database through each scan, validation, consumption, and cleanup; compare that source across preparation phases while obtaining fresh owner authority each time. Final replay consumption and core entry run synchronously under the reader's writer FIFO and native mutation witness. The core run settles after reader custody is released.

Run ownership, permission replacement, cancellation, the same anchor/version, and one-time consumption remain live fences. The internal prompt admission callback becomes awaitable. Public named SessionManager persistence APIs and their deprecated synchronous contracts are unchanged.

User Impact

This is an internal performance change: valid replay behavior, schemas, stored bytes, retention, durability, and update behavior are unchanged. No new service, cache, schema, dependency, or OPENCLAW_* environment name is added.

Production delta: +241 / −102 / net +139, 343 changed lines across five production files. The existing process-held incognito route keeps its owner; actor-bound reads use their captured actor. No new caller-thread SQL is added to grant callbacks.

Overlapping work: #165028 (shared anchor/source seam), #165205, #165193, and #162433. This change keeps focused hunks around current reader owners; the umbrella ownership design is outside this PR.

Evidence

Paired measurement uses clean baseline 3b60dc8ba2c34d9de93e7385e169d92801f5c3a2 and final candidate d14e903971c4e06f45840790fb467b04efa3c7c2 on one isolated Hetzner ccx33 host (8 CPUs), Node 24.21.0 / SQLite 3.53.4. All six sqlmeasure4 harness/calibration/analyzer files are byte-for-byte unchanged; three sequential repetitions per revision use separate synthetic fixtures. Statement counts include successful native executions and preserve per-site caller attribution.

Warmed successful statements per turn Baseline median [range] Candidate median [range]
MAIN, selected replay cohort 18.0 [18.0–18.0] 0.0 [0.0–0.0]
MAIN, all callers 209.4 [209.4–209.7] 191.1 [191.1–191.4]
Worker threads 2048.9 [2045.7–2052.5] 2081.2 [2080.5–2083.2]
All threads/processes 2290.7 [2286.6–2294.3] 2304.7 [2304.3–2306.7]

The selected causal reduction is exactly 18 MAIN statements/turn; the additional 0.3 difference in the overall median includes scheduling variation. Total SQL grows by 14.0/turn (~0.61%); this is a main-thread placement improvement, not latency evidence. Medians are computed separately per metric.

Per-site attribution across ten warmed turns (baseline source line numbers; only stacks passing through persisted-turn replay):

Baseline site Before MAIN After MAIN
session-accessor.sqlite-entry-read.ts:287 40 0
session-accessor.sqlite-entry-read.ts:81 40 0
session-accessor.sqlite-participant-projection.ts:56 40 0
openclaw-agent-db-readonly.ts:116 20 0
session-cold-storage-state.ts:57 20 0
session-accessor.sqlite-transcript-state.ts:75 20 0

All six replay caller cohorts are zero on MAIN in every candidate repetition. Both native calibrations match: 8 native calls, 2 prepares, 7 successful statements on each thread.

The byte-identical source replacement regression fails on the baseline for the intended reason: preparation resolves instead of rejecting (46.84 s wall).

All test commands use pnpm test <files> --maxWorkers=1:

Proof Passing tests Wall time
attempt-session-replay.test.ts 63 180.24 s
attempt-session.test.ts 24 13.62 s
agent-session-loop-next-turn.test.ts 27 23.99 s
Lifecycle preparation, hydration, model-context snapshot, incognito siblings 96 74.66 s
Runtime-process build graph, get-reply imports, worker runtime imports 15 14.27 s
12 indirect fixture callers 73 159.73 s
Foreground prompt submission 16 14.58 s

The replay suite exceeds 30 seconds because its existing end-to-end matrix proves restart/retry/compaction, writer/lifecycle replacement, and exact persisted-transcript behavior through real worker owners; the new regressions require the actual delayed worker/SDK mutation and physical-file boundaries. CI seconds are pending the PR run; no CI reruns were used as proof.

The replay boundary checks zero caller-thread SQL through initial preparation, re-preparation, and final admission. Delayed worker replies cover synchronous SDK rewrites, database closure, and run revocation. A byte-identical file replacement must not reopen replay authority. Permission and disposal tests cover the new awaited boundary before prompt publication and core entry.

Indirect caller audit: replay/session/lifecycle tests already route through the host-owned database-worker project, and session-manager/core-loop siblings use the forked agent-support project. No new routing entry was needed.

Required gates:

  • Full gateway setup/build passed (959.54 s on macOS); final-head qaRuntime build passed (62.6 s on the isolated host).
  • node scripts/check-changed.mjs --base 3b60dc8ba2c34d9de93e7385e169d92801f5c3a2 passed on the final head (1892.17 s), including core production and all 27 core-test type graphs.
  • Database-worker ratchet passed with no T1 call-count growth; Madge passed with 0 cycles (33.33 s).
  • Codex P2 autoreview: full implementation and subsequent fixture/target corrections are scoped-clean.
  • Exact-head SDK diff completed (249.38 s), reviewed digest 01df0af7: 128 reachable export effects across five declarations, with 0 direct export declaration changes and 0 entrypoints added/removed. The changed callback is the host-owned @internal symbol hook, also marked internal in v2026.9.8 and absent from supported SDK/session barrels. Public harness options and Gateway context services do not accept that callback; named public session methods retain their contracts. The anchor request/result fields are optional additions, and the raw database-reader input remains internal.

The line-cap failure was repaired by extracting the test-only prompt adapter, shrinking the oversized fixture below its baseline. The captured-target typecheck failure was repaired by preserving the original captured environment rather than widening or casting it. All affected tests and the complete changed gate passed afterward.

Hosted PR CI passed on exact head d14e903971c4e06f45840790fb467b04efa3c7c2: run 37270022415, 46 successful jobs and 23 intentional skips, with no failed or cancelled jobs. The required CI gate and security statuses passed. ClawSweeper completed its refreshed exact-head review with no actionable findings. The landing audit confirmed existing host-owned/forked test routing and the recorded SDK diff. Published-driver update proof is not applicable: the diff changes no update, Doctor, service lifecycle, migration, plugin-loading, schema, or persisted-format contract, and does not match the published-driver selector. The measured total-SQL increase is the remaining performance tradeoff; no known unresolved correctness finding remains.

…eaders

Validate the current writer row and transcript version in the existing reader snapshot. Keep live ownership, physical source identity, native mutation fencing, and single replay consumption through synchronous core entry.
@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 agents Agent runtime and tooling size: L labels Oct 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 5, 2026, 2:30 AM ET / 06:30 UTC (Revision 3).

ClawSweeper review

What this changes

The branch moves persisted-turn replay validation into existing transcript readers and makes internal prompt admission awaitable while preserving synchronous agent entry.

Merge readiness

✅ Ready for maintainer review

This remains a useful, distinct performance improvement. The reviewed source and recorded boundary proof reveal no blocking correctness or security defect.

Priority: P2
Reviewed head: d14e903971c4e06f45840790fb467b04efa3c7c2

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused implementation has strong paired measurements and boundary coverage, with no actionable introduced finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The recorded isolated workload exercises the changed replay owner with real SQLite workers and shows all six replay caller cohorts at zero MAIN statements on the pinned candidate. Production-worker fault cases cover rewrite, database closure, run revocation, and identical-file replacement before consumption; prompt/core cases cover permission replacement and disposal. No stored-data contract changes, so migration proof is not applicable. This review inspected source and recorded evidence without executing tests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The recorded isolated workload exercises the changed replay owner with real SQLite workers and shows all six replay caller cohorts at zero MAIN statements on the pinned candidate. Production-worker fault cases cover rewrite, database closure, run revocation, and identical-file replacement before consumption; prompt/core cases cover permission replacement and disposal. No stored-data contract changes, so migration proof is not applicable. This review inspected source and recorded evidence without executing tests.
Evidence reviewed 8 items Pinned introduced changes: Reviewed the merge-base-to-head production hunks separately from base-branch drift. Replay preparation retains physical source identity, validates writer and context facts through the anchor reader, and consumes once within its callback.
Final-effect authority checks: The reader retains writer FIFO custody and checks physical identity, current reader ownership, and the native mutation revision before consumption. Prompt admission then checks permission generation and session preparation identity before committing prompt state and entering the agent loop.
Production-worker refusal coverage: The introduced regressions delay an actual worker response, then rewrite the transcript, close the database, or revoke the run; each requires rejection before consumption. A separate case replaces the physical database with identical bytes. Permission and core-loop cases check rejection before prompt publication or model requests.
Findings None None.
Security None None.

How this fits together

Replay admission lets an interrupted agent resume an already-persisted user turn without appending it again. It checks session ownership and transcript state before publishing the prompt and starting model execution.

flowchart TD
  A[Interrupted user turn] --> B[Prepare transcript replay]
  B --> C[Retain original database]
  C --> D[Reader validates writer and version]
  D --> E[Recheck permissions and run authority]
  E --> F[Consume replay once]
  F --> G[Start agent synchronously]
  G --> H[Settle outside reader custody]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +139, Tests +212, Docs +10. Total +361 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 241 102 +139
Tests 5 255 43 +212
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 506 145 +361

Review metrics

Metric Value Why it matters
Replay SQL placement MAIN 18 → 0 statements/turn; total +14/turn The recorded workload supports removing synchronous replay reads while explicitly accounting for approximately 0.61% additional total SQL.
Production versus test growth production net +139; tests/support net +212 Production growth has a stated custody and admission justification, with added coverage for replacement and revocation boundaries.

Technical review

Best possible solution:

Keep replay validation with the existing transcript-reader owners, preserving live authority checks and synchronous core entry.

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

Not applicable as a bug reproduction: the performance claim has a pinned paired workload, and current-main source confirms synchronous replay checks remain.

Is this the best way to solve the issue?

Yes. Extending the existing reader snapshot and retaining its admission custody is a focused solution that preserves the established writer and prompt owners.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded internal performance improvement with measured main-thread SQL reduction and no demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The recorded isolated workload exercises the changed replay owner with real SQLite workers and shows all six replay caller cohorts at zero MAIN statements on the pinned candidate. Production-worker fault cases cover rewrite, database closure, run revocation, and identical-file replacement before consumption; prompt/core cases cover permission replacement and disposal. No stored-data contract changes, so migration proof is not applicable. This review inspected source and recorded evidence without executing tests.
  • proof: sufficient: Contributor real behavior proof is sufficient. The recorded isolated workload exercises the changed replay owner with real SQLite workers and shows all six replay caller cohorts at zero MAIN statements on the pinned candidate. Production-worker fault cases cover rewrite, database closure, run revocation, and identical-file replacement before consumption; prompt/core cases cover permission replacement and disposal. No stored-data contract changes, so migration proof is not applicable. This review inspected source and recorded evidence without executing tests.

Evidence

What I checked:

  • Pinned introduced changes: Reviewed the merge-base-to-head production hunks separately from base-branch drift. Replay preparation retains physical source identity, validates writer and context facts through the anchor reader, and consumes once within its callback. (src/agents/embedded-agent-runner/run/pre-persisted-user-turn.ts:67, d14e903971c4)
  • Final-effect authority checks: The reader retains writer FIFO custody and checks physical identity, current reader ownership, and the native mutation revision before consumption. Prompt admission then checks permission generation and session preparation identity before committing prompt state and entering the agent loop. (src/agents/sessions/agent-session-prompting.ts:129, d14e903971c4)
  • Production-worker refusal coverage: The introduced regressions delay an actual worker response, then rewrite the transcript, close the database, or revoke the run; each requires rejection before consumption. A separate case replaces the physical database with identical bytes. Permission and core-loop cases check rejection before prompt publication or model requests. (src/agents/embedded-agent-runner/run/attempt-session-replay.test.ts:103, d14e903971c4)
  • Recorded after-fix workload: The captured PR body records three paired repetitions on one isolated host using unchanged SQL instrumentation and synthetic fixtures. Replay-attributed main-thread statements fall from 18 to zero per warmed turn in every candidate repetition; total statements increase by 14 per turn, approximately 0.61%. It explicitly makes no latency claim and records passing replay, permission, lifecycle, and import-boundary validation on the pinned candidate. (d14e903971c4)
  • Current-main necessity: Fetched main still uses synchronous loadSessionEntry, loadTranscriptHeaderSync, and validateSessionTranscriptContextVersion in replay admission. The related merged native-patch PR handles lifecycle writes rather than this replay path; the supplied related open PRs do not establish a merged replacement. (src/agents/embedded-agent-runner/run/pre-persisted-user-turn.ts:85, d7f9ebd8de66)
  • Internal API and storage boundary: The changed preparation symbol is explicitly internal, and its production caller is the embedded attempt owner. The anchor additions are optional request/result facts; introduced hunks contain no schema, serialized-format, migration, dependency, or supported entrypoint changes. Documentation describes unchanged stored bytes, retention, durability, and update behavior. Public docs: docs/reference/database-schemas/worker-access.md. (docs/reference/database-schemas/worker-access.md:1757, d14e903971c4)

Likely related people:

  • steipete: 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 (2 earlier review cycles)
  • reviewed 2026-10-05T06:01:37.256Z sha d14e903 :: needs changes before merge. :: none
  • reviewed 2026-10-05T06:08:09.382Z sha d14e903 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit f23ccb5 into main Oct 5, 2026
147 of 150 checks passed
@steipete
steipete deleted the dbasync/replayadmit branch October 5, 2026 06:36
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
…eaders (openclaw#165367)

* perf(sessions): admit persisted-turn replays through the transcript readers

Validate the current writer row and transcript version in the existing reader snapshot. Keep live ownership, physical source identity, native mutation fencing, and single replay consumption through synchronous core entry.

* test(agents): extract the prompt admission fixture adapter

* fix(sessions): preserve the captured replay target environment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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