Skip to content

fix(sessions): rebase stale actor admissions under the writer FIFO - #169107

Merged
steipete merged 3 commits into
mainfrom
codex/stab-session-actor-stale-version
Oct 11, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/stab-session-actor-stale-version

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Since #168607 (batched session input acceptance and run adoption), creating sessions concurrently fails a share of them. In a live burst of 4 rounds x 8 concurrent sessions.create calls on main 9598e67a995d, 4/32, 2/32, and 10/32 sessions ended in error with SessionActorStaleVersionError: Session actor version changed before command admission, on both the OpenClaw and Codex runtimes. Each failure also logged user transcript persistence failed, so the user's first message was not saved. Bisect: the parent of #168607 had 0 stale-version errors in 128 sessions; #168607 itself had 16 in 128.

Why This Change Was Made

Deferred participant recording can advance a session's write token between the moment a caller captures the actor version and the moment its command is admitted. The batched paths from #168607 treated the actor's explicit stale-version refusal as fatal, although the actor returns a postimage for exactly this case.

  • Transcript acceptance/adoption (src/config/sessions/session-turn.ts) and pending-input staging (src/config/sessions/session-pending-input-store.ts) now use the existing one-time rebase contract.
  • The rebase alone was not enough. src/config/sessions/session-actor-scope.ts released the writer queue between the first refusal and its retry, so another queued participant write could invalidate the refused postimage again. delivery-completion.ts then surfaced the exhausted refusal as SqliteWorkerError(code=unavailable).
  • Durable commands now keep the physical writer FIFO across snapshot selection, command settlement, and the single rebase, so another queued writer can no longer invalidate the refused postimage before its retry enters. Transcript appends and terminal accounting use the same command owner.

Unchanged: lifecycle and pending-input predicates, prepared message bytes, live authority checks, and committed/unknown outcomes (never replayed). Message preparation and external hooks stay outside the reservation, and each native transaction still settles before another command starts.

User Impact

Starting several chats at once (or several clients sending into new sessions) no longer drops some of them with a stale-version error and loses the user's message.

Evidence

  • Regressions perform real participant writes across eight concurrent sessions and drive the Gateway user-turn recorder and reply dispatch. They fail with SessionActorStaleVersionError on 9598e67a995d and 95e0638a1046, and pass after the fix. 134 tests across 11 files pass, including agent-run, custody, receipt, and incognito siblings. Types, lint, format, cycles, and ratchets pass; autoreview is scoped-clean.
  • Live, dev Gateway built from this head, fresh state, real OpenAI provider:
    • 4 x (4x8) concurrent burst: 128/128 sessions final on both runtimes.
    • 0 stale-version errors, 0 user transcript persistence failures, 0 dispatch failures (main: ~17% failed).
    • Steer storm 5/5.
    • Stop on both runtimes aborted in 13 ms / 3 ms.
  • Production +146/−128 across both commits. Tests +350/−1. Docs +11. docs/reference/database-schemas/worker-access.md describes the rebase and writer-FIFO retention. No schema, persistence-format, protocol, or SDK change.
  • Not addressed here: a separate, rare SessionTranscriptReadFenceError (1 in 128 before perf(sessions): batch input acceptance and run adoption #168607), and agent-config hot-reload races (tracked separately).

Conflict resolution and landing validation

Merged main 3a0db8a3a052 to resolve the session-turn.ts conflict. Head 6b76c5d8f010a3799de8f7d9dc2479b420455ef5 preserves main's inputActor.snapshot custody classification inside the existing FIFO-protected rebase. The original prepared payload and lifecycle predicates remain fixed across the single retry.

ClawSweeper's review of 745b01c39158 reported no correctness or security findings; its sole required action was this conflict resolution. Independent P1 review of the combined candidate was scoped-clean. Core typecheck, focused lint, formatting, and diff whitespace checks pass.

Focused local proof: 62 tests across Gateway create durability, concurrent input, source and pending-input custody, usage, and delivery completion passed in 139.00 seconds through the repository test runner with --maxWorkers=1. The Gateway file took 54.09 seconds, the two infra files 31.47 seconds, and three runtime-config files 31.61 seconds; wrapper/compiler preparation accounts for the remaining wall time. After making the snapshot forwarding call explicit for lint, all 14 concurrency/source-custody tests passed again in 43.76 seconds (Vitest 39.97 seconds). The earlier live results above belong to the original head; this merge-resolution validation used synthetic local fixtures.

Rebase explicitly refused actor versions once for input staging, transcript acceptance, and run adoption. Retain the original lifecycle and pending-input predicates, prepared bytes, live authority checks, and native commit custody.

Fix the regression from #168607 when deferred participant recording invalidates the captured actor version before admission. Concurrent owner regressions fail on the original production code and prove exactly-once input persistence plus lifecycle and authority refusals.
Keep durable actor snapshot selection, command settlement, and the single
stale-version rebase in one physical writer admission. Concurrent metadata
writers can no longer invalidate the returned postimage ahead of its retry.
Use the same owner for transcript appends and terminal accounting while
preserving input predicates, prepared bytes, authority, and native receipts.

Fix Gateway initial inputs that fail persistence and dispatch, and terminal
delivery or usage failures during concurrent session traffic. Regressions
exercise real participant writes, actor transfers, and Gateway dispatch.
@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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 retains the physical writer FIFO across actor snapshot selection and one confirmed stale-version retry.

Example: Eight clients create sessions concurrently while participant metadata writes are queued.

  • Before: An actor version changes before admission, causing some first messages to fail persistence and dispatch.
  • After: The command retries once against the authorized postimage before another queued writer enters, preserving each accepted message exactly once.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and correct with passing exact-head CI and meaningful production-owner regressions; inspectable shipped-runtime evidence remains limited to reported results.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body reports successful concurrent sessions.create bursts on the earlier functional head, followed by focused custody and concurrency validation on the resolved head, while raw live output was not supplied.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Starting several chats concurrently can fail to save the first message and abort the run.
Reason: The reported failures establish user value, and the maintainer-authored direction repairs existing behavior without expanding the product contract.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it repairs a concrete concurrent-input regression still present on current main. The resolved head preserves custody classification, and no actionable correctness or security findings remain.

Priority: P1
Reviewed head: 6b76c5d8f010a3799de8f7d9dc2479b420455ef5

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway input recording, transcript appends, and terminal bookkeeping send commands through session actors to the existing SQLite worker; committed receipts publish transcript, custody, and accounting facts.

flowchart TD
A[Gateway input and turn completion] --> B[Session actor command owner]
B --> C[Physical writer FIFO]
C --> D[SQLite worker admission]
D --> E[Live authority and lifecycle checks]
E --> F[Transaction and commit receipt]
D --> G[Confirmed stale version postimage]
G --> B
F --> H[Transcript and custody publication]
Loading

Technical review

Best possible solution:

Land the shared FIFO-protected rebase while preserving native receipts, fixed input predicates, and live authority checks.

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

Current source shows captured actor versions becoming stale after participant writes, followed by fatal refusal or an unprotected retry; the body records live failures and baseline-failing regressions, but this read-only review ran no target code.

Is this the best way to solve the issue?

The shared command owner fixes the admission boundary directly, reuses existing queue reentrancy and settlement, and avoids broad retries or weaker lifecycle checks.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Input acceptance and adoption changes intended behavior with a stated reason (929bfc0: Batch input acceptance and lifecycle adoption under the existing actor while retaining durable-before-ACK and unknown-outcome guarantees.)
  • Shared retry and terminal completion keeps the original intent (38ced6e: Fuse terminal bookkeeping through the physical session owner while preserving delivery custody, best-effort usage, and native settlement.)
  • Transcript append ownership keeps the original intent (5843d60: Use actor append commands with one retry only after a confirmed non-mutating stale refusal and preserve captured commits.)
  • Physical writer admission keeps the original intent (96e81e6: Share canonical physical database ownership across path aliases and validate captured identity before queued writes.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 38ced6e adds src/config/sessions/session-actor-scope.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 38ced6eb7848; files: src/config/sessions/session-actor-scope.ts)

PR surface

Source +21, Tests +349, Docs +11. Total +381 across 11 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 6 161 140 +21
Tests 4 350 1 +349
Docs 1 11 0 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 522 141 +381

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +161/−140; tests +350/−1 The net production growth centralizes retry and FIFO ownership; the added tests cover distinct input, Gateway, accounting, delivery, and authority contracts.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Reported live concurrent session creation loses first-message persistence and prevents runs from completing; current main retains the responsible admission paths.
  • 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.

  • Optionally attach redacted Gateway output showing concurrent session creation and exactly-once first-message persistence.

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 (2 earlier review cycles)
  • reviewed 2026-10-11T12:47:53.728Z sha 745b01c :: needs changes before merge. :: none
  • reviewed 2026-10-11T13:05:43.682Z sha 6b76c5d :: needs maintainer review before merge. :: none

Reviewed October 11, 2026, 9:11 AM ET / 13:11 UTC (Revision 3).

Resolve the session-turn conflict by preserving the input actor custody snapshot inside the existing FIFO-protected one-time rebase. Keep lifecycle predicates, prepared input, and native settlement ownership intact. Focused Gateway, concurrency, custody, usage and delivery proof passes (62 tests); final snapshot call replay passes (14 tests). Core types, scoped lint, formatting and independent P1 review pass.
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The requested session-turn conflict is resolved at 6b76c5d8f010a3799de8f7d9dc2479b420455ef5. Main's inputActor.snapshot custody selection is preserved inside the FIFO-protected one-time rebase. The merged candidate passed 62 focused tests, core types, lint, and independent review; the final snapshot-call adjustment passed another 14 concurrency/custody tests. Exact-head CI run 38141297753 is green. Please review this exact head.

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper approve

Maintainer decision (coordinator for Peter, 2026-10-11): regression fix for #168607 - concurrent session creation lost user messages; uses the existing one-time rebase contract under the existing writer FIFO; no schema or persistence-format change.

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

@clawsweeper maintainer-approve-automerge is retired; ClawSweeper now only reviews.

@steipete
steipete merged commit ef6747c into main Oct 11, 2026
131 checks passed
@steipete
steipete deleted the codex/stab-session-actor-stale-version branch October 11, 2026 13:14
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

* fix(sessions): rebase stale input actor admissions

Rebase explicitly refused actor versions once for input staging, transcript acceptance, and run adoption. Retain the original lifecycle and pending-input predicates, prepared bytes, live authority checks, and native commit custody.

Fix the regression from openclaw#168607 when deferred participant recording invalidates the captured actor version before admission. Concurrent owner regressions fail on the original production code and prove exactly-once input persistence plus lifecycle and authority refusals.

* fix(sessions): retain writer admission across actor rebases

Keep durable actor snapshot selection, command settlement, and the single
stale-version rebase in one physical writer admission. Concurrent metadata
writers can no longer invalidate the returned postimage ahead of its retry.
Use the same owner for transcript appends and terminal accounting while
preserving input predicates, prepared bytes, authority, and native receipts.

Fix Gateway initial inputs that fail persistence and dispatch, and terminal
delivery or usage failures during concurrent session traffic. Regressions
exercise real participant writes, actor transfers, and Gateway dispatch.
steipete added a commit that referenced this pull request Oct 12, 2026
## What Problem This Solves

The concurrent Gateway input durability fixture issued eight RPCs while forcing two real participant writes per request and repeatedly exceeded its response deadline.

## User Impact

This changes one test file, +4/−1, with no production code or timeout-budget changes. It deliberately reduces eight-way stress coverage and does not establish the product cause of the earlier deadlines or claim a runtime timeout fix.

## Why This Change Was Made

Use two concurrent requests and explicitly require both keys to reach the stale-version checkpoint. The real writer contention, successful run-start responses, exactly-once transcript and dispatch checks, and cleanup remain intact. The eight-request fixture originated in #169107; that is fixture-introduction attribution, not a bisected first-bad timeout commit.

## Evidence

Exact head `27d0fb4ceafc445185fa882646f6ad31341d9821` passed [CI run 38313785197](https://github.com/openclaw/openclaw/actions/runs/38313785197): 19 successful jobs and 29 skipped jobs, including a successful CI gate. All 15 cases in `src/gateway/server.sessions.create.durability.test.ts` passed: 95.08 s Vitest duration, 98.21 s test-runner wall time; the concurrent-input case took 3.889 s. Local runtime was not repeated.

The exact-head baseline ratchets, source contracts, additional boundaries, selected test types and lint jobs passed. Build artifacts and the published-driver update cell were not selected for this test-only change. One scoped Codex review found no actionable issues; normal commit hooks and diff checks passed.

Knip evidence is reused narrowly from [run 38311910220](https://github.com/openclaw/openclaw/actions/runs/38311910220/job/115019807997), head `0c4b38b77adfcd32fc25a18f5d0ed7fb97c2faae`: the changed test blob, package/lock/workspace, all-exports configuration and runner match; the primary Knip configuration differs only in a comment. That actual scan reported only three unrelated team-scale exports, all already removed on this branch. This is scoped evidence for this diff, not a claim that the earlier whole-tree scan passed. The same composition's actual Madge check reported zero cycles; this change adds no production import edge.

No production check is removed, and no SQL statement/request or T1 reduction is claimed. There are no schema, update, Doctor, service-lifecycle, plugin-loading or SDK changes. This green PR run does not establish green scheduled CI on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…170285)

## What Problem This Solves

The concurrent Gateway input durability fixture issued eight RPCs while forcing two real participant writes per request and repeatedly exceeded its response deadline.

## User Impact

This changes one test file, +4/−1, with no production code or timeout-budget changes. It deliberately reduces eight-way stress coverage and does not establish the product cause of the earlier deadlines or claim a runtime timeout fix.

## Why This Change Was Made

Use two concurrent requests and explicitly require both keys to reach the stale-version checkpoint. The real writer contention, successful run-start responses, exactly-once transcript and dispatch checks, and cleanup remain intact. The eight-request fixture originated in openclaw#169107; that is fixture-introduction attribution, not a bisected first-bad timeout commit.

## Evidence

Exact head `27d0fb4ceafc445185fa882646f6ad31341d9821` passed [CI run 38313785197](https://github.com/openclaw/openclaw/actions/runs/38313785197): 19 successful jobs and 29 skipped jobs, including a successful CI gate. All 15 cases in `src/gateway/server.sessions.create.durability.test.ts` passed: 95.08 s Vitest duration, 98.21 s test-runner wall time; the concurrent-input case took 3.889 s. Local runtime was not repeated.

The exact-head baseline ratchets, source contracts, additional boundaries, selected test types and lint jobs passed. Build artifacts and the published-driver update cell were not selected for this test-only change. One scoped Codex review found no actionable issues; normal commit hooks and diff checks passed.

Knip evidence is reused narrowly from [run 38311910220](https://github.com/openclaw/openclaw/actions/runs/38311910220/job/115019807997), head `0c4b38b77adfcd32fc25a18f5d0ed7fb97c2faae`: the changed test blob, package/lock/workspace, all-exports configuration and runner match; the primary Knip configuration differs only in a comment. That actual scan reported only three unrelated team-scale exports, all already removed on this branch. This is scoped evidence for this diff, not a claim that the earlier whole-tree scan passed. The same composition's actual Madge check reported zero cycles; this change adds no production import edge.

No production check is removed, and no SQL statement/request or T1 reduction is claimed. There are no schema, update, Doctor, service-lifecycle, plugin-loading or SDK changes. This green PR run does not establish green scheduled CI on main.
steipete added a commit that referenced this pull request Oct 17, 2026
node-worker-launch-wire ran three 12-turn finalization load waves and reached its post-restart audit at ~237 s, timing out at the 240 s test budget and reddening unrelated PRs' changed-test shards. One wave keeps peak concurrency, all readiness samples and assertions; the file now finishes in ~117 s in CI. The original SessionActorStaleVersionError was fixed by #169107.

Fixes #169095
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 18, 2026
node-worker-launch-wire ran three 12-turn finalization load waves and reached its post-restart audit at ~237 s, timing out at the 240 s test budget and reddening unrelated PRs' changed-test shards. One wave keeps peak concurrency, all readiness samples and assertions; the file now finishes in ~117 s in CI. The original SessionActorStaleVersionError was fixed by openclaw#169107.

Fixes openclaw#169095
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]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 24, 2026
…rminal commit

The 03de seats logged "followup queue: terminal handling failed after
execution; refusing replay: Session actor version changed before command
admission" in busy rooms. The suspect was the fork's post-completion
scheduleContinuation in followup-runner.ts (its no-signal run and the
trailing turn.session.publish(getActiveSessionEntry())).

This regression drives the real followup runner, accounting,
scheduleContinuation and SQLite terminal completion with no continuation
signal, while room participants write the same session either right after
the terminal commit or while the terminal command commits, with and
without a tool-queued delegate that scheduleContinuation dispatches after
completion. It asserts one model run, one completed source settlement, no
"refusing replay", persisted usage and chain state, and the exact commit
order.

At this head all four cases pass. With runSessionActorCommand put back in
its 03de form (single stale-version rebase outside the writer FIFO, before
upstream openclaw#169107 ef6747c), both "while" cases fail with the seats' exact
line. The stack puts the throw in complete() at
agent-runner-completion.ts:175, called from followup-runner.ts:342 (the
upstream turnCompletion.complete() call), before the fork's
scheduleContinuation line runs. Removing the trailing publish leaves that
failure unchanged and changes nothing at this head: the publish only
stores the handle's own current entry back into its in-memory map.

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

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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