Skip to content

fix(sessions): avoid turn errors when write receipts overtake reads - #169174

Merged
steipete merged 2 commits into
mainfrom
dbasync/actorread
Oct 11, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/actorread

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes session reads failing with “Session actor changed before its read could publish” when a committed write receipt overtakes a worker read. A live soak observed this twice in roughly 108 cycles, including a correct reply reported by agent.wait as an error.

User Impact

An overtaken read returns the newer committed session snapshot and can complete normally. Caller authority still controls disclosure; schemas, stored data, update behavior, and SDK contracts are unchanged.

Why This Change Was Made

The Gateway owns both the actor and its receipt-maintained replica. A rejected stale read installation now reacquires that replica. If it is empty, the same command retries the existing worker read once, then fails if no snapshot can be installed. A snapshot superseded before disclosure is reacquired once and authorized again. No new generation, fence, or worker operation is introduced.

Removed failure checks and accepted edges:

  • A read overtaken by a committed receipt no longer fails just because its original snapshot lost publication; it returns newer committed facts.
  • A replaced disclosure snapshot no longer fails merely for having advanced; the replacement is authorized once. Further synchronous bookkeeping movement is accepted without an unbounded reacquisition loop. Genuine authority revocation and an unavailable replica still fail.

Evidence

  • Regression: both receipt-arrival cases fail on the original code with the exact publication/disclosure errors, then pass with the fix.
  • Local focused proof: actor 14/14 tests; replica 11/11 tests. Covers receipt arrival during worker read and disclosure, newer-state return, no additional read request for a resident replacement, one empty-replica retry, and bounded failure after a second superseding write.
  • Local wall time (pnpm test <file> --maxWorkers=1): actor 34.25 s (4.165 s test execution); replica 43.52 s (4.421 s test execution). Compilation/import dominates. Hosted CI cancelled the test matrix after an unrelated UI failure, so current-head per-file CI seconds are unavailable.
  • Independent Codex autoreview: initial P0–P2 scope clean; final conflict-integration P0/P1 scope clean. Two rounds total.
  • Remote actor/replica/kernel/worker/diagnostics suite passed all 47 tests across 5 files in 33.27 s on Testbox run 38149387509. check:changed passed formatting, core typing, all 28 test typecheck graphs, and its early guards, then stopped on one inherited full-tree Knip unused export. Production/script Knip scans passed. Type-aware oxlint and every skipped source guard were run explicitly and passed; Madge, export collisions, and T1/dialect ratchets passed.
  • Actor host T1 before/after: 0 → 0. The initial measured global inventory remains 616 raw / 614 normalized calls, unchanged; after main integration it is 612 raw / 610 normalized on both the integrated baseline and final head. Dialect debt in the changed production file remains zero.
  • LOC: production +14/-4; tests +84/-1; documentation +3/-0.

No update cell or SDK API diff is applicable.

SQL measurement

The unchanged shared harness ran three alternating base/candidate pairs plus the one permitted ambiguity pair on the same Testbox, comparing base 91a860e080610d5f1d7ac833b698effdf9e0ef4b with head e6c8c5b1d1dde990a4c0e9025e5df807e7bc9d60. Counts include all threads and split multi-statement execution into statements. Warmed figures are per-turn averages summarized across runs as median [min–max].

Warmed metric Three-pair base Three-pair candidate Four-pair base Four-pair candidate
Statements 341.6 [337.5–343.5] 337.4 [336.3–342.4] 342.05 [337.5–343.5] 337.25 [336.3–342.4]
Requests 89.9 [89.3–89.9] 89.8 [89.0–89.9] 89.9 [89.3–90.0] 89.6 [89.0–89.9]
MAIN statements 0 [0–0] 0 [0–0] 0 [0–0] 0 [0–0]

Actor-read first-turn work is exactly 4 statements / 4 requests in every valid run. Whole-workload actor-read medians remain 57 statements / 57 requests on both sides. Warmed actor-read medians are 4.4 / 4.4 versus 4.35 / 4.35; each read still executes one statement per request. Other warmed actor operations are unchanged: acceptInput 16/2, adoptRun 4/1, appendTranscriptEvent 23/2, completeTurn 6/1, deliverySettled 7/2 (statements/requests). The small aggregate warmed decrease is timing variance, not a claimed optimization.

The extra pair was required because first-turn statements increased. Four-pair first-turn medians are 1035.5→1111.5 statements and 200.5→208.5 requests; whole-workload medians are 9765.5→9782 statements (+0.17%) and 1711.5→1712.5 requests (+0.06%). The extra pair alone is 9774→9794 statements and 1709→1713 requests. The equal-or-lower whole-workload shortcut therefore does not pass; this is not reported as an aggregate SQL reduction.

A raw SQL/request-stack scan across all eight valid workloads found zero native SQL under session-actor.ts and zero SQL or worker sends under either the existing authorization call or the added replacement-authorization call. Every actor-read send comes from the existing worker operation; whole-workload actor-read medians are identical and the extra pair falls from 58 to 57 reads. Actor mutation counts are identical in every workload: 26 acceptInput, 13 adoptRun, 41 appendTranscriptEvent, 13 completeTurn, 26 deliverySettled, and 1 appendToolResult. The changed ordinary path adds no SQL/request work.

The extra pair's positive deltas occur in unchanged owners: model context +7 statements/+1 request, session corpus inventory +13/0, session entry +5/+1, row backfill +3/+1, tombstones +2/+1, prune +6/+1, transcript statistics +2/+1, and patch +14/0; offsets include lifecycle projection −13 statements and entry list −11. First-turn variation includes existing session-node/participant TEMP-trigger setup and schema inspection moving between phases; identical fingerprints already exist in the baseline. This residual is recorded as unchanged-owner timing/setup variance under the relaxed landing decision, supported by direct changed-path inspection, rather than waived as a T1 move or described as numerical non-increase.

All eight valid workloads completed. SQL diagnostics recorded 3 base / 5 candidate database is locked attempts in unchanged post-ready startup maintenance and idle-close state owners; none came from the actor and warmed turns had zero SQL errors. First/warmed median duration ratios were 1.045/0.991, within the 1.5 comparison limit.

One attempted extra baseline failed before the workload because remote source synchronization invalidated its task-owned Git metadata. Its unpaired candidate is excluded. The baseline metadata was repaired, exact source bytes verified, and the valid extra M/C pair completed. No additional pairs were run.

CI disposition

The exact-head CI run 38149421297 stopped after UI job 114499862139: chat-panel-layout.e2e.test.ts timed out waiting for a hidden 560×312 terminal canvas to become visible (1 failed, 91 passed). Its mock Gateway replaces WebSocket and never executes the session actor. The UI test, mock helpers, terminal implementation, panel layout/CSS, and workflow are unchanged by this PR.

Recent scheduled main job 114494370803, head 6233a19ea75bbcd079ec4dbe4660bfef9b9321ed, shows the same hidden-terminal-canvas timeout in sibling terminal-repaint/readiness tests, rather than the identical test. The CI monitor cancelled remaining jobs after the UI failure. This is recorded as unrelated inherited UI breakage, not passing CI; focused owner proof and all required static checks remain merge gates.

Landing uses the explicitly authorized head-pinned REST squash fallback after native review artifact initialization twice refused a moving tooling-root dependency mismatch. The first exact-head merge request was rejected with HTTP 405 after main changed the actor layout; it was confirmed unmerged before recovery.

Main integration

Merged main 5bd4f88535c66197b6d07442b82f7f68d94be6fa into this branch, producing ed22f47330558ac77a100d15abfb85643971108c. Main extracted the durable implementation into session-actor-sqlite.ts; conflict resolution preserves its wrapper and moves the same bounded recovery into that existing SQLite executor. The final diff remains four files, with unchanged production/test/documentation LOC. The measurement and callback-stack evidence above belongs to the pre-integration head and original file layout. No SQL statement, request, or recovery semantics changed in this port; the campaign's conflict-only measurement reuse rule applies. Post-integration Testbox proof passed all 81 tests across 10 actor/replica/kernel/worker/diagnostics/memory suites (28.83 s Vitest, 30.70 s test wrapper). Formatting and changed-file type-aware oxlint passed. Core typecheck (45.9 s), the session test type graph (44.2 s), Madge (12.6 s), export collisions, source guards, and T1/dialect ratchets all passed. Exact focused-command wall time was 31.085 s.

Full-tree Knip reports the same seven findings on final head and integrated baseline 5bd4f88535c66197b6d07442b82f7f68d94be6fa: six unused exports in extensions/telegram/src/bot-native-commands.runtime.ts (ensureConfiguredBindingRouteReady, getAgentScopedMediaLocalRoots, getSessionEntryAsync, recordDeliveredCommandExchange, resolveChunkMode, resolveStorePath) and the subagent export noted below. The exact rule/file/export match was reproduced by running the baseline scan; no PR-caused static failure remains.

Final-head CI run 38153491821 has green required CI, dependency-review, and security-sensitive-review gates. The earlier unrelated UI failure is historical evidence; the final merge does not require a CI-failure override.

The inherited static failure is loadSubagentMaintenanceCandidatesInDatabase in src/agents/subagents/registry/subagent-registry.store.sqlite.ts. An actual full-tree Knip scan on current-main ea576bd11d8c304c1a8cc53823b0081d65cee0cc reproduced that same rule/file/export; the file is byte-identical to the candidate. No failing static rule is introduced by this PR.

@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 in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 11, 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 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR recovers session reads overtaken by committed receipts using the current replica and one bounded worker-read retry.

Example: A read of agent:main:actor-replica overlaps a receipt changing updatedAt from 1 to 2 and label from before to after.

  • Before: The read throws “Session actor changed before its read could publish” despite newer committed state being available.
  • After: The read returns updatedAt 2 and label after, subject to caller authorization.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch has meaningful regression coverage and no identified defect, but supplied after-fix evidence remains below the shipped-entry-point level.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied execution evidence covers actor and replica tests, while the body still marks the shipped Gateway comparison as pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A completed agent reply can be reported as an error when a committed write overtakes a session read.
Reason: The reported incident and current source establish useful value, and the maintainer-authored direction explicitly accepts bounded bookkeeping movement while preserving authority checks.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses a reported session-read failure still present on main, and source review found no actionable correctness or security defect.

Priority: P2
Reviewed head: e6c8c5b1d1dde990a4c0e9025e5df807e7bc9d60

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The pending Gateway comparison has not supplied an after-fix trace of receipt supersession returning newer state and completing the turn normally.
Agent review details

How this fits together

The session actor connects turn-processing callers to the existing SQLite worker owner, installs committed receipts in a shared replica, and returns authorized session snapshots.

flowchart TD
A[Turn processing caller] --> B[Session actor]
B --> C[Physical writer FIFO]
C --> D[SQLite worker]
D --> E[Committed replica]
E --> B
B --> F[Caller authorization]
F --> G[Returned session snapshot]
Loading

Technical review

Best possible solution:

Recover through the existing receipt-maintained replica while retaining bounded retries and caller-owned disclosure authorization.

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

Main deterministically rejects a read whose installation or disclosure snapshot is superseded; the body reports live occurrences and base-failing regressions, but this read-only review executed no target code.

Is this the best way to solve the issue?

The shared actor is the appropriate repair boundary, and reacquiring its existing committed replica avoids another state owner or mutation replay.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Session actor read-publication and disclosure rejection changes intended behavior with a stated reason (d5173cc: The original actor required installed committed snapshots and current caller authority before disclosure.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +10, Tests +83, Docs +3. Total +96 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 14 4 +10
Tests 2 84 1 +83
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 101 5 +96

Review metrics

Metric Value Why it matters
Production versus test changes Production +14/-4; tests +84/-1 The small production increase implements bounded recovery; the tests cover both replacement points and retry exhaustion.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: An intermittent session-read failure can report a successful agent reply as an error, without evidence of widespread or release-blocking impact.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Record the pending Gateway comparison showing newer-state return and normal turn completion after receipt supersession.

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 (1 earlier review cycle)
  • reviewed 2026-10-11T15:03:19.634Z sha e6c8c5b :: needs maintainer review before merge. :: none

Reviewed October 11, 2026, 11:18 AM ET / 15:18 UTC (Revision 2).

@steipete
steipete merged commit fcf234a into main Oct 11, 2026
116 checks passed
@steipete
steipete deleted the dbasync/actorread branch October 11, 2026 16:12
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…penclaw#169174)

Use the receipt-maintained replica when a committed write overtakes a session actor read. Retry the existing worker read once only when the replica is still empty, and reauthorize a replacement before disclosure. Preserve live authority checks and bounded failure.

Regression coverage exercises newer receipts during worker reads and disclosure, plus one-read recovery and retry exhaustion.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant