Skip to content

fix(sqlite): release settled writes behind read cursors - #169064

Merged
steipete merged 1 commit into
mainfrom
codex/stab-session-actor-writer-leak
Oct 11, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/stab-session-actor-writer-leak

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

During a stability run on main 90f04bfb10df, every turn of one agent began failing 60-200 ms after dispatch with Session actor has an unsettled database writer. That included brand-new sessions; the transcript showed "Your request couldn't be completed", and nothing was logged before the first failure. It persisted until the Gateway restarted. Other agents (separate databases) kept working. While it was stuck, an external BEGIN IMMEDIATE; ROLLBACK on that agent's database succeeded instantly, so SQLite held no write lock; the stuck state was in-process.

Why This Change Was Made

src/infra/sqlite-schema-facts.ts released a settled write's shared data fence (finishSqliteDatabaseWrite) only when the handle's nativeDepth reached zero. nativeDepth also counts a SELECT iterator parked between yielded rows (sqlite-native-observer.ts). A write could therefore settle completely while an unrelated reader stayed open on the same connection, and its writer registration stayed in the shared cell. Siblings then read an undefined scoped write token, and the session actor (session-actor.worker.ts) refuses every session that shares that database.

The data fence now follows the existing mutationDepth counter, which tracks data, schema, and control operations. Explicit transactions and unfinished RETURNING cursors keep their fence until settlement; read-snapshot and schema lifetimes keep their nativeDepth owner. No retries, timeouts, caches, or new state. The faulty condition dates to 1d76f57d4be5 (#167965); the strict actor read that turns it into a hard failure arrived with #168602 and became the transcript path in #168539.

The exact production reader that was parked during the incident was not identified. This change fixes the demonstrated leak at the native owner that matches every observed symptom.

User Impact

An agent can no longer get stuck failing every message until a Gateway restart because an unrelated read was open when a write settled.

Evidence

  • Five native regressions fail on the original production code and pass after. Each checks that a sibling can take the SQLite write lock while its scoped token stays undefined until the unrelated reader closes, across autocommit, explicit commit and rollback, a throwing managed transaction callback, and RETURNING-cursor settlement (which stays fenced).
  • Six selected SQLite/session suites: 168 tests in 22.95 s; final native suite: 61 tests in 20.61 s. Types, lint, format, import cycles, and line caps pass; autoreview clean through P2.
  • Live no-regression run on a dev Gateway built from this head, real OpenAI provider:
    • 4x8 concurrent burst: 32/32 final on both runtimes.
    • Agent hot-reload race against chat.send: 6/6 delivered.
    • Multi-turn session normal.
    • The incident itself could not be re-triggered on demand, even on main.
  • Production +4/−5. Tests +82. Docs: docs/reference/database-schemas.md describes the corrected fence lifetime. No schema, stored data, protocol, or update behavior change.
  • Inherited and unrelated: pnpm check:max-lines-ratchet flags unchanged src/web-search/runtime.test.ts.

Release data-writer custody when write-capable native operations and explicit transactions settle. Independent read cursors keep their snapshots without blocking session actor receipts across the whole agent database. Cover autocommit, commit, rollback, throwing transaction callbacks, and RETURNING cursor settlement with native regressions.
@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 size: S 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: 👀 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 releases settled SQLite write fences even when an independent read cursor remains open.

Example: A connection pauses SELECT over rows 1 and 2, then commits INSERT of row 3.

  • Before: SQLite releases its write lock, but the shared writer fence remains until SELECT closes, preventing sibling session actors from obtaining a receipt.
  • After: The settled write releases its fence immediately; unfinished RETURNING cursors and explicit transactions remain fenced.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-supported repair with useful native integration coverage; confidence in the exact live incident remains limited by the unidentified reader and absence of a direct incident replay.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; native SQLite regressions exercise the changed settlement owner, while reported real-provider Gateway runs support only their stated no-regression scenarios.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An affected agent rejects every message, including new sessions, until the Gateway restarts.
Reason: The maintainer-authored repair addresses an evidenced native settlement defect within the existing storage owner and adds no public contract or configuration choice.

Regression provenance

Regression provenance — verified: source commit 1d76f57d4be5 by Peter Steinberger; canonical PR #167965 (blame-to-merge-commit).

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it repairs a concrete write-fence leak still present on current main, preserves unfinished-write fencing, and introduces no actionable defect found in this review.

Priority: P1
Reviewed head: c9be442a31420a1f935319bbfa27c036e7694a38

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied Gateway no-regression results do not demonstrate session-actor recovery with the specific parked-reader trigger; native baseline failures are reported rather than independently rerun.
Agent review details

How this fits together

Native SQLite operation observation feeds the physical-database admission owner, whose shared write receipts let sibling connections and session actors validate cached state.

flowchart LR
  A[SQLite statements and cursors] --> B[Native operation observer]
  B --> C[Schema and mutation lifetimes]
  C --> D[Database admission owner]
  D --> E[Shared write receipts]
  E --> F[Session actor reads]
Loading

Technical review

Best possible solution:

Land the focused native-owner repair with its transaction and unfinished-cursor regressions once required checks permit landing.

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

Source establishes the parked-SELECT write-fence leak and the session actor rejection it causes; the author reports five failing-before/passing-after native cases, but this read-only review ran no code and does not independently reproduce the original Gateway incident.

Is this the best way to solve the issue?

The patch fixes settlement at the existing native owner using an established mutation counter, preserving explicit transactions, unfinished write cursors, schema lifetimes, and receipt publication ordering without retries or new state.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Data-write fence settlement keeps the original intent (1d76f57: Replace runtime freshness probes with shared owner-published write revisions, publishing before native write custody is released.)
  • Iterator schema-fact expiration keeps the original intent (bb7d32e: Keep native iterator schema facts local to their snapshot while reusing physical-database admission.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Focused settlement repair: The introduced patch changes data-write settlement from nativeDepth to mutationDepth while retaining the explicit-transaction guard; schema settlement remains under nativeDepth. (src/infra/sqlite-schema-facts.ts:399, c9be442a3142)
  • Current-main failure path: Fetched main still requires nativeDepth to reach zero before releasing a settled write; a stepped SELECT iterator retains that depth until its native observation ends. (src/infra/sqlite-schema-facts.ts:401, 4db95aa552f7)
  • Caller-visible consequence: The session actor rejects reads when the scoped write token is undefined, producing the reported unsettled-writer error. (src/config/sessions/session-actor.worker.ts:116, c9be442a3142)
  • Native storage regressions: Added cases exercise real SQLite connections, independent lock acquisition, committed or rolled-back rows, scoped receipt availability, and continued fencing of an unfinished RETURNING writer; the author reports baseline failures and head passes. (src/infra/sqlite-schema-facts.native.test.ts:41, c9be442a3142)
  • Original publication contract: improve: reduce SQLite work during chat turns #167965 introduced the exact settlement condition while replacing foreign-commit probes with owner-published receipts; this repair preserves publication before fence release. (src/infra/sqlite-schema-facts.ts:401, 1d76f57d4be5)
  • Runtime evidence and its limits: The full PR body reports native regressions and successful real-provider Gateway bursts, hot reload, and multi-turn sessions, but explicitly states that the original incident could not be retriggered and its parked production reader was unidentified; discussion contains no additional behavior artifact. (c9be442a3142)

PR surface

Source -1, Tests +82, Docs +3. Total +84 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 4 5 -1
Tests 1 82 0 +82
Docs 1 4 1 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 90 6 +84

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +4/−5; tests +82 Production code shrinks while native integration cases cover distinct commit, rollback, callback-failure, and cursor-settlement contracts.

Labels

Label changes:

  • add P1: The reported main regression prevents every turn for an affected agent until Gateway restart, and source establishes the leaking fence path.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: The reported main regression prevents every turn for an affected agent until Gateway restart, and source establishes the leaking fence path.
  • 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.

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.

Reviewed October 11, 2026, 6:33 AM ET / 10:33 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper approve

Maintainer decision (coordinator for Peter, 2026-10-11): bug fix in in-memory database admission - releases a leaked write fence that wedged an agent until restart; no schema, stored data, or update behavior change.

@clawsweeper

clawsweeper Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@steipete
steipete merged commit 069a5b8 into main Oct 11, 2026
129 checks passed
@steipete
steipete deleted the codex/stab-session-actor-writer-leak branch October 11, 2026 10:42
@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
)

Release data-writer custody when write-capable native operations and explicit transactions settle. Independent read cursors keep their snapshots without blocking session actor receipts across the whole agent database. Cover autocommit, commit, rollback, throwing transaction callbacks, and RETURNING cursor settlement with native regressions.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 18, 2026
…1475 D2)

After an errored turn, every later turn on cael's room session failed in
about 100 ms with "Session actor has an unsettled database writer" until a
Gateway restart. On 855242b a settled write on a connection that still
holds a parked read cursor never releases its data-writer custody, so the
database-wide fence wedges every session actor command on that agent
database. Each actor turn here is a fresh durable acquisition over the real
agent worker, like production turns.

Fossil: a failed, committed, or autocommit write behind a parked cursor,
then two later turns must commit. Controls at the same boundary: native
entry-write and COMMIT failures settle so the same actor commits next, and
a lost COMMIT+ROLLBACK or worker exit leaves the next turn working without
replay.

Also carries upstream's native owner regressions from
openclaw#169064 (069a5b8) in sqlite-schema-facts.native.test.ts.

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 18, 2026
Carry openclaw#169064 (069a5b8, "fix(sqlite): release settled
writes behind read cursors") unchanged. Data-writer custody is released
when the connection has no active write-capable statement and no explicit
transaction (mutationDepth), not only when every native statement on the
connection has finished (nativeDepth). An independent read cursor, such as
one an errored or aborted turn leaves parked, no longer keeps a settled
write fencing every session actor on the agent database. Active write
cursors and explicit transactions still hold their fence until settlement.

No schema, stored data, or update behavior changes.

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 19, 2026
First-parent upstream f4f4868..069a5b8 (11 commits: openclaw#168607 batch
input acceptance and run adoption, 7158f2b, openclaw#168815, openclaw#168882 update
and service lifecycle, ec5fe47, openclaw#169036 test batch d049, 4db95aa,
cedb310 web-search split, openclaw#169056, openclaw#169061, and openclaw#169064 release
settled writes behind read cursors).

Conflicts:
- user-turn-transcript.ts: upstream moved persistUserTurnTranscript into
  user-turn-transcript.persistence.ts. Our earlier line-cap move
  (user-turn-transcript.persist.ts) was a pure move, so it is retired in
  favour of upstream's module. Our session-delivery ack replacement is
  kept and now also refuses once upstream's committedInput is set (the
  same state upstream's hasPersisted counts).
- agent-runner-execute.context-read.test.ts: both import additions kept.

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 19, 2026
… step 54

First-parent upstream cb1b6cd..19fe879: openclaw#168859
"refactor(infra): simplify database and worker coordination". Replaces
the cold-admission predecessor graph with keyed top-level ordering,
drops writer-preparation revocation (prepareSqliteDatabaseWriter and
friends), borrower counts, worker ancestry and snapshot-staging
supervision.

No conflicts. None of the 20 exports it removes is referenced by fork
code (only an upstream test-support local of the same name). Worker
access inventory regenerated on the merged tree.

This is the absorb target for #1475: openclaw#169064 (D2)
arrived at step 50; the D5 producer (writer-prep revocation) is gone here.

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 19, 2026
…omes (#1475 D1)

Carry adaptation for 454e86e on the 19fe879 absorb. The framed
commit admission now carries `publication: turn ?? commitPublication`
inside its outcome envelope, as the inline admission does since upstream
openclaw#168607 and as upstream's own openclaw#169843 (ca0a172) shapes it. The host
already hands `outcome.publication` to the caller's authority, so an
oversized session's turn keeps its commit-stage custody recheck.

No D2 code is involved; upstream openclaw#169064 is untouched.

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

docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. 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