Skip to content

fix(browser-sqlite): reject pending requests on OPFS close - #2213

Merged
KyleAMathews merged 6 commits into
TanStack:mainfrom
vincentdchn:fix/opfs-close-pending-requests
Oct 21, 2026
Merged

KyleAMathews merged 6 commits into
TanStack:mainfrom
vincentdchn:fix/opfs-close-pending-requests

Conversation

@vincentdchn

@vincentdchn vincentdchn commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

🎯 Changes

Before this PR, close() on a browser OPFS database could leave queries unsettled forever. The connection terminated its worker, so the responses for those queries could never arrive. A caller that waited for that work, for example a transaction or a cleanup step, also waited forever.

Now every request that the connection accepts settles exactly once. Close also behaves as one ordered step in the connection's work:

  1. Close ends admission when it starts. A later execute() rejects at once with the new SQLiteConnectionClosedError and does not reach the worker.
  2. The worker finishes the requests that it received before close, in order, and then closes. Those requests keep their real results.
  3. Concurrent close() calls share one close request and one outcome.
const results = await Promise.allSettled([db.close(), db.close()])
// Before: results[1] rejected with AbortError "The SQLite connection is closed".
// Now: both entries are fulfilled.

const closing = db.close()
await db.execute(`SELECT 1`) // Rejects with SQLiteConnectionClosedError.

Pagehide and worker failures do not change. They terminate the worker at once and reject pending work. If one of them occurs while close is in flight, close and the pending work reject with that event's error.

Why close needed changes in two layers

The first commit (from @vincentdchn) fixed the connection side. When close settled, it rejected the remaining requests with AbortError, the same as pagehide. Review found two more problems in that layer:

  • A second concurrent close() posted its own close request. The first close then rejected it.
  • An execute() submitted during close still went to the worker. The worker had already cleared its database state, so the error type depended on timing.

The connection now keeps one in-flight close promise and refuses new work while it closes. Disposal also takes the rejection reason and settles all pending work itself. This change removed a reject-then-dispose pair that six handlers repeated.

The second problem was in the worker. It handled each message concurrently. With OPFSCoopSyncVFS, a statement can wait for the OPFS access handle when another tab holds it. During that wait, the worker handled a close message. SQLite then refused to close the connection, because the waiting statement was not finalized:

close  → INTERNAL "unable to close due to unfinalized statements or unfinished backups"
insert → (resumes later on closed VFS files)

The worker now handles one request at a time. The browser driver already sends one request at a time through its own queue, so persistence traffic loses no parallelism. The order changes only for direct database.execute() callers and for close(). If a reply cannot be posted, the worker reports an uncaught error. The connection treats that error as terminal, so the failure does not block later requests.

New error class

SQLiteConnectionClosedError is new in @tanstack/db-sqlite-persistence-core, and the browser package also exports it. It replaces InvalidPersistedCollectionConfigError for requests made after close starts. That old class described a configuration problem, not a closed connection. Code that used instanceof InvalidPersistedCollectionConfigError to detect a closed connection must change to use the new class. Work that the connection accepted before close and then cancelled still rejects with AbortError.

Limits and trade-offs

  • close() can now wait while another tab holds the database's OPFS access handle. Pagehide still ends the connection at once. Close has no timeout.
  • BrowserWASQLiteDriver.close() does not wait for queued driver work, the same as the Node and OP-SQLite drivers. An open transaction rolls back, and queued work rejects with the closed-connection error. If driver close waited for queued work, it would wait for a transaction callback's application code, and that code can itself wait for close.
  • A database name of about 63 characters fails to open with a bare sqlite3_open_v2 error. This PR did not investigate that limit. The review record lists it.

🔬 Oracle Coverage

Two oracles check this change. Each oracle has its own law.

Connection close lane (tests/opfs-page-lifecycle-oracle.test.ts). The law is the connection's promise contract: every accepted request settles once, and close ends admission. This lane replaces the first commit's fixed table with generated histories. It has an independent model and fixed, random, and SEED/PATH replay campaigns. The histories vary these dimensions:

  • 0–3 pending executes, and the number and order of responses during close.
  • Each close outcome.
  • A concurrent close and an execute during close.
  • Pagehide or a Worker error before the close response.

The driver uses a controlled worker that can answer in any order. Thus the lane also covers a close response that arrives before pending responses. The lane checks exact settlements at close settlement and the exact requests that reach the worker.

Request-order oracle (tests/opfs-request-order-oracle.ts, new). The law is that the connection settles requests in acceptance order with sequential results. Close settles after them, and answered writes survive a reopen. One module holds the law, a sequential replay model, the fixed examples, the driver loop on the public connection, and the comparison. Two drivers run it:

  • The Node driver (tests/opfs-request-order-oracle.test.ts) runs the real worker module and the real wa-sqlite WASM build behind a bridge Worker. Its in-memory VFS has OPFSCoopSyncVFS's lock protocol. It runs fixed, random, and SEED/PATH campaigns.
  • The Chromium driver (e2e/opfs-request-order-oracle.opfs.spec.ts) runs all 32 fixed examples against real OPFS. It takes the access handle through the VFS's own BroadcastChannel and Web Lock handoff. CI runs it in the test:opfs-fairness job.

Each control below fails at least one oracle with an assertion, not a timeout:

  • The pre-PR connection and the first commit's connection.
  • Rejection of all work when close starts.
  • A concurrent close that does not share the in-flight promise.
  • Admission during close.
  • Rejection that occurs after close settles.
  • A close that ignores pagehide or a Worker error.
  • The concurrent worker, in both request-order drivers.
  • A worker that queues executes but not close, in both request-order drivers.

At first, the shared driver returned the access handle before close reached the worker. Both worker mutants then passed both drivers. The driver now waits for delivery before it returns the handle.

docs/contributing/oracle-reviews/pr-2213-opfs-close.md records the controls and the limits. The coverage map links both oracles.

The evidence does not cover browsers other than Chromium, frozen tabs, a crash between a write and close, or more than one other handle holder.

✅ Checklist

  • I have tested this code locally with pnpm test.

Local checks on the final head:

  • @tanstack/browser-db-sqlite-persistence unit and type suite: 20 files, 467 tests passed, no type errors.
  • test:opfs-fairness Chromium OPFS config, including the request-order Chromium driver: 39 passed.
  • @tanstack/db-sqlite-persistence-core typecheck passed. Changed-file lint and formatting passed.

The full repository pnpm test did not run locally on the final head. The PR description history keeps the local checks for the first commit.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • New Features

    • Added SQLiteConnectionClosedError for requests made after connection closure begins.
  • Bug Fixes

    • Closing connections now preserves request order, completes queued work first, and safely handles concurrent closes.
    • Pending writes finish before closure, preserving data after reopening.
    • Worker failures, page hiding, and interruptions now reject pending work consistently.
  • Documentation

    • Added guidance on close behavior, request ordering, and lifecycle interruptions.
  • Tests

    • Expanded coverage for close races, worker failures, delayed responses, lifecycle events, and post-close requests.

This pull request and its description were written by Isaac.

@changeset-bot

changeset-bot Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9b653d1

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 12 packages
Name Type
@tanstack/db-sqlite-persistence-core Patch
@tanstack/browser-db-sqlite-persistence Patch
@tanstack/capacitor-db-sqlite-persistence Patch
@tanstack/cloudflare-durable-objects-db-sqlite-persistence Patch
@tanstack/electron-db-sqlite-persistence Patch
@tanstack/expo-db-sqlite-persistence Patch
@tanstack/node-db-sqlite-persistence Patch
@tanstack/react-native-db-sqlite-persistence Patch
@tanstack/tauri-db-sqlite-persistence Patch
@tanstack/capacitor-db-sqlite-persistence-e2e-app Patch
@tanstack/expo-db-sqlite-persistence-e2e-app Patch
@tanstack/tauri-db-sqlite-persistence-e2e-app Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 364a7b5d-a7fb-4a13-9ccb-760a327c1a6d
📥 Commits

Reviewing files that changed from the base of the PR and between 3b14049 and d56a7ee.

📒 Files selected for processing: 8
  • .changeset/sqlite-connection-closed-error.md
  • docs/contributing/oracle-reviews/pr-2213-opfs-close.md
  • packages/browser-db-sqlite-persistence/README.md
  • packages/browser-db-sqlite-persistence/e2e/close-pending-write-oracle.opfs.spec.ts
  • packages/browser-db-sqlite-persistence/src/index.ts
  • packages/browser-db-sqlite-persistence/src/opfs-database.ts
  • packages/browser-db-sqlite-persistence/tests/opfs-page-lifecycle-oracle.test.ts
  • packages/db-sqlite-persistence-core/src/errors.ts
🚧 Files skipped from review as they are similar to previous changes: 1
  • packages/browser-db-sqlite-persistence/tests/opfs-page-lifecycle-oracle.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

📝 Walkthrough

Closing an OPFS-backed SQLite connection now shares one close outcome, rejects new requests during closing, propagates disposal errors, and aborts unresolved work after close settlement. Worker requests now run sequentially. Tests and documentation cover these lifecycle and ordering rules.

Changes: OPFS connection close and request ordering

Layer / File(s) Summary
Close settlement and request disposal
packages/db-sqlite-persistence-core/src/errors.ts, packages/browser-db-sqlite-persistence/src/index.ts, packages/browser-db-sqlite-persistence/src/opfs-database.ts
The package exports SQLiteConnectionClosedError. The database rejects requests during closing, shares concurrent close() results, propagates disposal reasons, and disposes pending work after close settlement.
Serialized worker execution
packages/browser-db-sqlite-persistence/src/opfs-worker.ts, packages/browser-db-sqlite-persistence/tests/opfs-worker-request-order-oracle.test.ts, packages/browser-db-sqlite-persistence/package.json
Worker requests now execute through a shared promise chain. The request-order oracle covers serialized operations, OPFS handle waits, close ordering, and post-close execution.
Close lifecycle validation and integration coverage
packages/browser-db-sqlite-persistence/tests/opfs-page-lifecycle-oracle.test.ts, packages/browser-db-sqlite-persistence/e2e/*, packages/browser-db-sqlite-persistence/playwright.opfs.config.ts
The lifecycle oracle covers close outcomes, concurrent calls, response ordering, interruptions, admission during close, and pending-work rejection. The browser test verifies pending-write completion and durability after reopening.
Documentation and release metadata
packages/browser-db-sqlite-persistence/README.md, .changeset/*, docs/contributing/oracle-coverage.md, docs/contributing/oracle-reviews/pr-2213-opfs-close.md
The README, changesets, coverage documentation, and review record describe the close contract, validation results, and known limitations.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant OPFSDatabase
  participant OPFSWorker
  Client->>OPFSDatabase: call close()
  OPFSDatabase->>OPFSWorker: queue close request
  OPFSWorker-->>OPFSDatabase: return close response
  OPFSDatabase-->>Client: settle close and pending requests
Loading

Suggested reviewers: zhy0216, kyleamathews

Merge Risk: ⚪ Minimal · up to d56a7

No actionable merge-blocking risk was established.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 8 files. (3 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title is concise, specific, and accurately describes the primary change: rejecting pending requests when an OPFS connection closes.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the required structure and provides detailed changes, oracle coverage, release impact, test results, and limitations. The full pnpm test checklist item remains unchecked, but…
Full details: Description check

Explanation

The description follows the required structure and provides detailed changes, oracle coverage, release impact, test results, and limitations. The full pnpm test checklist item remains unchecked, but the description clearly reports the targeted validation that passed and explains the limitation.

Full details: Docstring Coverage

Explanation

Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 8 files. (3 skipped: 3 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
More templates

@tanstack/angular-db

npm i https://pkg.pr.new/@tanstack/angular-db@2213

@tanstack/browser-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/browser-db-sqlite-persistence@2213

@tanstack/capacitor-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/capacitor-db-sqlite-persistence@2213

@tanstack/cloudflare-durable-objects-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/cloudflare-durable-objects-db-sqlite-persistence@2213

@tanstack/db

npm i https://pkg.pr.new/@tanstack/db@2213

@tanstack/db-ivm

npm i https://pkg.pr.new/@tanstack/db-ivm@2213

@tanstack/db-sqlite-persistence-core

npm i https://pkg.pr.new/@tanstack/db-sqlite-persistence-core@2213

@tanstack/electric-db-collection

npm i https://pkg.pr.new/@tanstack/electric-db-collection@2213

@tanstack/electron-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/electron-db-sqlite-persistence@2213

@tanstack/expo-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/expo-db-sqlite-persistence@2213

@tanstack/node-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/node-db-sqlite-persistence@2213

@tanstack/offline-transactions

npm i https://pkg.pr.new/@tanstack/offline-transactions@2213

@tanstack/powersync-db-collection

npm i https://pkg.pr.new/@tanstack/powersync-db-collection@2213

@tanstack/query-db-collection

npm i https://pkg.pr.new/@tanstack/query-db-collection@2213

@tanstack/react-db

npm i https://pkg.pr.new/@tanstack/react-db@2213

@tanstack/react-native-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/react-native-db-sqlite-persistence@2213

@tanstack/react-router-with-db

npm i https://pkg.pr.new/@tanstack/react-router-with-db@2213

@tanstack/rxdb-db-collection

npm i https://pkg.pr.new/@tanstack/rxdb-db-collection@2213

@tanstack/solid-db

npm i https://pkg.pr.new/@tanstack/solid-db@2213

@tanstack/svelte-db

npm i https://pkg.pr.new/@tanstack/svelte-db@2213

@tanstack/tauri-db-sqlite-persistence

npm i https://pkg.pr.new/@tanstack/tauri-db-sqlite-persistence@2213

@tanstack/trailbase-db-collection

npm i https://pkg.pr.new/@tanstack/trailbase-db-collection@2213

@tanstack/vue-db

npm i https://pkg.pr.new/@tanstack/vue-db@2213

commit: 9b653d1

Isaac and others added 5 commits October 21, 2026 13:03
Close now memoizes its in-flight promise, so concurrent close() calls share
one close request and outcome instead of the second rejecting with
AbortError. Requests submitted after close starts are refused without
reaching the worker, which had already cleared its database state.
Disposal now takes the rejection reason and settles pending work itself,
replacing the reject-then-dispose pair repeated in six handlers.

The pinned close table becomes a generated lane with an independent model
and fixed, random, and SEED/PATH campaigns. It varies responses answered
during close, release order, close outcome, concurrent close, and
admission during close, and asserts exact request reach. Rejecting at
close start, posting a second close, admitting during close, deferring
rejection, the previous fix, and the pre-fix hang each fail it.

Co-authored-by: Isaac <no-reply@databricks.com>
The worker handled each message concurrently. When an execute waited for
the OPFS access handle (OPFSCoopSyncVFS returns SQLITE_BUSY and wa-sqlite
retries after the Web Lock), a close message ran during the wait: SQLite
refused to close the unfinalized statement, close was answered before the
earlier execute, and the execute resumed on closed VFS files. The worker
now handles one request at a time, so close waits for earlier requests.
A failed reply is rethrown as an uncaught worker error, not left to stall
the queue.

Add a request-order oracle that runs the real worker module and wa-sqlite
WASM in Node over an in-memory VFS with OPFSCoopSyncVFS's lock protocol,
against a sequential replay model. The concurrent worker and a worker that
queues executes but not close both fail it.

The page lifecycle close lane now also crosses pagehide, Worker error, and
messageerror before the close response; ignoring either while close is in
flight fails it.

Co-authored-by: Isaac <no-reply@databricks.com>
…write

The page takes the OPFS access handle through OPFSCoopSyncVFS's own handoff
(notify the handle channel, hold its Web Lock), starts an insert that waits
behind it, then closes. With the serialized worker the insert and close
succeed in order, work after close is refused, and the row survives a
reopen. The previous concurrent worker fails it: the insert rejects with
AbortError and close with "unable to close due to unfinalized statements".

Record the review's calibration controls and remaining limits in
docs/contributing/oracle-reviews/pr-2213-opfs-close.md.

Co-authored-by: Isaac <no-reply@databricks.com>
A browser OPFS connection refused requests made after close with
InvalidPersistedCollectionConfigError, which names a configuration
problem. It now rejects them with SQLiteConnectionClosedError, exported
from the core and browser packages. Work accepted before close and then
cancelled still rejects with AbortError, the same as pagehide.

The lifecycle oracle's closed-connection observation and the Chromium
witness now expect the new class. The review record documents immediate
driver close as the accepted contract.

Co-authored-by: Isaac <no-reply@databricks.com>
…hromium

Node and Chromium check the same law, so they now share one oracle module
with the law, the sequential replay model, the fixed examples, the
public-connection driver loop, and the comparison. Each environment
supplies only a driver: how to open a connection and how to take and
return the OPFS access handle.

The Node driver now runs the public connection against the real worker
module through a bridge Worker, instead of posting raw worker messages.
Its VFS files outlive a connection, so both drivers check that answered
writes survive a reopen. The Chromium driver runs all 32 fixed examples
against real OPFS, which replaces the single fixed Chromium history.

Calibration found that the shared driver returned the handle before close
reached the worker, which hid the bug from both drivers. The driver now
waits for delivery first. The concurrent worker and a worker that queues
executes but not close then fail both drivers.

Co-authored-by: Isaac <no-reply@databricks.com>
@KyleAMathews
KyleAMathews merged commit b052e91 into TanStack:main Oct 21, 2026
25 checks passed
@github-actions github-actions Bot mentioned this pull request Oct 21, 2026
KyleAMathews added a commit that referenced this pull request Oct 21, 2026
…#2216)

* docs(oracles): treat environments as drivers of one oracle

ORC-014 described a real-provider receiving witness as something that
"may live in different tests", which reads as permission for a separate
test with its own expected results. State instead that when a controlled
and a real environment check the same law, the receiving witness is
another driver of the same oracle and reuses its law, model, histories,
and comparison. A witness with its own expectations is a second model and
needs an ORC-011 justification. Point to the shared-driver fairness
oracle as the layout to follow, and add the question to the review card.

Add a "Treat driver timing helpers as premises" section. A shared driver
returned a lock before close reached the worker, so both worker mutants
passed both drivers until the helper waited for delivery.

Make the oracle-authoring trigger explicit for oracle edits made while
fixing a bug or a review finding, in AGENTS.md and in both oracle skills.

Co-authored-by: Isaac <no-reply@databricks.com>

* docs(oracles): apply review fixes to the shared-driver guidance

Use the OPFS request-order oracle as the example of one oracle with Node
and Chromium production drivers. The previous fairness example restated
its own expected results in the Chromium spec, which the new rule forbids.

Scope the second-model clause inside ORC-014's shared-law case. A
receiving witness that states its own expected results must derive them
from the oracle's model or record why it cannot and the drift risk. An
independent second model needs ORC-011's shared-fault hypothesis. This
removes a contradiction between the bullet and the prose, and it leaves
different-law handoffs unchanged.

Require the timing-helper mutant to be rejected and link ORC-006. State
that a fixed-time wait still needs one of the two checks, and link the
PR #2213 review record as the recorded case. Use the glossary term
"production driver" throughout. Extend the oracle-authoring trigger to
edits of an oracle's production driver, history grammar, or comparison.

Co-authored-by: Isaac <no-reply@databricks.com>

* docs(oracles): describe the request-order drivers accurately

The example said the drivers supply only an entry point and access-handle control. They also supply database names and result reporting, and the Node driver generates random histories. The Chromium spec also checks page errors and result count. What matters for the rule still holds: neither driver nor the spec states expected results.

Co-authored-by: Isaac <no-reply@databricks.com>

---------

Co-authored-by: Isaac <isaac@example.com>
Co-authored-by: Isaac <no-reply@databricks.com>
@KyleAMathews

Copy link
Copy Markdown
Collaborator

🎉 This PR has been released!

Backfilled notification for published release candidates.

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.

2 participants