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): bound migration tightening safety checks (#1740)

Call White3fb0fd290137
diff --git a/scripts/migration_release_guard.py b/scripts/migration_release_guard.py
index 31565dd49..e77185ebb 100644
--- a/scripts/migration_release_guard.py
+++ b/scripts/migration_release_guard.py
@@ -7,7 +7,7 @@ never back. So editing a released revision's parentage does not change what thos
databases have already done -- it changes what they will do next, silently, with no error
at the moment of the edit and no error at the moment of the upgrade.
-Seven properties, one primitive: the graph as a released tag actually shipped it, read
+Eight properties, one primitive: the graph as a released tag actually shipped it, read
straight out of git. Nothing here is an allowlist of known-bad cases that outlives its
reason, and nothing needs an old Python environment -- ``env.py`` reads
``target_metadata`` only during autogenerate, so today's runtime can drive an older
@@ -27,6 +27,8 @@ reason, and nothing needs an old Python environment -- ``env.py`` reads
upgrades it
releases_with_state_but_no every release that wrote a database is inside the
_graph() window the property above walks
+ migration_safety_problems() each post-latest-release revision has one finite, explicit
+ migration-safety attestation
Readiness is not this module's opinion. ``unrepairable_releases`` drives
``run_migrations`` and asks ``background_tables_ready``, so it covers the repair and
@@ -338,6 +340,11 @@ GRAPH_FIELDS = {
GRAPH_EDGES = tuple(field for field in GRAPH_FIELDS if field != "revision")
+# The guard deliberately does not infer a data-safety obligation from Python or SQL. Every
+# new migration owns one explicit attestation, and only this finite vocabulary is accepted.
+MIGRATION_SAFETY_FIELD = "MIGRATION_SAFETY"
+MIGRATION_SAFETY_KINDS = frozenset({"additive", "deduplicate", "backfill", "copy"})
+
def declared_graph_fields(source: str) -> dict[str, object]:
"""The graph declarations a migration module makes, in either form Python allows.
@@ -369,6 +376,33 @@ def declared_graph_fields(source: str) -> dict[str, object]:
return declared
+def declared_migration_safety(source: str) -> str | _ComputedMetadata | None:
+ """Read exactly one top-level string literal without evaluating migration code."""
+ values: list[object] = []
+ try:
+ nodes = ast.parse(source).body
+ except SyntaxError:
+ return COMPUTED
+ for node in nodes:
+ if isinstance(node, ast.Assign) and len(node.targets) == 1:
+ target, value = node.targets[0], node.value
+ elif isinstance(node, ast.AnnAssign) and node.value is not None:
+ target, value = node.target, node.value
+ else:
+ continue
+ if isinstance(target, ast.Name) and target.id == MIGRATION_SAFETY_FIELD:
+ try:
+ values.append(ast.literal_eval(value))
+ except (ValueError, TypeError, SyntaxError):
+ return COMPUTED
+ if not values:
+ return None
+ if len(values) != 1:
+ return COMPUTED
+ literal = values[0]
+ return literal if isinstance(literal, str) else COMPUTED
+
+
def revision_claims(sources: dict[str, str]) -> dict[str, list[tuple[str, dict[str, object]]]]:
"""Every claim on every revision identifier, contested ones included.
@@ -668,6 +702,47 @@ def table_names(db_path: Path) -> set[str]:
connection.close()
+def _migration_safety_declaration_error(
+ revision: str, declaration: str | _ComputedMetadata | None
+) -> str | None:
+ if declaration is None:
+ return f"{revision} has no MIGRATION_SAFETY declaration"
+ if declaration is COMPUTED:
+ return f"{revision} MIGRATION_SAFETY is computed or malformed; only one literal string is supported"
+ if not isinstance(declaration, str):
+ return f"{revision} MIGRATION_SAFETY is malformed; only one literal string is supported"
+ if declaration not in MIGRATION_SAFETY_KINDS:
+ return f"{revision} MIGRATION_SAFETY contains unsupported kind: {declaration}"
+ return None
+
+
+def migration_safety_problems() -> list[str]:
+ """Require one explicit attestation for every revision after the latest release.
+
+ This is deliberately a metadata-only gate. ``unrepairable_releases`` owns real upgrade
+ execution and readiness evidence; duplicating that executor here would make the
+ attestation boundary both slow and a second source of migration behavior.
+ """
+ latest_release = latest_released_tag()
+ baseline_graph = revision_graph(released_sources(latest_release))
+ current_sources = working_tree_sources()
+ current_graph = revision_graph(current_sources)
+ new_revisions = set(current_graph) - set(baseline_graph)
+ if not new_revisions:
+ return []
+
+ problems = [
+ error
+ for revision in sorted(new_revisions)
+ if (error := _migration_safety_declaration_error(
+ revision,
+ declared_migration_safety(current_sources[current_graph[revision][0]]),
+ ))
+ ]
+
+ return problems
+
+
def fresh_install_tables() -> set[str]:
"""The tables a fresh install actually has, built the way production builds one."""
with tempfile.TemporaryDirectory() as workspace:
@@ -1508,6 +1583,8 @@ def collect_problems(
problems.extend(edited_released_bodies(baseline))
problems.extend(spent_body_edit_declarations(baseline))
+ problems.extend(migration_safety_problems())
+
if include_upgrade:
failures, refused = unrepairable_releases()
for tag, reasons in sorted(failures.items(), key=lambda item: version_key(item[0])):
@@ -1525,7 +1602,7 @@ def _build_parser() -> argparse.ArgumentParser:
parser.add_argument(
"--skip-upgrade",
action="store_true",
- help="check only the metadata properties, skipping the per-release upgrade",
+ help="skip per-release upgrade evidence while retaining metadata and attestation checks",
)
return parser
diff --git a/tests/test_migration_release_guard.py b/tests/test_migration_release_guard.py
index 1ddd098ce..2f4343719 100644
--- a/tests/test_migration_release_guard.py
+++ b/tests/test_migration_release_guard.py
@@ -1,10 +1,10 @@
-"""Cover the migration release guard's detection and the properties it asserts.
+"""Cover the migration release guard's graph and attestation properties.
-Two layers. The synthetic tests pin the detection itself, so the guard cannot decay into
-something that passes because it stopped looking. The repository tests are the guard
-running for real: three of them state the invariant the working tree must hold, and one
-runs the guard against the release that preceded the v3.0.11 splice, which is the known
-positive that keeps the other three honest.
+The synthetic tests pin the detection itself, so the guard cannot decay into something
+that passes because it stopped looking. The repository tests run the guard for real and
+exercise the release-history invariants it owns. Migration safety is intentionally an
+explicit, finite attestation contract; these tests do not infer data guarantees from
+Python or SQL source.
Anything reading release history needs tags, which a shallow CI checkout does not have.
Those tests skip there and the ``migration-release-guard`` workflow runs the same
@@ -536,6 +536,137 @@ def test_the_command_line_refuses_rather_than_passing_without_history(monkeypatc
assert "could not run" in capsys.readouterr().err
+ ("source", "expected"),
+ [
+ ('MIGRATION_SAFETY = "copy"\n', "copy"),
+ ('MIGRATION_SAFETY: str = "additive"\n', "additive"),
+ ('MIGRATION_SAFETY = ("copy",)\n', guard.COMPUTED),
+ ('MIGRATION_SAFETY = ["copy"]\n', guard.COMPUTED),
+ ('MIGRATION_SAFETY = make_safety()\n', guard.COMPUTED),
+ ('MIGRATION_SAFETY = "copy"\nMIGRATION_SAFETY = "backfill"\n', guard.COMPUTED),
+ ('if enabled:\n MIGRATION_SAFETY = "copy"\n', None),
+ ("", None),
+ ],
+ ids=["string", "annotated-string", "tuple", "list", "computed", "duplicate", "nested", "absent"],
+)
+def test_migration_safety_declaration_is_one_top_level_literal(source, expected):
+ """The declaration reader never executes migration code or evaluates SQL."""
+ actual = guard.declared_migration_safety(source)
+ if expected is guard.COMPUTED:
+ assert actual is guard.COMPUTED
+ else:
+ assert actual == expected
+
+
[email protected]("kind", sorted(guard.MIGRATION_SAFETY_KINDS))
+def test_each_safety_kind_is_an_accepted_attestation(kind):
+ assert guard._migration_safety_declaration_error("r", kind) is None
+
+
+ ("declaration", "expected_fragment"),
+ [
+ (None, "no MIGRATION_SAFETY"),
+ (guard.COMPUTED, "computed or malformed"),
+ ("future", "unsupported kind"),
+ ("copy", None),
+ ],
+ ids=["missing", "computed", "unsupported", "accepted"],
+)
+def test_safety_attestation_shape_fails_closed(declaration, expected_fragment):
+ error = guard._migration_safety_declaration_error("r", declaration)
+ if expected_fragment is None:
+ assert error is None
+ else:
+ assert expected_fragment in error
+
+
+def test_attestation_is_metadata_only_and_does_not_execute_alembic(monkeypatch):
+ """The graph supplies every subject without a second migration executor."""
+ revision = "20260105_0005"
+ shipped = dict(SHIPPED_GRAPH)
+ current = dict(shipped)
+ current[f"{revision}_new.py"] = _revision_file(revision, '"20260104_0004"') + 'MIGRATION_SAFETY = "additive"\n'
+ _graphs(monkeypatch, shipped, current)
+ monkeypatch.setattr(guard, "latest_released_tag", lambda: "v0.0.0")
+ monkeypatch.setattr(guard, "released_graphs", lambda: pytest.fail("attestation must not enumerate upgrade graphs"))
+ monkeypatch.setattr(guard.command, "upgrade", lambda *args, **kwargs: pytest.fail("attestation must not execute Alembic"))
+
+ assert guard.migration_safety_problems() == []
+
+
+def test_attestation_boundary_uses_latest_release_not_comparison_baseline(monkeypatch):
+ """An older metadata comparison cannot re-enroll revisions already released later."""
+ released_revision = "20260105_0005"
+ latest = dict(SHIPPED_GRAPH)
+ latest[f"{released_revision}_released.py"] = _revision_file(released_revision, '"20260104_0004"')
+ current = dict(latest)
+ monkeypatch.setattr(guard, "latest_released_tag", lambda: "v0.0.1")
+ monkeypatch.setattr(guard, "released_sources", lambda tag: SHIPPED_GRAPH if tag == "v0.0.0" else latest)
+ monkeypatch.setattr(guard, "working_tree_sources", lambda: current)
+ monkeypatch.setattr(guard, "releases_with_state_but_no_graph", lambda: [])
+ monkeypatch.setattr(guard, "fresh_install_tables", lambda: guard.HEAD_TABLES)
+ monkeypatch.setattr(guard, "new_slot_collisions", lambda baseline: {})
+ monkeypatch.setattr(guard, "rechained_revisions", lambda baseline: [])
+ monkeypatch.setattr(guard, "edited_released_bodies", lambda baseline: [])
+ monkeypatch.setattr(guard, "spent_body_edit_declarations", lambda baseline: [])
+ monkeypatch.setattr(guard, "unrepairable_releases", lambda: pytest.fail("--skip-upgrade must skip runtime upgrades"))
+
+ _, problems, refused = guard.collect_problems("v0.0.0", include_upgrade=False)
+
+ assert problems == []
+ assert refused == {}
+
+
+def test_only_revisions_after_latest_release_require_attestation(monkeypatch):
+ """A missing declaration is reported for a new revision, never for grandfathered history."""
+ released_revision = "20260105_0005"
+ new_revision = "20260106_0006"
+ latest = dict(SHIPPED_GRAPH)
+ latest[f"{released_revision}_released.py"] = _revision_file(released_revision, '"20260104_0004"')
+ current = dict(latest)
+ current[f"{new_revision}_new.py"] = _revision_file(new_revision, f'"{released_revision}"')
+ monkeypatch.setattr(guard, "latest_released_tag", lambda: "v0.0.1")
+ monkeypatch.setattr(guard, "released_sources", lambda tag: latest)
+ monkeypatch.setattr(guard, "working_tree_sources", lambda: current)
+
+ problems = guard.migration_safety_problems()
+
+ assert problems == [f"{new_revision} has no MIGRATION_SAFETY declaration"]
+
+
+ ("declaration", "expected_fragment"),
+ [
+ ("", "no MIGRATION_SAFETY"),
+ ('MIGRATION_SAFETY = "additive"\n', None),
+ ('MIGRATION_SAFETY = "future"\n', "unsupported kind"),
+ ('MIGRATION_SAFETY = ("copy",)\n', "computed or malformed"),
+ ],
+ ids=["missing", "accepted", "unknown", "non-string"],
+)
+def test_new_revision_requires_exact_attestation(monkeypatch, declaration, expected_fragment):
+ revision = "20260105_0005"
+ shipped = dict(SHIPPED_GRAPH)
+ current = dict(shipped)
+ current[f"{revision}_new.py"] = _revision_file(revision, '"20260104_0004"') + declaration
+ _graphs(monkeypatch, shipped, current)
+ monkeypatch.setattr(guard, "latest_released_tag", lambda: "v0.0.0")
+
+ problems = guard.migration_safety_problems()
+ if expected_fragment is None:
+ assert problems == []
+ else:
+ assert any(expected_fragment in problem and revision in problem for problem in problems)
+
+
+@requires_release_history
+def test_real_release_baseline_has_no_new_migration_safety_obligations():
+ """A current graph with no post-release revisions needs no new attestation run."""
+ assert guard.migration_safety_problems() == []
+
+
def test_head_tables_is_what_a_fresh_install_has():
"""The derivation source for the upgrade property must itself be measured, not maintained.