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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(storage): identify a rollback point by the state of the copy
cyhaab1038b2420
diff --git a/docs/plans/local-data-lifecycle.md b/docs/plans/local-data-lifecycle.mdindex 89393b82c..1424146b7 100644--- a/docs/plans/local-data-lifecycle.md+++ b/docs/plans/local-data-lifecycle.md@@ -21,9 +21,22 @@ downloads, sources, prebuilt assets, or version directories.10 MiB, retaining the newest 5 MiB. This preserves the inode used by live tailreaders 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. Retain the newest two SQLite- migration/repair rollback points and the newest three legacy JSON migration- snapshots.+ 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.+- 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.- Prune only strict Avibe formats: self-identifying managed backup directories,historical `sqlite-state-migration-*` directories with valid manifests, andthe exact legacy `vibe-pre-<revision>[-release-head]-repair-<timestamp>` filediff --git a/storage/backups.py b/storage/backups.pyindex 678cde8e0..bf707a994 100644--- a/storage/backups.py+++ b/storage/backups.py@@ -1,6 +1,7 @@from __future__ import annotationsimport errno+import hashlibimport jsonimport loggingimport os@@ -30,9 +31,10 @@ _LEGACY_SQLITE_REPAIR_RE = re.compile(r"(?P<timestamp>\d{8}T\d{6}Z)\.sqlite$")-# Where the schema stood when a backup was taken, and where it was headed:-# (from_revisions, to_revisions).-_Revisions = tuple[tuple[str, ...], tuple[str, ...]]+# 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,@@ -52,7 +54,7 @@ class _BackupCandidate:timestamp: datetimesuffix: intsequence: int | None = None- revisions: _Revisions | None = None+ state: _State | None = None@propertydef order_key(self) -> tuple[bool, int, datetime, int, str]:@@ -62,8 +64,8 @@ class _BackupCandidate:previous writes, so it is the one ordering input nothing outside theprocess can move. Wall-clock time can: an NTP correction, a manualchange, or state carried from a machine running ahead all reorder- timestamps after the fact, and a backup that lands out of order stops- being identifiable as the first attempt.+ 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 sortbelow every backup that has one -- which is simply true, since the@@ -143,7 +145,7 @@ def _directory_candidate(path: Path) -> _BackupCandidate | None:timestamp=timestamp,suffix=int(match.group("suffix") or 0),sequence=_manifest_sequence(manifest),- revisions=_manifest_revisions(manifest),+ state=_manifest_state(manifest),)@@ -152,21 +154,23 @@ def _manifest_sequence(manifest: dict) -> int | None:return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None-def _manifest_revisions(manifest: dict) -> _Revisions | None:- """Where the schema stood and where it was headed, when the manifest says.+def _manifest_state(manifest: dict) -> _State | None:+ """What the database was, as the manifest recorded it.- Manifests written before these fields existed simply have none, and a backup- with none cannot be linked to its neighbours at all.+ 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."""- from_revisions = manifest.get("from_revisions")- to_revisions = manifest.get("to_revisions")- if not isinstance(from_revisions, list) or not isinstance(to_revisions, list):+ revisions = manifest.get("from_revisions")+ digest = manifest.get("schema_digest")+ if not isinstance(revisions, list) or not isinstance(digest, str) or not digest:return None- return (- tuple(sorted(str(revision) for revision in from_revisions)),- tuple(sorted(str(revision) for revision in to_revisions)),- )+ return tuple(sorted(str(revision) for revision in revisions)), digestdef _legacy_sqlite_candidate(path: Path) -> _BackupCandidate | None:@@ -222,77 +226,48 @@ def _remove_candidate(candidate: _BackupCandidate) -> bool:return True-def _continues(previous: _BackupCandidate, current: _BackupCandidate) -> bool:- """Whether `current` is another attempt at the migration `previous` was for.-- Each manifest records where the schema stood when its backup was taken and- where that run was headed. Put two consecutive ones side by side and they- answer the only question that matters: had the earlier run finished? If it- had, the database would have been sitting at its destination when the next- backup was taken. It was not, so the earlier run is still unfinished and- these two are attempts at one rollback point.-- Deriving the answer from the pair, rather than reading an identity off- either one alone, is what makes it hold while a failing upgrade moves the- ground under it. `command.upgrade` walks several revisions, and entering an- `autocommit_block` commits the version stamps it has already earned -- so a- run that dies inside a later revision leaves the next attempt starting- somewhere new. An identity built from the starting point splits one episode- in two and throws away its clean first snapshot; an identity built from the- destination survives that but not a release upgrade arriving mid-episode,- which moves the destination instead. The comparison survives both, because- it never asks either backup to name the episode it belongs to.-- A backup with no recorded revisions cannot be linked either way, so it- begins an episode of its own.- """-- if previous.revisions is None or current.revisions is None:- return False- return current.revisions[0] != previous.revisions[1]---def _episodes(candidates: Iterable[_BackupCandidate]) -> list[list[_BackupCandidate]]:- """Split backups into runs of attempts at the same rollback point, oldest first."""-- episodes: list[list[_BackupCandidate]] = []- for candidate in sorted(candidates, key=lambda item: item.order_key):- if episodes and _continues(episodes[-1][-1], candidate):- episodes[-1].append(candidate)- else:- episodes.append([candidate])- return episodes--def _keep_priority(candidates: Iterable[_BackupCandidate]) -> list[_BackupCandidate]:"""Order backups by how much a rollback would want them, best first.- Retries of one unfinished migration are attempts at a single rollback point- rather than one rollback point each, and the two worth keeping are the ends.- The first predates any partially applied schema change -- an upgrade can- commit part of its work before raising, after which every later copy is of- the half-migrated database. The last carries every write made since. Copies- in between are worse than both on both counts, which is exactly why plain- newest-first is the wrong order here: it fills the window with the newest- two attempts and discards the only clean one.-- The episode holding the newest backup comes first, which is also how the- backup being taken right now keeps its slot: it is created with the highest- sequence there is, so its episode leads by construction rather than by a- second rule saying so.-- On a healthy machine every migration finishes, so each backup is an episode- by itself and this is the familiar newest-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."""- ranked: list[_BackupCandidate] = []+ best: dict[object, _BackupCandidate] = {}superseded: list[_BackupCandidate] = []- for members in sorted(_episodes(candidates), key=lambda group: group[-1].order_key, reverse=True):- ranked.append(members[-1])- if len(members) > 1:- ranked.append(members[0])- superseded.extend(members[1:-1])- return ranked + superseded+ 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()) + supersededdef prune_state_backups(@@ -383,6 +358,30 @@ def _next_sequence(backups_dir: Path) -> int:) + 1+def _schema_digest(connection: sqlite3.Connection) -> str:+ """Fingerprint the schema of the database behind `connection`.++ 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.+ """++ 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()++def _unique_backup_dir(backups_dir: Path, *, now: datetime) -> Path:timestamp = now.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")suffixes = [@@ -422,6 +421,10 @@ def create_sqlite_migration_backup(it just produced, so it never does: the copy reaches stable storage beforeany older one is deleted, and it is stamped with the next sequence, whichputs 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."""source_path = db_path.expanduser().resolve()@@ -443,6 +446,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)os.chmod(temp_db, 0o600)_fsync_file(temp_db)temp_db.replace(backup_db)@@ -453,6 +457,7 @@ def create_sqlite_migration_backup("created_at": created_at.astimezone(timezone.utc).isoformat(),"database": "vibe.sqlite","sequence": sequence,+ "schema_digest": schema_digest,"from_revisions": sorted(set(from_revisions)),"to_revisions": sorted(set(to_revisions)),}@@ -473,7 +478,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 that- # puts it at the head of the episode in progress.+ # 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)return backup_dirdiff --git a/tests/test_state_backups.py b/tests/test_state_backups.pyindex 3fa4db706..0850f8b1c 100644--- a/tests/test_state_backups.py+++ b/tests/test_state_backups.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport errnoimport json+import shutilimport sqlite3from datetime import datetime, timezonefrom pathlib import Path@@ -333,8 +334,7 @@ def _attempt(backups_dir: Path,*,hour: int,- frm: tuple[str, ...],- to: tuple[str, ...] = ("20260811_0051",),+ frm: tuple[str, ...] = ("20260806_0047",),) -> Path:"""One migration attempt's backup, at a chosen wall-clock hour."""@@ -342,66 +342,150 @@ def _attempt(db_path,backups_dir=backups_dir,from_revisions=frm,- to_revisions=to,+ to_revisions=("20260811_0051",),now=datetime(2026, 7, 10, hour, 0, tzinfo=timezone.utc),)-def test_attempt_order_survives_a_clock_that_moves_backwards(tmp_path: Path) -> None:- # A clock correction lands in the middle of a retry storm: the first attempt- # is stamped 10:00, the correction drags the next to 05:00, and the third- # comes back at 15:00. Sorted by wall-clock time the ends of the episode are- # 05:00 and 15:00 -- both taken after the upgrade began committing -- and the- # clean 10:00 snapshot is treated as a superseded middle and deleted. Order- # has to come from a counter this module writes, not from the clock.- db_path = tmp_path / "vibe.sqlite"- with sqlite3.connect(db_path) as conn:+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)")+++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.+ db_path = tmp_path / "vibe.sqlite"+ _database(db_path)+ backups_dir = tmp_path / "backups"++ _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)++ assert _sqlite_backup_roots(backups_dir) == sorted({clean.name, corrected.name})+ assert _rows(corrected / "vibe.sqlite") == ["after", "before"]+++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.+ db_path = tmp_path / "vibe.sqlite"+ _database(db_path)backups_dir = tmp_path / "backups"- clean = _attempt(db_path, backups_dir, hour=10, frm=("20260806_0047",))- _attempt(db_path, backups_dir, hour=5, frm=("20260809_0049",))- latest = _attempt(db_path, backups_dir, hour=15, frm=("20260809_0049",))+ 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)assert _sqlite_backup_roots(backups_dir) == sorted({clean.name, latest.name})-def test_one_episode_survives_an_upgrade_that_commits_revisions_before_failing(tmp_path: Path) -> None:- # `command.upgrade` walks several revisions in one call, and entering an- # autocommit block commits the version stamps already earned. A run that- # starts at 0047 can therefore reach 0049 and die inside 0050, leaving the- # next attempt starting from 0049 instead. Identifying the episode by where- # its attempts started splits it in two and lets the newer, already-damaged- # half take the whole window; what actually holds is that no attempt ever- # reached where it was headed.+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"- with sqlite3.connect(db_path) as conn:- conn.execute("create table marker (value text)")+ _database(db_path)backups_dir = tmp_path / "backups"- pristine = _attempt(db_path, backups_dir, hour=1, frm=("20260806_0047",))- _attempt(db_path, backups_dir, hour=2, frm=("20260809_0049",))- latest = _attempt(db_path, backups_dir, hour=3, frm=("20260809_0049",))+ _write(db_path, "before")+ restored_from = _attempt(db_path, backups_dir, hour=1)+ _partially_apply(db_path)+ _attempt(db_path, backups_dir, hour=2)++ 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)++ assert _sqlite_backup_roots(backups_dir) == sorted({restored.name, latest.name})+ assert _rows(restored / "vibe.sqlite") == ["after restore", "before"]+++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"- assert _sqlite_backup_roots(backups_dir) == sorted({pristine.name, latest.name})+ 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_finished_migration_ends_the_episode(tmp_path: Path) -> None:- # The other side of the same comparison: when a run does reach its- # destination, the next backup starts from there, and that is what marks the- # boundary. Two settled migrations are two rollback points rather than one- # episode with ends, so the window is the newest two -- never an ancient- # snapshot held open by an episode that closed long ago.+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.db_path = tmp_path / "vibe.sqlite"- with sqlite3.connect(db_path) as conn:- conn.execute("create table marker (value text)")+ _database(db_path)backups_dir = tmp_path / "backups"- _attempt(db_path, backups_dir, hour=1, frm=("20260806_0047",), to=("20260809_0049",))- second = _attempt(db_path, backups_dir, hour=2, frm=("20260809_0049",), to=("20260811_0050",))- third = _attempt(db_path, backups_dir, hour=3, frm=("20260811_0050",), to=("20260811_0051",))+ 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",))- assert _sqlite_backup_roots(backups_dir) == sorted({second.name, third.name})+ assert _sqlite_backup_roots(backups_dir) == sorted({before.name, after.name})def test_new_backup_reaches_stable_storage_before_older_ones_are_deleted(monkeypatch, tmp_path: Path) -> None: