Skip to content

fix(infra): stop finished node:sqlite iterators from restarting and pinning the WAL - #184076

Closed
ava-perry wants to merge 3 commits into
openclaw:mainfrom
ava-perry:docs-sqlite-node-24-18-0-iterator-143524
Closed

ava-perry wants to merge 3 commits into
openclaw:mainfrom
ava-perry:docs-sqlite-node-24-18-0-iterator-143524

Conversation

@ava-perry

Copy link
Copy Markdown
Contributor

Summary

On Node 24.16.0 through 24.18.0 (fixed in 24.18.1), calling next() on a node:sqlite StatementSync iterator that already returned done restarts the statement and leaves it stepped. The connection then holds a WAL read snapshot while isTransaction is false, so every WAL checkpoint stays blocked and the -wal file grows until the Gateway restarts. The upstream fix is nodejs/node@af9ff0490c (CVE-2026-58041, "sqlite: invalidate tag store iterators on statement reset"), which also marks the iterator done on SQLITE_DONE. Root cause, bisect and production before/after: #143524.

This PR:

  1. Guard (code). Once the observed iterator wrapper has seen done (from next() or from an earlier return()), later next() and return() calls are answered by the wrapper with a fresh copy of the terminal result and never reach the native iterator. The native iterator is not stepped after done and is not finalized twice. On main the engines field already excludes the affected releases; the guard removes the dependency on the probe and on the Node version.
  2. Docs. A "Known Node 24 issues" table on /install/node-compatibility (the Fixed-in cell names nodejs/node@af9ff0490c and CVE-2026-58041) and a "SQLite WAL grows and checkpoints stay blocked" runbook on /gateway/troubleshooting/gateway-service-and-process, linked from the troubleshooting index.

Why main's existing iterator check does not cover 24.18.0

Line numbers are on main c96f35d5d60.

  • Where and when it runs. assertSafeSqliteRuntime() (src/infra/sqlite-native-runtime.ts:124-184) runs from openNodeSqliteDatabase() (src/infra/node-sqlite.ts:112), once per process: the result is cached at sqlite-native-runtime.ts:127-129, and worker isolates reuse the parent's result through environment data (:130-140). It calls probeSqliteIteratorBehavior() (src/infra/sqlite-native-observer.ts:25-45) on a one-row :memory: statement (sqlite-native-runtime.ts:149-154).
  • What it decides. The probe steps the iterator past done once more and records nextAfterDoneIsTerminal = previous.next().done === true (sqlite-native-observer.ts:29). On 24.18.0 that extra next() restarts the statement and returns the row again, so the probe correctly reports false. The probe does not reject the runtime: the only hard gate in that function is the SQLite WAL-reset version check (assertSqliteWalResetSafeVersion, sqlite-native-runtime.ts:26-36, called at :135 and :157), and SQLite 3.53.1 on 24.18.0 passes it. The probe result is stored as iteratorBehavior and handed to the observer (node-sqlite.ts:107-115, sqlite-native-runtime.ts:168-183).
  • Why a post-done next() still reaches the native iterator. The only consumer is the observed iterator wrapper. When native next() returns done, it sets done = native.iteratorBehavior.nextAfterDoneIsTerminal (sqlite-native-observer.ts:346-347). On 24.18.0 that is false, so the wrapper only calls lifetime.stopObservation(true) (:351) and leaves done false. The next call passes the early-out at :336 (done is false), re-activates the lifetime (:339-342) and calls nativeNext.apply(this, args) (:345), which is exactly the restart. In other words the check makes the observer account for a restartable cursor (custody tracking); it does not prevent the restart, and nothing later steps the restarted statement to done or resets it, so the snapshot stays held. On runtimes where the probe returns true, the post-done call is still forwarded (:336, done || ...), it is just harmless there. return() after done is forwarded to native as well (:360-366).
  • Released builds. The probe is on main only. The v2026.10.5, v2026.10.6 and v2026.10.7 tags do not contain nextAfterDoneIsTerminal; their wrapper re-arms a finished lifetime and forwards post-done next() unconditionally. 2026.10.5's engines field (>=24.16.0 <25 || >=26.1.0) admits 24.16.0 through 24.18.0; 2026.10.6 and 2026.10.7 require >=24.22.1 <25 || >=26.12.1.

With this PR the wrapper answers from terminal before any of that (sqlite-native-observer.ts:340-342 and :363-365 on this branch), so the outcome no longer depends on the probe or on the Node version.

Scope

  • The guard covers iterators created by statement.iterate() on databases opened through openNodeSqliteDatabase(), where trackSqliteSchema() installs the observer (sqlite-schema-facts.ts:223). That is every OpenClaw state and agent database.
  • Grep for direct node:sqlite use outside it (non-test code under src, extensions, packages): new DatabaseSync( appears in src/gateway/worker-environments/bootstrap.ts (:memory:), the workspace-quiescence worker scripts, src/infra/update-managed-service-handoff-sqlite-source.ts, src/infra/bun-sqlite-close-probe.worker.ts, src/infra/sqlite-native-runtime.ts (the probe itself, :memory:) and the knowledge-source-ingest skill scripts. Of these, two call iterate(): the close-capability probe worker (bun-sqlite-close-probe.worker.ts:28, one next() on a temp database that it then closes, never past done) and the knowledge-source-ingest skill scripts (extensions/knowledge/skills/knowledge-source-ingest/scripts/source-manifest.mjs, discrawl-normalize.mjs), which use for...of loops in short-lived CLI processes on their own files. A for...of loop stops at done and never calls next() again. So neither is exposed, and no Gateway state or agent database iterates outside the observer.
  • iteratorBehavior.nextAfterDoneIsTerminal and iteratorBehavior.returnAfterDoneIsInert lose their only consumer in this diff. Grep finds no other reader: the remaining references are the probe (sqlite-native-observer.ts:16-45), admission parsing/transport (sqlite-native-runtime.ts:59-96) and one test (node-sqlite.test.ts:266-268). I left them in place to keep this PR small and can remove the probe and the transport field in a follow-up if you want.

Tests

Run on a temporary Linux VM (Debian 12, n2-standard-16), not on the reporting Windows host. Branch head 4ddc356d618 on base c96f35d5d60.

  • node scripts/run-vitest.mjs run src/infra/sqlite-native-observer.test.ts src/infra/node-sqlite.test.ts on Node 24.22.1: 2 files, 80 tests passed.
  • The extended test (sqlite-native-observer.test.ts:79) spies on the native iterator prototype's next and return, finishes an iterator once by exhaustion and once by return(), then calls next(), return(), next(), return(). It asserts all four results equal the terminal result, native next is not called again, native return is called 0 times (exhausted) or exactly once (returned), and no native execution stays pending.
  • Negative proofs on the same VM:
    • return guard removed: fails with expected "return" to be called +0 times, but got 2 times.
    • next guard removed (post-done next() forwarded as on main): fails with expected "next" to be called 3 times, but got 5 times.
    • main's sqlite-native-observer.ts with the new test: fails.
    • Guards restored: 12/12 pass.
  • Same test file on Node 24.16.0, 24.18.0, 24.18.1, 24.22.1, 26.4.0 and 26.5.1: 12/12 on each.
  • Standalone repro (no OpenClaw; finish an iterator, call next() once more, then wal_checkpoint(PASSIVE) from a second connection): restarts and holds the snapshot on 24.16.0, 24.17.0, 24.18.0 and 26.4.0; returns done and checkpoints fully on 24.18.1, 24.22.1 and 26.5.1. 26.5.1 carries the same CVE fix (nodejs/node@d08fde8a16).
  • pnpm tsgo:core, pnpm tsgo:test:src, pnpm tsgo:all: all exit 0.
  • oxlint on the two touched TS files: 0 warnings, 0 errors (293 rules). oxfmt check on all five touched files: clean. pnpm format:docs:check: clean (1400 files). markdownlint (lint:docs config): 0 issues.
  • pnpm docs:check-links: 16006 internal links, 0 broken. pnpm docs:check-mdx: passed. pnpm docs:check-links:anchors reports 7 findings, none from this diff (all present on main, e.g. docs/gateway/troubleshooting.md:87, an unchanged line). The new links resolve: /install/node-compatibility#supported-versions (## Supported versions), #known-node-24-issues, /gateway/troubleshooting/gateway-service-and-process#sqlite-wal-grows-and-checkpoints-stay-blocked, and /cli/doctor/sqlite-maintenance (docs/cli/doctor/sqlite-maintenance.md). openclaw logs --follow is documented in docs/cli/logs.md and listed by openclaw logs --help.

Tested Node range for the bug: leaks on 24.16.0, 24.17.0 and 24.18.0, fixed in 24.18.1 (also clean on 24.19.0 through 24.22.1 in the Gateway bisect on #143524). Gateway-level reproduction and bisect were on Windows; the standalone repro and this test run were on Linux, so the bug is not OS-specific.

Related: #143524 (root cause), #164294 (same fingerprint, most reports list Node 24.18.0).

Node 24 before 24.18.1 restarts a finished StatementSync iterator on next() and keeps a WAL read snapshot, so checkpoints stay blocked and the -wal file grows until restart. Adds a known-issues row to the Node compatibility page and a troubleshooting entry keyed to the symptoms reported in openclaw#143524.
…e native sqlite iterator

Node 24.16.0 through 24.18.0 (fixed in 24.18.1 by nodejs/node@af9ff0490c,
CVE-2026-58041) restart a finished StatementSync iterator on next() and
leave it stepped, holding a WAL read snapshot that blocks every checkpoint.

The observed iterator wrapper now answers next() and return() itself once
it has seen done, so the native iterator is never stepped again or
finalized twice, whatever the runtime probe reports.

Refs openclaw#143524
@clawsweeper

clawsweeper Bot commented Oct 26, 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 size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Oct 26, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR prevents completed SQLite iterators from reaching native next() or return() again and documents the associated WAL checkpoint problem.

Example: An observed SELECT iterator on Node 24.18.0 is exhausted, then next() is called again.

  • Before: The native iterator restarts the query and can retain a WAL read snapshot.
  • After: The wrapper returns a terminal result without stepping the native statement.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Proof is insufficient for the external-PR gate; the useful patch also has one incomplete-cutover finding.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Affected older Node bindings can retain an invisible WAL reader after iterator completion, causing continuing WAL growth and operational failures.
Reason: The terminal invariant matches upstream's correction and the documentation helps affected installations; this narrowly addresses one demonstrated mechanism rather than every cause of blocked checkpoints.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR: it contributes a focused iterator safeguard and useful recovery guidance, but leaves superseded runtime probing in place.

Priority: P2
Reviewed head: 4ddc356d61833246eb975dfe3ccb8ebac0b20581

Before merge

  • Add real behavior proof - The changed observer is exercised in reported Vitest runs against real native databases, including base-failing controls, but the linked Gateway logs show recovery after upgrading Node rather than running this patch; provide terminal output or redacted logs from the patched product exercising iterator completion and subsequent checkpoint progress, with IPs, API keys, phone numbers, and non-public endpoints removed. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Remove the superseded iterator capability probe in this cutover (P2) - These terminal branches remove the last production consumers of nextAfterDoneIsTerminal and returnAfterDoneIsInert. Nevertheless, every cold native admission still executes the iterator-behavior experiment, and sqlite-native-runtime.ts still validates, caches, and transports its unused results. The PR body explicitly defers their removal, contrary to the root AGENTS.md requirement to remove superseded machinery with its replacement. Remove the private flags and their probe/transport/test plumbing together, while retaining the necessary loaded-library metadata query through the existing admission owner.

Findings

  • [P2] Remove the superseded iterator capability probe in this cutover — src/infra/sqlite-native-observer.ts:353-355

Tests

  • Missing end-to-end proof: Provide a redacted run of the patched product exercising the completed-iterator path and showing checkpoints continue; the reported base-failing regression supports this but does not replace it.
Agent review details

How this fits together

The SQLite observer wraps statements opened through OpenClaw's database owner, translating native execution and iterator completion into custody and schema-observation updates.

flowchart TD
A[Database caller] --> B[OpenClaw database owner]
B --> C[Native operation observer]
C --> D[Statement iterator]
D --> E[Node SQLite binding]
E --> F[SQLite WAL]
C --> G[Execution custody]
Loading

Technical review

Best possible solution:

Keep terminal handling in the existing observer and retire unused iterator-capability probing and transport while preserving SQLite library admission.

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

The current observer source and upstream Node patch establish the restart mechanism on affected bindings, corroborated by the linked standalone output; no target code was executed during this review, and current Gateway runtime floors exclude those standard Node versions.

Is this the best way to solve the issue?

Enforcing terminal completion at the existing iterator owner addresses the demonstrated mechanism, but the obsolete capability machinery should be removed in the same cutover.

Full review comments:

  • [P2] Remove the superseded iterator capability probe in this cutover — src/infra/sqlite-native-observer.ts:353-355
    These terminal branches remove the last production consumers of nextAfterDoneIsTerminal and returnAfterDoneIsInert. Nevertheless, every cold native admission still executes the iterator-behavior experiment, and sqlite-native-runtime.ts still validates, caches, and transports its unused results. The PR body explicitly defers their removal, contrary to the root AGENTS.md requirement to remove superseded machinery with its replacement. Remove the private flags and their probe/transport/test plumbing together, while retaining the necessary loaded-library metadata query through the existing admission owner.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Native iterator completion and stale-return behavior changes intended behavior with a stated reason (bb7d32e: Shared admission probed runtime iterator behavior to preserve native semantics, with 697e5bc subsequently protecting newer cursor custody after stale returns.)
  • Troubleshooting index keeps the original intent (ff61243: Troubleshooting was split into symptom-specific runbooks while retaining the parent as an index.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/infra/sqlite-native-observer.test.ts src/infra/node-sqlite.test.ts src/state/openclaw-schema-metadata.test.ts src/infra/sqlite-schema-facts.native.test.ts --maxWorkers=1
  • pnpm tsgo:core
  • pnpm tsgo:test:src
  • rg -n 'SqliteIteratorBehavior|probeSqliteIteratorBehavior|nextAfterDoneIsTerminal|returnAfterDoneIsInert|iteratorBehavior' src
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit bb7d32e adds src/infra/sqlite-native-observer.ts:27 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bb7d32e55d48; files: src/infra/sqlite-native-observer.ts)
  • Vincent Koc: Raw commit ff61243 adds docs/gateway/troubleshooting.md:32 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: ff612431704a; files: docs/gateway/troubleshooting.md)

PR surface

Source +4, Tests +39, Docs +38. Total +81 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 18 14 +4
Tests 1 40 1 +39
Docs 3 47 9 +38
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 105 24 +81

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is bounded SQLite hardening and recovery documentation; current supported standard Node releases already contain the underlying native fix.
  • 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.

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 execution lanes are retired.

Reviewed October 25, 2026, 10:09 PM ET / October 26, 2026, 02:09 UTC.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @ava-perry for the investigation and fix! Landed the credited replacement in #190242 (2c0ab86), with real WAL checkpoint regressions and the obsolete probe removed.

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 gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants