Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(storage): give one owner to migrating a database, and count rollback positions (#1578)

Call White89e5dd1ad6cb
diff --git a/config/paths.py b/config/paths.py
index 255cc01b9..b7816fd1b 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -218,10 +218,6 @@ def get_sqlite_state_path() -> Path:
return get_state_dir() / "vibe.sqlite"
-def get_sqlite_migration_lock_path() -> Path:
- return get_state_dir() / "migration.lock"
-
-
def get_state_backups_dir() -> Path:
return get_state_dir() / "backups"
diff --git a/config/v2_config.py b/config/v2_config.py
index 1153a23b0..a755ff019 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -44,45 +44,27 @@ from vibe.i18n import normalize_language
logger = logging.getLogger(__name__)
CONFIG_LOCK = threading.RLock()
-_memory_config_tx_state = threading.local()
-_config_file_lock_state = threading.local()
+#: How long a config write waits for a peer process before giving up. Config
+#: writes are small and bounded, so a wait this long says the holder is stuck
+#: rather than busy, and a settings save that fails is better than one that
+#: never returns.
+CONFIG_FILE_LOCK_TIMEOUT_SECONDS = 30.0
-def _acquire_memory_config_file_lock(descriptor: int) -> None:
- """Acquire a cross-process exclusive lock with a platform-supported API."""
- if os.name == "nt":
- import msvcrt
+def _path_file_lock(lock_path: Path, *, timeout_seconds: float | None):
+ """The shared cross-process lock for one path.
- # Lock one byte of the file; Windows keeps the range until unlocked.
- os.lseek(descriptor, 0, os.SEEK_SET)
- try:
- os.write(descriptor, b"\0")
- except OSError:
- pass
- os.lseek(descriptor, 0, os.SEEK_SET)
- msvcrt.locking(descriptor, msvcrt.LK_LOCK, 1)
- return
- import fcntl
-
- fcntl.flock(descriptor, fcntl.LOCK_EX)
-
-
-def _release_memory_config_file_lock(descriptor: int) -> None:
- """Release the cross-process exclusive lock acquired by the helper above."""
-
- try:
- if os.name == "nt":
- import msvcrt
+ Nesting is safe, and that is why this file no longer keeps a lock of its
+ own: ``MigrationFileLock`` is re-entrant per path and thread, which both
+ transactions here used to hand-roll as a thread-local depth counter beside
+ a private descriptor and a private copy of the platform lock calls.
+ """
- os.lseek(descriptor, 0, os.SEEK_SET)
- msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
- else:
- import fcntl
+ # Import lazily because storage's package initializer imports V2Config.
+ from storage.lock import MigrationFileLock
- fcntl.flock(descriptor, fcntl.LOCK_UN)
- except Exception:
- pass
+ return MigrationFileLock(lock_path, timeout_seconds=timeout_seconds)
def _fsync_directory(path: Path) -> None:
@@ -142,36 +124,21 @@ def _memory_config_transaction(config_path: Path) -> Iterator[None]:
Lock order is always ``CONFIG_LOCK`` then the file lock, matching existing
callers that already hold ``CONFIG_LOCK`` when they enter ``save_config``.
- Nested acquisitions only re-enter the process lock.
+ Nesting re-enters both: ``MigrationFileLock`` is re-entrant per path and
+ thread, which is what this used to hand-roll as a thread-local depth counter
+ beside its own descriptor and its own platform lock calls.
"""
- depth = getattr(_memory_config_tx_state, "depth", 0)
- if depth > 0:
- with CONFIG_LOCK:
- yield
- return
-
lock_path = config_path.parent / "memory-config.tx.lock"
- lock_path.parent.mkdir(parents=True, exist_ok=True)
- descriptor = os.open(
- lock_path,
- os.O_RDWR | os.O_CREAT | getattr(os, "O_CLOEXEC", 0),
- 0o600,
- )
- _memory_config_tx_state.depth = 1
# CONFIG_LOCK first so threads that already hold it (remote_access/settings
# helpers) never wait on the file lock while another waiter holds the file
# lock and waits for CONFIG_LOCK.
with CONFIG_LOCK:
- try:
- _acquire_memory_config_file_lock(descriptor)
- try:
- yield
- finally:
- _release_memory_config_file_lock(descriptor)
- finally:
- _memory_config_tx_state.depth = 0
- os.close(descriptor)
+ # Unbounded, as this always was: the section holds a config read-modify-
+ # write, so the only way to wait forever is for a live peer to still be
+ # inside one.
+ with _path_file_lock(lock_path, timeout_seconds=None):
+ yield
@contextmanager
@@ -184,8 +151,8 @@ def config_write_transaction(config_path: Optional[Path] = None) -> Iterator["V2
fields (the stale-snapshot race ``CONFIG_LOCK`` cannot fix because it
is process-local while the UI API and controller are separate
processes). Lock order and re-entrancy match the Memory transaction:
- ``CONFIG_LOCK`` first, then the file lock; nested acquisitions
- re-enter the process lock only.
+ ``CONFIG_LOCK`` first, then the file lock; both are re-entrant, so a
+ nested transaction on the same config takes the same pair.
Yields a freshly loaded ``V2Config``; mutate it in place and it is
saved on clean context exit. Mutator exceptions abort with no write.
@@ -1506,40 +1473,12 @@ def _backup_config_file(
def _config_file_lock(path: Path):
- """Return the shared cross-process lock for one config path."""
-
- # Import lazily because storage's package initializer imports V2Config.
- from storage.lock import MigrationFileLock
-
- return MigrationFileLock(path.with_name(f".{path.name}.lock"))
+ """The shared cross-process lock guarding one config file."""
-
-@contextmanager
-def _config_file_transaction_lock(path: Path) -> Iterator[None]:
- """Hold one config migration lock, re-entering it within this thread."""
-
- key = os.path.normcase(os.path.abspath(os.fspath(path)))
- locks = getattr(_config_file_lock_state, "locks", None)
- if locks is None:
- locks = {}
- _config_file_lock_state.locks = locks
- active = locks.get(key)
- if active is not None:
- lock, depth = active
- locks[key] = (lock, depth + 1)
- try:
- yield
- finally:
- locks[key] = (lock, depth)
- return
-
- lock = _config_file_lock(path)
- with lock:
- locks[key] = (lock, 1)
- try:
- yield
- finally:
- del locks[key]
+ return _path_file_lock(
+ path.with_name(f".{path.name}.lock"),
+ timeout_seconds=CONFIG_FILE_LOCK_TIMEOUT_SECONDS,
+ )
@contextmanager
@@ -1558,7 +1497,7 @@ def config_file_lock(config_path: Optional[Path] = None) -> Iterator[None]:
path = config_path or paths.get_config_path()
path.parent.mkdir(parents=True, exist_ok=True)
with _memory_config_transaction(path):
- with _config_file_transaction_lock(path):
+ with _config_file_lock(path):
yield
@@ -1615,7 +1554,7 @@ def _persist_migrated_config_payload(
try:
with CONFIG_LOCK:
- with _config_file_transaction_lock(path):
+ with _config_file_lock(path):
try:
current_raw = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as exc:
diff --git a/core/chat_discovery.py b/core/chat_discovery.py
index ac0e6a616..96e064210 100644
--- a/core/chat_discovery.py
+++ b/core/chat_discovery.py
@@ -67,9 +67,7 @@ _refresh_locks_lock = threading.Lock()
_refresh_locks: dict[str, threading.Lock] = {}
_scheduled_refreshes_lock = threading.Lock()
_scheduled_refreshes: set[str] = set()
-_migration_lock = threading.Lock()
_legacy_migration_lock = threading.Lock()
-_migrated_db_paths: set[Path] = set()
@dataclass
@@ -161,13 +159,26 @@ def _db_path(db_path: Path | None = None) -> Path:
def _ensure_sqlite(db_path: Path | None = None) -> Path:
+ """Make the discovery tables usable, the same way every other store does.
+
+ This used to keep its own lock and its own set of already-migrated paths --
+ a third answer to a question `ensure_sqlite_state` and `run_migrations`
+ already answer between them, and a weaker one on both counts: the lock was
+ process-local, so it never excluded the Web UI process, and the memo skipped
+ `ensure_sqlite_state` entirely. Discovery can be the first code to touch the
+ database on a machine upgrading from JSON state, and when it was, it created
+ the schema without the JSON import every other entry point guarantees.
+ """
+
target = _db_path(db_path)
+ if db_path is None:
+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
+
+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
+ return target
guard_source_checkout_default_state_migration(target)
target.parent.mkdir(parents=True, exist_ok=True)
- with _migration_lock:
- if target not in _migrated_db_paths:
- run_migrations(target)
- _migrated_db_paths.add(target)
+ run_migrations(target)
return target
diff --git a/storage/backups.py b/storage/backups.py
index a35427fb4..0fb58791f 100644
--- a/storage/backups.py
+++ b/storage/backups.py
@@ -15,6 +15,9 @@ from typing import Iterable
logger = logging.getLogger(__name__)
+#: Retention counts rollback POSITIONS, not copies. A position keeps the first
+#: and the last copy taken there, so the ceiling is twice these numbers and is
+#: only reached by repeated attempts at one upgrade. See `prune_state_backups`.
JSON_STATE_BACKUP_RETENTION = 3
SQLITE_BACKUP_RETENTION = 2
BACKUP_MANIFEST_VERSION = 1
@@ -47,19 +50,69 @@ class _BackupCandidate:
kind: str
timestamp: datetime
suffix: int
+ #: The revisions the copied database was stamped with, or None when the
+ #: backup does not record them. Two copies taken at the same revisions were
+ #: taken to roll back to the same place in the schema history.
+ position: tuple[str, ...] | None = None
+ #: Where this backup falls among the managed backups written into its
+ #: window, counted by the code that wrote it, or None for one written before
+ #: the field existed. This is what the wall clock cannot say: a clock that
+ #: steps backward between two attempts dates the second backup before the
+ #: first, and every rule that reads write order out of timestamps then reads
+ #: it backwards.
+ sequence: int | None = None
+
+ @property
+ def position_key(self) -> tuple[str, str]:
+ """Which rollback position this copy belongs to.
+
+ A copy that does not record its revisions is its own position rather
+ than a member of a shared unknown one. Grouping unknowns together would
+ let one of them stand in for another, and nothing here knows they are
+ interchangeable; keeping them separate reproduces exactly the
+ newest-N-copies behavior those backups have always had.
+ """
+
+ if self.position is None:
+ return ("copy", self.root.name)
+ return ("revisions", "\x1f".join(self.position))
@property
def order_key(self) -> tuple[datetime, int, str]:
- """Creation order, as the backup's own name records it.
+ """When the backup's own name says it was taken.
- A movable clock can reorder this, and that is tolerable here, because
- ordering only decides which of the older copies to drop first. The copy
- a call just made is not defended by outranking them -- it is handed to
- `prune_state_backups` as protected, which no clock can undo.
+ Never an answer to which backup came first: a clock that steps backward
+ names a later one with an earlier stamp. Read `written_order` for that,
+ and use this only to break its ties.
"""
return (self.timestamp, self.suffix, self.root.name)
+ @property
+ def written_order(self) -> tuple[int, int, datetime, int, str]:
+ """The order the backups were written in, as their writers recorded it.
+
+ The one declaration of that order, because every rule that re-derived it
+ from the timestamps was wrong in the same way: the stamp is a label the
+ writer chose, and a clock corrected backwards between two attempts
+ reverses it. Both things pruning decides -- which position leaves the
+ window, and which copies a position keeps -- read it from here.
+
+ A backup with no counter was written by a release that did not have the
+ field, so it precedes every counted one. That ordering is a fact about
+ which binary made it, not a guess: this release always writes the
+ counter, and the release before it never could. Among themselves those
+ backups have no recorded order and the stamps are all there is -- the
+ one place a clock still decides anything here, and only for backups an
+ installed release already made, which nothing can retrofit. Rewriting
+ their manifests to invent an order would freeze that same guess into the
+ artifact a rollback is supposed to be able to trust.
+ """
+
+ if self.sequence is None:
+ return (0, 0, *self.order_key)
+ return (1, self.sequence, *self.order_key)
+
def _parse_timestamp(value: str) -> datetime | None:
try:
@@ -123,9 +176,52 @@ def _directory_candidate(path: Path) -> _BackupCandidate | None:
kind=kind,
timestamp=timestamp,
suffix=int(match.group("suffix") or 0),
+ position=_manifest_position(manifest),
+ sequence=_manifest_sequence(manifest),
)
+def _normalized_position(revisions: Iterable[str]) -> tuple[str, ...]:
+ """One canonical name for a place in the schema history.
+
+ Alembic reports the heads of a branched history in no fixed order, so the
+ same place can be read back as a differently ordered list. Both the code
+ that writes a backup and the code that groups backups derive the name here,
+ because two spellings of one position would make the writer count a fresh
+ sequence for a position the pruner already knows.
+ """
+
+ return tuple(sorted(set(revisions)))
+
+
+def _manifest_position(manifest: dict) -> tuple[str, ...] | None:
+ """The revisions the copied database carried, when the manifest records them.
+
+ An empty list is a position -- an unversioned database is a place in the
+ schema history like any other -- so this answers None only when the field is
+ absent or malformed.
+ """
+
+ recorded = manifest.get("from_revisions")
+ if not isinstance(recorded, list) or not all(isinstance(item, str) for item in recorded):
+ return None
+ return _normalized_position(recorded)
+
+
+def _manifest_sequence(manifest: dict) -> int | None:
+ """Where the writer counted this backup among the window's backups.
+
+ Absent for every backup written before the field existed, which is why no
+ caller may require it. `bool` is rejected because it is an `int` that never
+ came from a counter.
+ """
+
+ recorded = manifest.get("backup_sequence")
+ if not isinstance(recorded, int) or isinstance(recorded, bool) or recorded < 0:
+ return None
+ return recorded
+
+
def _legacy_sqlite_candidate(path: Path) -> _BackupCandidate | None:
if path.is_symlink() or not path.is_file():
return None
@@ -163,6 +259,33 @@ def _managed_candidates(backups_dir: Path) -> list[_BackupCandidate]:
return candidates
+def next_backup_sequence(backups_dir: Path) -> int:
+ """The number to record in the backup about to be written here.
+
+ Counted from the window rather than from a stored counter, because the
+ window is the only thing that survives a crash between two attempts. It
+ stays monotonic because pruning always keeps the newest backup it keeps at
+ all, so the highest number is still there to count from; a window pruned
+ down to nothing restarts at zero with nothing left to compare against.
+
+ Counted across both windows sharing the directory, since the number says
+ when a backup was written and comparisons never cross kinds anyway. One
+ counter is also one fewer thing that can disagree with itself.
+
+ Two writers racing here would both claim one number. The migration lock is
+ held across this call on every path that reaches it, so that race is not
+ reachable today, and its effect would be a position keeping one copy too
+ many rather than one too few.
+ """
+
+ recorded = [
+ candidate.sequence
+ for candidate in _managed_candidates(backups_dir)
+ if candidate.sequence is not None
+ ]
+ return max(recorded, default=-1) + 1
+
+
def _remove_candidate(candidate: _BackupCandidate) -> bool:
if candidate.root.is_symlink():
return False
@@ -188,12 +311,34 @@ def prune_state_backups(
) -> list[Path]:
"""Keep a bounded rollback window of backups created by Avibe.
- Newest first, and `protect` -- the backup its caller has just finished
- writing -- is kept ahead of all of them. Ranking it there rather than
- trusting it to sort highest is the difference between a bound and a bug: a
- copy left behind by a machine whose clock ran ahead is dated into the future
- forever, and every ordering rule that decides the fresh copy's fate by
- comparing timestamps hands the slot to that stale one instead.
+ The window holds the newest `retention` rollback POSITIONS, and of each one
+ the first and the last copy taken there. Counting positions rather than
+ copies is what makes the bound survive a migration that keeps failing: every
+ entry point that reaches `run_migrations` re-attempts it and copies the
+ database again, so a window counting copies fills with re-attempts of one
+ upgrade and evicts the copy taken before the first of them -- the only one in
+ the window predating the damage, and the one a user reaching for a rollback
+ wants. Positions do not accumulate that way, because those re-attempts all
+ copy a database sitting at the same revisions.
+
+ Keeping two copies per position, the first and the last, is not a doubled
+ quota; it is the pair that brackets everything that happened there. Which one
+ is worth keeping cannot be decided from the position alone, and the two
+ plausible rules fail on opposite cases: a re-attempt after a partial repair
+ makes the later copy the damaged one, while an operator who restores a copy
+ and keeps serving writes makes the later copy the only one holding that
+ work. Keeping both ends answers both without asking the label a question it
+ cannot answer. A healthy machine is unaffected -- successive upgrades each
+ start from a different revision, so each is its own position with one copy in
+ it -- and so are copies whose position is unknown, since each is its own
+ position and the window is again the newest `retention` copies.
+
+ `protect` -- the backup its caller has just finished writing -- is kept ahead
+ of all of them. Ranking it there rather than trusting it to sort highest is
+ the difference between a bound and a bug: a copy left behind by a machine
+ whose clock ran ahead is dated into the future forever, and every ordering
+ rule that decides the fresh copy's fate by comparing timestamps hands the
+ slot to that stale one instead.
Unknown files, symlinks, incomplete backups, and directories without a
recognized manifest are intentionally left untouched.
@@ -208,16 +353,42 @@ def prune_state_backups(
removed: list[Path] = []
for kind, limit in limits.items():
matching = [candidate for candidate in candidates if candidate.kind == kind]
- ordered = sorted(matching, key=lambda item: item.order_key, reverse=True)
+ positions: dict[tuple[str, str], list[_BackupCandidate]] = {}
+ for candidate in matching:
+ positions.setdefault(candidate.position_key, []).append(candidate)
+ ordered = sorted(
+ positions.values(),
+ key=lambda group: max(item.written_order for item in group),
+ reverse=True,
+ )
if protect is not None:
- ordered.sort(key=lambda item: item.root != protect)
- keep = {candidate.root for candidate in ordered[:limit]}
+ ordered.sort(key=lambda group: all(item.root != protect for item in group))
+ keep: set[Path] = set()
+ for group in ordered[:limit]:
+ keep |= _kept_within_position(group, protect)
for candidate in sorted(matching, key=lambda item: item.order_key):
if candidate.root not in keep and _remove_candidate(candidate):
removed.append(candidate.root)
return removed
+def _kept_within_position(group: list[_BackupCandidate], protect: Path | None) -> set[Path]:
+ """The copies to keep from one rollback position: the first and the last.
+
+ `protect` takes the last slot when it is here, for the same reason it ranks
+ first among positions -- a clock that ran ahead can leave a stale copy
+ sorting later than the one just written. It never takes the first slot: the
+ copy a call has just made is the newest thing at this position, and letting
+ it hold both ends would drop the only copy predating the damage.
+ """
+
+ ordered = sorted(group, key=lambda item: item.written_order)
+ protected = next((item for item in group if item.root == protect), None)
+ latest = protected if protected is not None else ordered[-1]
+ first = next((item for item in ordered if item.root != latest.root), latest)
+ return {first.root, latest.root}
+
+
def _fsync_file(path: Path) -> None:
"""Push a file's contents to stable storage.
@@ -335,6 +506,11 @@ def create_sqlite_migration_backup(
The manifest records the revisions read back from the copy rather than
anything the caller reported, because between a caller sampling them and
this function running, another process can advance the database.
+
+ It also records where this copy falls among the backups already in the
+ window. Write order is knowable only here, while the copy is being made;
+ anything reading it back later has nothing but the wall clock, and a clock
+ that steps backward between two attempts reports the order reversed.
"""
source_path = db_path.expanduser().resolve()
@@ -367,14 +543,21 @@ def create_sqlite_migration_backup(
os.chmod(temp_db, 0o600)
_fsync_file(temp_db)
temp_db.replace(backup_db)
+ position = _normalized_position(from_revisions)
manifest = {
"schema_version": BACKUP_MANIFEST_VERSION,
"managed_by": "avibe",
"kind": "sqlite-migration",
"created_at": created_at.astimezone(timezone.utc).isoformat(),
"database": "vibe.sqlite",
- "from_revisions": list(from_revisions),
+ "from_revisions": list(position),
"to_revisions": sorted(set(to_revisions)),
+ # Additive on purpose: a backup is recognized by an exact
+ # `schema_version`, so raising it would make every copy this release
+ # writes invisible to the release before it -- unrecognized, never
+ # pruned, and never offered as a rollback point. An older reader
+ # ignores this field and prunes the window exactly as it does today.
+ "backup_sequence": next_backup_sequence(target_root),
}
manifest_path = backup_dir / "manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
diff --git a/storage/importer.py b/storage/importer.py
index 44fe8e834..737996945 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -22,9 +22,9 @@ from config.v2_sessions import (
migrate_session_state_mappings,
)
from config.v2_settings import SettingsState, load_settings_state_from_json
-from storage.backups import BACKUP_MANIFEST_VERSION, prune_state_backups
+from storage.backups import BACKUP_MANIFEST_VERSION, next_backup_sequence, prune_state_backups
from storage.db import create_sqlite_engine
-from storage.lock import MigrationFileLock
+from storage.lock import MigrationFileLock, migration_lock_path_for
from storage.migrations import guard_source_checkout_default_state_migration, run_migrations
from storage.models import (
agents,
@@ -101,9 +101,12 @@ def ensure_sqlite_state(
target_db=target_db,
use_default_dirs=db_path is None and state_dir is None,
)
- lock_path = target_state_dir / "migration.lock"
-
- with MigrationFileLock(lock_path):
+ # The same lock `run_migrations` takes, re-entered rather than duplicated,
+ # and derived from the database so the two can never resolve differently.
+ # Held across the JSON import as well: the import is the other half of
+ # establishing this database, and a second process must not start migrating
+ # it in between.
+ with MigrationFileLock(migration_lock_path_for(target_db), timeout_seconds=None):
run_migrations(target_db, prune_backups_after_upgrade=False)
engine = create_sqlite_engine(target_db)
report: MigrationImportReport | None = None
@@ -294,6 +297,12 @@ def _backup_json_state(state_dir: Path) -> Path:
"managed_by": "avibe",
"kind": "json-state-migration",
"created_at": _utc_now_iso(),
+ # Recorded here for the same reason the sqlite window records it:
+ # nothing reading this directory later can tell what a clock did
+ # between two snapshots. Written by both kinds so that reading the
+ # order off the timestamps stays a compatibility path for backups an
+ # older release made, rather than a rule still in use.
+ "backup_sequence": next_backup_sequence(backups_dir),
"files": {},
}
for name in (
diff --git a/storage/lock.py b/storage/lock.py
index 87d877e17..d75b71559 100644
--- a/storage/lock.py
+++ b/storage/lock.py
@@ -1,52 +1,147 @@
from __future__ import annotations
+import logging
import os
+import threading
import time
from pathlib import Path
from types import TracebackType
from typing import Optional, Type
-from config import paths
+
+logger = logging.getLogger(__name__)
+
+#: How long a blocked acquire waits before it starts saying so. A migration that
+#: takes minutes is legitimate, and the process waiting behind it looks hung from
+#: the outside; naming the holder is what turns that into a diagnosable wait.
+_WAIT_LOG_INTERVAL_SECONDS = 15.0
class MigrationLockTimeout(TimeoutError):
pass
-class MigrationFileLock:
- """Small cross-process lock for startup migrations."""
+def migration_lock_path_for(db_path: Path) -> Path:
+ """The lock guarding migrations of one SQLite state database.
+
+ Derived from the database rather than from the state directory, and stated
+ once here, because the thing being protected is that file: two callers that
+ disagree about which directory is "the" state directory would otherwise
+ take two different locks over one database and both proceed.
+ """
+
+ return db_path.expanduser().resolve().with_name("migration.lock")
+
+
+class _PathLockState:
+ """The one in-process owner of a lock path.
+
+ The OS lock alone cannot express re-entrance. ``fcntl.flock`` attaches to an
+ open file description, so a second ``open`` of the same path -- which is what
+ a nested acquire does -- is a *different* description and blocks against the
+ first, in the very thread that holds it. That is a self-deadlock, and it is
+ reachable from ordinary nesting: ``ensure_sqlite_state`` holds the migration
+ lock across the call to ``run_migrations``, which takes it too.
+
+ Holding the depth here rather than on the lock object is what makes
+ re-entrance a property of the path instead of one caller's instance. Nested
+ callers do not share objects; they only share the file they are protecting.
+ """
- def __init__(self, lock_path: Path | None = None, *, timeout_seconds: float = 30.0):
- self.lock_path = lock_path or paths.get_sqlite_migration_lock_path()
+ def __init__(self) -> None:
+ self.gate = threading.RLock()
+ self.depth = 0
+ self.handle = None
+ self.users = 0
+
+
+_registry_lock = threading.Lock()
+_states: dict[str, _PathLockState] = {}
+
+
+def _state_key(lock_path: Path) -> str:
+ return os.path.normcase(os.path.realpath(os.fspath(lock_path)))
+
+
+def _checkout_state(key: str) -> _PathLockState:
+ with _registry_lock:
+ state = _states.get(key)
+ if state is None:
+ state = _PathLockState()
+ _states[key] = state
+ state.users += 1
+ return state
+
+
+def _return_state(key: str) -> None:
+ with _registry_lock:
+ state = _states.get(key)
+ if state is None:
+ return
+ state.users -= 1
+ if state.users <= 0:
+ _states.pop(key, None)
+
+
+class MigrationFileLock:
+ """A cross-process lock for one path, re-entrant within a thread.
+
+ Two guarantees, needed together by the same callers: at most one process on
+ the machine holds the path, and at most one thread inside each process holds
+ it -- while a thread that already holds it may take it again.
+
+ The second guarantee makes this thread-owned, so the thread that acquires is
+ the thread that releases. Re-entrance is what forces that: a lock that any
+ thread may hand to any other has no holder to compare a nested acquire
+ against. A caller that waits on one thread and works on another must keep
+ the whole acquire-release pair on the waiting thread.
+
+ ``timeout_seconds`` bounds the whole acquire, gate and file lock together.
+ ``0`` makes it a try-lock that never blocks. ``None`` waits indefinitely,
+ which is the right answer whenever the work behind the lock has no upper
+ bound: the OS drops a file lock when its holder dies, so the only way to
+ wait forever is for a live process to still be working.
+ """
+
+ def __init__(self, lock_path: Path, *, timeout_seconds: float | None = 30.0):
+ self.lock_path = lock_path
self.timeout_seconds = timeout_seconds
- self._handle = None
+ self._key = _state_key(self.lock_path)
+ self._state: _PathLockState | None = None
+ self._entries = 0
def acquire(self) -> None:
- self.lock_path.parent.mkdir(parents=True, exist_ok=True)
- handle = open(self.lock_path, "a+", encoding="utf-8")
- deadline = time.monotonic() + self.timeout_seconds
- while True:
- handle.seek(0)
- if _try_lock(handle):
- handle.seek(0)
- handle.truncate()
- handle.write(str(os.getpid()))
- handle.flush()
- self._handle = handle
- return
- if time.monotonic() >= deadline:
- handle.close()
- raise MigrationLockTimeout(f"Timed out waiting for migration lock: {self.lock_path}")
- time.sleep(0.1)
+ deadline = None if self.timeout_seconds is None else time.monotonic() + self.timeout_seconds
+ state = _checkout_state(self._key)
+ if not _acquire_gate(state.gate, deadline):
+ _return_state(self._key)
+ raise MigrationLockTimeout(f"Timed out waiting for migration lock: {self.lock_path}")
+ try:
+ if state.depth == 0:
+ state.handle = _acquire_file_lock(self.lock_path, deadline)
+ except BaseException:
+ state.gate.release()
+ _return_state(self._key)
+ raise
+ state.depth += 1
+ self._state = state
+ self._entries += 1
def release(self) -> None:
- if self._handle is None:
+ state = self._state
+ if state is None or self._entries == 0:
return
+ self._entries -= 1
+ if self._entries == 0:
+ self._state = None
+ state.depth -= 1
try:
- _unlock(self._handle)
+ if state.depth == 0 and state.handle is not None:
+ handle, state.handle = state.handle, None
+ _release_file_lock(handle)
finally:
- self._handle.close()
- self._handle = None
+ state.gate.release()
+ _return_state(self._key)
def __enter__(self) -> "MigrationFileLock":
self.acquire()
@@ -61,6 +156,70 @@ class MigrationFileLock:
self.release()
+def _acquire_gate(gate, deadline: float | None) -> bool:
+ if deadline is None:
+ gate.acquire()
+ return True
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ # Still one real attempt: a zero timeout is a try-lock, not a refusal,
+ # and a thread already holding the gate re-enters it here.
+ return gate.acquire(blocking=False)
+ return gate.acquire(timeout=remaining)
+
+
+def _acquire_file_lock(lock_path: Path, deadline: float | None):
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ handle = open(lock_path, "a+", encoding="utf-8")
+ next_log = time.monotonic() + _WAIT_LOG_INTERVAL_SECONDS
+ while True:
+ # Every attempt locks the same byte. Windows locks a range starting at
+ # the current position, and both the append-mode open and the read below
+ # leave it at the end of the file, so seeking is what keeps two waiters
+ # contending for one byte instead of two disjoint ones.
+ handle.seek(0)
+ if _try_lock(handle):
+ handle.seek(0)
+ handle.truncate()
+ handle.write(str(os.getpid()))
+ handle.flush()
+ return handle
+ now = time.monotonic()
+ if deadline is not None and now >= deadline:
+ handle.close()
+ raise MigrationLockTimeout(f"Timed out waiting for migration lock: {lock_path}")
+ if now >= next_log:
+ next_log = now + _WAIT_LOG_INTERVAL_SECONDS
+ logger.info(
+ "Waiting for the migration lock at %s, held by pid %s",
+ lock_path,
+ _recorded_holder(handle),
+ )
+ time.sleep(0.1)
+
+
+def _release_file_lock(handle) -> None:
+ try:
+ _unlock(handle)
+ finally:
+ handle.close()
+
+
+def _recorded_holder(handle) -> str:
+ """Whoever last wrote the lock file, for the waiting message only.
+
+ Advisory: a holder writes its pid just after taking the lock, so a reader
+ can catch the previous holder's pid for an instant. Nothing decides anything
+ on this value.
+ """
+
+ try:
+ handle.seek(0)
+ return handle.read().strip() or "unknown"
+ except OSError:
+ return "unknown"
+
+
def _try_lock(handle) -> bool:
if os.name == "nt":
import msvcrt
diff --git a/storage/migrations.py b/storage/migrations.py
index cc13e5f08..8c42aa8b9 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -15,13 +15,16 @@ from alembic.script import ScriptDirectory
from config import paths
from storage.backups import create_sqlite_migration_backup, prune_state_backups
from storage.db import create_sqlite_engine, sqlite_url
+from storage.lock import MigrationFileLock, migration_lock_path_for
logger = logging.getLogger(__name__)
# Alembic's EnvironmentContext installs module-level proxies while an upgrade
# runs. Concurrent store initialization can otherwise tear down another
-# thread's proxy and surface errors such as KeyError("config").
+# thread's proxy and surface errors such as KeyError("config"). This owns that
+# hazard and nothing else: the proxies are per interpreter, not per database, so
+# it must stay global, and it says nothing about other processes.
_MIGRATION_LOCK = threading.RLock()
INITIAL_REVISION = "20260501_0001"
@@ -226,14 +229,43 @@ def run_migrations(
revision: str = "head",
prune_backups_after_upgrade: bool = True,
) -> None:
+ """Bring one SQLite state database to `revision`, one migrator at a time.
+
+ Exclusion belongs here rather than at the call sites, because "at most one
+ migrator per database" is a property of the database, and a call site can
+ only promise it for itself. It was previously promised by `ensure_sqlite_state`
+ alone, which left every other entry point -- the discovery helpers, a store
+ constructed with an explicit `db_path`, the background-table bootstrap --
+ running `command.upgrade` against a file another process could be upgrading
+ at the same moment. The controller and the Web UI are separate processes on
+ one state directory, so that pairing is the ordinary case, not a corner.
+
+ Both locks are load-bearing and neither substitutes for the other: the file
+ lock is machine-wide and per database, and `_MIGRATION_LOCK` is per
+ interpreter and global, guarding Alembic's module-level proxies.
+
+ The file lock is taken first, and always first, which is what makes the pair
+ deadlock-free. Taking the global one first would also let a thread hold every
+ database's migrations in this process while it waits on a foreign process --
+ a remote stall propagating into unrelated local work.
+
+ The wait is deliberately unbounded. A file lock is released by the OS when
+ its holder dies, so the only way to wait forever is for a live process to
+ still be migrating -- and a migration's duration is bounded by the data, not
+ by anything we could name here. Any deadline would be a guess that turns a
+ slow, correct upgrade into a failed startup for every other entry point.
+ Waiting is logged with the holder's pid so the wait stays diagnosable.
+ """
+
target_db = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()
guard_source_checkout_default_state_migration(target_db)
- with _MIGRATION_LOCK:
- _run_migrations_locked(
- target_db,
- revision=revision,
- prune_backups_after_upgrade=prune_backups_after_upgrade,
- )
+ with MigrationFileLock(migration_lock_path_for(target_db), timeout_seconds=None):
+ with _MIGRATION_LOCK:
+ _run_migrations_locked(
+ target_db,
+ revision=revision,
+ prune_backups_after_upgrade=prune_backups_after_upgrade,
+ )
def _run_migrations_locked(
diff --git a/tests/conftest.py b/tests/conftest.py
index 7799ed8b0..6827c37ba 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -48,6 +48,7 @@ import shutil
import sqlite3
import sys
import warnings
+from contextlib import contextmanager
from functools import wraps
from pathlib import Path
@@ -242,6 +243,50 @@ def _reset_cached_sqlite_engines():
_reset()
+def hold_migration_lock_elsewhere():
+ """Hold a migration lock path from a thread that is genuinely not the caller.
+
+ Taking it in the calling thread is not a stand-in for a competing holder and
+ never was, it only used to look like one: `MigrationFileLock` is re-entrant
+ per path and thread, so code under test running in that same thread takes the
+ lock again and proceeds. A test written that way asserts nothing about
+ exclusion and keeps passing after the exclusion is gone.
+ """
+
+ import threading
+
+ from storage.lock import MigrationFileLock
+
+ @contextmanager
+ def _holder(lock_path: Path):
+ acquired = threading.Event()
+ release = threading.Event()
+ failures: list[BaseException] = []
+
+ def hold() -> None:
+ try:
+ with MigrationFileLock(lock_path, timeout_seconds=None):
+ acquired.set()
+ release.wait(30)
+ except BaseException as exc: # surfaced to the test, never swallowed
+ failures.append(exc)
+ acquired.set()
+
+ holder = threading.Thread(target=hold, name="migration-lock-holder", daemon=True)
+ holder.start()
+ assert acquired.wait(30), f"lock holder never started for {lock_path}"
+ assert not failures, failures[0]
+ try:
+ yield
+ finally:
+ release.set()
+ holder.join(30)
+ assert not failures, failures[0]
+
+ return _holder
+
+
@pytest.fixture(autouse=True)
def _reset_memory_artifact_manager():
"""Keep the managed Memory runtime bound to the current test home."""
diff --git a/tests/test_git_runtime.py b/tests/test_git_runtime.py
index 32fe8dd65..d21bf1033 100644
--- a/tests/test_git_runtime.py
+++ b/tests/test_git_runtime.py
@@ -13,7 +13,6 @@ import pytest
from core import git_runtime, managed_runtime
from core.git_runtime import GitRuntimeManager
-from storage.lock import MigrationFileLock
def _write_git_archive(tmp_path: Path, *, version: str = "2.55.0") -> Path:
@@ -213,18 +212,18 @@ def test_managers_for_same_runtime_share_install_lock(tmp_path: Path) -> None:
def test_install_and_clean_refuse_runtime_file_lock_held_elsewhere(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
+ hold_migration_lock_elsewhere,
) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
archive = _write_git_archive(tmp_path)
manifest = _write_manifest(tmp_path, archive)
manager = GitRuntimeManager(manifest_path=manifest)
- external_lock = MigrationFileLock(manager._install_file_lock_path)
- external_lock.acquire()
- try:
+ # "Elsewhere" has to mean another thread. The lock is re-entrant per path and
+ # thread, so holding it here would let ensure() take it again and report a
+ # refusal that never happened.
+ with hold_migration_lock_elsewhere(manager._install_file_lock_path):
install_result = manager.ensure()
clean_result = manager.clean()
- finally:
- external_lock.release()
assert install_result["ok"] is False
assert install_result["reason"] == "git_install_already_running"
diff --git a/tests/test_migration_lock.py b/tests/test_migration_lock.py
new file mode 100644
index 000000000..14031cbbb
--- /dev/null
+++ b/tests/test_migration_lock.py
@@ -0,0 +1,174 @@
+"""What the migration lock promises, stated as properties.
+
+Two of them, needed together by the same callers: at most one migrator per
+database across every process on the machine, and re-entrance for the thread
+that already holds it. Neither can be observed from the calling thread alone --
+the lock is re-entrant, so a test that takes it and then checks the code under
+test is refused has only checked that re-entrance works.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from storage.lock import MigrationFileLock, MigrationLockTimeout, migration_lock_path_for
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+
+
+def _free_for_another_thread(lock_path: Path) -> bool:
+ """Whether a thread that is not this one could take the lock right now."""
+
+ outcome: list[bool] = []
+
+ def attempt() -> None:
+ try:
+ with MigrationFileLock(lock_path, timeout_seconds=0):
+ outcome.append(True)
+ except MigrationLockTimeout:
+ outcome.append(False)
+
+ probe = threading.Thread(target=attempt, daemon=True)
+ probe.start()
+ probe.join(30)
+ assert outcome, "the probe neither took the lock nor was refused"
+ return outcome[0]
+
+
+def test_the_holder_re_enters_while_every_other_thread_is_excluded(tmp_path: Path) -> None:
+ # Nesting is ordinary, not a corner: ensure_sqlite_state holds this lock
+ # across run_migrations, which takes it too. It cannot come from the OS lock
+ # either -- flock attaches to an open file description, so the nested open a
+ # second acquire performs is a different description and blocks against the
+ # first, in the very thread already holding it.
+ lock_path = tmp_path / "migration.lock"
+ assert _free_for_another_thread(lock_path) is True
+
+ with MigrationFileLock(lock_path, timeout_seconds=None):
+ assert _free_for_another_thread(lock_path) is False
+ with MigrationFileLock(lock_path, timeout_seconds=0):
+ assert _free_for_another_thread(lock_path) is False
+ # Leaving the inner acquire must not hand the lock away while the outer
+ # one is still holding it.
+ assert _free_for_another_thread(lock_path) is False
+
+ assert _free_for_another_thread(lock_path) is True
+
+
+def test_re_entrance_belongs_to_the_path_not_to_one_lock_object(tmp_path: Path) -> None:
+ # Nested callers do not share objects. `ensure_sqlite_state` and
+ # `run_migrations` each construct their own lock; all they share is the file
+ # they are protecting, so that file is where the depth has to live.
+ lock_path = tmp_path / "migration.lock"
+ outer = MigrationFileLock(lock_path, timeout_seconds=None)
+ inner = MigrationFileLock(lock_path, timeout_seconds=0)
+
+ with outer:
+ with inner:
+ assert _free_for_another_thread(lock_path) is False
+ assert _free_for_another_thread(lock_path) is False
+
+ assert _free_for_another_thread(lock_path) is True
+
+
+def test_the_lock_follows_the_database_not_the_route_taken_to_it(tmp_path: Path) -> None:
+ # Two callers that disagree about which directory is "the" state directory
+ # would otherwise take two different locks over one database and both
+ # proceed, which is the whole failure this lock exists to prevent.
+ state_dir = tmp_path / "state"
+ state_dir.mkdir()
+ db_path = state_dir / "vibe.sqlite"
+ db_path.touch()
+ alias = tmp_path / "alias"
+ alias.symlink_to(state_dir, target_is_directory=True)
+
+ assert migration_lock_path_for(alias / "vibe.sqlite") == migration_lock_path_for(db_path)
+ assert migration_lock_path_for(state_dir / "." / "vibe.sqlite") == migration_lock_path_for(db_path)
+ assert migration_lock_path_for(db_path).parent == db_path.resolve().parent
+
+
+def test_run_migrations_excludes_another_process_on_the_same_database(tmp_path: Path) -> None:
+ # The controller and the Web UI are separate processes over one state
+ # directory, so a second migrator is the ordinary pairing rather than a
+ # corner. A thread lock cannot express this, which is why the entry points
+ # that only had one could run `command.upgrade` against a file another
+ # process was upgrading at the same moment.
+ state_dir = tmp_path / "state"
+ state_dir.mkdir()
+ db_path = state_dir / "vibe.sqlite"
+ ready = tmp_path / "ready"
+ done = tmp_path / "done"
+ code = (
+ "import sys\n"
+ "from pathlib import Path\n"
+ "from storage.migrations import run_migrations\n"
+ "Path(sys.argv[2]).write_text('ready', encoding='utf-8')\n"
+ "run_migrations(Path(sys.argv[1]), revision='20260627_0025')\n"
+ "Path(sys.argv[3]).write_text('done', encoding='utf-8')\n"
+ )
+
+ with MigrationFileLock(migration_lock_path_for(db_path), timeout_seconds=None):
+ child = subprocess.Popen(
+ [sys.executable, "-c", code, str(db_path), str(ready), str(done)],
+ cwd=REPO_ROOT,
+ env=_child_env(tmp_path),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+ try:
+ _wait_for(ready.exists, "the child never reached run_migrations")
+ # It announced itself before the call, so from here on it is either
+ # blocked on the lock or has walked straight past it.
+ time.sleep(1.0)
+ assert child.poll() is None, "the child returned while the lock was held elsewhere"
+ assert not done.exists()
+ assert not db_path.exists(), "the child migrated a database this process had locked"
+ except BaseException:
+ child.kill()
+ child.communicate()
+ raise
+
+ stdout, stderr = child.communicate(timeout=120)
+ assert child.returncode == 0, f"child failed: {stdout}\n{stderr}"
+ assert done.exists()
+ assert db_path.is_file()
+
+
+def _child_env(home: Path) -> dict[str, str]:
+ """A child that cannot reach the developer's real state.
+
+ conftest isolates this process, and the child inherits none of that, so it
+ is stated again here rather than assumed.
+ """
+
+ isolated = home / "home"
+ isolated.mkdir(exist_ok=True)
+ env = dict(os.environ)
+ env.update(
+ {
+ "HOME": str(isolated),
+ "AVIBE_HOME": str(isolated / ".avibe"),
+ "XDG_CONFIG_HOME": str(isolated / "config"),
+ "XDG_DATA_HOME": str(isolated / "data"),
+ "XDG_STATE_HOME": str(isolated / "state"),
+ "XDG_CACHE_HOME": str(isolated / "cache"),
+ }
+ )
+ return env
+
+
+def _wait_for(condition, message: str, *, timeout: float = 60.0) -> None:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if condition():
+ return
+ time.sleep(0.05)
+ pytest.fail(message)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index beb0954fd..f89743648 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -23,7 +23,7 @@ from config import paths
from config.v2_settings import ChannelSettings, RoutingSettings, SettingsState, SettingsStore
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.importer import JSON_IMPORT_MARKER, ensure_sqlite_state, reset_ensured_sqlite_state
-from storage.lock import MigrationFileLock
+from storage.lock import migration_lock_path_for
from storage import importer, message_deliveries, messages_service, migrations
from storage.background import SQLiteBackgroundTaskStore
from storage.migrations import UnsafeDefaultStateMigrationError, background_tables_ready, run_migrations
@@ -5632,7 +5632,9 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
}
-def test_ensure_sqlite_state_short_circuits_after_first_success(tmp_path: Path, monkeypatch) -> None:
+def test_ensure_sqlite_state_short_circuits_after_first_success(
+ tmp_path: Path, monkeypatch, hold_migration_lock_elsewhere
+) -> None:
# Callers put ensure_sqlite_state in front of ordinary operations (a login,
# a read-only query, a skill delete), so a repeat call must cost nothing.
# Re-running the pipeline per request serialized unrelated work on the
@@ -5655,11 +5657,26 @@ def test_ensure_sqlite_state_short_circuits_after_first_success(tmp_path: Path,
monkeypatch.setattr(importer, "run_migrations", counting_run_migrations)
# An already-held migration lock is exactly the contention that failed the
- # login. The repeat call must not queue behind it, so holding it here would
- # deadlock the test if the short-circuit regressed.
- with MigrationFileLock(state_dir / "migration.lock", timeout_seconds=1.0):
- second = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
-
+ # login, and only another thread can hold it against this one: the lock is
+ # re-entrant per path and thread, so taking it here would let the repeat call
+ # take it again and pass whether or not it short-circuits. The call runs on
+ # its own thread for the same reason the wait behind that lock is unbounded --
+ # a regression has to fail this test rather than hang it.
+ outcome: list = []
+
+ def repeat_call() -> None:
+ outcome.append(
+ ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+ )
+
+ with hold_migration_lock_elsewhere(migration_lock_path_for(db_path)):
+ caller = threading.Thread(target=repeat_call, daemon=True)
+ caller.start()
+ caller.join(30)
+ assert not caller.is_alive(), "the repeat call queued behind the held migration lock"
+
+ assert outcome, "the repeat call raised instead of short-circuiting"
+ second = outcome[0]
assert second is first
assert migrations_run == 0
diff --git a/tests/test_state_backups.py b/tests/test_state_backups.py
index c85181138..84aa896ea 100644
--- a/tests/test_state_backups.py
+++ b/tests/test_state_backups.py
@@ -264,20 +264,39 @@ def test_repeated_migration_failures_keep_the_rollback_window_bounded(monkeypatc
state_dir.mkdir()
db_path = state_dir / "vibe.sqlite"
run_migrations(db_path, revision="20260627_0025")
- monkeypatch.setattr(
- "storage.migrations.command.upgrade",
- lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("migration boom")),
- )
+ before_the_storm = _db_contents(db_path)
+
+ def failing_upgrade(*args, **kwargs):
+ # Committing before failing is the ordinary shape, not a contrived one:
+ # each attempt leaves the database a little further from where the storm
+ # started, which is exactly what makes the earliest copy the valuable one
+ # and every later copy a worse answer to the same question.
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table if not exists boom (attempt integer)")
+ conn.execute("insert into boom (attempt) values ((select count(*) from boom))")
+ raise RuntimeError("migration boom")
+
+ monkeypatch.setattr("storage.migrations.command.upgrade", failing_upgrade)
for _ in range(SQLITE_BACKUP_RETENTION + 3):
with pytest.raises(RuntimeError, match="migration boom"):
ensure_sqlite_state(db_path=db_path, state_dir=state_dir)
surviving = _sqlite_backup_roots(state_dir / "backups")
- assert 0 < len(surviving) <= SQLITE_BACKUP_RETENTION
+ assert 0 < len(surviving) <= SQLITE_BACKUP_RETENTION * 2
for name in surviving:
with sqlite3.connect(state_dir / "backups" / name / "vibe.sqlite") as backup:
assert backup.execute("PRAGMA quick_check").fetchone() == ("ok",)
+ # Bounded is half the promise. The attempts all copy a database sitting at
+ # the same revisions, so a window counting copies fills with them and evicts
+ # the one copy taken before the first attempt -- the only one predating
+ # whatever the failing migration did on its way down, and the one an operator
+ # reaches for. Counting rollback positions instead keeps it here for as long
+ # as the storm lasts.
+ assert any(
+ _db_contents(state_dir / "backups" / name / "vibe.sqlite") == before_the_storm
+ for name in surviving
+ )
def _db_contents(path: Path) -> list[tuple[str, list[tuple]]]:
@@ -331,7 +350,122 @@ def test_every_call_holds_the_database_as_it_stands_at_that_call(tmp_path: Path)
rollback_point()
assert len(set(taken)) == len(taken)
- assert len(_sqlite_backup_roots(backups_dir)) == SQLITE_BACKUP_RETENTION
+ # Two stamps were visited, so the window holds two positions, and of each the
+ # first and the last copy taken there. The pre-restore original is the first
+ # copy at its position and survives; the copy holding the writes accepted
+ # after the restore is the last one there and survives too. Neither rule
+ # alone gets both -- that is why the pair is what a position keeps.
+ assert set(_sqlite_backup_roots(backups_dir)) == {taken[0].name, taken[3].name, taken[4].name}
+
+
+def test_the_first_copy_at_a_position_survives_however_the_clock_moves(tmp_path: Path) -> None:
+ # A position keeps its first and its last copy, and "first" was read back out
+ # of the backup's timestamp -- the same mistake, one layer down, as every
+ # rule this change already discarded: a label standing in for a fact only the
+ # writer knew. A clock corrected backwards between two attempts dates the
+ # later copy earlier, so the retry after a partial migration becomes both the
+ # first and the last copy of its position and evicts the clean one it was
+ # supposed to bracket. Stated as the property -- the database as it stood
+ # when the position was first copied stays restorable -- because the clock
+ # can be wrong in more ways than a test can list.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('clean')")
+ before_the_storm = _db_contents(db_path)
+
+ # Each attempt is stamped earlier than the one before it, and none of them
+ # moves the revision, so all three copies belong to one position.
+ taken: list[Path] = []
+ for moment, damage in (
+ (datetime(2026, 8, 6, 12, 0, tzinfo=timezone.utc), "first retry"),
+ (datetime(2026, 8, 6, 11, 59, tzinfo=timezone.utc), "second retry"),
+ (datetime(2026, 8, 6, 11, 58, tzinfo=timezone.utc), None),
+ ):
+ taken.append(create_sqlite_migration_backup(db_path, backups_dir=backups_dir, now=moment))
+ if damage is not None:
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("update payload set value = ?", (damage,))
+
+ surviving = _sqlite_backup_roots(backups_dir)
+ assert surviving == sorted({taken[0].name, taken[2].name})
+ assert any(_db_contents(backups_dir / name / "vibe.sqlite") == before_the_storm for name in surviving)
+
+
+def _as_pre_sequence_backup(backup_dir: Path) -> Path:
+ """Turn a backup into one the previous release would have written.
+
+ Produced by the current writer and then stripped, rather than hand-built, so
+ a change to the manifest cannot leave this fixture describing a shape no
+ release ever wrote.
+ """
+
+ manifest_path = backup_dir / "manifest.json"
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ del manifest["backup_sequence"]
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+ return backup_dir
+
+
+def test_backups_from_before_the_counter_still_come_first(tmp_path: Path) -> None:
+ # A window is mixed for exactly as long as it takes the copies an older
+ # release wrote to age out, and during that time the counter cannot order it
+ # by itself. Falling back to the stamps for the whole group puts the clock
+ # back in charge of the one decision it was just taken off -- with a clock
+ # corrected backwards, a retry dated earlier than the clean copy from the
+ # previous release becomes the first copy of the position and evicts it.
+ #
+ # The fact that settles it is not in the timestamps: a copy without a
+ # counter was written by a release that did not have one, so it precedes
+ # every counted copy no matter what either name says.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('clean')")
+ before_the_storm = _db_contents(db_path)
+
+ from_the_previous_release = _as_pre_sequence_backup(
+ create_sqlite_migration_backup(
+ db_path, backups_dir=backups_dir, now=datetime(2026, 8, 6, 12, 0, tzinfo=timezone.utc)
+ )
+ )
+ retries: list[Path] = []
+ for moment, damage in (
+ (datetime(2026, 8, 6, 11, 0, tzinfo=timezone.utc), "first retry"),
+ (datetime(2026, 8, 6, 10, 0, tzinfo=timezone.utc), "second retry"),
+ ):
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("update payload set value = ?", (damage,))
+ retries.append(create_sqlite_migration_backup(db_path, backups_dir=backups_dir, now=moment))
+
+ surviving = _sqlite_backup_roots(backups_dir)
+ assert surviving == sorted({from_the_previous_release.name, retries[-1].name})
+ assert any(_db_contents(backups_dir / name / "vibe.sqlite") == before_the_storm for name in surviving)
+
+
+def test_a_position_dated_in_the_future_does_not_evict_a_newer_one(tmp_path: Path) -> None:
+ # The window ranks positions against each other too, and that ranking read
+ # the same timestamps. State carried from a machine running ahead is dated
+ # into the future permanently, so ranking by the stamp parks it at the top
+ # of the window forever and every genuinely newer position falls out beneath
+ # it. Same class as the copies inside a position, so it reads the same
+ # recorded order.
+ db_path = tmp_path / "vibe.sqlite"
+ backups_dir = tmp_path / "backups"
+ taken: list[Path] = []
+ for revision, moment in (
+ ("20260806_0047", datetime(2099, 1, 1, tzinfo=timezone.utc)),
+ ("20260809_0049", datetime(2026, 8, 9, 1, 0, tzinfo=timezone.utc)),
+ ("20260811_0050", datetime(2026, 8, 11, 1, 0, tzinfo=timezone.utc)),
+ ):
+ _stamp(db_path, revision)
+ taken.append(create_sqlite_migration_backup(db_path, backups_dir=backups_dir, now=moment))
+
+ assert _sqlite_backup_roots(backups_dir) == sorted({taken[1].name, taken[2].name})
def test_the_manifest_records_the_revisions_read_from_the_copy(tmp_path: Path) -> None:
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 9ef8024b8..b916d97d7 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -29,12 +29,13 @@ from config.v2_config import TelegramConfig
@pytest.fixture(autouse=True)
def _reset_chat_discovery_cache():
- """chat_discovery keeps process-global debounce/migration caches keyed on
+ """chat_discovery keeps a process-global debounce cache keyed on
(platform, chat_id) — not on the DB path — so a chat remembered by one test
short-circuits remember_chat in a later test that points get_vibe_remote_dir at
- a fresh tmp dir. Clear them between tests for isolation."""
+ a fresh tmp dir. Clear it between tests for isolation. The migrated-target memo
+ it used to keep alongside is now `ensure_sqlite_state`'s, which conftest's
+ `_reset_cached_sqlite_engines` already resets for every test."""
chat_discovery._debounce_cache.clear()
- chat_discovery._migrated_db_paths.clear()
yield
diff --git a/vibe/log_sink.py b/vibe/log_sink.py
index 4f1668ad2..bf6787dc3 100644
--- a/vibe/log_sink.py
+++ b/vibe/log_sink.py
@@ -122,6 +122,7 @@ def copy_bounded_log(
lock = MigrationFileLock(path.with_name(f".{path.name}.sink.lock"), timeout_seconds=0.25)
lock_ready = threading.Event()
lock_stop = threading.Event()
+ lock_done = threading.Event()
lock_acquired = False
pending: deque[bytes] = deque()
pending_bytes = 0
@@ -129,20 +130,33 @@ def copy_bounded_log(
source_failed = False
pending_ready = threading.Condition()
- def _acquire_lock() -> None:
+ def _hold_lock() -> None:
+ """Take the sink lock, then hold it here until the copy is finished.
+
+ The release stays on this thread because the lock is re-entrant, and a
+ re-entrant lock belongs to the thread that took it: handing the release
+ to the draining thread is the one thing thread ownership cannot express.
+ The retry loop is what keeps the wait cancellable -- an unbounded acquire
+ could not be given up when the source ends before the peer sink does.
+ """
+
nonlocal lock_acquired
while not lock_stop.is_set():
try:
lock.acquire()
- lock_acquired = True
- break
except MigrationLockTimeout:
continue
except OSError:
break
+ lock_acquired = True
+ break
lock_ready.set()
+ if not lock_acquired:
+ return
+ lock_done.wait()
+ lock.release()
- lock_thread = threading.Thread(target=_acquire_lock, name=f"log-sink-lock-{path.name}", daemon=True)
+ lock_thread = threading.Thread(target=_hold_lock, name=f"log-sink-lock-{path.name}", daemon=True)
lock_thread.start()
def _read_source() -> None:
@@ -211,9 +225,8 @@ def copy_bounded_log(
return False
finally:
lock_stop.set()
+ lock_done.set()
lock_thread.join(timeout=1.0)
- if lock_acquired:
- lock.release()
def main(argv: list[str] | None = None) -> int: