From 0c27a8f343694e104de1c2d9f466ad8a95f73770 Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Thu, 10 Sep 2026 15:39:06 -0700 Subject: [PATCH] Check v2 archives against the contract before a reader can MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mobile now builds its version 2 writer before the reader that consumes it (ADR 0004), which leaves a gap: until #96 lands, nothing in the app can tell a correct archive from a plausible one. #98 would produce the first real-data fixtures with no way to know they were right, and a wrong fixture committed early is one every later reader issue is then built against. conformance.py closes that gap. It checks any .cyd against the pinned canonical schema rather than against Mobile's own idea of the format: ZIP layout and entry types, manifest reconciliation in both directions, metadata shape and its agreement with the archive row, an exact match against schema.sql, foreign keys, asset digests and byte counts, orphan payloads, and completeness being true if and only if every asset is available. A checker that passes everything would be worse than none, so self_test.py mutates the canonical fixture twelve ways and requires each to be rejected. It earned its place immediately by catching a bug here: the entry-type check rejected any entry whose mode carried no file-type bits, which is what zipfile.writestr and plenty of real writers emit. Every case "failed" for that one wrong reason. Cases are resealed with a recomputed manifest, because a broken writer fails while internally consistent, and without resealing the manifest digest catches everything before the deeper checks ever run. check_account_readiness.py covers the other half of the prerequisite, the part only a person with the device can do. Media downloads finish after records land, and a pending download becomes an unavailable asset — so an account that looks saved exports as `incomplete` while claiming to be the `complete` fixture. It also reprints the interchange groups Mobile cannot populate at all, so the fixture's real coverage is visible at the moment it is being made rather than only in the docs. bundle.py is the pin-loading and download code test_bundle.py already had. Co-Authored-By: Claude Opus 5 (1M context) --- .github/workflows/release.yml | 3 + .github/workflows/test.yml | 3 + .gitignore | 4 + docs/bluesky-archive-fixtures.md | 102 +++++++ package.json | 3 + scripts/archive-contract/bundle.py | 45 ++++ scripts/archive-contract/conformance.py | 341 ++++++++++++++++++++++++ scripts/archive-contract/self_test.py | 189 +++++++++++++ scripts/archive-contract/test_bundle.py | 37 +-- scripts/dev/check_account_readiness.py | 152 +++++++++++ 10 files changed, 853 insertions(+), 26 deletions(-) create mode 100644 docs/bluesky-archive-fixtures.md create mode 100644 scripts/archive-contract/bundle.py create mode 100755 scripts/archive-contract/conformance.py create mode 100755 scripts/archive-contract/self_test.py create mode 100755 scripts/dev/check_account_readiness.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b8309d6..5ce4dca 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,6 +35,9 @@ jobs: - name: Run canonical Bluesky archive contract tests run: npm run test:archive-contract + - name: Verify the archive conformance checker still rejects bad archives + run: npm run test:archive-conformance + - name: Check for a newer canonical Bluesky archive bundle env: GITHUB_TOKEN: ${{ github.token }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 720fc6c..13d7275 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,6 +33,9 @@ jobs: - name: Run canonical Bluesky archive contract tests run: npm run test:archive-contract + - name: Verify the archive conformance checker still rejects bad archives + run: npm run test:archive-conformance + - name: Check for a newer canonical Bluesky archive bundle env: GITHUB_TOKEN: ${{ github.token }} diff --git a/.gitignore b/.gitignore index 9746ba5..c93bfb7 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,7 @@ PLAN.md build-*.ipa build-*.aab google-play-service-account.json + +# Python +__pycache__/ +*.pyc diff --git a/docs/bluesky-archive-fixtures.md b/docs/bluesky-archive-fixtures.md new file mode 100644 index 0000000..36a3bc4 --- /dev/null +++ b/docs/bluesky-archive-fixtures.md @@ -0,0 +1,102 @@ +# Producing real-data Cyd Bluesky archive fixtures + +How to turn a curated Bluesky test account into the committed `complete` and +`incomplete` fixtures that #98 requires and #96 is built against. + +## What these fixtures are for + +They carry real facets, CIDs, JPEG and MP4 bytes, and real identifiers, which +synthetic generation does not reproduce. They are **not** a replacement for the +pinned canonical fixtures, which remain the semantic oracle (ADR 0008, ADR +0016). Keep running `npm run test:archive-contract`. + +They are also **not a superset**. Mobile cannot populate several interchange +groups at all, so these fixtures exercise less of the contract than +`complete.cyd` does: + +| Interchange | Why Mobile leaves it empty | +| --- | --- | +| `relationships` block, mute | Mobile stores follows only | +| `profiles.avatar_asset_id`, banner | avatars are URLs, never content-addressed | +| `profiles.description`, `records.indexed_at` | not stored | +| captured historical profiles | `profile` is `UNIQUE(did)`, updated in place | +| `records.first_observed_at` vs `observed_at` | one `savedAt` column, so both are equal | +| `assets` kind `preview`, `thumbnail` | `media_asset` is `image\|video` only | +| `record_assets` owner `profile`, `message` | written only from post persistence | + +`check_account_readiness.py` reprints this list, so it stays visible at the +moment it matters rather than only here. + +## 1. Curate the account first + +Media dominates the size; `data.db` is tens of KiB. Budget **5 MiB** for the +committed fixture, and reach it by deleting data from the test account before +exporting rather than by trimming the archive afterward — committed media +persists in repository history, so a fixture regenerated a few times over is +permanently expensive. + +Aim to cover, in as few records as possible: a plain post, a reply, a quote +post, a post with an external link, a post with images, a post with video, a +repost, a like, a bookmark, one chat conversation with a couple of messages, +and a follow. One or two records per category is enough — this is a semantic +fixture, not a load test. + +Third parties land in `relationships` and `conversation_members`. Point the +follow and the chat at a second account you control so the fixture is entirely +yours. + +## 2. Save everything, and let media finish + +Connect the test account in a dev build and run each save job. Media downloads +continue after the records land, and a pending download silently becomes an +`unavailable` asset — which turns a fixture meant to be `complete` into an +`incomplete` one that still looks fine. + +## 3. Pull the account database and check readiness + +Account data lives at `/accounts/bluesky-/`, holding `data.db` +and `media/`. On Android that is: + +```bash +adb exec-out run-as systems.lockdown.cydmobile \ + cat files/accounts/bluesky-/data.db > /tmp/data.db +``` + +On an iOS simulator it is under +`~/Library/Developer/CoreSimulator/Devices//data/Containers/Data/Application//Documents/`. + +```bash +npm run check:account-readiness -- /tmp/data.db +``` + +It reports category coverage, context coverage, media download state, and the +projected fixture size, and exits non-zero when the account is not ready. + +## 4. Export, then check conformance + +Export through Mobile's v2 writer, then — before trusting the result — check it +against the pinned contract rather than against Mobile's own idea of the format: + +```bash +npm run check:archive-conformance -- path/to/complete.cyd +``` + +This matters more than usual right now: Mobile builds its writer before the +reader that would otherwise catch its mistakes (ADR 0004), so until #96 lands +this checker is the only thing standing between a broken writer and a fixture +that enshrines its bugs. + +## 5. Produce the incomplete variant + +`incomplete.cyd` differs from `complete.cyd` by one unavailable asset. Get there +by failing a single download rather than by damaging the account — set one +`media_asset` row to `downloadState = 'failed'` and export again. The result +must report `completeness: incomplete`, keep every other record intact, and +still pass conformance. + +## 6. Commit with provenance + +Record alongside the fixtures: which test account produced them, the app +version and commit, the date, which records were curated in, and the steps to +regenerate. A fixture nobody can regenerate becomes unchangeable the moment the +contract moves. diff --git a/package.json b/package.json index 4b9021a..61b663c 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,9 @@ "lint": "expo lint && tsc --noEmit", "test": "jest", "test:archive-contract": "python3 scripts/archive-contract/test_bundle.py", + "test:archive-conformance": "python3 scripts/archive-contract/self_test.py", + "check:archive-conformance": "python3 scripts/archive-contract/conformance.py", + "check:account-readiness": "python3 scripts/dev/check_account_readiness.py", "test:watch": "jest --watch", "test:coverage": "jest --coverage" }, diff --git a/scripts/archive-contract/bundle.py b/scripts/archive-contract/bundle.py new file mode 100644 index 0000000..7c243d1 --- /dev/null +++ b/scripts/archive-contract/bundle.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Shared access to the pinned canonical Cyd Bluesky archive contract bundle.""" + +from __future__ import annotations + +import json +import os +import urllib.request +from pathlib import Path + + +SCRIPT_ROOT = Path(__file__).resolve().parent +PIN = json.loads((SCRIPT_ROOT / "pin.json").read_text(encoding="utf-8")) + + +def base_url() -> str: + return ( + f"https://raw.githubusercontent.com/{PIN['repository']}/" + f"{PIN['commit']}/{PIN['path']}" + ) + + +def fetch(relative_path: str) -> bytes: + """Read one file out of the pinned bundle.""" + request = urllib.request.Request( + f"{base_url()}/{relative_path}", + headers={ + "User-Agent": "cyd-mobile-ci", + **( + {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"} + if os.environ.get("GITHUB_TOKEN") + else {} + ), + }, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return response.read() + + +def download(relative_paths: tuple[str, ...], destination: Path) -> None: + """Copy files out of the pinned bundle into a local directory.""" + for relative_path in relative_paths: + output = destination / relative_path + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(fetch(relative_path)) diff --git a/scripts/archive-contract/conformance.py b/scripts/archive-contract/conformance.py new file mode 100755 index 0000000..ebc526a --- /dev/null +++ b/scripts/archive-contract/conformance.py @@ -0,0 +1,341 @@ +#!/usr/bin/env python3 +"""Check any .cyd file against the pinned Cyd Bluesky archive v2 contract. + +Cyd Mobile builds its version 2 writer before the reader that consumes it +(ADR 0004), so for a while nothing in the app can tell a correct archive from a +plausible one. This does, against the pinned canonical schema rather than +against Mobile's own idea of the format. + +Usage: + conformance.py # check the pinned canonical fixtures + conformance.py path/to/x.cyd # check one archive +""" + +from __future__ import annotations + +import hashlib +import json +import re +import sqlite3 +import stat +import sys +import tempfile +import zipfile +from pathlib import Path + +import bundle + + +MEDIA_PATH = re.compile(r"^media/sha256/([0-9a-f]{2})/([0-9a-f]{64})$") +TIMESTAMP = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$") +FIXED_ENTRIES = {"metadata.json", "manifest.json", "data.db"} +METADATA_KEYS = { + "format", + "platform", + "version", + "createdAt", + "accountDid", + "accountUuid", + "completeness", +} + + +class Failures(list): + def check(self, condition: bool, message: str) -> bool: + if not condition: + self.append(message) + return condition + + +def entry_path_is_safe(name: str) -> bool: + if not name or name.startswith("/") or "\\" in name: + return False + if re.match(r"^[A-Za-z]:", name): + return False + if any(ord(character) < 0x20 for character in name): + return False + segments = name.split("/") + return all(segment not in ("", ".", "..") for segment in segments) + + +def check_zip_structure(archive: zipfile.ZipFile, failures: Failures) -> list[str]: + """Entry names, entry types, and the fixed v2 layout.""" + payloads: list[str] = [] + seen: dict[str, str] = {} + + for info in archive.infolist(): + name = info.filename + if info.flag_bits & 0x1: + failures.append(f"{name}: encrypted entries are forbidden") + if info.flag_bits & 0x800 == 0 and not name.isascii(): + failures.append(f"{name}: non-ASCII name without the UTF-8 flag") + if not entry_path_is_safe(name.rstrip("/")): + failures.append(f"{name}: not a normalized relative path") + continue + + lowered = name.rstrip("/").lower() + if lowered in seen and seen[lowered] != name: + failures.append(f"{name}: duplicates {seen[lowered]} case-insensitively") + seen[lowered] = name + + if info.is_dir(): + continue + + # Only judge the entry type when the writer actually recorded one: + # plenty of valid writers leave the file-type bits empty. + file_type = (info.external_attr >> 16) & 0o170000 + if file_type and not stat.S_ISREG(file_type): + failures.append(f"{name}: entries must be regular files or directories") + continue + + if name not in FIXED_ENTRIES and not MEDIA_PATH.match(name): + failures.append(f"{name}: not part of the version 2 layout") + payloads.append(name) + + for required in sorted(FIXED_ENTRIES): + failures.check(required in payloads, f"{required}: missing") + return payloads + + +def check_manifest( + archive: zipfile.ZipFile, payloads: list[str], failures: Failures +) -> None: + try: + manifest = json.loads(archive.read("manifest.json")) + except (KeyError, ValueError) as error: + failures.append(f"manifest.json: unreadable ({error})") + return + + failures.check( + manifest.get("algorithm") == "sha256", + "manifest.json: algorithm must be sha256", + ) + listed = manifest.get("payloads") + if not isinstance(listed, list): + failures.append("manifest.json: payloads must be a list") + return + + paths = [entry.get("path") for entry in listed] + expected = sorted(name for name in payloads if name != "manifest.json") + failures.check( + paths == sorted(paths), "manifest.json: payloads must be sorted by path" + ) + failures.check( + sorted(paths) == expected, + "manifest.json: payload list and archive entries disagree " + f"(only in manifest: {sorted(set(paths) - set(expected))}, " + f"only in archive: {sorted(set(expected) - set(paths))})", + ) + + for entry in listed: + path = entry.get("path") + if path not in expected: + continue + content = archive.read(path) + failures.check( + entry.get("bytes") == len(content), + f"{path}: manifest declares {entry.get('bytes')} bytes, found {len(content)}", + ) + digest = hashlib.sha256(content).hexdigest() + failures.check( + entry.get("sha256") == digest, + f"{path}: manifest digest does not match contents", + ) + + +def check_metadata(archive: zipfile.ZipFile, failures: Failures) -> dict: + try: + metadata = json.loads(archive.read("metadata.json")) + except (KeyError, ValueError) as error: + failures.append(f"metadata.json: unreadable ({error})") + return {} + + failures.check( + METADATA_KEYS <= set(metadata), + f"metadata.json: missing {sorted(METADATA_KEYS - set(metadata))}", + ) + failures.check( + metadata.get("format") == "cyd-archive", "metadata.json: format must be cyd-archive" + ) + failures.check( + metadata.get("platform") == "bluesky", "metadata.json: platform must be bluesky" + ) + failures.check(metadata.get("version") == 2, "metadata.json: version must be 2") + failures.check( + bool(TIMESTAMP.match(str(metadata.get("createdAt")))), + "metadata.json: createdAt must be RFC 3339 UTC with milliseconds", + ) + failures.check( + metadata.get("completeness") in ("complete", "incomplete"), + "metadata.json: completeness must be complete or incomplete", + ) + return metadata + + +def check_database( + database: sqlite3.Connection, schema_sql: str, failures: Failures +) -> None: + """The interchange database must implement the pinned schema exactly.""" + reference = sqlite3.connect(":memory:") + reference.executescript(schema_sql) + + def objects(connection: sqlite3.Connection) -> dict[tuple[str, str], str]: + return { + (row[0], row[1]): " ".join((row[2] or "").split()) + for row in connection.execute( + "SELECT type, name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" + ) + } + + actual, expected = objects(database), objects(reference) + for key in sorted(expected.keys() - actual.keys()): + failures.append(f"data.db: missing {key[0]} {key[1]}") + for key in sorted(actual.keys() - expected.keys()): + failures.append(f"data.db: unexpected {key[0]} {key[1]}") + for key in sorted(expected.keys() & actual.keys()): + failures.check( + actual[key] == expected[key], + f"data.db: {key[0]} {key[1]} does not match the pinned schema", + ) + + for pragma, want in (("application_id", 0x43594232), ("user_version", 2)): + got = database.execute(f"PRAGMA {pragma};").fetchone()[0] + failures.check(got == want, f"data.db: {pragma} is {got}, expected {want}") + + failures.check( + database.execute("PRAGMA integrity_check;").fetchone()[0] == "ok", + "data.db: failed integrity_check", + ) + violations = database.execute("PRAGMA foreign_key_check;").fetchall() + failures.check(not violations, f"data.db: {len(violations)} foreign key violations") + reference.close() + + +def check_semantics( + database: sqlite3.Connection, + archive: zipfile.ZipFile, + payloads: list[str], + metadata: dict, + failures: Failures, +) -> None: + """Cross-checks the schema alone cannot express.""" + rows = database.execute("SELECT * FROM archive").fetchall() + if not failures.check(len(rows) == 1, f"archive: expected 1 row, found {len(rows)}"): + return + row = rows[0] + for key, column in ( + ("format", "format"), + ("platform", "platform"), + ("version", "version"), + ("createdAt", "created_at"), + ("accountDid", "account_did"), + ("accountUuid", "account_uuid"), + ("completeness", "completeness"), + ): + failures.check( + metadata.get(key) == row[column], + f"metadata.{key} is {metadata.get(key)!r}, archive.{column} is {row[column]!r}", + ) + + identity = database.execute("SELECT * FROM identity").fetchall() + failures.check( + len(identity) == 1, f"identity: expected 1 row, found {len(identity)}" + ) + if identity: + failures.check( + identity[0]["did"] == row["account_did"], + "identity.did does not match archive.account_did", + ) + + assets = database.execute("SELECT * FROM assets").fetchall() + referenced: set[str] = set() + for asset in assets: + if asset["availability"] != "available": + continue + path, digest = asset["archive_path"], asset["sha256"] + referenced.add(path) + if not failures.check( + path in payloads, f"assets[{asset['id']}]: {path} is not in the archive" + ): + continue + match = MEDIA_PATH.match(path) + failures.check( + bool(match) and match.group(2) == digest and match.group(1) == digest[:2], + f"assets[{asset['id']}]: path does not end in its digest", + ) + content = archive.read(path) + failures.check( + hashlib.sha256(content).hexdigest() == digest, + f"assets[{asset['id']}]: payload does not match its declared digest", + ) + failures.check( + asset["byte_count"] == len(content), + f"assets[{asset['id']}]: declares {asset['byte_count']} bytes, found {len(content)}", + ) + + orphans = sorted(set(name for name in payloads if MEDIA_PATH.match(name)) - referenced) + for orphan in orphans: + failures.append(f"{orphan}: media payload no asset row references") + + complete = all(asset["availability"] == "available" for asset in assets) + failures.check( + (metadata.get("completeness") == "complete") == complete, + "completeness must be 'complete' if and only if every asset is available", + ) + + +def check_archive(path: Path, schema_sql: str) -> Failures: + failures = Failures() + with zipfile.ZipFile(path) as archive: + payloads = check_zip_structure(archive, failures) + check_manifest(archive, payloads, failures) + metadata = check_metadata(archive, failures) + if "data.db" not in payloads: + return failures + with tempfile.TemporaryDirectory(prefix="cyd-conformance-") as directory: + extracted = Path(directory) / "data.db" + extracted.write_bytes(archive.read("data.db")) + database = sqlite3.connect(extracted) + database.row_factory = sqlite3.Row + try: + check_database(database, schema_sql, failures) + check_semantics(database, archive, payloads, metadata, failures) + finally: + database.close() + return failures + + +def main() -> int: + schema_sql = bundle.fetch("schema.sql").decode("utf-8") + targets: list[tuple[str, Path]] = [] + stack = tempfile.TemporaryDirectory(prefix="cyd-conformance-fixtures-") + + if len(sys.argv) > 1: + targets = [(argument, Path(argument)) for argument in sys.argv[1:]] + else: + root = Path(stack.name) + names = ("fixtures/complete.cyd", "fixtures/incomplete.cyd") + bundle.download(names, root) + targets = [(f"canonical {Path(n).name}", root / n) for n in names] + + failed = False + with stack: + for label, path in targets: + failures = check_archive(path, schema_sql) + if failures: + failed = True + print(f"FAIL {label}") + for failure in failures: + print(f" - {failure}") + else: + print(f"ok {label}") + + if failed: + print("\nArchive does not conform to the pinned Bluesky v2 contract.") + return 1 + print(f"\nConforms to the Bluesky v2 contract pinned at {bundle.PIN['commit']}.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/archive-contract/self_test.py b/scripts/archive-contract/self_test.py new file mode 100755 index 0000000..1d2a9ee --- /dev/null +++ b/scripts/archive-contract/self_test.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Prove the conformance checker rejects archives it should reject. + +A checker that passes everything would let a broken version 2 writer look +correct, which matters more than usual while Mobile builds its writer before +the reader that would otherwise catch it (ADR 0004). Each case below mutates +the pinned canonical fixture and must be caught. + +Cases are resealed with a recomputed manifest, because that is how a broken +writer actually fails: internally consistent, and wrong. Without resealing, +the manifest digest catches everything first and the deeper checks never run. +""" + +from __future__ import annotations + +import hashlib +import json +import sqlite3 +import stat +import tempfile +import zipfile +from pathlib import Path + +import bundle +import conformance + + +def seal(source: Path, destination: Path, entries: dict[str, bytes], reseal: bool) -> None: + if reseal: + entries["manifest.json"] = json.dumps( + { + "algorithm": "sha256", + "payloads": [ + { + "path": name, + "bytes": len(entries[name]), + "sha256": hashlib.sha256(entries[name]).hexdigest(), + } + for name in sorted(entries) + if name != "manifest.json" + ], + } + ).encode("utf-8") + + with zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as archive: + for name, content in entries.items(): + info = zipfile.ZipInfo(name, (2026, 1, 15, 12, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + info.create_system = 3 + symlink = name.startswith("symlink:") + info.external_attr = ( + (stat.S_IFLNK | 0o777) if symlink else (stat.S_IFREG | 0o644) + ) << 16 + archive.writestr(info, content) + + +def edit_database(work: Path, entries: dict[str, bytes], sql: str) -> dict[str, bytes]: + scratch = work / "scratch.db" + scratch.write_bytes(entries["data.db"]) + database = sqlite3.connect(scratch) + database.executescript(sql) + database.commit() + database.close() + entries["data.db"] = scratch.read_bytes() + return entries + + +def add(entries: dict[str, bytes], name: str, content: bytes) -> dict[str, bytes]: + entries[name] = content + return entries + + +def replace_json( + entries: dict[str, bytes], name: str, changes: dict +) -> dict[str, bytes]: + entries[name] = json.dumps({**json.loads(entries[name]), **changes}).encode("utf-8") + return entries + + +DROP_ONE_ASSET = """ +UPDATE assets + SET availability = 'unavailable', byte_count = NULL, sha256 = NULL, + archive_path = NULL, unavailable_reason = 'download failed' + WHERE id = (SELECT id FROM assets WHERE availability = 'available' LIMIT 1); +""" + + +def cases(work: Path): + """(label, mutate, reseal) — every one must be rejected.""" + return [ + ("stray entry outside the layout", lambda e: add(e, "notes.txt", b"hi"), True), + ("path traversal", lambda e: add(e, "../escape.json", b"{}"), True), + ("symlink entry", lambda e: add(e, "symlink:link", b"data.db"), True), + ("truncated payload", lambda e: e.update({"data.db": e["data.db"][:-200]}) or e, False), + ("forged manifest digest", _forge_manifest, False), + ( + "metadata disagrees with the archive row", + lambda e: replace_json(e, "metadata.json", {"accountDid": "did:plc:someoneelse"}), + True, + ), + ( + "unsupported version", + lambda e: replace_json(e, "metadata.json", {"version": 3}), + True, + ), + ( + "Mobile private column leaked into the interchange schema", + lambda e: edit_database(work, e, "ALTER TABLE records ADD COLUMN mobile_private TEXT;"), + True, + ), + ( + "dropped index", + lambda e: edit_database(work, e, "DROP INDEX records_author;"), + True, + ), + ( + "asset unavailable while metadata still claims complete", + lambda e: edit_database(work, e, DROP_ONE_ASSET), + True, + ), + ( + "asset byte count lies about its payload", + lambda e: edit_database( + work, + e, + "UPDATE assets SET byte_count = byte_count + 1 " + "WHERE id = (SELECT id FROM assets WHERE availability = 'available' LIMIT 1);", + ), + True, + ), + ( + "orphan media payload nothing references", + lambda e: add(e, f"media/sha256/ab/{'ab' * 32}", b"orphan"), + True, + ), + ] + + +def _forge_manifest(entries: dict[str, bytes]) -> dict[str, bytes]: + manifest = json.loads(entries["manifest.json"]) + manifest["payloads"][0]["sha256"] = "0" * 64 + entries["manifest.json"] = json.dumps(manifest).encode("utf-8") + return entries + + +def main() -> int: + with tempfile.TemporaryDirectory(prefix="cyd-conformance-self-test-") as directory: + work = Path(directory) + bundle.download(("fixtures/complete.cyd", "fixtures/incomplete.cyd"), work) + schema_sql = bundle.fetch("schema.sql").decode("utf-8") + source = work / "fixtures" / "complete.cyd" + + with zipfile.ZipFile(source) as archive: + original = { + info.filename: archive.read(info) + for info in archive.infolist() + if not info.is_dir() + } + + bugs = 0 + + for name in ("complete.cyd", "incomplete.cyd"): + failures = conformance.check_archive(work / "fixtures" / name, schema_sql) + if failures: + bugs += 1 + print(f"BUG! canonical {name} should conform: {failures[0]}") + else: + print(f"ok canonical {name} conforms") + + for label, mutate, reseal in cases(work): + target = work / "case.cyd" + target.unlink(missing_ok=True) + seal(source, target, mutate(dict(original)), reseal) + failures = conformance.check_archive(target, schema_sql) + if failures: + print(f"ok rejected: {label}") + else: + bugs += 1 + print(f"BUG! accepted an archive it should reject: {label}") + + if bugs: + print(f"\n{bugs} conformance checker problems.") + return 1 + print("\nThe conformance checker accepts the canonical fixtures and rejects each mutation.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/archive-contract/test_bundle.py b/scripts/archive-contract/test_bundle.py index 0675e45..e35e9aa 100644 --- a/scripts/archive-contract/test_bundle.py +++ b/scripts/archive-contract/test_bundle.py @@ -9,14 +9,14 @@ import sqlite3 import subprocess import tempfile -import urllib.request import zipfile from pathlib import Path from typing import Any +import bundle -SCRIPT_ROOT = Path(__file__).resolve().parent -PIN = json.loads((SCRIPT_ROOT / "pin.json").read_text(encoding="utf-8")) + +PIN = bundle.PIN FILES = ( "fixtures/complete.cyd", "fixtures/incomplete.cyd", @@ -24,21 +24,6 @@ ) -def download_bundle(destination: Path) -> None: - base_url = ( - f"https://raw.githubusercontent.com/{PIN['repository']}/" - f"{PIN['commit']}/{PIN['path']}" - ) - for relative_path in FILES: - output = destination / relative_path - output.parent.mkdir(parents=True, exist_ok=True) - request = urllib.request.Request( - f"{base_url}/{relative_path}", headers={"User-Agent": "cyd-mobile-ci"} - ) - with urllib.request.urlopen(request, timeout=30) as response: - output.write_bytes(response.read()) - - def rows(database: sqlite3.Connection, query: str) -> list[dict[str, Any]]: return [dict(row) for row in database.execute(query).fetchall()] @@ -68,8 +53,8 @@ def raw_mobile_tables(database: sqlite3.Connection) -> dict[str, Any]: return {table: rows(database, query) for table, query in queries.items()} -def prepare_fixture(bundle: Path, fixture_name: str) -> None: - archive_path = bundle / "fixtures" / fixture_name +def prepare_fixture(bundle_root: Path, fixture_name: str) -> None: + archive_path = bundle_root / "fixtures" / fixture_name with tempfile.TemporaryDirectory(prefix="cyd-bluesky-v2-") as extracted: with zipfile.ZipFile(archive_path) as archive: archive.extractall(extracted) @@ -92,7 +77,7 @@ def prepare_fixture(bundle: Path, fixture_name: str) -> None: database = sqlite3.connect(Path(extracted) / "data.db") database.row_factory = sqlite3.Row try: - mobile_input = bundle / "mobile-input" / f"{fixture_name}.json" + mobile_input = bundle_root / "mobile-input" / f"{fixture_name}.json" mobile_input.parent.mkdir(parents=True, exist_ok=True) mobile_input.write_text( json.dumps( @@ -106,10 +91,10 @@ def prepare_fixture(bundle: Path, fixture_name: str) -> None: def main() -> None: with tempfile.TemporaryDirectory(prefix="cyd-contract-") as directory: - bundle = Path(directory) - download_bundle(bundle) - prepare_fixture(bundle, "complete.cyd") - prepare_fixture(bundle, "incomplete.cyd") + bundle_root = Path(directory) + bundle.download(FILES, bundle_root) + prepare_fixture(bundle_root, "complete.cyd") + prepare_fixture(bundle_root, "incomplete.cyd") subprocess.run( [ "npm", @@ -119,7 +104,7 @@ def main() -> None: "services/__tests__/archive-contract-bundle.test.ts", ], check=True, - env={**os.environ, "CYD_BLUESKY_CONTRACT_ROOT": str(bundle)}, + env={**os.environ, "CYD_BLUESKY_CONTRACT_ROOT": str(bundle_root)}, ) print(f"Canonical Bluesky archive semantics match {PIN['commit']}.") diff --git a/scripts/dev/check_account_readiness.py b/scripts/dev/check_account_readiness.py new file mode 100755 index 0000000..b22c18c --- /dev/null +++ b/scripts/dev/check_account_readiness.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Report whether a Bluesky local account is ready to export as a v2 fixture. + +Run this against a copy of an account database pulled off a device, before +exporting it as a canonical-adjacent test fixture. A pending media download +silently becomes an unavailable asset, which turns a fixture meant to be +`complete` into an `incomplete` one that still looks fine. + +Usage: + check_account_readiness.py path/to/data.db [--media-dir path/to/media] +""" + +from __future__ import annotations + +import argparse +import sqlite3 +import sys +from pathlib import Path + + +SIZE_BUDGET_BYTES = 5 * 1024 * 1024 + +# Interchange groups Mobile cannot populate today, so a fixture exported from +# Mobile is a complement to the canonical fixtures rather than a superset. +KNOWN_GAPS = ( + ("relationships (block, mute)", "Mobile stores follows only"), + ("profiles.avatar_asset_id / banner", "avatars are URLs, never content-addressed"), + ("profiles.description", "not stored"), + ("captured historical profiles", "profile is UNIQUE(did), updated in place"), + ("records.first_observed_at vs observed_at", "one savedAt column"), + ("records.indexed_at", "not stored"), + ("assets kind preview / thumbnail", "media_asset is image|video only"), + ("record_assets owner profile / message", "written only from post persistence"), +) + + +def human(count: int) -> str: + size = float(count) + for unit in ("B", "KiB", "MiB", "GiB"): + if size < 1024 or unit == "GiB": + return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} B" + size /= 1024 + return f"{size:.1f} GiB" + + +def scalar(database: sqlite3.Connection, query: str) -> int: + return database.execute(query).fetchone()[0] or 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("database", type=Path) + parser.add_argument("--media-dir", type=Path, default=None) + arguments = parser.parse_args() + + if not arguments.database.exists(): + print(f"No account database at {arguments.database}") + return 2 + + database = sqlite3.connect(f"file:{arguments.database}?mode=ro", uri=True) + database.row_factory = sqlite3.Row + problems: list[str] = [] + + print(f"Account database: {arguments.database} ({human(arguments.database.stat().st_size)})\n") + + print("Selected-record coverage") + counts = { + "posts": "SELECT COUNT(*) FROM post WHERE isRepost = 0", + "reposts": "SELECT COUNT(*) FROM post WHERE isRepost = 1", + "likes": "SELECT COUNT(*) FROM post WHERE viewerLiked = 1", + "bookmarks": "SELECT COUNT(*) FROM bookmark", + "chats": "SELECT COUNT(*) FROM conversation", + "messages": "SELECT COUNT(*) FROM message", + "follows": "SELECT COUNT(*) FROM follow", + } + for label, query in counts.items(): + total = scalar(database, query) + marker = " " if total else "! " + if not total: + problems.append(f"no {label} saved — that category will be empty in the fixture") + print(f" {marker}{label:<10} {total}") + + print("\nContext coverage") + for label, query in ( + ("replies", "SELECT COUNT(*) FROM post WHERE isReply = 1"), + ("quotes", "SELECT COUNT(*) FROM post WHERE isQuote = 1"), + ("externals", "SELECT COUNT(*) FROM post_external"), + ("source-deleted", "SELECT COUNT(*) FROM post WHERE deletedPostAt IS NOT NULL"), + ): + total = scalar(database, query) + print(f" {label:<15} {total}") + + print("\nMedia") + states = database.execute( + "SELECT downloadState, COUNT(*) AS total, COALESCE(SUM(byteLength), 0) AS bytes " + "FROM media_asset GROUP BY downloadState ORDER BY downloadState" + ).fetchall() + if not states: + problems.append("no media assets at all — the fixture will exercise no payloads") + print(" ! none") + for row in states: + marker = " " if row["downloadState"] == "complete" else "! " + print(f" {marker}{row['downloadState']:<12} {row['total']:<5} {human(row['bytes'])}") + if row["downloadState"] != "complete": + problems.append( + f"{row['total']} media assets are '{row['downloadState']}' — " + "a fixture exported now will be 'incomplete', not 'complete'" + ) + + kinds = database.execute( + "SELECT mediaType, COUNT(*) AS total FROM media_asset " + "WHERE downloadState = 'complete' GROUP BY mediaType" + ).fetchall() + present = {row["mediaType"] for row in kinds} + for row in kinds: + print(f" {row['mediaType']:<13} {row['total']}") + for missing in {"image", "video"} - present: + problems.append(f"no preserved {missing} — the fixture will not exercise {missing} payloads") + + media_bytes = scalar( + database, + "SELECT COALESCE(SUM(byteLength), 0) FROM media_asset WHERE downloadState = 'complete'", + ) + projected = media_bytes + arguments.database.stat().st_size + print(f"\nProjected fixture size (uncompressed): {human(projected)}") + if projected > SIZE_BUDGET_BYTES: + problems.append( + f"projected fixture is {human(projected)}, over the {human(SIZE_BUDGET_BYTES)} budget — " + "curate the account further before exporting" + ) + + if arguments.media_dir: + on_disk = sum(f.stat().st_size for f in arguments.media_dir.rglob("*") if f.is_file()) + print(f"Media directory on disk: {human(on_disk)}") + + print("\nInterchange groups Mobile cannot populate (expected to be empty)") + for group, reason in KNOWN_GAPS: + print(f" {group} — {reason}") + + database.close() + + if problems: + print("\nNot ready:") + for problem in problems: + print(f" - {problem}") + return 1 + print("\nReady to export.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())