Skip to content

fix(node:sqlite): finalize outstanding statements on close (upstream #40005) - #9

Merged
steipete merged 14 commits into
mainfrom
claude/node-sqlite-close-finalize
Sep 27, 2026
Merged

steipete merged 14 commits into
mainfrom
claude/node-sqlite-close-finalize

Conversation

@steipete

@steipete steipete commented Sep 27, 2026 •

Copy link
Copy Markdown

What does this PR do?

Lands the node:sqlite close-finalize fix on the fork by merging the head of upstream oven-sh/bun#40005 (900eae3009991d27a524a8c0d54f9ed66e4acef4, still open upstream) as a merge parent. The approach follows #1, and it adds Node-parity tests on top.

In Bun 1.4.2, DatabaseSync.close() and [Symbol.dispose]() call sqlite3_close_v2() without finalizing outstanding StatementSync handles. SQLite then leaves the connection as a zombie. The descriptors, POSIX locks, and -wal/-shm files stay open until every statement wrapper is garbage-collected. After this change, both paths finalize the wrapper-owned statements first, matching Node. The connection then closes at once: the last connection checkpoints the WAL, unlinks both sidecars, and releases its locks and descriptors.

Review of the native change

  • NodeSqliteConnectionRecord is refcounted and shared by a connection and its statements. It tracks the raw sqlite3_stmt* handles owned by StatementSync wrappers, not JS cells, so GC sweep order does not matter. Explicit close()/dispose sets statementsFinalized, moves the set out, and finalizes it before sqlite3_close_v2(). A wrapper swept later sees the flag and does not double-finalize.

  • Only wrapper-owned handles are finalized. sqlite3_next_stmt(), which the first version used, also returns private statements that virtual-table modules (FTS5, R*Tree, sqlite-vec) prepare and later finalize in xDisconnect. I confirmed that the old walk still crashes here. With dea4e29 reverted, the FTS5, R*Tree, and vec0 tests below all fail (ASAN SEGV in sqlite3_finalize).

  • These unchanged paths still leave the connection as a zombie, by upstream's deliberate choice:

    • GC-destructor close and VM-termination close, which must not run user JS.
    • A close() re-entered from a UDF or authorizer. It is deferred to ~BusyScope, where an aggregate xFinal must not fire.

    The worker-exit sweep still checkpoints unclosed databases.

  • Pre-existing and unchanged: on a finalized statement, iterator.return() and next() on an exhausted iterator return { done: true }. Node throws ERR_INVALID_STATE in both cases. NodeSqlite.cpp documents this as a deliberate divergence, so IteratorClose after db.close() does not throw. next() on a live iterator matches Node.

Tests added

The new block is describe("close() and Symbol.dispose() with outstanding statements"). It sits away from oven-sh#40005's hunks; its only overlap is the harness import line (see Upstream reconciliation). Each case asserts sidecars before and after close, plus finalized-statement errors.

Requirement Tests
Close and dispose with live and iterating statements close/dispose × a retained run() statement, a live iterate() cursor, an exhausted cursor, a tag store, and a mix (10 cases). This complements upstream's unused/get/all cases.
WAL checkpoint wal_autocheckpoint = 0, then close with a live cursor. The main file grows to exactly page_count × page_size, and the sidecars are gone.
File and lock release Another process switches journal_mode to DELETE and takes locking_mode = EXCLUSIVE + BEGIN EXCLUSIVE with timeout: 0, then the file is deleted and the directory is empty. A worker closes one of two databases while it keeps running, and the main thread then takes exclusive access. That second case is the shared-worker shape OpenClaw needs.
Virtual tables FTS5 and R*Tree, file-backed WAL, 3 close/reopen cycles with completed and live queries. sqlite-vec vec0 gets the same treatment in a subprocess, plus a rowid lookup that makes vec0 cache a private statement.
Repeated cycles without leaks 50 open/close cycles alternate close() and dispose while retaining 150 statements and cursors. Every cycle leaves no sidecars, the /dev/fd delta is 0, and the file can be deleted, which is the Windows handle check.

The vec0 test skips where it cannot run: musl (sqlite-vec's Linux x64 build links libc.so.6 with GLIBC_2.14 symbol versions), platforms without a prebuilt (for example windows-arm64), and macOS without an extension-capable library. Apple's system SQLite omits extension loading, so on macOS the test selects Homebrew SQLite in its subprocess, as OpenClaw does.

How did you verify your code works?

All runs used macOS 27 arm64. Apple's system SQLite 3.54.0 backed the in-process tests; Homebrew SQLite 3.53.4 backed vec0 and the stress runs, with sqlite-vec 0.1.9 (sha512 matches the lockfile).

Check Result
bun bd test test/js/node/sqlite/node-sqlite.test.ts (debug+ASAN, b7b1c3a08) 143 pass, 4 skip, 0 fail (126 existing + 17 new)
bun run build:release test test/js/node/sqlite/node-sqlite.test.ts 143 pass, 4 skip, 0 fail, 3.84 s
Same file on the unpatched fork base (openclaw/main NodeSqlite.{cpp,h}, debug+ASAN) 120 pass, 23 fail: exactly the 17 new tests + upstream's 6 WAL-sidecar tests
USE_SYSTEM_BUN=1 (Bun 1.4.2) 17/17 new tests fail for the intended reasons: sidecars left, no checkpoint, database is locked, leakedFds: 101
Same 17 test bodies, extracted verbatim and run under Node v26.9.0 with a minimal bun:test shim 17/17 pass; the same shim under Bun 1.4.2 gives 0/17
dea4e29 reverted (old sqlite3_next_stmt() walk), debug+ASAN FTS5, R*Tree, vec0 and upstream's FTS5 test fail: ASAN SEGV in sqlite3_finalize
18 vendored test/js/node/test/parallel/test-sqlite-* files 18/18 files, 319 pass, 4 skip, on both debug+ASAN and release
[email protected] + [email protected] --check (CI's formatter config), git diff --check, bun test test/internal/source-lints/ clean; 196 pass (includes lockfile-registry-only)

Shared-worker stress (not committed). 4 long-lived workers multiplex 16 databases. Each has a WAL table, FTS5, and vec0. Every round, each database reopens, inserts, runs FTS/KNN/rowid queries, retains live cursors and a tag store, and closes (alternating close() and dispose) inside its still-running worker. The main thread then demands exclusive access. The identical script ran on every runtime:

Runtime Cycles Lock failures Sidecars left fd delta RSS delta
Node 26.9.0 3,216 0 0 0 37 MiB
This PR, release 3,216 0 0 0 12 MiB
This PR, debug+ASAN 176 0 0 0 (ASAN quarantine)
Bun 1.4.2 416 416 416 +800 83 MiB

Also checked: close() racing an in-flight backup(). Node and this PR both resolve the backup with a complete copy (2,000 rows, integrity_check ok). This PR releases the source's sidecars at close(); Node releases them when the backup settles.

Not verified here: Linux and Windows execution. The Windows-specific assertions are the rmSync() checks, which I could not run. The fork's GitHub CI has no native test lanes; its PR checks are lint, format, and type jobs. No Rust changes, so rust:check-all was not needed.

Upstream reconciliation

OpenClaw follow-up: retiring the Bun-only dedicated-worker layout

Yes, for runtimes that include this fix. OpenClaw's docs set the condition: "revisit after the upstream close fix ships and repeated close/reopen tests prove native handles and locks are released". The shared-worker stress above is that proof, in Node's layout: 4 workers, 3,216 cycles, sqlite-vec and FTS5 included, zero lock, sidecar, or descriptor leaks. OpenClaw's own usage is covered too. It registers scalar UDFs, which cannot trigger the deferred-close or xFinal paths, and it awaits backup() before closing.

The change belongs in openclaw/openclaw. It should gate on capability, not on process.versions.bun. Stock Bun 1.4.x is still a supported opt-in runtime and keeps the leak until upstream ships oven-sh#40005, and a version string does not show whether a fork build includes the fix.

  1. Probe once. In requireNodeSqlite()/assertSafeSqliteRuntime() (src/infra/node-sqlite.ts), open a temp WAL database. Keep a stepped statement and a live iterator referenced, call close(), and check that -wal/-shm are gone. Record releasesHandlesOnClose, and replace the "Bun follow-up" comment there.

  2. src/infra/sqlite-worker-broker.ts, acquireSlot(): when the probe passes, use this.maxWorkers shared slots and the borrowed-generation slot, as Node does. Drop the MAX_STORES-per-database branch and the "Return Bun to shared workers after node:sqlite: finalize outstanding prepared statements in DatabaseSync.close() oven-sh/bun#40005" comment.

  3. src/infra/sqlite-worker-broker-lifecycle.ts, closeActor(): when the probe passes, call markNativeStopped() after the close reply. Use the Node retirement condition (a failed slot, or one with no pending opens whose actors have all closed) instead of always retiring on Bun, which "keep[s] pathname ownership until VM exit". Keep the Darwin ensureSqliteLibrarySelected() call; it is library selection, not handle release.

  4. Tests: run the Bun-skipped suites under the fork build as the acceptance gate:

    • sqlite-worker-native-stop and sqlite-worker-open-refusal (skipIf(bun))
    • the nodeIt cases in sqlite-worker-broker, sqlite-worker-store, sqlite-worker-store.generation, and sqlite-worker-shared-state-idle
    • the broker lifecycle in sqlite-readonly-worker.auth

    Then gate those suites on the probe rather than on Bun.

  5. Docs: in docs/install/bun-compatibility.md, scope the "SQLite handles" and "SQLite storage workers" limitations to runtimes without the fix, and add a history row.

Two residual differences remain, and neither affects OpenClaw's usage: a close() re-entered from inside a UDF or authorizer still defers finalization to GC, and a database dropped without close() still relies on GC or the worker-exit sweep.

robobun and others added 12 commits August 21, 2026 21:34
….close()

With an unfinalized statement, sqlite3_close_v2 only zombifies the
connection and the OS file handle stays open until every statement
wrapper is GC'd. On Windows that handle locks the database file, so
deleting it (or its directory) after close() fails with EBUSY.

close() and Symbol.dispose now finalize every outstanding statement
through sqlite3_next_stmt before sqlite3_close_v2, like Node. A shared
refcounted record per connection tells statement wrappers that their
handle is already gone, so the GC destructor does not double-finalize
regardless of sweep order. The GC-destructor and VM-termination close
paths keep the zombify behavior: finalizing a half-stepped statement
can fire a user aggregate's xFinal, which must not run there.

Fixes oven-sh#40001
…nalize walk

A close() re-entered from the statement walk (or a deferred close that
completes during it) must not clear m_registeredCallbacks while the
outer walk can still invoke the UDF contexts it roots. Guard the clears
with a walk-depth counter and clear once the outermost walk finishes.
releaseSupersededRegistration() clears individual slots of the same
vector the walk-depth guard protects. A re-entrant registration from
the walk's xFinal must not unroot callbacks the rest of the walk can
still invoke. Drop only the bookkeeping entry in that window and let
the outermost walk's tail release the roots.
Add Node-parity coverage for DatabaseSync.close() and Symbol.dispose()
with retained statements: run(), live and exhausted iterate() cursors,
tag stores, WAL checkpoint into the main file, file locks released to
another process and from a still-running worker, FTS5/R*Tree/sqlite-vec
vec0 private statements across reopen cycles, and descriptor/sidecar
leaks over repeated open/close cycles. Expected values match Node
v26.9.0; every new case fails on Bun 1.4.2.

Pin sqlite-vec 0.1.9 (the version OpenClaw ships) for the vec0 case.
@autofix-troubleshooter

Copy link
Copy Markdown

Hi! I'm the autofix logoautofix.ci troubleshooter bot.

It looks like you correctly set up a CI job that uses the autofix.ci GitHub Action, but the autofix.ci GitHub App has not been installed for this repository. This means that autofix.ci unfortunately does not have the permissions to fix this pull request. If you are the repository owner, please install the app and then restart the CI workflow! 😃

@steipete
steipete merged commit 19e77a7 into main Sep 27, 2026
5 checks passed
@steipete
steipete deleted the claude/node-sqlite-close-finalize branch September 27, 2026 05:54
steipete pushed a commit to fuller-stack-dev/bun that referenced this pull request Oct 20, 2026
…module-graph.test.ts (oven-sh#45674)

### What does this PR do?

Fixes the flaky "50 graphs alive at once, each with its own state, then
all exit and are collected" in
`test/js/bun/module-graph/module-graph.test.ts`. It failed in 2 of 31
builds of main, 125686 to 127114 (Ubuntu 25.04 x64, Windows 11 aarch64)
and passed on the retry.

The test registered one array, `graphs[25].big`, with a
`FinalizationRegistry` and failed if 100 collections did not finalize
it. It now tracks the array of every one of the 50 graphs with
`Lifetimes` from `module-graph-lifetimes.ts`, as
`module-graph-gc.test.ts` does. There, an object that is not finalized
counts as kept alive only if a root reaches it in the debugging heap
snapshot, and the failure message is the path from that root.

Two things change with the helper, and the first is what makes the runs
below pass:

1. **Where the collection runs.** The helper calls `Bun.gc(true)` from a
timer callback, main's `collected()` from the continuation of the async
test. The `runInternalMicrotask` frame that holds the stale word
(artifact 2) is not on the stack in a timer callback. In 240 of 240 runs
all 50 arrays were finalized by the first collection.
2. **What is asserted if one is left.** Not that it was finalized, but
that no root reaches it.

### Why it failed

On main one of the 50 graphs outlives the collections in almost every
run, and the test fails when that one is number 25. Whole file, CI's
environment, 840 runs:

| graphs left after the collections | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| runs | 2 | 802 | 3 | 33 |

12 of the 840 failed. In the failing runs looked at (9 heap snapshots,
12 stack dumps) nothing in the heap holds the one that is left, and one
word on the native stack points at it.

All of what follows is the Linux x64 binary that CI built for main at
7f3bc6a, with `BUN_GARBAGE_COLLECTOR_LEVEL=1
BUN_RUNTIME_TRANSPILER_CACHE_PATH=0` as in `scripts/runner.node.ts`. The
failure needs both that environment and the whole file: 0 of 240 without
the environment, 0 of 1600 with the test alone. I did not look at the
Windows failure.

<details><summary>Artifact 1: the heap snapshot</summary>

`generateHeapSnapshotForDebugging()` right after the 100 collections.
These are the array and every cell from which it can be reached:

```
snapshot: 27033 cells, 99750 edges, 586 roots; arrays named `big` still in it: 1
  cell   1532 Promise                0x34cf520fa40  incoming edges 0  in `roots` no  a root reaches it no
  cell   1555 ModuleRecord           0x34cf527e980  incoming edges 3  in `roots` no  a root reaches it no
  cell   1573 ModuleNamespaceObject  0x34cef51dd50  incoming edges 3  in `roots` no  a root reaches it no
  cell   1591 JSModuleEnvironment    0x34cf5278950  incoming edges 3  in `roots` no  a root reaches it no
  cell   1626 Array                  0x34cef3755a0  incoming edges 2  in `roots` no  a root reaches it no
  cell   1631 Function               0x34cef45a100  incoming edges 2  in `roots` no  a root reaches it no
  cell   1653 Function               0x34cef45a0e0  incoming edges 2  in `roots` no  a root reaches it no
```

The snapshots of 8 other failing runs have the same seven kinds of cell,
with the `Promise` (fulfilled with the `ModuleRecord`) as the only one
without an incoming edge.
</details>

<details><summary>Artifact 2: the stack word and the frame that owns it
(gdb, same run as artifact 1)</summary>

The test writes the snapshot and sends itself SIGUSR2, and gdb stops
there.

```
Thread 1 "bun-profile" received signal SIGUSR2, User defined signal 2.
(gdb) info registers rsp rbp
rsp            0x7fffffffa0c8
rbp            0x7fffffffa240

words in [rsp, end of stack) = [0x7fffffffa0c8, 0x7ffffffff000) that point into one of those cells: 1
  0x7fffffffa8a0 holds 0x34cf520fa40 = Promise+0; it lies in the frame with rbp 0x7fffffffa8f0, at rbp-0x50
(gdb) x/gx 0x7fffffffa8a0
0x7fffffffa8a0:	0x0000034cf520fa40
(gdb) info symbol 0x1bccee0        # where that frame's callee returns to
JSC::runInternalMicrotask(...) + 6976

rbp chain
  openclaw#3  rbp 0x7fffffffa540  Bun::Process_functionKill
  openclaw#4  rbp 0x7fffffffa550  (JIT code)
  openclaw#5  rbp 0x7fffffffa5d0  op_call_ignore_result_return_location
  openclaw#6  rbp 0x7fffffffa680  llint_call_javascript
  openclaw#7  rbp 0x7fffffffa7e0  JSC::asyncFunctionGeneratorBodyCall
  openclaw#8  rbp 0x7fffffffa8f0  JSC::runInternalMicrotask            <- owns 0x7fffffffa8a0
  openclaw#9  rbp 0x7fffffffab70  JSC::MicrotaskQueue::drainWithUseCallOnEachMicrotask
  openclaw#10 rbp 0x7fffffffac00  JSC::VM::drainMicrotasks
  openclaw#11 rbp 0x7fffffffac20  Zig::GlobalObject::drainMicrotasks
  openclaw#12 rbp 0x7fffffffac50  <bun_jsc::event_loop::EventLoop>::exit
  openclaw#13 rbp 0x7fffffffacf0  TimerObjectInternals::fire
```

12 failing runs that dumped their own stack from `/proc/self/mem` show
the same: one word, `Promise+0`, at `rbp-0x50` of
`runInternalMicrotask`. In the 5 of them where I looked for it, the
frame's callee returns to the same `0x1bccee0`, which is
`JSMicrotask.cpp:2053`.

**Who wrote it.** A hardware watchpoint on `0x7fffffffa8a0`, set at the
first line of the test, sees 10 writes. The last one is the `Promise`:
`pushq %r14` in the prologue of `JSC::ModuleGraphLoadingState::create`
(`ModuleGraphLoadingState.cpp:71`, rbp `0x7fffffffa8b0`), which saves a
register of its caller.

**Why it stays.** The 100 collections run in the continuation of an
async function, so each runs under a `runInternalMicrotask` frame at
that same address. In the disassembly the function has 9 stores to
`-0x50(%rbp)`. Following the jump table and every branch, only case 14
of the switch (resume an async function) reaches the call at
`JSMicrotask.cpp:2053`, and none of the 9 stores is on a way to it. The
slot is inside a live frame, so stack sanitizing does not cover it.

So the graph that is left is the one whose load called `create` last at
that depth.
</details>

### How did you verify your code works?

**Failure rate.** Whole file, 12 copies side by side, main and this PR
in alternating rounds:

| | main | this PR |
|---|---|---|
| runs that failed | 12 of 1200 (all this test) | 0 of 1200 |

**What the snapshot says about a survivor.** With this PR there was none
to ask about: in those 240 runs, with a logging copy of the helper, the
snapshot was never taken. So this is main's test as it is, followed by
the helper's `Heap` asked about the 50 addresses, 1080 runs. The old
assertion failed in 12 of them. In 11 the array was in the snapshot with
no root reaching it, in 1 it was gone by then, in 0 a root reached it.

In 7 of the 1080 runs a root did reach two other arrays. In the one run
whose paths were printed, both start at `root(JITWorkList)`, a
compilation that is still running. `stillAlive` goes on collecting while
a root reaches something.

**Real references must fail.** One line added before `graphs.length =
0`. All 9 fail, with these messages:

| graph 25 is held by | message |
|---|---|
| a global, the namespace | `root(ProtectedValues) GlobalObject
-Property:held-> ModuleNamespaceObject -> ModuleRecord ->
JSModuleEnvironment -> Array` |
| a global closure over `inc` | `root(ProtectedValues) GlobalObject
-Property:held-> Function -> JSLexicalEnvironment -Variable:inc->
Function(inc) -> JSModuleEnvironment -> Array` |
| a local of the suspended test | `root(Output) FunctionCodeBlock -> ...
-Variable:pendingHeap-> Promise -> AsyncFunctionGenerator -> ...` |
| `setInterval(inc)` | `root(StrongHandles) StrongRootBlock -> Timeout
-Property:callback-> Function(inc) -> JSModuleEnvironment
-Variable:big-> Array` |
| `process.on(..., inc)` | `root(ProtectedValues) GlobalObject ->
Process -> Function(inc) -> JSModuleEnvironment -Variable:big-> Array` |
| a reaction of a pending promise | `root(ProtectedValues) GlobalObject
-Property:held-> Promise -> Function(inc) -> JSModuleEnvironment
-Variable:big-> Array` |
| a `FinalizationRegistry` held value | `root(ProtectedValues)
GlobalObject -Property:held-> FinalizationRegistry -> Array` |
| a `WeakMap` value of a live key | `root(Output) Array` |
| an `AbortSignal` listener | `root(WeakSets) AbortSignal ->
Function(inc) -> JSModuleEnvironment -Variable:big-> Array` |

With `globalThis.held = graphs[7]` instead, main's test passes 5 of 5
and this PR's fails 5 of 5.

**Debug build**, default timeout: the test passes 6 of 6 alone and in 6
of 6 runs of the whole file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants