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): make the rollback point unconditional again

cyh29b654645dba
diff --git a/docs/plans/local-data-lifecycle.md b/docs/plans/local-data-lifecycle.md
index b1089e999..b51b1d606 100644
--- a/docs/plans/local-data-lifecycle.md
+++ b/docs/plans/local-data-lifecycle.md
@@ -25,25 +25,29 @@ downloads, sources, prebuilt assets, or version directories.
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.
+- Take the copy unconditionally, and never reuse one already in the window. A
+ copy is a rollback point only if restoring it loses no committed data, and
+ nothing readable from a copy proves that: a migration that commits row
+ changes and then fails moves neither the schema nor the revision stamp, and
+ an operator who restores a copy and keeps serving writes moves the contents
+ under a stamp that never changed. Every rule that recognised a copy as "the
+ same rollback point" was a label standing in for the contents, and each one
+ could be made to agree while the contents differed.
- Bound the window to the newest two SQLite migration/repair rollback points
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.
+- The window bounds disk, and that is all it promises beyond holding the
+ database as it stands at each call. It cannot also promise to keep the last
+ copy taken before a migration started damaging the database: under a
+ migration that keeps failing, the attempts after the first copy an
+ already-damaged database, and no property measurable from those copies
+ distinguishes them from the clean one. That property belongs to not retrying
+ a failed migration once per service entry point, not to retention.
- 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.
+ an operator choosing a rollback point reads the manifest to do it.
- 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 e2688de34..6576132b1 100644
--- a/storage/backups.py
+++ b/storage/backups.py
@@ -47,7 +47,6 @@ class _BackupCandidate:
kind: str
timestamp: datetime
suffix: int
- revisions: tuple[str, ...] | None = None
@property
def order_key(self) -> tuple[datetime, int, str]:
@@ -124,25 +123,9 @@ def _directory_candidate(path: Path) -> _BackupCandidate | None:
kind=kind,
timestamp=timestamp,
suffix=int(match.group("suffix") or 0),
- revisions=_manifest_revisions(manifest),
)
-def _manifest_revisions(manifest: dict) -> tuple[str, ...] | None:
- """The revisions the backup's own copy of the database was stamped with.
-
- 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.
- """
-
- value = manifest.get("from_revisions")
- if not isinstance(value, list):
- return None
- return tuple(sorted(str(revision) for revision in value))
-
-
def _legacy_sqlite_candidate(path: Path) -> _BackupCandidate | None:
if path.is_symlink() or not path.is_file():
return None
@@ -280,8 +263,8 @@ def _stamped_revisions(connection: sqlite3.Connection) -> tuple[str, ...]:
"""The alembic revisions the database behind `connection` is stamped with.
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.
+ what an unversioned database is. This is recorded, never compared: a stamp
+ names where a database claims to be, not what it holds.
"""
try:
@@ -291,15 +274,6 @@ def _stamped_revisions(connection: sqlite3.Connection) -> tuple[str, ...]:
return tuple(sorted({str(row[0]) for row in rows}))
-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."""
-
- 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:
timestamp = now.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
suffixes = [
@@ -334,24 +308,23 @@ def create_sqlite_migration_backup(
the bound true for callers not yet written, including the ones that opt out
of their own pruning.
- 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 copy is unconditional, and the window promises exactly one thing: a
+ restorable copy of the database as it stands at this call. Nothing here
+ tries to recognize a copy it already holds and reuse it. Earlier revisions
+ of this change did, by ranking the copies on wall-clock adjacency, then on
+ the schema transition each attempt recorded, then on a fingerprint of each
+ copy's schema, and finally by skipping the copy when a backup carried the
+ same revision stamp -- and every one of those is a label standing in for the
+ database's contents. Labels can be made to agree while the contents differ:
+ a migration that commits row changes and then fails moves neither schema nor
+ stamp, and an operator who restores a copy and keeps serving writes moves
+ the contents under a stamp that never changed. Reusing a copy on any of
+ those grounds hands back a rollback point missing committed data, which is
+ worse than having none, because it is reported as one.
+
+ The copy 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
@@ -368,11 +341,6 @@ def create_sqlite_migration_backup(
# 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"
@@ -415,8 +383,7 @@ def create_sqlite_migration_backup(
# cleanup above runs and nothing is pruned at all. Being after the try means
# 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 be findable as the
- # rollback point that lets the next attempt skip its copy.
+ # because a directory without one is not yet a recognized candidate and
+ # would not count itself against the bound.
prune_state_backups(target_root, json_retention=None, protect=backup_dir)
return backup_dir
diff --git a/tests/test_state_backups.py b/tests/test_state_backups.py
index aabb37a27..1332ce29d 100644
--- a/tests/test_state_backups.py
+++ b/tests/test_state_backups.py
@@ -279,86 +279,66 @@ def test_repeated_migration_failures_keep_the_rollback_window_bounded(monkeypatc
assert backup.execute("PRAGMA quick_check").fetchone() == ("ok",)
-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)"),
- )
-
- 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) == 1
- assert not _table_exists(state_dir / "backups" / surviving[0] / "vibe.sqlite", "half_migrated")
-
-
-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")
+def _db_contents(path: Path) -> list[tuple[str, list[tuple]]]:
+ with sqlite3.connect(path) as conn:
+ tables = [
+ row[0]
+ for row in conn.execute("select name from sqlite_master where type = 'table' order by name")
+ ]
+ return [(table, conn.execute(f'select * from "{table}"').fetchall()) for table in tables]
+
+
+def test_every_call_holds_the_database_as_it_stands_at_that_call(tmp_path: Path) -> None:
+ # The one promise the window makes, stated as a property over however the
+ # database moves rather than as a list of the ways it can. That distinction
+ # is the whole history of this change: earlier revisions tried to recognise a
+ # copy already held and reuse it, ranking copies by wall-clock adjacency,
+ # then by the schema transition each attempt recorded, then by a fingerprint
+ # of each copy's schema, then by the revision stamp -- and each rule was
+ # defeated by a movement that leaves every label a backup can compare exactly
+ # as it was. Two of them are exercised below: a migration that commits rows
+ # without touching schema or stamp, and an operator restoring a copy and then
+ # serving writes under a stamp that never moved.
+ 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 ('original')")
- monkeypatch.setattr(
- "storage.migrations.command.upgrade",
- _fails_after_committing(db_path, "update payload set value = 'rewritten'"),
- )
- 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) == 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"]
+ taken: list[Path] = []
+ def rollback_point() -> Path:
+ backup = create_sqlite_migration_backup(db_path, backups_dir=backups_dir)
+ assert _db_contents(backup / "vibe.sqlite") == _db_contents(db_path)
+ taken.append(backup)
+ return backup
-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"
- backups_dir = tmp_path / "backups"
- _stamp(db_path, "20260806_0047")
-
- 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
+ def write(statement: str) -> None:
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(statement)
+ first = rollback_point()
+ write("update payload set value = 'rewritten'")
+ rollback_point()
+ shutil.copy(first / "vibe.sqlite", db_path)
+ write("insert into payload (value) values ('accepted after the restore')")
+ rollback_point()
+ write("create table added (value text)")
+ rollback_point()
_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})
+ rollback_point()
+
+ assert len(set(taken)) == len(taken)
+ assert len(_sqlite_backup_roots(backups_dir)) == SQLITE_BACKUP_RETENTION
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.
+ # nothing: an operator reading it to choose a rollback point is told the copy
+ # holds a schema it may never have held.
db_path = tmp_path / "vibe.sqlite"
backups_dir = tmp_path / "backups"
_stamp(db_path, "20260811_0050")