Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Harden SQLite concurrency handling

jinzhenj79d0857fc91d
diff --git a/docs/next/architecture.md b/docs/next/architecture.md
index b4f418b8..edb223eb 100644
--- a/docs/next/architecture.md
+++ b/docs/next/architecture.md
@@ -173,7 +173,7 @@ metadata 更新规则:入库阶段写基础 metadata;解析完成后,只
| `config` | SQLite KV 配置 |
| `_migrations` | schema 版本追踪 |
-SQLite 运行在 WAL 模式,使用 FTS5 提供搜索能力。每次 DB 操作打开独立 `aiosqlite` 连接,提交后关闭,避免跨 worker 游标冲突。
+SQLite 运行在 WAL 模式,使用 FTS5 提供搜索能力。每次 DB 操作打开独立 `aiosqlite` 连接,提交后关闭,避免跨 worker 游标冲突。WAL mode 只在初始化时设置;运行期连接配置显式 busy timeout。单 doclib 进程内的写操作通过共享写锁串行化,普通读取保持并发;`SQLITE_BUSY` / `SQLITE_LOCKED` 使用有上限的指数退避重试,耗尽后对外返回可重试的 `server_busy`。
## 4. 数据流
diff --git a/docs/next/config.md b/docs/next/config.md
index afdbedd2..eb18edd2 100644
--- a/docs/next/config.md
+++ b/docs/next/config.md
@@ -67,6 +67,9 @@ MinerU 有两类配置:
| doclib | `doclib.parse_server_startup_grace_sec` | `30` | managed parse-server 启动宽限时间 |
| doclib | `doclib.parse_server_stop_timeout_sec` | `10` | managed parse-server 停止超时 |
| sqlite | `doclib.sqlite.path` | `~/.mineru/doclib.db` | SQLite DB 路径 |
+| sqlite | `doclib.sqlite.busy_timeout_ms` | `5000` | SQLite 锁等待时间(毫秒) |
+| sqlite | `doclib.sqlite.lock_retry_attempts` | `3` | `SQLITE_BUSY` / `SQLITE_LOCKED` 的额外重试次数 |
+| sqlite | `doclib.sqlite.lock_retry_base_delay_ms` | `50` | SQLite 锁重试的指数退避初始延迟(毫秒) |
| sqlite | `doclib.sqlite.mmap_size` | `268435456` | mmap size |
| sqlite | `doclib.sqlite.cache_size` | `-20000` | SQLite cache size |
| sqlite | `doclib.sqlite.wal_autocheckpoint` | `1000` | WAL checkpoint 阈值 |
diff --git a/docs/next/errors.md b/docs/next/errors.md
index a0b6e3bf..79022908 100644
--- a/docs/next/errors.md
+++ b/docs/next/errors.md
@@ -159,6 +159,7 @@ Tier 语义见 [解析 Tier](tiers.md)。本节定义 `flash`、`medium`、`high
| `invalid_request_error` | `model_not_found` | 404 | 否 | `model` | 请求的模型不存在 | `check_model_id` |
| `api_error` | `internal_error` | 500 | 否 | null | 服务端未预期错误 | `report_with_request_id` |
| `api_error` | `service_unavailable` | 503 | 是 | null | 服务暂不可用或依赖暂不可用 | `retry_later` |
+| `api_error` | `server_busy` | 503 | 是 | null | server 暂时无法接收请求,或 SQLite 锁竞争在有限重试后仍未恢复 | `retry_later` |
## 10. CLI 本地错误
@@ -169,7 +170,6 @@ CLI 在调用 server 前或通信层面产生本地错误。它们使用同一 `
| `invalid_request_error` | `file_not_found` | 否 | 本地文件路径不存在 | `check_path` |
| `invalid_request_error` | `file_permission_denied` | 否 | 本地文件无读取权限 | `fix_file_permission` |
| `api_error` | `server_not_running` | 是 | CLI 无法连接 doclib UDS | `run_mineru_server_start` |
-| `api_error` | `server_busy` | 是 | server 队列满或无法接收新任务 | `retry_later` |
| `api_error` | `server_protocol_error` | 是 | CLI 与 server 协议不兼容或响应损坏 | `upgrade_or_restart_server` |
CLI 在 TTY 中可以用表格或 rich 文本展示,但非 TTY、`--json` 或 Agent 调用场景应输出结构化错误。
diff --git a/mineru/config.py b/mineru/config.py
index a7f1408a..4dbce84c 100644
--- a/mineru/config.py
+++ b/mineru/config.py
@@ -226,6 +226,9 @@ class LogConfig(BaseModel):
class SQLiteConfig(BaseModel):
path: str = _default_path("doclib.db")
+ busy_timeout_ms: int = Field(default=5000, ge=0)
+ lock_retry_attempts: int = Field(default=3, ge=0)
+ lock_retry_base_delay_ms: int = Field(default=50, ge=0)
mmap_size: int = 268435456
cache_size: int = -20000
wal_autocheckpoint: int = 1000
diff --git a/mineru/doclib/background/ingest.py b/mineru/doclib/background/ingest.py
index f601d9c2..bed7e9fd 100644
--- a/mineru/doclib/background/ingest.py
+++ b/mineru/doclib/background/ingest.py
@@ -84,7 +84,7 @@ class IngestWorkerPool:
timeout = now - self.lock_timeout_ms
return cast(
FileRow | None,
- await self.parse_svc.db.fetchone(
+ await self.parse_svc.db.fetchone_write(
"UPDATE files SET locked_at=? "
"WHERE id = ("
" SELECT id FROM files "
diff --git a/mineru/doclib/core/db.py b/mineru/doclib/core/db.py
index 43c954bc..a31a129f 100644
--- a/mineru/doclib/core/db.py
+++ b/mineru/doclib/core/db.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+import asyncio
import os
+import sqlite3
import time
from collections.abc import Awaitable, Callable
from pathlib import Path
@@ -9,6 +11,7 @@ from typing import TypeVar
import aiosqlite
from ...config import SQLiteConfig
+from ...errors import ServerBusyError
from ..config_defaults import CONFIG_DEFAULTS
SCHEMA_VERSION = 1
@@ -16,6 +19,9 @@ _MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
_T = TypeVar("_T")
_CREATE_TABLES_SQL: list[str] = [] # filled by _load_init_sql()
+_DEFAULT_BUSY_TIMEOUT_MS = 5000
+_DEFAULT_LOCK_RETRY_ATTEMPTS = 3
+_DEFAULT_LOCK_RETRY_BASE_DELAY_MS = 50
def _load_init_sql() -> list[str]:
@@ -48,33 +54,29 @@ DEFAULT_EXCLUDE_RULES = [
class DatabaseManager:
- """Per-operation connection manager — no pooling, no shared state."""
+ """Per-operation connections with concurrent reads and process-local serialized writes."""
def __init__(self, db_path: str, sqlite_cfg: SQLiteConfig | None = None) -> None:
self.db_path = db_path
self.sqlite_cfg = sqlite_cfg # SQLiteConfig or None
+ self._write_lock = asyncio.Lock()
# ── lifecycle ──────────────────────────────────────────────────
async def initialize(self) -> None:
"""Create tables, apply migrations, seed default data. Idempotent."""
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
- conn = await aiosqlite.connect(self.db_path)
+ conn = await self._connect()
try:
await conn.execute("PRAGMA journal_mode=WAL")
- await conn.execute("PRAGMA foreign_keys=ON")
if self.sqlite_cfg:
await conn.execute(f"PRAGMA synchronous={self.sqlite_cfg.synchronous}")
await conn.execute(f"PRAGMA mmap_size={self.sqlite_cfg.mmap_size}")
await conn.execute(f"PRAGMA cache_size={self.sqlite_cfg.cache_size}")
await conn.execute(f"PRAGMA temp_store={self.sqlite_cfg.temp_store}")
- await conn.execute(
- f"PRAGMA wal_autocheckpoint={self.sqlite_cfg.wal_autocheckpoint}"
- )
- await conn.execute(
- f"PRAGMA journal_size_limit={self.sqlite_cfg.journal_size_limit}"
- )
+ await conn.execute(f"PRAGMA wal_autocheckpoint={self.sqlite_cfg.wal_autocheckpoint}")
+ await conn.execute(f"PRAGMA journal_size_limit={self.sqlite_cfg.journal_size_limit}")
else:
await conn.execute("PRAGMA synchronous=NORMAL")
await conn.execute("PRAGMA mmap_size=268435456")
@@ -88,9 +90,7 @@ class DatabaseManager:
# ── migrations ──────────────────────────────────────────
for version in range(1, SCHEMA_VERSION + 1):
- cursor = await conn.execute(
- "SELECT 1 FROM _migrations WHERE version=?", (version,)
- )
+ cursor = await conn.execute("SELECT 1 FROM _migrations WHERE version=?", (version,))
if await cursor.fetchone() is None:
await _apply_migration(conn, version)
await conn.execute(
@@ -121,28 +121,60 @@ class DatabaseManager:
await conn.close()
async def _connect(self) -> aiosqlite.Connection:
- conn = await aiosqlite.connect(self.db_path)
- await conn.execute("PRAGMA journal_mode=WAL")
- await conn.execute("PRAGMA foreign_keys=ON")
- conn.row_factory = aiosqlite.Row
- return conn
+ busy_timeout_ms = self.sqlite_cfg.busy_timeout_ms if self.sqlite_cfg else _DEFAULT_BUSY_TIMEOUT_MS
+ conn = await aiosqlite.connect(self.db_path, timeout=busy_timeout_ms / 1000)
+ try:
+ await conn.execute(f"PRAGMA busy_timeout={busy_timeout_ms}")
+ await conn.execute("PRAGMA foreign_keys=ON")
+ conn.row_factory = aiosqlite.Row
+ return conn
+ except Exception:
+ await conn.close()
+ raise
async def close(self) -> None:
pass # no cached connection
# ── query helpers ──────────────────────────────────────────────
- async def _with_connection(self, operation: Callable[[aiosqlite.Connection], Awaitable[_T]]) -> _T:
- conn = await self._connect()
- try:
- result = await operation(conn)
- await conn.commit()
- return result
- except Exception:
- await self._rollback_quietly(conn)
- raise
- finally:
- await conn.close()
+ async def _with_connection(
+ self,
+ operation: Callable[[aiosqlite.Connection], Awaitable[_T]],
+ *,
+ write: bool = False,
+ ) -> _T:
+ if write:
+ async with self._write_lock:
+ return await self._run_with_retry(operation)
+ return await self._run_with_retry(operation)
+
+ async def _run_with_retry(self, operation: Callable[[aiosqlite.Connection], Awaitable[_T]]) -> _T:
+ retry_attempts = self.sqlite_cfg.lock_retry_attempts if self.sqlite_cfg else _DEFAULT_LOCK_RETRY_ATTEMPTS
+ base_delay_ms = self.sqlite_cfg.lock_retry_base_delay_ms if self.sqlite_cfg else _DEFAULT_LOCK_RETRY_BASE_DELAY_MS
+
+ for attempt in range(retry_attempts + 1):
+ conn: aiosqlite.Connection | None = None
+ try:
+ conn = await self._connect()
+ result = await operation(conn)
+ await conn.commit()
+ return result
+ except Exception as exc:
+ if conn is not None:
+ await self._rollback_quietly(conn)
+ if not _is_sqlite_lock_error(exc):
+ raise
+ if attempt >= retry_attempts:
+ raise ServerBusyError("Doclib database is busy. Retry the request.") from exc
+ finally:
+ if conn is not None:
+ await conn.close()
+
+ delay_seconds = (base_delay_ms / 1000) * (2**attempt)
+ if delay_seconds > 0:
+ await asyncio.sleep(delay_seconds)
+
+ raise AssertionError("SQLite retry loop exited unexpectedly")
@staticmethod
async def _rollback_quietly(conn: aiosqlite.Connection) -> None:
@@ -155,7 +187,7 @@ class DatabaseManager:
async def _operation(conn: aiosqlite.Connection) -> aiosqlite.Cursor:
return await conn.execute(sql, params or ())
- return await self._with_connection(_operation)
+ return await self._with_connection(_operation, write=True)
async def execute_insert(self, sql: str, params: tuple | None = None) -> int:
async def _operation(conn: aiosqlite.Connection) -> int:
@@ -165,7 +197,7 @@ class DatabaseManager:
raise RuntimeError("SQLite insert did not return a row id.")
return lastid
- return await self._with_connection(_operation)
+ return await self._with_connection(_operation, write=True)
async def fetchone(self, sql: str, params: tuple | None = None) -> dict | None:
async def _operation(conn: aiosqlite.Connection) -> dict | None:
@@ -175,6 +207,16 @@ class DatabaseManager:
return await self._with_connection(_operation)
+ async def fetchone_write(self, sql: str, params: tuple | None = None) -> dict | None:
+ """Execute a write statement that returns at most one row."""
+
+ async def _operation(conn: aiosqlite.Connection) -> dict | None:
+ cursor = await conn.execute(sql, params or ())
+ row = await cursor.fetchone()
+ return dict(row) if row else None
+
+ return await self._with_connection(_operation, write=True)
+
async def fetchall(self, sql: str, params: tuple | None = None) -> list[dict]:
async def _operation(conn: aiosqlite.Connection) -> list[dict]:
cursor = await conn.execute(sql, params or ())
@@ -188,12 +230,13 @@ class DatabaseManager:
async def execute_atomic(self, statements: list[tuple[str, tuple]]) -> int:
"""Execute multiple statements in a single transaction."""
+
async def _operation(conn: aiosqlite.Connection) -> int:
for sql, params in statements:
await conn.execute(sql, params)
return len(statements)
- return await self._with_connection(_operation)
+ return await self._with_connection(_operation, write=True)
# ── helpers ────────────────────────────────────────────────────────
@@ -203,6 +246,16 @@ def _now_ms() -> int:
return int(time.time() * 1000)
+def _is_sqlite_lock_error(exc: Exception) -> bool:
+ if not isinstance(exc, sqlite3.OperationalError):
+ return False
+ error_code = getattr(exc, "sqlite_errorcode", None)
+ if isinstance(error_code, int) and error_code & 0xFF in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):
+ return True
+ message = str(exc).lower()
+ return "database is locked" in message or "database table is locked" in message
+
+
async def _apply_migration(conn: aiosqlite.Connection, version: int) -> None:
"""Apply a single schema migration from its SQL file."""
candidates = sorted(_MIGRATIONS_DIR.glob(f"{version:03d}_*.sql"))
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index c5e8b25e..5c0de1d1 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -846,7 +846,7 @@ class ParseService:
timeout = now - self.parse_lock_timeout_ms
task = cast(
ParseRow | None,
- await self.db.fetchone(
+ await self.db.fetchone_write(
"UPDATE parses SET locked_at=?, status=? "
"WHERE id = ("
" SELECT id FROM parses WHERE status=? "
diff --git a/mineru/doclib/services/scan_svc.py b/mineru/doclib/services/scan_svc.py
index 2866e002..d88992c7 100644
--- a/mineru/doclib/services/scan_svc.py
+++ b/mineru/doclib/services/scan_svc.py
@@ -114,8 +114,7 @@ class ScanService:
now = _now_ms()
scan_id = await self.db.execute_insert(
- "INSERT INTO scans (path, kind, source, watch_id, status, created_at, updated_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO scans (path, kind, source, watch_id, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(normalized_path, kind, source, watch_id, SCAN_STATUS_PENDING, now, now),
)
row = cast(ScanRow | None, await self.db.fetchone("SELECT * FROM scans WHERE id=?", (scan_id,)))
@@ -168,7 +167,7 @@ class ScanService:
timeout = now - self.scan_lock_timeout_ms
return cast(
ScanRow | None,
- await self.db.fetchone(
+ await self.db.fetchone_write(
"UPDATE scans SET locked_at=?, status=?, started_at=COALESCE(started_at, ?), updated_at=? "
"WHERE id = ("
" SELECT id FROM scans WHERE status=? AND (locked_at IS NULL OR locked_at < ?) "
diff --git a/mineru/errors.py b/mineru/errors.py
index 2e22e524..5c8d7a4b 100644
--- a/mineru/errors.py
+++ b/mineru/errors.py
@@ -118,6 +118,7 @@ _ERROR_CODE_STATUS_MAP: dict[str, int] = {
"tier_not_cached": 404,
"upload_not_found": 404,
"watch_not_found": 404,
+ "server_busy": 503,
}
@@ -183,6 +184,11 @@ class ServerNotRunningError(MineruError):
super().__init__("server_not_running", "Local mineru server is not running. Run 'mineru server start'.")
+class ServerBusyError(MineruError):
+ def __init__(self, message: str = "MinerU server is busy. Retry the request.") -> None:
+ super().__init__("server_busy", message)
+
+
# ── FastAPI error response builder ─────────────────────────────────
diff --git a/tests/unittest/test_doclib_config.py b/tests/unittest/test_doclib_config.py
index 359026ad..cf7974e5 100644
--- a/tests/unittest/test_doclib_config.py
+++ b/tests/unittest/test_doclib_config.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from pathlib import Path
+
import pytest
from mineru.config import (
@@ -43,7 +45,7 @@ def test_interpolate_env_rejects_missing_required_value(monkeypatch: pytest.Monk
_interpolate_env("${MINERU_TEST_MISSING}")
-def test_load_config_reads_yaml_and_interpolates_env(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_load_config_reads_yaml_and_interpolates_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("MINERU_TEST_DATA", str(tmp_path / "data"))
config_file = tmp_path / "config.yaml"
config_file.write_text(
@@ -81,6 +83,9 @@ def test_apply_env_overrides_uses_greedy_field_path_matching(monkeypatch: pytest
monkeypatch.setenv("TEST_MINERU_DOCLIB_PARSE_SERVER_PROBE_TIMEOUT_SEC", "29")
monkeypatch.setenv("TEST_MINERU_DOCLIB_PARSE_SERVER_STARTUP_GRACE_SEC", "31")
monkeypatch.setenv("TEST_MINERU_DOCLIB_PARSE_SERVER_STOP_TIMEOUT_SEC", "37")
+ monkeypatch.setenv("TEST_MINERU_DOCLIB_SQLITE_BUSY_TIMEOUT_MS", "1000")
+ monkeypatch.setenv("TEST_MINERU_DOCLIB_SQLITE_LOCK_RETRY_ATTEMPTS", "4")
+ monkeypatch.setenv("TEST_MINERU_DOCLIB_SQLITE_LOCK_RETRY_BASE_DELAY_MS", "25")
monkeypatch.setenv("TEST_MINERU_DOCLIB_SQLITE_MMAP_SIZE", "0")
monkeypatch.setenv("TEST_MINERU_UNKNOWN_FIELD", "ignored")
monkeypatch.setenv("TEST_MINERU_CONFIG", "/tmp/ignored.yaml")
@@ -99,10 +104,13 @@ def test_apply_env_overrides_uses_greedy_field_path_matching(monkeypatch: pytest
assert cfg.doclib.parse_server_probe_timeout_sec == 29
assert cfg.doclib.parse_server_startup_grace_sec == 31
assert cfg.doclib.parse_server_stop_timeout_sec == 37
+ assert cfg.doclib.sqlite.busy_timeout_ms == 1000
+ assert cfg.doclib.sqlite.lock_retry_attempts == 4
+ assert cfg.doclib.sqlite.lock_retry_base_delay_ms == 25
assert cfg.doclib.sqlite.mmap_size == 0
-def test_read_config_uses_default_config_under_mineru_home(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_read_config_uses_default_config_under_mineru_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
mineru_home = tmp_path / "mineru-home"
mineru_home.mkdir()
monkeypatch.setenv("MINERU_HOME", str(mineru_home))
diff --git a/tests/unittest/test_doclib_db.py b/tests/unittest/test_doclib_db.py
index ced34085..e1da1a24 100644
--- a/tests/unittest/test_doclib_db.py
+++ b/tests/unittest/test_doclib_db.py
@@ -1,12 +1,54 @@
import asyncio
import sqlite3
+from pathlib import Path
+from typing import Any
import pytest
+from mineru.config import SQLiteConfig
from mineru.doclib.core.db import DatabaseManager
+from mineru.errors import ServerBusyError
-def test_failed_write_rolls_back_and_closes_connection(tmp_path) -> None:
+class _Cursor:
+ def __init__(self, row: dict[str, Any] | None = None) -> None:
+ self._row = row
+
+ async def fetchone(self) -> dict[str, Any] | None:
+ return self._row
+
+ async def fetchall(self) -> list[dict[str, Any]]:
+ return [self._row] if self._row is not None else []
+
+
+class _FakeConnection:
+ def __init__(self, *, locked: bool = False, delay: float = 0.0) -> None:
+ self.locked = locked
+ self.delay = delay
+ self.statements: list[str] = []
+ self.committed = False
+ self.rolled_back = False
+ self.closed = False
+
+ async def execute(self, sql: str, _params: tuple[Any, ...] = ()) -> _Cursor:
+ self.statements.append(sql)
+ if self.delay:
+ await asyncio.sleep(self.delay)
+ if self.locked:
+ raise sqlite3.OperationalError("database is locked")
+ return _Cursor({"value": 1})
+
+ async def commit(self) -> None:
+ self.committed = True
+
+ async def rollback(self) -> None:
+ self.rolled_back = True
+
+ async def close(self) -> None:
+ self.closed = True
+
+
+def test_failed_write_rolls_back_and_closes_connection(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.execute("CREATE TABLE parent (id INTEGER PRIMARY KEY)")
@@ -20,3 +62,210 @@ def test_failed_write_rolls_back_and_closes_connection(tmp_path) -> None:
assert row == {"id": 1}
asyncio.run(_run())
+
+
+def test_initialize_enables_wal_mode(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+
+ await db.initialize()
+
+ row = await db.fetchone("PRAGMA journal_mode")
+ assert row == {"journal_mode": "wal"}
+
+ asyncio.run(_run())
+
+
+def test_operational_connection_sets_busy_timeout_without_resetting_wal(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _run() -> None:
+ connection = _FakeConnection()
+ connect_timeouts: list[float] = []
+
+ async def _connect(_path: str, *, timeout: float) -> _FakeConnection:
+ connect_timeouts.append(timeout)
+ return connection
+
+ monkeypatch.setattr("mineru.doclib.core.db.aiosqlite.connect", _connect)
+ db = DatabaseManager("/tmp/doclib.db", SQLiteConfig(busy_timeout_ms=4321))
+
+ await db._connect()
+
+ assert connect_timeouts == [4.321]
+ assert connection.statements == ["PRAGMA busy_timeout=4321", "PRAGMA foreign_keys=ON"]
+
+ asyncio.run(_run())
+
+
+def test_locked_operation_retries_with_a_fresh_connection() -> None:
+ async def _run() -> None:
+ db = DatabaseManager(
+ "/tmp/doclib.db",
+ SQLiteConfig(lock_retry_attempts=1, lock_retry_base_delay_ms=0),
+ )
+ connections = [_FakeConnection(locked=True), _FakeConnection()]
+
+ async def _connect() -> _FakeConnection:
+ return connections.pop(0)
+
+ db._connect = _connect # type: ignore[method-assign]
+
+ row = await db.fetchone("SELECT 1 AS value")
+
+ assert row == {"value": 1}
+ assert not connections
+
+ asyncio.run(_run())
+
+
+def test_exhausted_lock_retries_raise_server_busy() -> None:
+ async def _run() -> None:
+ db = DatabaseManager(
+ "/tmp/doclib.db",
+ SQLiteConfig(lock_retry_attempts=2, lock_retry_base_delay_ms=0),
+ )
+ connect_count = 0
+
+ async def _connect() -> _FakeConnection:
+ nonlocal connect_count
+ connect_count += 1
+ return _FakeConnection(locked=True)
+
+ db._connect = _connect # type: ignore[method-assign]
+
+ with pytest.raises(ServerBusyError) as exc_info:
+ await db.fetchone("SELECT 1")
+
+ assert exc_info.value.code == "server_busy"
+ assert connect_count == 3
+
+ asyncio.run(_run())
+
+
+def test_write_returning_operations_are_serialized() -> None:
+ async def _run() -> None:
+ db = DatabaseManager("/tmp/doclib.db", SQLiteConfig(lock_retry_attempts=0))
+ active_operations = 0
+ max_active_operations = 0
+
+ class _TrackedConnection(_FakeConnection):
+ async def execute(self, sql: str, params: tuple[Any, ...] = ()) -> _Cursor:
+ nonlocal active_operations, max_active_operations
+ active_operations += 1
+ max_active_operations = max(max_active_operations, active_operations)
+ try:
+ await asyncio.sleep(0.01)
+ return await super().execute(sql, params)
+ finally:
+ active_operations -= 1
+
+ async def _connect() -> _FakeConnection:
+ return _TrackedConnection()
+
+ db._connect = _connect # type: ignore[method-assign]
+
+ await asyncio.gather(
+ db.fetchone_write("UPDATE tasks SET locked_at=1 WHERE id=1 RETURNING *"),
+ db.fetchone_write("UPDATE tasks SET locked_at=1 WHERE id=2 RETURNING *"),
+ )
+
+ assert max_active_operations == 1
+
+ asyncio.run(_run())
+
+
+def test_read_operations_remain_concurrent() -> None:
+ async def _run() -> None:
+ db = DatabaseManager("/tmp/doclib.db", SQLiteConfig(lock_retry_attempts=0))
+ active_operations = 0
+ max_active_operations = 0
+
+ class _TrackedConnection(_FakeConnection):
+ async def execute(self, sql: str, params: tuple[Any, ...] = ()) -> _Cursor:
+ nonlocal active_operations, max_active_operations
+ active_operations += 1
+ max_active_operations = max(max_active_operations, active_operations)
+ try:
+ await asyncio.sleep(0.01)
+ return await super().execute(sql, params)
+ finally:
+ active_operations -= 1
+
+ async def _connect() -> _FakeConnection:
+ return _TrackedConnection()
+
+ db._connect = _connect # type: ignore[method-assign]
+
+ await asyncio.gather(
+ db.fetchone("SELECT 1"),
+ db.fetchall("SELECT 2"),
+ )
+
+ assert max_active_operations == 2
+
+ asyncio.run(_run())
+
+
+def test_write_recovers_after_external_sqlite_lock_is_released(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db_path = tmp_path / "doclib.db"
+ db = DatabaseManager(
+ str(db_path),
+ SQLiteConfig(
+ busy_timeout_ms=10,
+ lock_retry_attempts=5,
+ lock_retry_base_delay_ms=10,
+ ),
+ )
+ await db.initialize()
+ await db.execute("CREATE TABLE counters (id INTEGER PRIMARY KEY, value INTEGER NOT NULL)")
+ await db.execute_insert("INSERT INTO counters(id, value) VALUES (1, 0)")
+
+ blocker = sqlite3.connect(db_path, timeout=0)
+ blocker.execute("BEGIN IMMEDIATE")
+ blocker.execute("UPDATE counters SET value=1 WHERE id=1")
+ try:
+ update_task = asyncio.create_task(db.execute("UPDATE counters SET value=value+1 WHERE id=1"))
+ await asyncio.sleep(0.05)
+ blocker.commit()
+ await update_task
+ finally:
+ blocker.close()
+
+ row = await db.fetchone("SELECT value FROM counters WHERE id=1")
+ assert row == {"value": 2}
+
+ asyncio.run(_run())
+
+
+def test_concurrent_reads_and_writes_complete_without_lock_errors(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(
+ str(tmp_path / "doclib.db"),
+ SQLiteConfig(
+ busy_timeout_ms=100,
+ lock_retry_attempts=3,
+ lock_retry_base_delay_ms=5,
+ ),
+ )
+ await db.initialize()
+ await db.execute("CREATE TABLE counters (id INTEGER PRIMARY KEY, value INTEGER NOT NULL)")
+ await db.execute_insert("INSERT INTO counters(id, value) VALUES (1, 0)")
+
+ async def _reader() -> None:
+ for _ in range(10):
+ row = await db.fetchone("SELECT value FROM counters WHERE id=1")
+ assert row is not None
+
+ async def _writer() -> None:
+ for _ in range(20):
+ await db.fetchone_write("UPDATE counters SET value=value+1 WHERE id=1 RETURNING value")
+
+ await asyncio.gather(
+ *(_reader() for _ in range(32)),
+ *(_writer() for _ in range(4)),
+ )
+
+ row = await db.fetchone("SELECT value FROM counters WHERE id=1")
+ assert row == {"value": 80}
+
+ asyncio.run(_run())
diff --git a/tests/unittest/test_errors.py b/tests/unittest/test_errors.py
index 02ce02bd..f6dacb92 100644
--- a/tests/unittest/test_errors.py
+++ b/tests/unittest/test_errors.py
@@ -100,6 +100,7 @@ def test_http_status_for_error_codes_is_stable() -> None:
assert http_status_for("engine_unavailable") == 503
assert http_status_for("parse_wait_timeout") == 408
assert http_status_for("parse_server_unavailable") == 500
+ assert http_status_for("server_busy") == 503
assert http_status_for("internal_error") == 500