From 1a54befba839940bee65cacc65da35ee77c84cef Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:36:09 -0400 Subject: [PATCH 1/2] fix(session): serialize session-store schema setup on Windows too SQLiteSessionStore runs its WAL switch and schema creation under _migration_lock, which serializes worker processes with fcntl.flock but was a no-op on Windows. Processes opening the store together there raced: on a fresh database 14 of 30 concurrent opens failed with "database is locked" (PRAGMA journal_mode = WAL) or "trigger practice_capture_update already exists". Take an msvcrt byte-range lock when fcntl is unavailable, in the same shape as the grants, cron and Codex-auth locks. --- deeptutor/services/session/sqlite_store.py | 18 +++++++++++++- tests/services/session/test_sqlite_store.py | 26 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py index 7be969626..61b65d779 100644 --- a/deeptutor/services/session/sqlite_store.py +++ b/deeptutor/services/session/sqlite_store.py @@ -17,10 +17,14 @@ import time from typing import Any import uuid -try: # POSIX is the supported production target; fallback keeps Windows dev usable. +try: # POSIX import fcntl except ImportError: # pragma: no cover - exercised only on Windows fcntl = None # type: ignore[assignment] +try: # Windows + import msvcrt +except ImportError: # pragma: no cover - exercised only off Windows + msvcrt = None # type: ignore[assignment] from deeptutor.core.assessment import ( ASSESSMENT_RESULTS, @@ -65,11 +69,23 @@ def _migration_lock(db_path: Path) -> Iterator[None]: with lock_path.open("a+b") as lock_file: if fcntl is not None: fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) + elif msvcrt is not None: + # Without a lock, workers starting together race the WAL switch + # ("database is locked") and CREATE TRIGGER ("already exists"). + lock_file.seek(0, 2) + if lock_file.tell() == 0: + lock_file.write(b"\0") + lock_file.flush() + lock_file.seek(0) + msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1) try: yield finally: if fcntl is not None: fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN) + elif msvcrt is not None: + lock_file.seek(0) + msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1) # Sentinel so ``add_message`` can distinguish "caller wants the legacy diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.py index 5ba24842c..40230d26a 100644 --- a/tests/services/session/test_sqlite_store.py +++ b/tests/services/session/test_sqlite_store.py @@ -5,6 +5,7 @@ import json from pathlib import Path import sqlite3 import time +from types import SimpleNamespace import pytest @@ -1258,3 +1259,28 @@ def test_branch_context_messages_carry_private_metadata(store: SQLiteSessionStor messages = asyncio.run(store.get_messages_for_context(session["id"], leaf_message_id=leaf)) assert messages[-1]["metadata"]["provider_response_state"] == state + + +def test_schema_setup_takes_the_windows_lock_without_fcntl(tmp_path, monkeypatch) -> None: + # Workers opening the store together race the WAL switch ("database is + # locked") and CREATE TRIGGER ("already exists") unless setup is + # serialized across processes on Windows too. + import deeptutor.services.session.sqlite_store as module + + calls: list[int] = [] + + def locking(_fileno: int, mode: int, length: int) -> None: + assert length == 1 + calls.append(mode) + + monkeypatch.setattr(module, "fcntl", None) + monkeypatch.setattr( + module, + "msvcrt", + SimpleNamespace(LK_LOCK=1, LK_UNLCK=0, locking=locking), + raising=False, + ) + + SQLiteSessionStore(tmp_path / "chat_history.db") + + assert calls == [1, 0] From fd04d19469eb02602fff43b5e3405b1d817a26e9 Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:47:42 -0400 Subject: [PATCH 2/2] fix(session): keep waiting for the Windows schema lock past LK_LOCK's limit msvcrt's LK_LOCK gives up with EDEADLK after about ten seconds, and a one-time upgrade of a large session database can hold the lock longer than that. Retry on EDEADLK so the other workers wait, as flock does on POSIX; any other lock error still propagates. --- deeptutor/services/session/sqlite_store.py | 12 ++++++- tests/services/session/test_sqlite_store.py | 40 +++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py index 61b65d779..0cdfd03fa 100644 --- a/deeptutor/services/session/sqlite_store.py +++ b/deeptutor/services/session/sqlite_store.py @@ -8,6 +8,7 @@ import asyncio from collections.abc import Iterator, Sequence from contextlib import contextmanager from dataclasses import dataclass +import errno import json import os from pathlib import Path @@ -77,7 +78,16 @@ def _migration_lock(db_path: Path) -> Iterator[None]: lock_file.write(b"\0") lock_file.flush() lock_file.seek(0) - msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1) + # LK_LOCK gives up with EDEADLK after about ten seconds, and a + # one-time upgrade of a large database can take longer than that. + # Keep waiting, as flock does on POSIX. + while True: + try: + msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1) + break + except OSError as exc: + if exc.errno != errno.EDEADLK: + raise try: yield finally: diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.py index 40230d26a..2ab536490 100644 --- a/tests/services/session/test_sqlite_store.py +++ b/tests/services/session/test_sqlite_store.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import errno import json from pathlib import Path import sqlite3 @@ -1284,3 +1285,42 @@ def test_schema_setup_takes_the_windows_lock_without_fcntl(tmp_path, monkeypatch SQLiteSessionStore(tmp_path / "chat_history.db") assert calls == [1, 0] + + +def _msvcrt_failing_first_lock(calls: list[int], error: OSError) -> SimpleNamespace: + def locking(_fileno: int, mode: int, length: int) -> None: + calls.append(mode) + if calls == [1]: + raise error + + return SimpleNamespace(LK_LOCK=1, LK_UNLCK=0, locking=locking) + + +def test_windows_schema_lock_keeps_waiting_after_lk_lock_gives_up(tmp_path, monkeypatch) -> None: + # LK_LOCK raises EDEADLK after about ten seconds, but another worker's + # one-time upgrade of a large database can hold the lock for longer. + import deeptutor.services.session.sqlite_store as module + + calls: list[int] = [] + timeout = OSError(errno.EDEADLK, "Resource deadlock avoided") + monkeypatch.setattr(module, "fcntl", None) + monkeypatch.setattr(module, "msvcrt", _msvcrt_failing_first_lock(calls, timeout), raising=False) + + SQLiteSessionStore(tmp_path / "chat_history.db") + + assert calls == [1, 1, 0] + + +def test_windows_schema_lock_raises_other_lock_errors(tmp_path, monkeypatch) -> None: + import deeptutor.services.session.sqlite_store as module + + calls: list[int] = [] + denied = OSError(errno.EACCES, "Permission denied") + monkeypatch.setattr(module, "fcntl", None) + monkeypatch.setattr(module, "msvcrt", _msvcrt_failing_first_lock(calls, denied), raising=False) + + with pytest.raises(OSError) as exc_info: + SQLiteSessionStore(tmp_path / "chat_history.db") + + assert exc_info.value.errno == errno.EACCES + assert calls == [1]