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): stop copying the database into a rollback point it already holds

cyh7652685856f3
diff --git a/docs/plans/local-data-lifecycle.md b/docs/plans/local-data-lifecycle.md
index 1424146b7..b1089e999 100644
--- a/docs/plans/local-data-lifecycle.md
+++ b/docs/plans/local-data-lifecycle.md
@@ -21,22 +21,29 @@ downloads, sources, prebuilt assets, or version directories.
10 MiB, retaining the newest 5 MiB. This preserves the inode used by live tail
readers and avoids racing a subprocess that is actively appending output.
- Before an existing SQLite database advances to another schema revision,
- create a consistent SQLite online backup, and bound the rollback window in
- the same call. Creating the copy is unconditional, so the bound has to be
- too: gating it on the upgrade finishing leaves the window unbounded in the
- one situation that produces attempt after attempt.
+ hold a consistent SQLite online backup of it, and bound the rollback window
+ in the same call. Creating the rollback point is unconditional, so the bound
+ has to be too: gating it on the upgrade finishing leaves the window unbounded
+ in the one situation that produces attempt after attempt.
+- Take no new copy when the window already holds one stamped with the revisions
+ the database is stamped with now. That is the same rollback point. A
+ migration failing partway is retried by every service entry point that
+ touches the store, and copying the database again on each attempt is what
+ makes the window grow -- and what puts the snapshot taken before the damage
+ at risk, since no rule that inspects the copies can reliably tell it from the
+ ones taken after. A partial upgrade that commits row changes without touching
+ the schema or the revision stamp is identical to the clean database in
+ everything a backup can measure. Not taking the copy keeps the clean snapshot
+ by never producing anything that could displace it.
- Bound the window to the newest two SQLite migration/repair rollback points
- and the newest three legacy JSON migration snapshots. A rollback point is a
- distinct database state -- the revisions a copy was stamped with plus a
- fingerprint of its schema, both read from the copy itself. Two copies of the
- same state are the same rollback point taken twice, and the newer one holds
- every write the older one holds, so the window keeps the newest copy of each
- state, newest state first, and spends any slot left over on the copies that
- were superseded. On a healthy machine every migration finishes and every copy
- is a state of its own, which is the newest two. Under a migration that keeps
- failing partway, every attempt after the first copies the same half-migrated
- database, so those attempts are one state holding one slot between them and
- cannot crowd out the snapshot taken before the damage.
+ and the newest three legacy JSON migration snapshots, with the copy a call
+ has just written protected from that call's own prune. Copies left by a
+ machine whose clock ran ahead are dated into the future permanently, so
+ ordering alone cannot defend a fresh rollback point.
+- Record in each manifest the revisions read back from the copy, not the ones
+ the caller reported: another process can advance the database in between, and
+ the next attempt uses the manifest to decide whether the rollback point it
+ needs already exists.
- Prune only strict Avibe formats: self-identifying managed backup directories,
historical `sqlite-state-migration-*` directories with valid manifests, and
the exact legacy `vibe-pre-<revision>[-release-head]-repair-<timestamp>` file
diff --git a/storage/backups.py b/storage/backups.py
index bf707a994..e2688de34 100644
--- a/storage/backups.py
+++ b/storage/backups.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import errno
-import hashlib
import json
import logging
import os
@@ -31,11 +30,6 @@ _LEGACY_SQLITE_REPAIR_RE = re.compile(
r"(?P<timestamp>\d{8}T\d{6}Z)\.sqlite$"
)
-# What a backup's database actually was: the revisions it was stamped with, and
-# a fingerprint of the schema those revisions claim to describe. Two copies are
-# the same rollback point only if they agree on both.
-_State = tuple[tuple[str, ...], str]
-
# A platform or filesystem declining to sync a directory is an answer, not a
# fault. Anything else -- ENOSPC, EIO -- means the data may not be on the disk,
# so it must reach the caller instead of being logged and forgotten.
@@ -53,33 +47,19 @@ class _BackupCandidate:
kind: str
timestamp: datetime
suffix: int
- sequence: int | None = None
- state: _State | None = None
+ revisions: tuple[str, ...] | None = None
@property
- def order_key(self) -> tuple[bool, int, datetime, int, str]:
- """Creation order, measured by us where possible.
-
- The sequence is a counter this module writes and increments from its own
- previous writes, so it is the one ordering input nothing outside the
- process can move. Wall-clock time can: an NTP correction, a manual
- change, or state carried from a machine running ahead all reorder
- timestamps after the fact, and a copy that lands out of order takes the
- slot of the one that actually holds more of the user's writes.
-
- Backups written before the counter existed have no sequence, and sort
- below every backup that has one -- which is simply true, since the
- counter only started being written later. Among themselves the timestamp
- is the best evidence available.
+ def order_key(self) -> tuple[datetime, int, str]:
+ """Creation order, as the backup's own name records it.
+
+ 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.
"""
- return (
- self.sequence is not None,
- self.sequence or 0,
- self.timestamp,
- self.suffix,
- self.root.name,
- )
+ return (self.timestamp, self.suffix, self.root.name)
def _parse_timestamp(value: str) -> datetime | None:
@@ -144,33 +124,23 @@ def _directory_candidate(path: Path) -> _BackupCandidate | None:
kind=kind,
timestamp=timestamp,
suffix=int(match.group("suffix") or 0),
- sequence=_manifest_sequence(manifest),
- state=_manifest_state(manifest),
+ revisions=_manifest_revisions(manifest),
)
-def _manifest_sequence(manifest: dict) -> int | None:
- value = manifest.get("sequence")
- return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
-
-
-def _manifest_state(manifest: dict) -> _State | None:
- """What the database was, as the manifest recorded it.
+def _manifest_revisions(manifest: dict) -> tuple[str, ...] | None:
+ """The revisions the backup's own copy of the database was stamped with.
- Both halves are required, because either one alone mistakes a different
- rollback point for the same one: a partially applied upgrade moves the
- schema while the revisions stand still, and a data-only migration moves the
- revisions while the schema stands still.
-
- Manifests written before the fingerprint existed have no state, and a backup
- with no state can only be compared to itself.
+ A manifest that does not record them, or records them in a shape this
+ version does not understand, yields `None` -- which never matches anything,
+ so such a backup can never be mistaken for the rollback point a caller is
+ about to look for.
"""
- revisions = manifest.get("from_revisions")
- digest = manifest.get("schema_digest")
- if not isinstance(revisions, list) or not isinstance(digest, str) or not digest:
+ value = manifest.get("from_revisions")
+ if not isinstance(value, list):
return None
- return tuple(sorted(str(revision) for revision in revisions)), digest
+ return tuple(sorted(str(revision) for revision in value))
def _legacy_sqlite_candidate(path: Path) -> _BackupCandidate | None:
@@ -226,58 +196,22 @@ def _remove_candidate(candidate: _BackupCandidate) -> bool:
return True
-def _keep_priority(candidates: Iterable[_BackupCandidate]) -> list[_BackupCandidate]:
- """Order backups by how much a rollback would want them, best first.
-
- Two copies of the same database in the same state are the same rollback
- point taken twice, and the newer one dominates: it holds every write the
- older one holds, plus the writes made since. So the window keeps the newest
- copy of each distinct state, newest state first. That is the whole policy --
- there is no second rule for it to disagree with.
-
- It is what makes a retry storm survivable. An upgrade can commit part of its
- work and then raise -- a SQLite table rebuild inside an autocommit block
- that fails a later check is exactly that shape -- and from the next attempt
- on, every copy is of the half-migrated database. Those retries are all one
- state, so they hold one slot between them instead of crowding out the
- snapshot taken before the damage, which is a state nothing else can produce.
-
- Reading the state off the database instead of inferring it from the events
- around the backup is the point. Earlier revisions of this code tried to
- recognise a run of retries from wall-clock time, and then from the schema
- transition each attempt recorded; the environment moves both. A clock
- correction reorders the attempts. `command.upgrade` walks several revisions
- in one call, and entering an autocommit block commits the version stamps
- already earned, so the transition an attempt reports is not the one the
- attempt before it reported. A fingerprint taken from the copy moves only
- when the database moves -- including backwards, which is what an operator
- restoring a rollback point does, and why a post-restore snapshot correctly
- reads as the state it was restored to rather than as one more retry.
-
- On a healthy machine every migration finishes and every backup is a state of
- its own, so this is the familiar newest-first. Backups too old to record a
- state stand alone, for the same reason: nothing about them can be compared.
- """
-
- best: dict[object, _BackupCandidate] = {}
- superseded: list[_BackupCandidate] = []
- for candidate in sorted(candidates, key=lambda item: item.order_key, reverse=True):
- key = candidate.state if candidate.state is not None else candidate.root
- if key in best:
- superseded.append(candidate)
- else:
- best[key] = candidate
- return list(best.values()) + superseded
-
-
def prune_state_backups(
backups_dir: Path,
*,
json_retention: int | None = JSON_STATE_BACKUP_RETENTION,
sqlite_retention: int | None = SQLITE_BACKUP_RETENTION,
+ protect: Path | None = None,
) -> 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.
+
Unknown files, symlinks, incomplete backups, and directories without a
recognized manifest are intentionally left untouched.
"""
@@ -291,7 +225,10 @@ def prune_state_backups(
removed: list[Path] = []
for kind, limit in limits.items():
matching = [candidate for candidate in candidates if candidate.kind == kind]
- keep = {candidate.root for candidate in _keep_priority(matching)[:limit]}
+ ordered = sorted(matching, key=lambda item: item.order_key, reverse=True)
+ if protect is not None:
+ ordered.sort(key=lambda item: item.root != protect)
+ keep = {candidate.root for candidate in ordered[:limit]}
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)
@@ -339,47 +276,28 @@ def _fsync_directory(path: Path) -> None:
os.close(fd)
-def _next_sequence(backups_dir: Path) -> int:
- """One past the highest sequence any backup on disk carries.
+def _stamped_revisions(connection: sqlite3.Connection) -> tuple[str, ...]:
+ """The alembic revisions the database behind `connection` is stamped with.
- Counting from what survives rather than from a stored high-water mark is
- what keeps the counter honest across pruning: the new backup only has to
- outrank the backups that still exist, and reusing a number whose backup was
- deleted costs nothing. It cannot collide with a live one by construction.
+ A database with no `alembic_version` table yields the empty tuple, which is
+ a state like any other: it is what an unversioned database is, and two
+ copies of it are the same rollback point.
"""
- return max(
- (
- candidate.sequence
- for candidate in _managed_candidates(backups_dir)
- if candidate.sequence is not None
- ),
- default=0,
- ) + 1
-
-
-def _schema_digest(connection: sqlite3.Connection) -> str:
- """Fingerprint the schema of the database behind `connection`.
+ try:
+ rows = connection.execute("select version_num from alembic_version").fetchall()
+ except sqlite3.DatabaseError:
+ return ()
+ return tuple(sorted({str(row[0]) for row in rows}))
- Taken from the copy this call just wrote, so it describes the bytes being
- preserved rather than anything reported about them. That is what makes it
- usable as an identity: a partially applied upgrade changes the schema
- without changing the revision the database is stamped with, and restoring a
- rollback point changes it back.
- `sqlite_master` is a handful of rows next to a copy of the whole database,
- so the measurement is free in the only place it is taken.
- """
+def _rollback_point_held(backups_dir: Path, revisions: tuple[str, ...]) -> Path | None:
+ """A surviving backup of the database as it is stamped now, if there is one."""
- digest = hashlib.sha256()
- for row in connection.execute(
- "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name, tbl_name"
- ):
- for column in row:
- digest.update(b"\x00" if column is None else str(column).encode("utf-8"))
- digest.update(b"\x1f")
- digest.update(b"\x1e")
- return digest.hexdigest()
+ for candidate in sorted(_managed_candidates(backups_dir), key=lambda item: item.order_key, reverse=True):
+ if candidate.kind == "sqlite" and candidate.revisions == revisions:
+ return candidate.root
+ return None
def _unique_backup_dir(backups_dir: Path, *, now: datetime) -> Path:
@@ -402,11 +320,10 @@ def create_sqlite_migration_backup(
db_path: Path,
*,
backups_dir: Path | None = None,
- from_revisions: Iterable[str] = (),
to_revisions: Iterable[str] = (),
now: datetime | None = None,
) -> Path:
- """Add a consistent, self-identifying SQLite backup to a bounded rollback window.
+ """Hold a rollback point for the database as it stands, in a bounded window.
Bounding the window belongs here rather than at the call sites. A backup is
a rollback point the moment it is durable, so whether the migration that
@@ -417,22 +334,45 @@ def create_sqlite_migration_backup(
the bound true for callers not yet written, including the ones that opt out
of their own pruning.
- Owning it here also means this call is the only thing that can destroy what
- it just produced, so it never does: the copy reaches stable storage before
- any older one is deleted, and it is stamped with the next sequence, which
- puts it ahead of every backup on disk without having to trust a clock.
-
- The manifest also records what the copy actually is -- the revisions it was
- stamped with and a fingerprint of its schema -- which is what lets the window
- tell a fresh rollback point from another copy of one it already holds.
+ The copy is skipped entirely when the window already holds one stamped with
+ the revisions the database is stamped with now. That is the same rollback
+ point, and taking it again is what created the problem this function exists
+ to solve: a migration failing partway is retried by every service entry
+ point that touches the store, and the copies pile up faster than any
+ retention rule can sort them out. Not making them is cheaper than deciding
+ which to keep, and safer -- earlier revisions of this code tried to rank the
+ copies by wall-clock adjacency, then by the schema transition each attempt
+ recorded, then by a fingerprint of each copy's schema, and each rule in turn
+ was defeated by something the environment could move or by damage the copy
+ could not show. A migration that commits row changes and then fails leaves a
+ half-migrated database that is byte-comparable to the clean one in every
+ respect a backup can measure. So the clean copy is the one kept, by never
+ being displaced.
+
+ A copy that is taken reaches stable storage before any older one is deleted,
+ and is protected from its own prune, so this call can never destroy what it
+ just produced.
+
+ 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.
"""
source_path = db_path.expanduser().resolve()
created_at = now or datetime.now(timezone.utc)
target_root = (backups_dir or source_path.parent / "backups").expanduser().resolve()
- target_root.mkdir(parents=True, exist_ok=True)
- # Read before anything is written, so the count is of finished backups only.
- sequence = _next_sequence(target_root)
+ if not target_root.exists():
+ target_root.mkdir(parents=True, exist_ok=True)
+ # The entry for the window itself has to be on the disk before anything
+ # in it counts as durable; a crash that keeps the upgrade but loses this
+ # directory leaves no rollback point at all.
+ _fsync_directory(target_root.parent)
+
+ with sqlite3.connect(f"{source_path.as_uri()}?mode=ro", uri=True) as probe:
+ held = _rollback_point_held(target_root, _stamped_revisions(probe))
+ if held is not None:
+ return held
+
backup_dir = _unique_backup_dir(target_root, now=created_at)
backup_dir.mkdir(mode=0o700)
temp_db = backup_dir / "vibe.sqlite.tmp"
@@ -446,7 +386,7 @@ def create_sqlite_migration_backup(
check = destination.execute("PRAGMA quick_check").fetchone()
if check != ("ok",):
raise sqlite3.DatabaseError(f"SQLite backup quick_check failed: {check!r}")
- schema_digest = _schema_digest(destination)
+ from_revisions = _stamped_revisions(destination)
os.chmod(temp_db, 0o600)
_fsync_file(temp_db)
temp_db.replace(backup_db)
@@ -456,9 +396,7 @@ def create_sqlite_migration_backup(
"kind": "sqlite-migration",
"created_at": created_at.astimezone(timezone.utc).isoformat(),
"database": "vibe.sqlite",
- "sequence": sequence,
- "schema_digest": schema_digest,
- "from_revisions": sorted(set(from_revisions)),
+ "from_revisions": list(from_revisions),
"to_revisions": sorted(set(to_revisions)),
}
manifest_path = backup_dir / "manifest.json"
@@ -478,7 +416,7 @@ def create_sqlite_migration_backup(
# a failure while pruning cannot reach that cleanup and delete the rollback
# point this call just made. And it has to follow the manifest write,
# because a directory without one is not yet a recognized candidate: it
- # would neither count itself against the bound nor carry the sequence and
- # state that decide which copies the bound keeps.
- prune_state_backups(target_root, json_retention=None)
+ # would neither count itself against the bound nor be findable as the
+ # rollback point that lets the next attempt skip its copy.
+ prune_state_backups(target_root, json_retention=None, protect=backup_dir)
return backup_dir
diff --git a/storage/migrations.py b/storage/migrations.py
index 6b5d703b3..602ec4f71 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -234,13 +234,9 @@ def _run_migrations_locked(
cfg = alembic_config(target_db)
backup_revisions = _migration_backup_revisions(target_db, cfg, revision)
if backup_revisions is not None:
- current_revisions, target_revisions = backup_revisions
- backup_path = create_sqlite_migration_backup(
- target_db,
- from_revisions=current_revisions,
- to_revisions=target_revisions,
- )
- logger.info("Created pre-migration SQLite backup at %s", backup_path)
+ _current_revisions, target_revisions = backup_revisions
+ backup_path = create_sqlite_migration_backup(target_db, to_revisions=target_revisions)
+ logger.info("Pre-migration SQLite rollback point at %s", backup_path)
_reset_unreleased_initial_schema_drift(target_db)
_repair_unreleased_head_schema_drift(target_db)
_stamp_existing_initial_schema(target_db, cfg)
diff --git a/tests/test_state_backups.py b/tests/test_state_backups.py
index 0850f8b1c..aabb37a27 100644
--- a/tests/test_state_backups.py
+++ b/tests/test_state_backups.py
@@ -132,7 +132,6 @@ def test_create_sqlite_migration_backup_is_consistent_without_copying_live_sidec
backup_dir = create_sqlite_migration_backup(
db_path,
- from_revisions={"old"},
to_revisions={"new"},
now=datetime(2026, 7, 10, 3, 0, tzinfo=timezone.utc),
)
@@ -142,7 +141,7 @@ def test_create_sqlite_migration_backup_is_consistent_without_copying_live_sidec
manifest = json.loads((backup_dir / "manifest.json").read_text(encoding="utf-8"))
assert manifest["managed_by"] == "avibe"
assert manifest["kind"] == "sqlite-migration"
- assert manifest["from_revisions"] == ["old"]
+ assert manifest["from_revisions"] == []
assert manifest["to_revisions"] == ["new"]
# Legacy repair copies are part of the same sqlite window, so adding a
# backup prunes them to the same bound instead of accumulating beside
@@ -229,14 +228,37 @@ def test_startup_prunes_only_after_migration_backup_succeeds(monkeypatch, tmp_pa
assert all(path.exists() for path in existing)
+def _stamp(path: Path, revision: str) -> None:
+ with sqlite3.connect(path) as conn:
+ conn.execute("create table if not exists alembic_version (version_num varchar(32) not null)")
+ conn.execute("delete from alembic_version")
+ conn.execute("insert into alembic_version (version_num) values (?)", (revision,))
+
+
+def _fails_after_committing(db_path: Path, statement: str):
+ """An upgrade that commits work and then raises.
+
+ The shape a SQLite table rebuild inside an autocommit block leaves when a
+ later check fails: the work is on disk, alembic never stamped, so every
+ entry point that touches the store retries it.
+ """
+
+ def _upgrade(*args, **kwargs):
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(statement)
+ raise RuntimeError("upgrade failed after committing")
+
+ return _upgrade
+
+
def test_repeated_migration_failures_keep_the_rollback_window_bounded(monkeypatch, tmp_path: Path) -> None:
- # A migration that fails is retried, and the OAuth callback retries it once
- # per unauthenticated request. Every attempt copies the whole database, and
- # pruning used to be gated on the upgrade and the import that follow -- so
- # the one situation that produces attempts without end was also the one
- # where nothing ever reclaimed them. Assert the bound itself rather than a
- # count of attempts: whatever the retry storm does, the window it leaves
- # behind is the retention bound, and what survives is the newest copies.
+ # A migration that fails is retried, and every service entry point that
+ # touches the store retries it once more. Pruning used to be gated on the
+ # upgrade and the import that follow, so the one situation that produces
+ # attempts without end was also the one where nothing ever reclaimed them.
+ # Assert the bound itself rather than a count of attempts: whatever the
+ # retry storm does, the window it leaves behind is within the retention
+ # bound and every copy in it is restorable.
state_dir = tmp_path / "state"
state_dir.mkdir()
db_path = state_dir / "vibe.sqlite"
@@ -246,246 +268,145 @@ def test_repeated_migration_failures_keep_the_rollback_window_bounded(monkeypatc
lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("migration boom")),
)
- created: list[str] = []
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)
- created.append(max(_sqlite_backup_roots(state_dir / "backups")))
surviving = _sqlite_backup_roots(state_dir / "backups")
- assert len(surviving) == SQLITE_BACKUP_RETENTION
- assert surviving == sorted({created[0], created[-1]})
- # A bounded window is only worth keeping if it is still restorable.
+ assert 0 < len(surviving) <= SQLITE_BACKUP_RETENTION
for name in surviving:
with sqlite3.connect(state_dir / "backups" / name / "vibe.sqlite") as backup:
assert backup.execute("PRAGMA quick_check").fetchone() == ("ok",)
-def test_retry_window_keeps_the_snapshot_taken_before_a_partial_upgrade(monkeypatch, tmp_path: Path) -> None:
- # An upgrade can commit part of its work and then raise -- a SQLite table
- # rebuild inside an autocommit block that fails a later check is exactly
- # that shape. From the next attempt on, every copy is of the half-migrated
- # database, so keeping the newest copies fills the window with damage and
- # discards the only snapshot that can undo it. Consecutive manifests show
- # the run never reached where it was headed, which is what makes the
- # attempts one episode; the window keeps its ends.
+def test_retrying_a_failed_migration_does_not_take_another_copy(monkeypatch, tmp_path: Path) -> None:
+ # The retries are all attempts to leave the same revision, so they all want
+ # the same rollback point -- and it already exists after the first one. Not
+ # making the copies is what keeps the clean snapshot: nothing is produced
+ # that could displace it, however long the migration keeps failing.
state_dir = tmp_path / "state"
state_dir.mkdir()
db_path = state_dir / "vibe.sqlite"
run_migrations(db_path, revision="20260627_0025")
+ monkeypatch.setattr(
+ "storage.migrations.command.upgrade",
+ _fails_after_committing(db_path, "create table if not exists half_migrated (value text)"),
+ )
- def _partially_commit_then_fail(*args, **kwargs):
- with sqlite3.connect(db_path) as conn:
- conn.execute("create table if not exists half_migrated (value text)")
- raise RuntimeError("upgrade failed after committing")
-
- monkeypatch.setattr("storage.migrations.command.upgrade", _partially_commit_then_fail)
-
- for _ in range(SQLITE_BACKUP_RETENTION + 2):
+ for _ in range(SQLITE_BACKUP_RETENTION + 4):
with pytest.raises(RuntimeError, match="upgrade failed after committing"):
run_migrations(db_path)
surviving = _sqlite_backup_roots(state_dir / "backups")
- assert len(surviving) == SQLITE_BACKUP_RETENTION
- intact = [
- name
- for name in surviving
- if not _table_exists(state_dir / "backups" / name / "vibe.sqlite", "half_migrated")
- ]
- assert intact, "the snapshot taken before the first partial upgrade must survive the retries"
+ assert len(surviving) == 1
+ assert not _table_exists(state_dir / "backups" / surviving[0] / "vibe.sqlite", "half_migrated")
-def test_future_dated_copies_do_not_outrank_the_migration_in_progress(monkeypatch, tmp_path: Path) -> None:
- # A clock corrected backwards, or state carried from a machine running
- # ahead, leaves unrelated copies dated after everything the current
- # migration produces. Being newest on disk is not the same as being newest
- # in creation order: ranked by timestamp those copies take the window, and
- # both ends of the failing migration -- the clean snapshot and the latest
- # one -- are lost to backups that have nothing to do with it.
+def test_a_migration_that_only_commits_rows_still_leaves_a_clean_snapshot(
+ monkeypatch, tmp_path: Path
+) -> None:
+ # Not every partial upgrade is visible in the schema. One that commits row
+ # changes and then fails a validation leaves a database whose tables,
+ # indexes and revision stamp are all exactly what they were, so no
+ # fingerprint taken from a copy can tell the damaged database from the clean
+ # one. Any rule that decides which copies to keep by inspecting them is
+ # blind here; not taking the copies is not.
state_dir = tmp_path / "state"
state_dir.mkdir()
db_path = state_dir / "vibe.sqlite"
run_migrations(db_path, revision="20260627_0025")
- backups_dir = state_dir / "backups"
- backups_dir.mkdir()
- from_the_future = _legacy_sqlite_backup(backups_dir, "vibe-pre-0026-repair-20990101T020000Z.sqlite")
-
- def _partially_commit_then_fail(*args, **kwargs):
- with sqlite3.connect(db_path) as conn:
- conn.execute("create table if not exists half_migrated (value text)")
- raise RuntimeError("upgrade failed after committing")
-
- monkeypatch.setattr("storage.migrations.command.upgrade", _partially_commit_then_fail)
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table payload (value text)")
+ conn.execute("insert into payload (value) values ('original')")
+ monkeypatch.setattr(
+ "storage.migrations.command.upgrade",
+ _fails_after_committing(db_path, "update payload set value = 'rewritten'"),
+ )
- for _ in range(SQLITE_BACKUP_RETENTION + 1):
+ for _ in range(SQLITE_BACKUP_RETENTION + 4):
with pytest.raises(RuntimeError, match="upgrade failed after committing"):
run_migrations(db_path)
- surviving = _sqlite_backup_roots(backups_dir)
- assert len(surviving) == SQLITE_BACKUP_RETENTION
- assert from_the_future.name not in surviving, "a future timestamp is not a claim on the window"
- assert any(
- not _table_exists(backups_dir / name / "vibe.sqlite", "half_migrated") for name in surviving
- ), "the snapshot from before the partial upgrade must keep its slot"
-
-
-def _attempt(
- db_path: Path,
- backups_dir: Path,
- *,
- hour: int,
- frm: tuple[str, ...] = ("20260806_0047",),
-) -> Path:
- """One migration attempt's backup, at a chosen wall-clock hour."""
-
- return create_sqlite_migration_backup(
- db_path,
- backups_dir=backups_dir,
- from_revisions=frm,
- to_revisions=("20260811_0051",),
- now=datetime(2026, 7, 10, hour, 0, tzinfo=timezone.utc),
- )
-
-
-def _database(path: Path) -> None:
- with sqlite3.connect(path) as conn:
- conn.execute("create table marker (value text)")
-
-
-def _write(path: Path, value: str) -> None:
- with sqlite3.connect(path) as conn:
- conn.execute("insert into marker (value) values (?)", (value,))
-
-
-def _rows(path: Path) -> list[str]:
- with sqlite3.connect(path) as conn:
- return sorted(row[0] for row in conn.execute("select value from marker"))
-
-
-def _partially_apply(path: Path) -> None:
- """The shape an upgrade leaves when it commits work and then raises.
-
- A table appears; the revision the database is stamped with does not move,
- because alembic never reached the stamp.
- """
-
- with sqlite3.connect(path) as conn:
- conn.execute("create table if not exists half_migrated (value text)")
+ surviving = _sqlite_backup_roots(state_dir / "backups")
+ assert len(surviving) == 1
+ with sqlite3.connect(state_dir / "backups" / surviving[0] / "vibe.sqlite") as backup:
+ assert [row[0] for row in backup.execute("select value from payload")] == ["original"]
-def test_the_copy_that_keeps_a_state_is_the_one_holding_its_writes(tmp_path: Path) -> None:
- # Two attempts at the same failing migration are copies of one state, so one
- # slot covers both -- and it has to be the copy carrying the writes made
- # since the other. A clock correction landing mid-storm stamps the later
- # attempt as the earlier of the two, so choosing by wall-clock time keeps the
- # copy that is missing everything written in between. Order comes from a
- # counter this module writes instead.
+def test_a_further_revision_reached_takes_its_own_rollback_point(tmp_path: Path) -> None:
+ # The other half of the same rule. When the database really has moved to a
+ # revision the window does not hold, that is a rollback point nothing else
+ # can provide, and it is taken -- so a healthy machine still gets a copy per
+ # migration, and an upgrade that commits some of its stamps before failing
+ # still gets one for each boundary it actually reached.
db_path = tmp_path / "vibe.sqlite"
- _database(db_path)
backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260806_0047")
- _write(db_path, "before")
- clean = _attempt(db_path, backups_dir, hour=1)
- _partially_apply(db_path)
- _attempt(db_path, backups_dir, hour=15)
- _write(db_path, "after")
- corrected = _attempt(db_path, backups_dir, hour=5)
+ first = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ again = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ assert again == first
- assert _sqlite_backup_roots(backups_dir) == sorted({clean.name, corrected.name})
- assert _rows(corrected / "vibe.sqlite") == ["after", "before"]
+ _stamp(db_path, "20260809_0049")
+ advanced = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ assert advanced != first
+ assert _sqlite_backup_roots(backups_dir) == sorted({first.name, advanced.name})
-def test_a_storm_of_identical_retries_holds_one_slot_between_them(tmp_path: Path) -> None:
- # Why the window survives a retry storm at all. Every attempt after the
- # first copies the same half-migrated database, so they are one state and
- # hold one slot between them however many there are -- which is what leaves
- # room for the snapshot taken before the damage, a state nothing else can
- # produce.
+def test_the_manifest_records_the_revisions_read_from_the_copy(tmp_path: Path) -> None:
+ # Callers sample the revisions before handing the work over, and another
+ # process can advance the database in between. A manifest describing
+ # something other than the copy it sits next to is worse than one that says
+ # nothing: the next attempt uses it to decide whether the rollback point it
+ # needs already exists.
db_path = tmp_path / "vibe.sqlite"
- _database(db_path)
backups_dir = tmp_path / "backups"
+ _stamp(db_path, "20260811_0050")
- clean = _attempt(db_path, backups_dir, hour=1)
- _partially_apply(db_path)
- for hour in range(2, 10):
- latest = _attempt(db_path, backups_dir, hour=hour)
+ backup_dir = create_sqlite_migration_backup(
+ db_path, backups_dir=backups_dir, to_revisions={"20260811_0051"}
+ )
- assert _sqlite_backup_roots(backups_dir) == sorted({clean.name, latest.name})
+ manifest = json.loads((backup_dir / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["from_revisions"] == ["20260811_0050"]
+ assert manifest["to_revisions"] == ["20260811_0051"]
-def test_restoring_a_rollback_point_makes_it_the_current_state_again(tmp_path: Path) -> None:
- # An operator restores the clean snapshot, the service comes back up on the
- # old schema and accepts writes, and the migration fails again. The restored
- # database is that clean state once more, so the snapshot taken after it is a
- # newer copy of the same state and supersedes the one restored from. That is
- # the whole point: it is the only copy that is both clean and holds the
- # writes made since the restore, and a rollback that landed on the original
- # would lose every one of them.
- db_path = tmp_path / "vibe.sqlite"
- _database(db_path)
- backups_dir = tmp_path / "backups"
-
- _write(db_path, "before")
- restored_from = _attempt(db_path, backups_dir, hour=1)
- _partially_apply(db_path)
- _attempt(db_path, backups_dir, hour=2)
+def test_the_window_directory_is_durable_before_the_backup_counts(monkeypatch, tmp_path: Path) -> None:
+ # Creating the backup directory also adds an entry to its parent. A crash
+ # that keeps the upgraded database but loses that entry leaves no rollback
+ # point at all, with every fsync this code makes having succeeded.
+ synced: list[Path] = []
+ monkeypatch.setattr(backups, "_fsync_directory", lambda path: synced.append(Path(path)))
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ db_path.parent.mkdir()
+ _stamp(db_path, "20260806_0047")
- shutil.copy(restored_from / "vibe.sqlite", db_path)
- _write(db_path, "after restore")
- restored = _attempt(db_path, backups_dir, hour=3)
- _partially_apply(db_path)
- latest = _attempt(db_path, backups_dir, hour=4)
+ create_sqlite_migration_backup(db_path)
- assert _sqlite_backup_roots(backups_dir) == sorted({restored.name, latest.name})
- assert _rows(restored / "vibe.sqlite") == ["after restore", "before"]
+ assert db_path.parent in synced
-def test_a_duplicated_sequence_cannot_take_a_state_out_of_the_window(
- monkeypatch, tmp_path: Path
-) -> None:
- # Sequence allocation reads the highest sequence on disk and adds one, and
- # two processes can do that at the same moment and both win -- `storage.
- # migrations` serializes upgrades with a lock that is process-local, so the
- # UI server and the controller can reach this at once. The collision leaves
- # ordering within a state falling back on the clock, and a process that
- # stalled between reserving its directory and copying can publish the
- # already-damaged database stamped earlier than the clean copy that beat it
- # there. Identifying a copy by what it is rather than by its place in a run
- # of attempts is what makes that harmless: the clean snapshot is a state of
- # its own, and no ordering accident can take its slot.
- monkeypatch.setattr(backups, "_next_sequence", lambda _root: 1)
- db_path = tmp_path / "vibe.sqlite"
- _database(db_path)
- backups_dir = tmp_path / "backups"
-
- clean = _attempt(db_path, backups_dir, hour=2)
- _partially_apply(db_path)
- _attempt(db_path, backups_dir, hour=1)
- latest = _attempt(db_path, backups_dir, hour=3)
-
- assert _sqlite_backup_roots(backups_dir) == sorted({clean.name, latest.name})
-
-
-def test_a_migration_that_moves_only_the_revision_is_a_new_rollback_point(tmp_path: Path) -> None:
- # Not every migration changes the schema. One that only moves data and
- # stamps the new revision leaves the DDL identical on both sides of it, and
- # the two copies are still different rollback points: restoring the wrong
- # one leaves the database at a revision whose migration has not run against
- # its data. So the revisions belong in the identity next to the fingerprint,
- # and neither half stands in for the other.
- #
- # Here the data-only migration settles and the next one starts failing. The
- # snapshot taken before the data moved is the only way back behind it, and
- # it has to outrank a second copy of the state the retries are stuck in.
+def test_a_fresh_rollback_point_outlives_copies_dated_after_it(tmp_path: Path) -> None:
+ # A clock corrected backwards, or state carried from a machine running
+ # ahead, leaves unrelated copies dated after everything the current
+ # migration produces -- permanently, since nothing rewrites their names.
+ # Ordering alone therefore cannot defend the copy a call has just made, so
+ # the call protects it explicitly.
db_path = tmp_path / "vibe.sqlite"
- _database(db_path)
backups_dir = tmp_path / "backups"
+ backups_dir.mkdir()
+ _stamp(db_path, "20260806_0047")
+ for index in range(SQLITE_BACKUP_RETENTION + 1):
+ _legacy_sqlite_backup(
+ backups_dir, f"vibe-pre-002{index}-repair-2099010{index + 1}T020000Z.sqlite"
+ )
- before = _attempt(db_path, backups_dir, hour=1, frm=("20260806_0047",))
- _attempt(db_path, backups_dir, hour=2, frm=("20260809_0049",))
- after = _attempt(db_path, backups_dir, hour=3, frm=("20260809_0049",))
+ fresh = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
- assert _sqlite_backup_roots(backups_dir) == sorted({before.name, after.name})
+ surviving = _sqlite_backup_roots(backups_dir)
+ assert len(surviving) == SQLITE_BACKUP_RETENTION
+ assert fresh.name in surviving
def test_new_backup_reaches_stable_storage_before_older_ones_are_deleted(monkeypatch, tmp_path: Path) -> None: