Skip to content

Commit e82fd6c

Browse files
rustyconoverclaude
andcommitted
SQLite storage: survive concurrent opens of a fresh db
Several worker processes opening the same brand-new SQLite file at once could fail immediately with "database is locked": converting a fresh file to WAL needs an exclusive lock, and SQLite returns SQLITE_BUSY there without calling the busy handler, so the 30s connect timeout never applied. FunctionStorageSqlite also set busy_timeout only after the WAL switch, and nothing serialized first-time schema setup. New vgi._sqlite_wal (connect_wal / enable_wal / immediate_transaction): set busy_timeout first, retry journal_mode=WAL on SQLITE_BUSY/LOCKED with a bounded backoff (5ms doubling to 100ms, up to 30s), and run schema setup under BEGIN IMMEDIATE. Used by FunctionStorageSqlite, CatalogStorageSqlite, the simple_writable, schema_reconcile and txfix fixture workers, and the transactional_write test reference (whose check-then-create could race). No public API change. New test: 12 spawned processes open one fresh db behind a barrier, for both storage classes, three rounds each; all must succeed and the schema (sqlite_master and schema_version) must match that of a lone opener. Without the fix 1-11 of 12 openers fail with "database is locked" on every run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 42eb80d commit e82fd6c

9 files changed

Lines changed: 235 additions & 34 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@
22

33
## Unreleased
44

5+
### Fixes
6+
7+
- **Concurrent opens of a fresh SQLite storage file no longer fail with "database is locked".** When several worker
8+
processes opened the same new `FunctionStorageSqlite` or `CatalogStorageSqlite` file at once, the switch to WAL
9+
could fail at once with `SQLITE_BUSY`: SQLite does not call the busy handler there, so the 30 s connect timeout did
10+
not apply, and `FunctionStorageSqlite` set `busy_timeout` only after the switch. Both now set `busy_timeout` first,
11+
retry the WAL switch on `SQLITE_BUSY` with a bounded backoff (up to the same 30 s), and create their schema inside
12+
`BEGIN IMMEDIATE` so concurrent first-time setup serializes. The `simple_writable`, `schema_reconcile` and `txfix`
13+
fixture workers do the same. No API change.
14+
515
### Protocol 3.3: write-path wire changes
616

717
Part of `vgi.v3` / `3.3.0` (the version string does not change again).

‎tests/catalog/transactional_write_reference.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from vgi_rpc import ArrowSerializableDataclass
4141
from vgi_rpc.rpc import OutputCollector
4242

43+
from vgi._sqlite_wal import enable_wal, immediate_transaction
4344
from vgi._test_fixtures.simple_writable import _parse_write_options
4445
from vgi.catalog import (
4546
AttachOpaqueData,
@@ -148,12 +149,13 @@ def initialize(cls) -> None:
148149
return
149150
cls.root = root
150151
with closing(cls.connect()) as db:
151-
db.execute("PRAGMA journal_mode=WAL")
152-
if db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='items'").fetchone() is None:
153-
db.execute("BEGIN")
154-
db.execute('CREATE TABLE "items" (id BIGINT, label VARCHAR)')
155-
db.execute('INSERT INTO "items" VALUES (?, ?)', (-1, "baseline"))
156-
db.execute("COMMIT")
152+
enable_wal(db, timeout=10)
153+
# Check-and-create under the write lock, so concurrent first
154+
# openers cannot both see no table and both create it.
155+
with immediate_transaction(db):
156+
if db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='items'").fetchone() is None:
157+
db.execute('CREATE TABLE "items" (id BIGINT, label VARCHAR)')
158+
db.execute('INSERT INTO "items" VALUES (?, ?)', (-1, "baseline"))
157159

158160
@classmethod
159161
def connect(cls) -> sqlite3.Connection:
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""Several processes opening one fresh SQLite storage file at the same instant.
2+
3+
Each worker process of a pooled VGI worker builds its own storage object, and on
4+
a fresh host they all point at a database file that does not exist yet. Turning
5+
a new file into WAL needs an exclusive lock that SQLite refuses with
6+
``SQLITE_BUSY`` without consulting the busy handler, so without a retry some
7+
openers failed at once with "database is locked".
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import multiprocessing
13+
import sqlite3
14+
import traceback
15+
from multiprocessing.synchronize import Barrier
16+
from pathlib import Path
17+
from typing import Any
18+
19+
import pytest
20+
21+
from vgi.catalog.storage import CatalogStorageSqlite
22+
from vgi.function_storage import FunctionStorageSqlite
23+
24+
_PROCESSES = 12
25+
_ROUNDS = 3
26+
27+
_STORAGES: dict[str, Any] = {
28+
"function": FunctionStorageSqlite,
29+
"catalog": CatalogStorageSqlite,
30+
}
31+
32+
33+
def _open(kind: str, db_path: str, barrier: Barrier) -> str | None:
34+
"""Open the storage once everyone is ready, and use it; return a traceback on failure."""
35+
try:
36+
barrier.wait(timeout=60)
37+
storage = _STORAGES[kind](db_path)
38+
if kind == "function":
39+
storage.state_counter_add(b"s", b"ns", b"k", 1)
40+
storage.close()
41+
else:
42+
storage.attach_put(b"attach-" + str(multiprocessing.current_process().pid).encode(), "cat", {})
43+
return None
44+
except BaseException:
45+
return traceback.format_exc()
46+
47+
48+
def _schema(db_path: str) -> tuple[int, list[tuple[str, str, str | None]]]:
49+
with sqlite3.connect(db_path) as conn:
50+
version = conn.execute("PRAGMA schema_version").fetchone()[0]
51+
mode = conn.execute("PRAGMA journal_mode").fetchone()[0]
52+
assert mode == "wal"
53+
objects = conn.execute(
54+
"SELECT type, name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name"
55+
).fetchall()
56+
return version, objects
57+
58+
59+
@pytest.mark.parametrize("kind", sorted(_STORAGES))
60+
def test_concurrent_open_of_fresh_db(kind: str, tmp_path: Path) -> None:
61+
"""Every process succeeds and the schema matches one built by a lone opener, created exactly once."""
62+
reference = str(tmp_path / "reference.db")
63+
_STORAGES[kind](reference)
64+
expected = _schema(reference)
65+
66+
ctx = multiprocessing.get_context("spawn")
67+
with ctx.Manager() as manager, ctx.Pool(_PROCESSES) as pool:
68+
for round_no in range(_ROUNDS):
69+
db_path = str(tmp_path / f"shared-{round_no}.db")
70+
barrier = manager.Barrier(_PROCESSES)
71+
errors = [e for e in pool.starmap(_open, [(kind, db_path, barrier)] * _PROCESSES) if e is not None]
72+
assert errors == [], f"{len(errors)}/{_PROCESSES} openers failed; first:\n{errors[0]}"
73+
# schema_version counts schema changes: equal to a lone opener's
74+
# means the tables were created exactly once, never dropped and
75+
# re-created by a racing opener.
76+
assert _schema(db_path) == expected
77+
with sqlite3.connect(db_path) as conn:
78+
if kind == "function":
79+
assert conn.execute("SELECT n FROM function_counter").fetchall() == [(_PROCESSES,)]
80+
else:
81+
assert conn.execute("SELECT COUNT(*) FROM catalog_attachments").fetchone()[0] == _PROCESSES

‎vgi/_sqlite_wal.py‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Open a SQLite file in WAL mode safely when several processes open it at once.
4+
5+
Pooled workers routinely open the same brand-new database file at the same
6+
moment. Three things go wrong without care:
7+
8+
* ``PRAGMA journal_mode=WAL`` on a fresh rollback-journal file needs an
9+
exclusive lock, and when two connections try it together SQLite returns
10+
``SQLITE_BUSY`` ("database is locked") *without* calling the busy handler
11+
(waiting could deadlock) — so ``sqlite3.connect(timeout=...)`` does not
12+
cover it. :func:`enable_wal` retries it with a bounded backoff.
13+
* Every statement must wait for another process's lock rather than fail, so
14+
``busy_timeout`` is set before anything else.
15+
* Concurrent first-time schema setup can hit the read-to-write lock upgrade
16+
that SQLite also reports as an immediate ``SQLITE_BUSY``.
17+
:func:`immediate_transaction` takes the write lock up front with
18+
``BEGIN IMMEDIATE`` (which does honour ``busy_timeout``), so setup
19+
serializes.
20+
"""
21+
22+
from __future__ import annotations
23+
24+
import contextlib
25+
import sqlite3
26+
import time
27+
from collections.abc import Iterator
28+
from typing import Any
29+
30+
__all__ = ["BUSY_TIMEOUT_S", "connect_wal", "enable_wal", "immediate_transaction"]
31+
32+
#: How long any statement waits for another connection's lock, in seconds.
33+
BUSY_TIMEOUT_S = 30.0
34+
35+
_BUSY_CODES = frozenset({sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED})
36+
37+
38+
def _is_busy(exc: sqlite3.OperationalError) -> bool:
39+
code = getattr(exc, "sqlite_errorcode", None)
40+
if isinstance(code, int):
41+
return (code & 0xFF) in _BUSY_CODES
42+
message = str(exc)
43+
return "database is locked" in message or "database table is locked" in message
44+
45+
46+
def enable_wal(conn: sqlite3.Connection, *, timeout: float = BUSY_TIMEOUT_S) -> None:
47+
"""Set ``busy_timeout``, then switch ``conn`` to WAL, retrying on ``SQLITE_BUSY``.
48+
49+
Raises the last ``sqlite3.OperationalError`` once ``timeout`` seconds have
50+
passed, or at once for any error other than busy/locked.
51+
"""
52+
conn.execute(f"PRAGMA busy_timeout={int(timeout * 1000)}")
53+
deadline = time.monotonic() + timeout
54+
delay = 0.005
55+
while True:
56+
try:
57+
conn.execute("PRAGMA journal_mode=WAL").fetchall()
58+
return
59+
except sqlite3.OperationalError as exc:
60+
if not _is_busy(exc) or time.monotonic() >= deadline:
61+
raise
62+
time.sleep(delay)
63+
delay = min(delay * 2, 0.1)
64+
65+
66+
def connect_wal(database: str, *, timeout: float = BUSY_TIMEOUT_S, **kwargs: Any) -> sqlite3.Connection:
67+
"""``sqlite3.connect`` plus :func:`enable_wal`; extra keyword arguments go to ``connect``."""
68+
conn: sqlite3.Connection = sqlite3.connect(database, timeout=timeout, **kwargs)
69+
try:
70+
enable_wal(conn, timeout=timeout)
71+
except BaseException:
72+
conn.close()
73+
raise
74+
return conn
75+
76+
77+
@contextlib.contextmanager
78+
def immediate_transaction(conn: sqlite3.Connection) -> Iterator[sqlite3.Connection]:
79+
"""Run the block in ``BEGIN IMMEDIATE`` … ``COMMIT``, rolling back on error.
80+
81+
Taking the write lock up front makes concurrent schema setup serialize on
82+
it instead of failing. Works whatever ``conn.isolation_level`` is.
83+
"""
84+
conn.execute("BEGIN IMMEDIATE")
85+
try:
86+
yield conn
87+
except BaseException:
88+
with contextlib.suppress(sqlite3.Error):
89+
conn.rollback()
90+
raise
91+
conn.commit()

‎vgi/_test_fixtures/schema_reconcile/worker.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
from vgi_rpc.rpc import OutputCollector
3838

3939
from vgi import Worker
40+
from vgi._sqlite_wal import connect_wal, immediate_transaction
4041
from vgi._test_fixtures.constraint_facts import fixed_not_null
4142
from vgi.catalog import Catalog, Schema
4243
from vgi.catalog.capabilities import CONSTRAINT_ENFORCE, CONSTRAINT_RECORDS_READ, CatalogCapabilities
@@ -198,12 +199,17 @@ def _db_path() -> str:
198199

199200

200201
def _connect() -> sqlite3.Connection:
201-
conn = sqlite3.connect(_db_path(), timeout=30.0)
202-
conn.execute("PRAGMA journal_mode=WAL")
203-
for spec in TABLES.values():
204-
conn.execute(
205-
f"CREATE TABLE IF NOT EXISTS {spec.storage_table} ( rid_blob BLOB PRIMARY KEY, payload BLOB NOT NULL)"
206-
)
202+
conn = connect_wal(_db_path())
203+
try:
204+
with immediate_transaction(conn):
205+
for spec in TABLES.values():
206+
conn.execute(
207+
f"CREATE TABLE IF NOT EXISTS {spec.storage_table} ("
208+
" rid_blob BLOB PRIMARY KEY, payload BLOB NOT NULL)"
209+
)
210+
except BaseException:
211+
conn.close()
212+
raise
207213
return conn
208214

209215

‎vgi/_test_fixtures/simple_writable.py‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from vgi_rpc import ArrowSerializableDataclass, Transient
5151
from vgi_rpc.rpc import OutputCollector
5252

53+
from vgi._sqlite_wal import connect_wal, immediate_transaction
5354
from vgi.catalog import (
5455
FUNCTION_VISIBILITY_TABLE_ONLY,
5556
AttachOpaqueData,
@@ -174,15 +175,17 @@ def _ensure_init(attach_opaque_data: bytes) -> None:
174175
if attach_opaque_data in _INITIALIZED:
175176
return
176177
os.makedirs(_DB_DIR, exist_ok=True)
177-
conn = sqlite3.connect(_db_path(attach_opaque_data), isolation_level=None)
178+
conn = connect_wal(_db_path(attach_opaque_data), isolation_level=None)
178179
try:
179-
conn.execute("PRAGMA journal_mode=WAL;")
180-
for tname, tschema in _table_specs().items():
181-
cols = ", ".join(f'"{f.name}" {_sql_type(f.type)}' for f in tschema)
182-
conn.execute(f'CREATE TABLE IF NOT EXISTS "{tname}" ({cols})')
183-
conn.execute(f'CREATE TABLE IF NOT EXISTS "{_CREATED}" (name TEXT PRIMARY KEY, columns BLOB NOT NULL)')
184-
conn.execute(f'CREATE TABLE IF NOT EXISTS "{_VERSION}" (one INTEGER PRIMARY KEY, version INTEGER NOT NULL)')
185-
conn.execute(f'INSERT OR IGNORE INTO "{_VERSION}" (one, version) VALUES (1, 1)')
180+
with immediate_transaction(conn):
181+
for tname, tschema in _table_specs().items():
182+
cols = ", ".join(f'"{f.name}" {_sql_type(f.type)}' for f in tschema)
183+
conn.execute(f'CREATE TABLE IF NOT EXISTS "{tname}" ({cols})')
184+
conn.execute(f'CREATE TABLE IF NOT EXISTS "{_CREATED}" (name TEXT PRIMARY KEY, columns BLOB NOT NULL)')
185+
conn.execute(
186+
f'CREATE TABLE IF NOT EXISTS "{_VERSION}" (one INTEGER PRIMARY KEY, version INTEGER NOT NULL)'
187+
)
188+
conn.execute(f'INSERT OR IGNORE INTO "{_VERSION}" (one, version) VALUES (1, 1)')
186189
finally:
187190
conn.close()
188191
_INITIALIZED.add(attach_opaque_data)
@@ -191,9 +194,8 @@ def _ensure_init(attach_opaque_data: bytes) -> None:
191194
@contextlib.contextmanager
192195
def _connect(attach_opaque_data: bytes) -> Iterator[sqlite3.Connection]:
193196
_ensure_init(attach_opaque_data)
194-
conn = sqlite3.connect(_db_path(attach_opaque_data), isolation_level=None)
197+
conn = connect_wal(_db_path(attach_opaque_data), isolation_level=None)
195198
try:
196-
conn.execute("PRAGMA journal_mode=WAL;")
197199
yield conn
198200
finally:
199201
conn.close()

‎vgi/_test_fixtures/writable_tx.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
from vgi_rpc import ArrowSerializableDataclass
5050
from vgi_rpc.rpc import OutputCollector
5151

52+
from vgi._sqlite_wal import enable_wal
5253
from vgi.arguments import Arg, TableInput
5354
from vgi.catalog import (
5455
AttachOpaqueData,
@@ -144,11 +145,14 @@ def _state() -> Iterator[sqlite3.Connection]:
144145
os.makedirs(directory, exist_ok=True)
145146
conn = sqlite3.connect(os.path.join(directory, _STATE_FILE), timeout=30, isolation_level=None)
146147
try:
147-
conn.execute("PRAGMA busy_timeout = 30000")
148-
conn.execute("PRAGMA journal_mode = WAL")
149-
conn.executescript(_DDL)
148+
enable_wal(conn)
150149
conn.execute("BEGIN IMMEDIATE")
151150
try:
151+
# Inside the transaction (executescript would COMMIT first), so a
152+
# fresh file's schema is created by exactly one process.
153+
for statement in _DDL.split(";"):
154+
if statement.strip():
155+
conn.execute(statement)
152156
yield conn
153157
except BaseException:
154158
conn.execute("ROLLBACK")

‎vgi/catalog/storage.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import uuid
1919
from typing import Any, Protocol
2020

21+
from vgi._sqlite_wal import connect_wal
2122
from vgi.catalog.catalog_interface import AttachOpaqueData, TransactionOpaqueData
2223

2324
__all__ = [
@@ -158,14 +159,16 @@ def __init__(self, db_path: str | None = None) -> None:
158159

159160
def _connect(self) -> sqlite3.Connection:
160161
"""Create a new database connection."""
161-
conn = sqlite3.connect(self.db_path, timeout=30.0)
162-
conn.execute("PRAGMA journal_mode=WAL")
163-
return conn
162+
return connect_wal(self.db_path)
164163

165164
def _ensure_tables(self) -> None:
166165
"""Create all storage tables if they don't exist."""
167166
conn = self._connect()
168167
try:
168+
# BEGIN IMMEDIATE takes the write lock up front (honouring busy_timeout),
169+
# so several processes setting up one fresh file serialize instead of
170+
# racing. If anything below raises, close() discards the transaction.
171+
conn.execute("BEGIN IMMEDIATE")
169172
# Attachment table
170173
conn.execute("""
171174
CREATE TABLE IF NOT EXISTS catalog_attachments (

‎vgi/function_storage.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
import pyarrow as pa
3333

34+
from vgi._sqlite_wal import connect_wal
3435
from vgi._storage_profile import _PROFILE_ON, _profiler, io_call_bytes
3536

3637
# When the parent vgi.* logger is configured at DEBUG, this emits one line
@@ -962,9 +963,7 @@ def _connect(self) -> sqlite3.Connection:
962963
# Memory DBs use MEMORY journal mode implicitly; no WAL,
963964
# no fsync — the whole point of using :memory: here.
964965
return sqlite3.connect(self._memory_uri, uri=True, timeout=30.0)
965-
conn = sqlite3.connect(self.db_path, timeout=30.0)
966-
conn.execute("PRAGMA journal_mode=WAL")
967-
return conn
966+
return connect_wal(self.db_path)
968967

969968
def _conn(self) -> sqlite3.Connection:
970969
"""Return the calling thread's persistent connection, creating it lazily.
@@ -982,10 +981,9 @@ def _conn(self) -> sqlite3.Connection:
982981
if self._memory_uri is not None:
983982
conn = sqlite3.connect(self._memory_uri, uri=True, timeout=30.0)
984983
else:
985-
conn = sqlite3.connect(self.db_path, timeout=30.0)
986-
conn.execute("PRAGMA journal_mode=WAL")
984+
# busy_timeout first, then WAL with a retry on SQLITE_BUSY (vgi._sqlite_wal).
985+
conn = connect_wal(self.db_path)
987986
conn.execute("PRAGMA synchronous=NORMAL")
988-
conn.execute("PRAGMA busy_timeout=30000")
989987
conn.execute("PRAGMA temp_store=MEMORY")
990988
conn.execute("PRAGMA cache_size=-65536")
991989
self._tls.conn = conn
@@ -1051,6 +1049,10 @@ def _ensure_tables(self) -> None:
10511049
"""
10521050
conn = self._connect()
10531051
try:
1052+
# BEGIN IMMEDIATE takes the write lock up front (honouring busy_timeout),
1053+
# so several processes setting up one fresh file serialize instead of
1054+
# racing. If anything below raises, close() discards the transaction.
1055+
conn.execute("BEGIN IMMEDIATE")
10541056
# Self-heal an older on-disk DB to the unified minimal schema. The
10551057
# local SQLite tier is single-connection-per-process with no network
10561058
# retries, so it carries none of the DO's HTTP idempotency machinery

0 commit comments

Comments
 (0)