#!/usr/bin/env python3 """Reconcile legacy archives and a private SQLite history without writing to S3.""" from contextlib import ExitStack from pathlib import Path from subprocess import DEVNULL from tempfile import TemporaryDirectory from urllib.request import urlopen from uuid import uuid4 import gzip import json import sqlite3 from fixture import BIN, command, fixture_env, mysql_container, port, postgres, start_hub, wait_until def main(): with ExitStack() as cleanup: root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-legacy-"))) endpoint = f"http://127.0.0.1:{port()}" container = "tessera-legacy-" + uuid4().hex command("docker", "run", "--rm", "-d", "--name", container, "-p", f"{endpoint.removeprefix('http://')}:5000", "motoserver/moto:5.1.12", stdout=DEVNULL) cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL) def ready(): try: with urlopen(endpoint, timeout=1) as response: return response.status == 200 except OSError: return False wait_until(ready) env = {**fixture_env(), "AWS_ACCESS_KEY_ID": "fixture-legacy-key", "AWS_SECRET_ACCESS_KEY": "fixture-legacy-secret", "AWS_DEFAULT_REGION": "us-east-1", "AWS_EC2_METADATA_DISABLED": "true", "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key"} bucket = "legacy-fixture" aws = ("aws", "--endpoint-url", endpoint, "s3api") command(*aws, "create-bucket", "--bucket", bucket, env=env, stdout=DEVNULL) postgres_archive = gzip.compress(b"CREATE TABLE sample(value int);\nINSERT INTO sample VALUES (1);\n") mysql = gzip.compress(b"CREATE TABLE sample(value INT) ENGINE=InnoDB;\nINSERT INTO sample VALUES (2);\n") payloads = {"postgres": postgres_archive, "mysql": mysql} for engine, payload in payloads.items(): file = root / f"{engine}.sql.gz" file.write_bytes(payload) command(*aws, "put-object", "--bucket", bucket, "--key", f"{engine}/2026-11-10.sql.gz", "--body", file, env=env, stdout=DEVNULL) history = root / "history.sqlite" with sqlite3.connect(history) as db: db.executescript("CREATE TABLE jobs(id INTEGER PRIMARY KEY, phase TEXT); INSERT INTO jobs VALUES(42,'archived');") pg_root = root / "pg" pg_root.mkdir() pg, _ = postgres(cleanup, pg_root, ["legacy_fixture"]) mysql_client, _, _ = mysql_container(cleanup, root) api, _, _, _ = start_hub(cleanup, root) cli = (BIN / "tessera", "--data-dir", root / "hub") for engine, payload in payloads.items(): orbit = api("orbits", {"name": engine, "provider": "wormhole", "provider_config": {}}) args = (*cli, "legacy-import", "--bucket", bucket, "--prefix", engine + "/", "--endpoint", endpoint, "--orbit-id", orbit["id"], "--application", engine, "--engine", engine, "--history", history) def report(*extra): result = command(*args, *extra, env=env, capture_output=True) return json.loads(result.stdout) inventory = report("--inventory-only") assert inventory["count"] == 1 and inventory["bytes"] == len(payload) assert inventory["objects"][0]["status"] == "inventoried" imported = report() snapshot = imported["objects"][0]["snapshot_id"] assert imported["objects"][0]["status"] == "imported" restored = api(f"snapshots/{snapshot}/download", raw=True) assert restored == payload if engine == "postgres": command("psql", *pg, "-d", "legacy_fixture", "-v", "ON_ERROR_STOP=1", input=gzip.decompress(restored), stdout=DEVNULL) value = command("psql", *pg, "-d", "legacy_fixture", "-Atc", "SELECT value FROM sample", text=True, capture_output=True) assert value.stdout.strip() == "1" else: command(*mysql_client, "-D", "fixture", input=gzip.decompress(restored), stdout=DEVNULL) value = command(*mysql_client, "-D", "fixture", "-NB", "-e", "SELECT value FROM sample", text=True, capture_output=True) assert value.stdout.strip() == "2" visible = next(entry for entry in api("snapshots") if entry["id"] == snapshot) assert visible["size_bytes"] == len(payload) assert visible["taken_at"] == imported["objects"][0]["last_modified"] repeated = report() assert repeated["objects"][0]["snapshot_id"] == snapshot assert repeated["objects"][0]["status"] == "already_imported" history_id = imported["history_snapshot_id"] api(f"snapshots/{history_id}/download", expected=404) exported = root / f"{engine}-history.sqlite" command(*cli, "legacy-history", history_id, exported, env=env, stdout=DEVNULL) with sqlite3.connect(exported.as_uri() + "?mode=ro", uri=True) as db: assert db.execute("SELECT phase FROM jobs WHERE id=42").fetchone()[0] == "archived" api(f"snapshots/{snapshot}", expected=204, method="DELETE") command(*cli, "gc", env=env, stdout=DEVNULL) assert report()["objects"][0]["status"] == "already_imported" api(f"snapshots/{snapshot}/download", expected=404) original = command(*aws, "head-object", "--bucket", bucket, "--key", f"{engine}/2026-11-10.sql.gz", env=env, capture_output=True) assert json.loads(original.stdout)["ContentLength"] == len(payload) assert api("snapshots") == [] print("Read-only PostgreSQL/MySQL archive reconciliation, idempotency after GC, and private history verified") if __name__ == "__main__": main()