Fixing "database is locked" and Float Drift in Concurrent Python SQLite Apps

2026-12-03来源 dev.toEnglish
Fixing "database is locked" and Float Drift in Concurrent Python SQLite Apps

Python's built-in sqlite3 module works cleanly in single-threaded scripts, right up until you combine a UI loop, background polling workers, and financial totals in the same desktop app. On Windows especially, three subtle problems surface fast:

  1. Concurrent readers and writers collide with sqlite3.OperationalError: database is locked under default DELETE rollback journaling.
  2. Opening and closing sqlite3.connect(path) on every helper call forces repeated PRAGMA setup and triggers SQLite WAL checkpoint/unlink cycles when the last handle closes, turning sub-millisecond writes into 200 to 440ms disk stalls.
  3. Tracking dollar amounts as float accumulates binary rounding drift, while naive ON CONFLICT DO UPDATE queries quietly wipe existing local notes whenever a lightweight sync passes an empty string.

Enabling PRAGMA journal_mode = WAL, keeping persistent per-thread connections behind an RLock, versioning schema migrations, and storing currency strictly in integer cents (amount_cents) solves these issues with zero external dependencies. The complete code, concurrency tests, and reproducible benchmarks are in the companion repository: https://github.com/zheomara/sqlite-wal-ledger-demo.

Concurrent SQLite WAL architecture with per-thread persistent connections and RLock

1. Persistent Per-Thread Connections Instead of Per-Query Open/Close

A common instinct when seeing sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread is to open a fresh sqlite3.connect() inside every repository method and close it in finally. On Windows, closing the final open handle on a WAL database triggers checkpoint and -wal/-shm cleanup overhead on every call, dragging down throughput.

In LedgerDB, _get_file_conn() caches one persistent connection per thread ID inside self._thread_conns with busy_timeout = 30000 and synchronous = NORMAL. Notice the Windows cleanup nuance: creating each handle with check_same_thread=False lets LedgerDB.close() close every worker thread's handle from the main or test-teardown thread, avoiding PermissionError when temporary directories clean up on Windows.

Inside _get_connection(write=...), writers acquire self._write_lock (threading.RLock), whereas read-only callers (write=False) query their WAL snapshot concurrently without blocking writers.

class LedgerDB: # ... initialized with self._db_path, self._write_lock, self._conn_lock, self._thread_conns def _get_file_conn(self) -> sqlite3.Connection: tid = threading.get_ident() with self._conn_lock: if self._closed: raise RuntimeError("LedgerDB is closed.") conn = self._thread_conns.get(tid) if conn is None: # check_same_thread=False allows deterministic close() from the owner thread. conn = sqlite3.connect(self._db_path, timeout=30.0, check_same_thread=False) conn.row_factory = sqlite3.Row conn.execute("PRAGMA busy_timeout = 30000") conn.execute("PRAGMA synchronous = NORMAL") conn.execute("PRAGMA foreign_keys = ON") self._thread_conns[tid] = conn return conn @contextmanager def _get_connection(self, write: bool = True) -> Iterator[sqlite3.Connection]: if self._is_memory: with self._write_lock: if self._closed or self._mem_conn is None: raise RuntimeError("In-memory LedgerDB connection is closed.") conn = self._mem_conn try: yield conn conn.commit() except Exception: try: conn.rollback() except Exception: pass raise return if write: with self._write_lock: conn = self._get_file_conn() try: yield conn conn.commit() except Exception: try: conn.rollback() except Exception: pass raise else: # Concurrent WAL readers execute without acquiring _write_lock. conn = self._get_file_conn() try: yield conn finally: if conn.in_transaction: conn.rollback() 

2. Idempotent Migrations (v1 to v2) and Composite Indexes

Editing CREATE TABLE statements in place breaks existing user databases on upgrade. Instead, _init_and_migrate() checks COALESCE(MAX(version), 0) in schema_migrations and applies _apply_migration_v1 and _apply_migration_v2 sequentially.

Migration v2 adds three secondary indexes, including the composite index idx_ledger_source_state:

class LedgerDB: # ... migration v1 creates ledger_entries, withdrawals, and schema_migrations def _apply_migration_v2(self, conn: sqlite3.Connection) -> None: now = datetime.now().isoformat() conn.execute("CREATE INDEX IF NOT EXISTS idx_ledger_state ON ledger_entries(state)") conn.execute( "CREATE INDEX IF NOT EXISTS idx_ledger_source_state ON ledger_entries(source, state)" ) conn.execute("CREATE INDEX IF NOT EXISTS idx_ledger_created_at ON ledger_entries(created_at)") conn.execute( "INSERT OR IGNORE INTO schema_migrations (version, description, applied_at) VALUES (?, ?, ?)", (2, "Add state, composite (source, state), and created_at indexes", now), ) 

Even with a UNIQUE(source, external_id) constraint in v1, EXPLAIN QUERY PLAN shows that filtering by WHERE source = ? AND state = ? can only use the leading source column of SQLite's autoindex and must inspect every row for that source. Adding idx_ledger_source_state narrows the search directly to (source=? AND state=?).

3. Non-Destructive Batch Upserts and Chunked ID Hydration

Background scrapers and feed pollers often resend summary rows whose notes field is "", even after the user or another pass already saved detailed notes locally. A standard ON CONFLICT DO UPDATE SET notes = excluded.notes overwrites those saved notes with empty strings.

Wrapping the conflict update in COALESCE(NULLIF(excluded.notes, ''), ledger_entries.notes) preserves existing non-empty notes whenever an incoming payload is blank. Afterward, upsert_entries_batch() groups external_id values by source and queries their database IDs in 400-item chunks so large batches (600+ rows) stay well below SQLite's host-parameter ceiling (SQLITE_MAX_VARIABLE_NUMBER).

class LedgerDB: # ... batch ingestion and db_id hydration def upsert_entries_batch(self, entries: List[LedgerEntry]) -> int: """ Upserts ledger entries in a single transaction, preserves existing non-empty notes, and hydrates `entry.db_id` in <=400-item chunks so SQLite parameter limits are respected. """ if not entries: return 0 now = datetime.now().isoformat() deduped: Dict[Tuple[str, str], LedgerEntry] = {} for item in entries: key = (item.source, item.external_id) prev = deduped.get(key) if prev is not None and prev.notes and not item.notes: item.notes = prev.notes deduped[key] = item params = [ ( e.source, e.external_id, e.title, int(e.amount_cents), e.state.value if isinstance(e.state, EntryState) else str(e.state), e.notes or "", max(0, int(e.duration_seconds)), e.created_at or now, e.resolved_at, ) for e in deduped.values() ] with self._get_connection() as conn: cur = conn.cursor() cur.executemany( """ INSERT INTO ledger_entries ( source, external_id, title, amount_cents, state, notes, duration_seconds, created_at, resolved_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(source, external_id) DO UPDATE SET title = excluded.title, amount_cents = excluded.amount_cents, notes = COALESCE(NULLIF(excluded.notes, ''), ledger_entries.notes) """, params, ) # Group external IDs by source and query in <= 400-item chunks to hydrate db_id. by_source: Dict[str, List[str]] = {} for src, ext_id in deduped: by_source.setdefault(src, []).append(ext_id) id_map: Dict[Tuple[str, str], int] = {} chunk_size = 400 for src, ext_ids in by_source.items(): for i in range(0, len(ext_ids), chunk_size): chunk = ext_ids[i : i + chunk_size] placeholders = ",".join("?" for _ in chunk) cur.execute( f"SELECT id, external_id FROM ledger_entries WHERE source = ? AND external_id IN ({placeholders})", [src, *chunk], ) for row in cur.fetchall(): id_map[(src, row["external_id"])] = int(row["id"]) for e in entries: e.db_id = id_map.get((e.source, e.external_id)) return len(params) 

4. Integer-Cent Accounting and Defensive Validation

Summing decimal dollar payouts as Python float values leaks tiny binary rounding errors that require awkward tolerance checks later. Storing amount_cents, gross_cents, fee_cents, and net_cents as SQLite INTEGER columns keeps every sum exact.

Two defensive details in record_withdrawal_cents() and get_summary() avoid common reporting bugs: rejecting non-positive withdrawals with ValueError while clamping fee_percent to [0.0, 100.0], and excluding 0-cent placeholders from AVG(CASE WHEN amount_cents > 0 THEN amount_cents END) so zero-value records never drag down positive payout averages.

class LedgerDB: # ... withdrawal validation and integer-cent summary def record_withdrawal_cents( self, gross_cents: int, fee_percent: float = 8.0, method: str = "Bank", ) -> int: """Records a withdrawal in integer cents after validating gross > 0 and clamping fee %.""" gross = int(gross_cents) if gross <= 0: raise ValueError("Withdrawal amount must be positive") clamped_pct = max(0.0, min(100.0, float(fee_percent))) fee_cents = int(round(gross * (clamped_pct / 100.0))) net_cents = gross - fee_cents now = datetime.now().isoformat() with self._get_connection() as conn: cur = conn.cursor() cur.execute( """ INSERT INTO withdrawals (gross_cents, fee_percent, fee_cents, net_cents, method, withdrawn_at) VALUES (?, ?, ?, ?, ?, ?) """, (gross, clamped_pct, fee_cents, net_cents, str(method or "Bank"), now), ) return int(cur.lastrowid) def get_summary(self, fee_percent: float = 8.0) -> LedgerSummary: """Computes exact integer-cent ledger totals, excluding 0-cent entries from payout averages.""" fee_rate = max(0.0, min(1.0, float(fee_percent) / 100.0)) with self._get_connection(write=False) as conn: cur = conn.cursor() cur.execute(""" SELECT COUNT(*) AS total_entries, COALESCE(SUM(CASE WHEN state IN ('approved', 'paid') THEN amount_cents ELSE 0 END), 0) AS approved_gross, COALESCE(SUM(CASE WHEN state = 'pending' THEN amount_cents ELSE 0 END), 0) AS pending_gross, AVG(CASE WHEN amount_cents > 0 THEN amount_cents END) AS avg_pos_cents FROM ledger_entries """) row = cur.fetchone() approved_gross = int(row["approved_gross"] or 0) pending_gross = int(row["pending_gross"] or 0) total_entries = int(row["total_entries"] or 0) avg_pos = int(round(row["avg_pos_cents"])) if row["avg_pos_cents"] is not None else 0 cur.execute("SELECT COALESCE(SUM(net_cents), 0) AS total_withdrawn FROM withdrawals") withdrawn_net = int(cur.fetchone()["total_withdrawn"] or 0) approved_fee = int(round(approved_gross * fee_rate)) approved_net = approved_gross - approved_fee withdrawable = max(0, approved_net - withdrawn_net) return LedgerSummary( approved_gross_cents=approved_gross, approved_net_cents=approved_net, pending_gross_cents=pending_gross, withdrawn_net_cents=withdrawn_net, withdrawable_cents=withdrawable, avg_positive_payout_cents=avg_pos, total_entries=total_entries, ) 

5. Measured Benchmark Results (benchmark_sqlite_wal.py)

Running benchmark_sqlite_wal.py exercises three scenarios side-by-side: 4 concurrent writers and 4 concurrent readers (25 operations each), 10,000 × $0.07 precision accumulation, and 100 filtered lookups across 10,000 rows.

Terminal benchmark output showing 0 WAL lock errors, 0 integer-cent drift, and composite index speedup

Benchmark Baseline / Unindexed LedgerDB (WAL + RLock + v2 Index)
Concurrency (4 Writers + 4 Readers) 125 lock errors in 6202.4 ms (DELETE, 0.01s timeout) 0 lock errors in 64.8 ms (100 / 100 rows persisted)
Sum Precision (10,000 × $0.07) 700.000000000091 (0.000000000091 IEEE-754 drift) 70000 cents (0 drift)
100 Queries (10,000 Rows, WHERE source=? AND state=?) 42.96 ms (sqlite_autoindex_ledger_entries_1 (source=?)) 33.36 ms (idx_ledger_source_state (source=? AND state=?))

Run both the unit/concurrency tests and the benchmark locally from the repository root:

py -u -m unittest discover -s tests -p "test_*.py" -v py -u benchmark_sqlite_wal.py 

(On macOS/Linux, substitute python3 for py.)

6. Trade-Offs and Scaling Boundaries

LedgerDB is designed for single-process Python desktop apps and local worker pipelines, not distributed backends. The in-process RLock serializes writes cleanly across threads inside one Python process, while multiple OS processes writing concurrently fall back to WAL + busy_timeout. Once write concurrency spans multiple machines or high-throughput web workers, moving to PostgreSQL is the right step.

Setting PRAGMA synchronous = NORMAL in WAL mode trades a narrow edge case for significantly faster writes on Windows disks. It remains safe against application crashes, though an abrupt OS power loss right before a WAL checkpoint can roll back the very latest committed transaction unless you switch to PRAGMA synchronous = FULL.

Full runnable code, migration tests, and cross-platform CI workflow: https://github.com/zheomara/sqlite-wal-ledger-demo

原文:https://www.a8q9.cn/en/article/fixing-database-is-locked-and-float-drift-in-concurrent-python-sqlite-apps-bddb3c.html

相关文章