From 8ce855c8985a7e3bb88d0d9359d19f4ef8b1e29c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 16:46:51 +0000 Subject: [PATCH] feat(backups): deterministic class-B cohort planner for the Turso mesh (#13456) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Slice 1: a pure planner that takes a runtime Turso inventory, excludes the class-A databases (fleet-queue, fleet-platform, atlas), assigns every remaining database to exactly one stable 14-day cohort (sha256(name)[:8] % 14), and emits the cohort due for a supplied date (days-since-epoch % 14) as a machine-readable JSON dry-run plan. No exports, R2 writes, credentials, retries, or schedule — those are follow-up slices. Property-style tests (stdlib-only, fixed seed) prove in-range, unique, order-independent assignments; examples cover the class-A exclusions and date-to-cohort selection. Test: python3 -m unittest discover -s pkgs/cold-store-reaper/tests -v (also runnable as: python3 -m pytest pkgs/cold-store-reaper/tests/test_turso_mesh_cohort.py) --- .../scripts/turso-mesh-cohorts.py | 207 +++++++++++++++++ .../tests/test_turso_mesh_cohort.py | 216 ++++++++++++++++++ 2 files changed, 423 insertions(+) create mode 100755 pkgs/cold-store-reaper/scripts/turso-mesh-cohorts.py create mode 100644 pkgs/cold-store-reaper/tests/test_turso_mesh_cohort.py diff --git a/pkgs/cold-store-reaper/scripts/turso-mesh-cohorts.py b/pkgs/cold-store-reaper/scripts/turso-mesh-cohorts.py new file mode 100755 index 0000000000..03ea4ad5cb --- /dev/null +++ b/pkgs/cold-store-reaper/scripts/turso-mesh-cohorts.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Deterministic class-B cohort planner for the Turso backup mesh (#13456). + +The mesh design (``doc/2026-11-23T16-34-18Z_design_backup_mesh/note.md`` +§4) divides the general Turso databases (class B — everything except +the platform set) into 14 daily cohorts by a stable hash of the +database name; each database is snapshotted once per 14 days. This +script is the planner only: it takes an explicit runtime inventory +and a date and emits the due cohort as a machine-readable dry-run +plan. It performs no export, writes nothing to R2, touches no +credential, and schedules nothing — those are follow-up slices. + +Rules (all deterministic; the same inventory and date always produce +the same plan, regardless of input ordering): + +* Class A — ``fleet-queue``, ``fleet-platform``, ``atlas`` — is + excluded from the rotation (design §4: weekly, double the mesh + cadence, leg #13455). Excluded names are reported in the plan, never + silently dropped. +* Cohort of a database: ``int(sha256(name)[:8]) % 14`` — SHA-256 of + the UTF-8 name, first 8 bytes big-endian. A name hash is stable + across runs, hosts, and Python versions, so a database never moves + cohort when the inventory grows; new databases join automatically. +* Cohort due on a date: ``(date - 1970-01-01).days % 14`` — days + since the Unix epoch, so the rotation is anchored to a fixed date + and every cohort comes due exactly once per 14-day cycle. + +Inventory format: one database name per line (blank lines ignored, +surrounding whitespace stripped, duplicates collapsed). Feed it from +``turso db list`` at run time — never hard-code the inventory here. + +Usage: + turso db list | python3 scripts/turso-mesh-cohorts.py --date 2026-11-24 + python3 scripts/turso-mesh-cohorts.py --inventory dbs.txt --all + python3 scripts/turso-mesh-cohorts.py --inventory dbs.txt --cohort 3 + +Output is JSON on stdout. Exit 0 on success, 2 on a usage error +(bad date, cohort out of range, unreadable inventory). + +Argument contract (#3352): the whole command line is declared in +``main()`` and parsed strictly with argparse before any inventory +read; an unknown flag, stray positional, or typo'd flag is a usage +error naming the offending argument, exit 2. +""" + +import argparse +import hashlib +import json +import sys +from datetime import date + +COHORTS = 14 +EPOCH = date(1970, 1, 1) + +CLASS_A = frozenset({"fleet-queue", "fleet-platform", "atlas"}) + + +def cohort_of(name): + """The 14-day cohort index of one database name (0..13).""" + digest = hashlib.sha256(name.encode("utf-8")).digest() + return int.from_bytes(digest[:8], "big") % COHORTS + + +def cohort_for_date(day): + """The cohort due on a date: days since the epoch, mod 14.""" + return (day - EPOCH).days % COHORTS + + +def read_inventory(lines): + """Parse one-name-per-line inventory text into a sorted unique list.""" + names = set() + for line in lines: + name = line.strip() + if name: + names.add(name) + return sorted(names) + + +def split_classes(inventory): + """Split an inventory into (class-B names, excluded class-A names).""" + class_b = [name for name in inventory if name not in CLASS_A] + excluded = sorted(name for name in inventory if name in CLASS_A) + return class_b, excluded + + +def assign(inventory): + """Assign every class-B database to exactly one cohort. + + Returns (cohorts, excluded) where cohorts is a list of 14 sorted + name lists and excluded is the sorted class-A list. + """ + class_b, excluded = split_classes(inventory) + cohorts = [[] for _ in range(COHORTS)] + for name in class_b: + cohorts[cohort_of(name)].append(name) + return [sorted(members) for members in cohorts], excluded + + +def plan(inventory, day): + """The dry-run plan for one date: the due cohort and its databases.""" + cohorts, excluded = assign(inventory) + due = cohort_for_date(day) + return { + "date": day.isoformat(), + "cohort": due, + "databases": cohorts[due], + "excluded_class_a": excluded, + "class_b_total": sum(len(members) for members in cohorts), + "cohorts": COHORTS, + } + + +def full_plan(inventory, day): + """The plan for all 14 cohorts on one date (audit / --all output).""" + cohorts, excluded = assign(inventory) + return { + "date": day.isoformat(), + "cohort": cohort_for_date(day), + "cohorts": [ + {"cohort": index, "databases": members} + for index, members in enumerate(cohorts) + ], + "excluded_class_a": excluded, + "class_b_total": sum(len(members) for members in cohorts), + "cohort_count": COHORTS, + } + + +def parse_date(text): + """Parse a YYYY-MM-DD date, raising ValueError on anything else.""" + year, month, day = text.split("-") + if len(year) != 4 or len(month) != 2 or len(day) != 2: + raise ValueError("date must be YYYY-MM-DD, got %r" % text) + return date(int(year), int(month), int(day)) + + +def main(argv=None): + parser = argparse.ArgumentParser( + description="Plan the class-B Turso mesh cohort due on a date (#13456)." + ) + parser.add_argument( + "--inventory", + metavar="FILE", + help="one database name per line; default reads stdin", + ) + parser.add_argument( + "--date", + default=date.today().isoformat(), + help="the run date, YYYY-MM-DD (default: today)", + ) + group = parser.add_mutually_exclusive_group() + group.add_argument( + "--all", + action="store_true", + help="emit all 14 cohorts instead of only the due one", + ) + group.add_argument( + "--cohort", + type=int, + metavar="N", + help="emit cohort N (0..13) instead of the date's due cohort", + ) + args = parser.parse_args(argv) + + try: + day = parse_date(args.date) + except ValueError as exc: + print("turso-mesh-cohorts: %s" % exc, file=sys.stderr) + return 2 + if args.cohort is not None and not 0 <= args.cohort < COHORTS: + print( + "turso-mesh-cohorts: cohort must be 0..%d, got %d" + % (COHORTS - 1, args.cohort), + file=sys.stderr, + ) + return 2 + + try: + if args.inventory: + with open(args.inventory, encoding="utf-8") as handle: + inventory = read_inventory(handle) + else: + inventory = read_inventory(sys.stdin) + except OSError as exc: + print("turso-mesh-cohorts: cannot read inventory: %s" % exc, file=sys.stderr) + return 2 + + if args.all: + result = full_plan(inventory, day) + elif args.cohort is not None: + cohorts, excluded = assign(inventory) + result = { + "date": day.isoformat(), + "cohort": args.cohort, + "databases": cohorts[args.cohort], + "excluded_class_a": excluded, + "class_b_total": sum(len(members) for members in cohorts), + "cohorts": COHORTS, + } + else: + result = plan(inventory, day) + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pkgs/cold-store-reaper/tests/test_turso_mesh_cohort.py b/pkgs/cold-store-reaper/tests/test_turso_mesh_cohort.py new file mode 100644 index 0000000000..b337f18193 --- /dev/null +++ b/pkgs/cold-store-reaper/tests/test_turso_mesh_cohort.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Tests for scripts/turso-mesh-cohorts.py (#13456, slice 1). + +Oracles: +- Example tests: the cohort rule in the script's docstring + (``sha256(name)[:8] % 14`` for assignment, days-since-epoch mod 14 + for the due cohort) recomputed independently here, plus the design's + class-A set (``fleet-queue``, ``fleet-platform``, ``atlas``). +- Property-style tests (stdlib-only, fixed seed — no hypothesis in + this repo's Python tooling, per test_repair_dump_property.py): + a generator emits random inventories and the invariants are + checked directly: cohort indices in range, every class-B database + in exactly one cohort, and inventory permutation changing nothing. + A failing case prints its seed and case index. + +Usage: python3 -m unittest discover -s pkgs/cold-store-reaper/tests -v +""" + +import json +import random +import subprocess +import sys +import unittest +from datetime import date +from pathlib import Path + +PLANNER = Path(__file__).resolve().parent.parent / "scripts" / "turso-mesh-cohorts.py" + +CLASS_A = ("fleet-queue", "fleet-platform", "atlas") +SEED = 20261123 + + +def run_cli(*args, stdin_text=""): + return subprocess.run( + [sys.executable, str(PLANNER), *args], + input=stdin_text.encode(), + capture_output=True, + check=False, + ) + + +def plan_for(inventory, day): + result = run_cli("--date", day.isoformat(), stdin_text="\n".join(inventory)) + assert result.returncode == 0, result.stderr + return json.loads(result.stdout.decode()) + + +class TestCohortRule(unittest.TestCase): + def test_epoch_date_is_cohort_zero(self): + # Oracle: (1970-01-01 - epoch).days % 14 == 0. + self.assertEqual(plan_for([], date(1970, 1, 1))["cohort"], 0) + + def test_date_to_cohort_is_days_since_epoch_mod_14(self): + # Oracle: the rule recomputed independently from the date. + for day in (date(1970, 1, 2), date(1970, 1, 15), date(2026, 11, 24)): + expected = (day - date(1970, 1, 1)).days % 14 + self.assertEqual(plan_for([], day)["cohort"], expected) + + def test_class_a_databases_are_excluded_and_reported(self): + # Oracle: the design's class-A set; excluded names appear in + # excluded_class_a and in no cohort. + inventory = list(CLASS_A) + ["general-db", "other-db"] + got = plan_for(inventory, date(2026, 11, 24)) + self.assertEqual(got["excluded_class_a"], sorted(CLASS_A)) + self.assertEqual(got["class_b_total"], 2) + self.assertNotIn("atlas", got["databases"]) + full = json.loads( + run_cli( + "--date", "2026-11-24", "--all", stdin_text="\n".join(inventory) + ).stdout.decode() + ) + held = [name for cohort in full["cohorts"] for name in cohort["databases"]] + for name in CLASS_A: + self.assertNotIn(name, held) + + def test_cohort_assignment_matches_sha256_rule(self): + # Oracle: sha256(name)[:8] % 14, recomputed here. + import hashlib + + inventory = ["alpha-db", "beta-db", "gamma-db", "fleet-queue"] + got = json.loads( + run_cli( + "--date", "2026-11-24", "--all", stdin_text="\n".join(inventory) + ).stdout.decode() + ) + by_cohort = { + entry["cohort"]: entry["databases"] for entry in got["cohorts"] + } + for name in ("alpha-db", "beta-db", "gamma-db"): + expected = int.from_bytes( + hashlib.sha256(name.encode()).digest()[:8], "big" + ) % 14 + self.assertIn(name, by_cohort[expected]) + + def test_due_cohort_databases_are_that_cohorts_members(self): + inventory = ["alpha-db", "beta-db", "gamma-db", "delta-db"] + day = date(2026, 11, 24) + due = plan_for(inventory, day) + full = json.loads( + run_cli("--date", day.isoformat(), "--all", stdin_text="\n".join(inventory)).stdout.decode() + ) + members = next( + entry["databases"] for entry in full["cohorts"] if entry["cohort"] == due["cohort"] + ) + self.assertEqual(due["databases"], members) + + def test_same_inventory_and_date_always_give_the_same_plan(self): + inventory = ["zeta-db", "alpha-db", "fleet-platform", "beta-db"] + first = plan_for(inventory, date(2026, 11, 24)) + second = plan_for(list(reversed(inventory)), date(2026, 11, 24)) + self.assertEqual(first, second) + + def test_inventory_order_and_duplicates_do_not_change_the_plan(self): + inventory = ["one-db", "two-db", "three-db", "atlas"] + base = plan_for(inventory, date(2026, 11, 24)) + shuffled = plan_for( + ["three-db", "one-db", "two-db", "two-db", "atlas", "one-db"], + date(2026, 11, 24), + ) + self.assertEqual(base, shuffled) + + def test_empty_inventory_is_a_valid_empty_plan(self): + got = plan_for([], date(2026, 11, 24)) + self.assertEqual(got["databases"], []) + self.assertEqual(got["class_b_total"], 0) + self.assertEqual(got["excluded_class_a"], []) + + def test_cohort_flag_selects_one_cohort(self): + inventory = ["alpha-db", "beta-db", "gamma-db"] + got = json.loads( + run_cli("--date", "2026-11-24", "--cohort", "5", stdin_text="\n".join(inventory)).stdout.decode() + ) + full = json.loads( + run_cli("--date", "2026-11-24", "--all", stdin_text="\n".join(inventory)).stdout.decode() + ) + members = next( + entry["databases"] for entry in full["cohorts"] if entry["cohort"] == 5 + ) + self.assertEqual(got["cohort"], 5) + self.assertEqual(got["databases"], members) + + def test_bad_date_and_bad_cohort_are_usage_errors(self): + self.assertEqual(run_cli("--date", "2026-13-01").returncode, 2) + self.assertEqual(run_cli("--date", "tomorrow").returncode, 2) + self.assertEqual(run_cli("--cohort", "14").returncode, 2) + self.assertEqual(run_cli("--cohort", "-1").returncode, 2) + self.assertEqual(run_cli("--bogus-flag").returncode, 2) + + def test_inventory_file_input_matches_stdin(self): + import tempfile + + inventory = ["file-db", "stdin-db", "atlas"] + with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as handle: + handle.write("\n".join(inventory) + "\n") + path = handle.name + try: + from_file = json.loads( + run_cli("--date", "2026-11-24", "--inventory", path).stdout.decode() + ) + finally: + Path(path).unlink() + self.assertEqual(from_file, plan_for(inventory, date(2026, 11, 24))) + + +class TestCohortInvariants(unittest.TestCase): + """Property-style invariants over generated inventories (#13456).""" + + def test_generated_inventories(self): + rng = random.Random(SEED) + alphabet = "abcdefghij-" + for case in range(200): + size = rng.randrange(0, 60) + inventory = [ + "".join(rng.choice(alphabet) for _ in range(rng.randrange(1, 12))) + for _ in range(size) + ] + # Sprinkle class-A names in: they must never land in a cohort. + if case % 3 == 0: + inventory += list(CLASS_A) + day = date(2026, 11, 24) + try: + got = plan_for(inventory, day) + full = json.loads( + run_cli( + "--date", day.isoformat(), "--all", + stdin_text="\n".join(inventory), + ).stdout.decode() + ) + except AssertionError: + print("seed=%d case=%d inventory=%r" % (SEED, case, inventory)) + raise + class_b = sorted(set(inventory) - set(CLASS_A)) + held = [name for entry in full["cohorts"] for name in entry["databases"]] + # In range: 14 cohorts, indices 0..13. + self.assertEqual(len(full["cohorts"]), 14) + self.assertEqual([entry["cohort"] for entry in full["cohorts"]], list(range(14))) + # Unique: every class-B database in exactly one cohort. + self.assertEqual(sorted(held), class_b) + self.assertEqual(len(held), len(set(held))) + # Order-independent: a permutation changes nothing. + shuffled = inventory[:] + rng.shuffle(shuffled) + again = plan_for(shuffled, day) + self.assertEqual(got, again, "seed=%d case=%d" % (SEED, case)) + # Due cohort: the plan's databases are that cohort's members. + members = next( + entry["databases"] + for entry in full["cohorts"] + if entry["cohort"] == got["cohort"] + ) + self.assertEqual(got["databases"], members) + self.assertEqual(got["class_b_total"], len(class_b)) + + +if __name__ == "__main__": + unittest.main()