diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py index 7be969626..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 @@ -17,10 +18,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 +70,32 @@ 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) + # 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: 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..2ab536490 100644 --- a/tests/services/session/test_sqlite_store.py +++ b/tests/services/session/test_sqlite_store.py @@ -1,10 +1,12 @@ from __future__ import annotations import asyncio +import errno import json from pathlib import Path import sqlite3 import time +from types import SimpleNamespace import pytest @@ -1258,3 +1260,67 @@ 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] + + +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]