|
| 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 |
0 commit comments