scripts: read-only pool readiness check for G3 precondition 3
scripts/region-ha-g3/pool-readiness.py+374 −0scripts/region_ha_g3_pool_readiness_test.py+359 −0scripts/testdata/region-ha-locks.json+57 −0
Intent
<task-notification> <task-id>bdawvsrbm</task-id> <tool-use-id>toolu_01MsTCS2P6xktgEE9mVAwqQ3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/bdawvsrbm.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 4 fix round" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 24.0 g CO₂e (3,001,133 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2-prep, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/scripts/region-ha-g3/pool-readiness.py b/scripts/region-ha-g3/pool-readiness.py| new file mode 100755 |
| index 000000000..d81e6febe |
| --- /dev/null |
| +++ b/scripts/region-ha-g3/pool-readiness.py |
| @@ -0,0 +1,374 @@ |
| +#!/usr/bin/env python3 |
| +# Copy pass pending after review: TEXT, REASONS and argparse help below. |
| +"""Read-only, operator-run host facts for region HA spec section 13 precondition 3.""" |
| +import argparse |
| +from datetime import datetime, timezone |
| +import json |
| +import os |
| +from pathlib import Path |
| +import re |
| +import subprocess |
| +import sys |
| +import tempfile |
| + |
| + |
| +TEXT = { |
| + "scope": "Only the named accounts were read.", |
| + "summary": "This diagnostic reports host observations for the named pool.", |
| + "proxy": "A clean marker and a complete version 2 files manifest are the proxy for files_published_at.", |
| + "read_only": "Only list-objects-v2 and get-object are allowed.", |
| +} |
| +REASONS = { |
| + "socket_non_hibernating": "The socket instance does not allow hibernation.", |
| + "lock_absent": "No lock was found to establish a clean release.", |
| + "lock_old_format": "The lock is not an HA release marker or an HA owner with an instance ID.", |
| + "marker_unclean": "The last release marker records an incomplete final publish.", |
| + "awake": "The HA owner has an unexpired lease, so run this diagnostic again when the host is asleep.", |
| + "lock_expired_unreleased": "The HA owner expired without a release marker and may have an unpaid release or a suspect holder.", |
| + "lock_invalid": "The lock could not be decoded as a lease or a release marker.", |
| + "no_replica": "No replica was found for this host.", |
| + "files_incomplete": "The files manifest is missing, unreadable, unsupported or contains incomplete items.", |
| + "record_invalid": "The instance record could not be decoded with the required field types.", |
| + "record_identity_mismatch": "The instance record identity does not match its object key.", |
| + "read_error": "A required read failed or returned an invalid listing, so readiness is unknown.", |
| +} |
| +UNKNOWN = {"awake", "lock_invalid", "record_invalid", "record_identity_mismatch", "read_error"} |
| +OWNER = re.compile(r"box/v1;ref=[^;=]+;(?:iid=(?P<iid>[^;=]+);)?pid=(?P<pid>[1-9][0-9]*);ha=1") |
| +RFC3339 = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})") |
| +REPLICA = re.compile(r"000[0-9]/([0-9a-f]{16})-([0-9a-f]{16})\.ltx") |
| + |
| + |
| +class ReadError(Exception): |
| + pass |
| + |
| + |
| +def decode(body): |
| + value = json.loads(body) |
| + if not isinstance(value, dict): |
| + raise ValueError() |
| + return value |
| + |
| + |
| +class AWSRunner: |
| + """The only process boundary; tests inject a runner with the same signature.""" |
| + |
| + def __init__(self, profile, region): |
| + self.profile, self.region = profile, region |
| + |
| + def __call__(self, verb, *, bucket, key=None, prefix=None, delimiter=None, |
| + max_keys=None, continuation_token=None): |
| + if verb not in {"list-objects-v2", "get-object"}: |
| + raise ValueError(TEXT["read_only"]) |
| + command = ["aws", "--profile", self.profile, "--region", self.region, |
| + "--output", "json", "--no-cli-pager", "--no-paginate", |
| + "--cli-connect-timeout", "2", "--cli-read-timeout", "10", |
| + "s3api", verb, "--bucket", bucket] |
| + for name, value in (("key", key), ("prefix", prefix), ("delimiter", delimiter), |
| + ("max-keys", max_keys), ("continuation-token", continuation_token)): |
| + if value is not None: |
| + command.extend(["--" + name, str(value)]) |
| + env = dict(os.environ, AWS_MAX_ATTEMPTS="1", AWS_RETRY_MODE="standard", AWS_PAGER="") |
| + for name in list(env): |
| + if name.startswith("AWS_ENDPOINT_URL") or name in { |
| + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", |
| + "AWS_SECURITY_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"}: |
| + del env[name] |
| + base = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| + try: |
| + Path(base).mkdir(parents=True, exist_ok=True) |
| + with tempfile.TemporaryDirectory(prefix="pool-readiness-", dir=base) as scratch: |
| + target = Path(scratch) / "object" |
| + if verb == "get-object": |
| + command.append(str(target)) |
| + result = subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True, |
| + env=env, timeout=20, check=False) |
| + if result.returncode: |
| + # NoSuchBucket, access denial and transport errors are not absence. |
| + if verb == "get-object" and b"(NoSuchKey)" in result.stderr: |
| + return None |
| + raise ReadError() |
| + if verb == "get-object": |
| + return target.read_bytes() |
| + return decode(result.stdout) |
| + except (OSError, subprocess.SubprocessError, ValueError) as exc: |
| + raise ReadError() from exc |
| + |
| + |
| +class Reads: |
| + def __init__(self, runner): |
| + self.runner = runner |
| + self.counts = {"list": 0, "get": 0} |
| + |
| + def get(self, bucket, key): |
| + self.counts["get"] += 1 |
| + return self.runner("get-object", bucket=bucket, key=key) |
| + |
| + def pages(self, bucket, prefix, delimiter=None): |
| + token = None |
| + seen = set() |
| + while True: |
| + self.counts["list"] += 1 |
| + page = self.runner("list-objects-v2", bucket=bucket, prefix=prefix, |
| + delimiter=delimiter, max_keys=1000, continuation_token=token) |
| + if not isinstance(page, dict) or type(page.get("IsTruncated", False)) is not bool: |
| + raise ReadError() |
| + for collection, field in (("Contents", "Key"), ("CommonPrefixes", "Prefix")): |
| + items = page.get(collection, []) |
| + if not isinstance(items, list): |
| + raise ReadError() |
| + for item in items: |
| + value = item.get(field) if isinstance(item, dict) else None |
| + if not isinstance(value, str) or not value.startswith(prefix): |
| + raise ReadError() |
| + next_token = page.get("NextContinuationToken") |
| + if page.get("IsTruncated"): |
| + if not isinstance(next_token, str) or not next_token or next_token in seen: |
| + raise ReadError() |
| + seen.add(next_token) |
| + yield page |
| + if not page.get("IsTruncated"): |
| + return |
| + token = next_token |
| + |
| + |
| +def timestamp(value): |
| + if not isinstance(value, str) or not RFC3339.fullmatch(value): |
| + raise ValueError() |
| + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) |
| + if parsed.year == 1: |
| + raise ValueError() |
| + return parsed |
| + |
| + |
| +def classify_lock(body, now): |
| + if body is None: |
| + return {"state": "lock_absent"} |
| + try: |
| + lock = decode(body) |
| + expires = timestamp(lock.get("expires_at")) |
| + owner = lock.get("owner", "") |
| + generation = lock.get("generation", 0) |
| + if (not isinstance(owner, str) or type(generation) is not int |
| + or not -(2 ** 63) <= generation < 2 ** 63): |
| + raise ValueError() |
| + release = lock.get("carlos_release") |
| + if release is not None or owner.startswith("released/v1;"): |
| + if (not isinstance(release, dict) or type(release.get("v")) is not int |
| + or release["v"] != 1 or type(release.get("clean")) is not bool): |
| + raise ValueError() |
| + for field in ("box", "iid", "lifetime", "files_gen"): |
| + if not isinstance(release.get(field, ""), str): |
| + raise ValueError() |
| + txid = release.get("txid", 0) |
| + if type(txid) is not int or not 0 <= txid < 2 ** 64: |
| + raise ValueError() |
| + timestamp(release.get("at")) |
| + state = "marker_clean" if release["clean"] else "marker_unclean" |
| + else: |
| + parsed = OWNER.fullmatch(owner) |
| + if (parsed is None or not parsed.group("iid") |
| + or len(parsed.group("pid")) > 19 or int(parsed.group("pid")) >= 2 ** 63): |
| + state = "lock_old_format" |
| + elif expires > now: |
| + state = "awake" |
| + else: |
| + state = "lock_expired_unreleased" |
| + # No box identities or raw objects are printed. |
| + return {"state": state, "generation": lock.get("generation", 0), |
| + "expires_at": lock["expires_at"]} |
| + except (ValueError, TypeError, UnicodeError): |
| + return {"state": "lock_invalid"} |
| + |
| + |
| +def complete_files(body): |
| + try: |
| + manifest = decode(body) |
| + if type(manifest.get("v")) is not int or manifest["v"] != 2: |
| + return False |
| + for field in ("entries", "platform"): |
| + items = manifest.get(field) |
| + if items is None: |
| + items = {} |
| + if not isinstance(items, dict): |
| + return False |
| + for entry in items.values(): |
| + if not isinstance(entry, dict): |
| + return False |
| + torn, skipped = entry.get("torn", False), entry.get("skipped", "") |
| + if type(torn) is not bool or not isinstance(skipped, str) or torn or skipped: |
| + return False |
| + return True |
| + except (ValueError, TypeError, UnicodeError): |
| + return False |
| + |
| + |
| +def record_valid(record): |
| + for field in ("host", "account", "app", "pool", "region", "kind", "addr", "runtime"): |
| + if field in record and not isinstance(record[field], str): |
| + return False |
| + for field in ("ha", "hibernate"): |
| + if field in record and record[field] is not None and type(record[field]) is not bool: |
| + return False |
| + addrs = record.get("addrs") |
| + return addrs is None or (isinstance(addrs, list) and all(isinstance(a, str) for a in addrs)) |
| + |
| + |
| +def socket_non_hibernating(record): |
| + socket = ((record.get("kind") or "instance") == "instance" |
| + and not record.get("addrs") and not record.get("addr")) |
| + hibernate = record.get("hibernate") |
| + if hibernate is None: |
| + hibernate = socket |
| + return socket and not record.get("runtime") and not hibernate |
| + |
| + |
| +def has_replica(reads, bucket, prefix): |
| + # litestream v0.5.14 s3/replica_client.go:702-703,1392 uses <path>/<level>/<txids>.ltx. |
| + # lease/endpoint.go:144-146 passes HibernatePrefix straight through, without ltx/. |
| + # Scan pages once, stopping at the first replica; unrelated objects do not count. |
| + for page in reads.pages(bucket, prefix): |
| + for item in page.get("Contents", []): |
| + match = REPLICA.fullmatch(item["Key"][len(prefix):]) |
| + if match and 0 < int(match[1], 16) <= int(match[2], 16): |
| + return True |
| + return False |
| + |
| + |
| +def verdict(codes): |
| + if any(code in UNKNOWN for code in codes): |
| + return "unknown" |
| + return "not_ready" if codes else "ready" |
| + |
| + |
| +def reasons(codes): |
| + return [{"code": code, "description": REASONS[code]} for code in dict.fromkeys(codes)] |
| + |
| + |
| +def inspect_record(args, reads, key, account, app, now): |
| + start = dict(reads.counts) |
| + host = key.rsplit("/", 1)[-1][:-5] |
| + row = {"host": host, "account": account, "app": app, "pool": args.pool, |
| + "lock": {"state": "not_read"}} |
| + codes = [] |
| + try: |
| + record = decode(reads.get(args.deployment_bucket, key)) |
| + if not record_valid(record): |
| + codes.append("record_invalid") |
| + elif (record.get("host"), record.get("account"), record.get("app")) != (host, account, app): |
| + codes.append("record_identity_mismatch") |
| + elif record.get("ha") is not True or record.get("pool") != args.pool or record.get("region") != args.region: |
| + return None |
| + except ReadError: |
| + codes.append("read_error") |
| + except (ValueError, TypeError, UnicodeError): |
| + codes.append("record_invalid") |
| + if not codes: |
| + if socket_non_hibernating(record): |
| + codes.append("socket_non_hibernating") |
| + prefix = args.prefix + "/" + host + "/" |
| + try: |
| + row["lock"] = classify_lock(reads.get(args.data_bucket, prefix + "lock.json"), now) |
| + if row["lock"]["state"] != "marker_clean": |
| + codes.append(row["lock"]["state"]) |
| + except ReadError: |
| + row["lock"] = {"state": "read_error"} |
| + codes.append("read_error") |
| + try: |
| + if not has_replica(reads, args.data_bucket, prefix): |
| + codes.append("no_replica") |
| + except ReadError: |
| + codes.append("read_error") |
| + try: |
| + if not complete_files(reads.get(args.data_bucket, prefix + "files/0/manifest.json")): |
| + codes.append("files_incomplete") |
| + except ReadError: |
| + codes.append("read_error") |
| + row.update(verdict=verdict(codes), reasons=reasons(codes), |
| + reads={kind: reads.counts[kind] - start[kind] for kind in start}) |
| + return row |
| + |
| + |
| +def segment(value): |
| + if not value or value in {".", ".."} or any(c in value for c in "/\\\x00") or value.startswith("-"): |
| + raise argparse.ArgumentTypeError("Use a nonempty path segment.") |
| + return value |
| + |
| + |
| +def parse_args(argv): |
| + parser = argparse.ArgumentParser(description=TEXT["summary"]) |
| + for name in ("profile", "region", "deployment-bucket", "data-bucket", "pool"): |
| + parser.add_argument("--" + name, required=True, type=segment) |
| + parser.add_argument("--account", required=True, action="append", type=segment, |
| + help="Read this account only; repeat for more accounts.") |
| + parser.add_argument("--prefix", default="instances", help="Use this data bucket prefix.") |
| + parser.add_argument("--strict", action="store_true", help="Return 1 unless readiness is established.") |
| + args = parser.parse_args(argv) |
| + try: |
| + for part in args.prefix.split("/"): |
| + segment(part) |
| + except argparse.ArgumentTypeError as exc: |
| + parser.error(str(exc)) |
| + args.account = list(dict.fromkeys(args.account)) |
| + return args |
| + |
| + |
| +def main(argv=None, *, runner=None, now=None, out=None): |
| + args = parse_args(argv) |
| + out = sys.stdout if out is None else out |
| + now = datetime.now(timezone.utc) if now is None else now |
| + reads = Reads(AWSRunner(args.profile, args.region) if runner is None else runner) |
| + totals = {"hosts": 0, "ready": 0, "not_ready": 0, "unknown": 0} |
| + errors = [] |
| + seen_apps, seen_keys = set(), set() |
| + for account in args.account: |
| + account_prefix = f"apps/{account}/" |
| + try: |
| + for page in reads.pages(args.deployment_bucket, account_prefix, "/"): |
| + for item in page.get("CommonPrefixes", []): |
| + app_prefix = item["Prefix"] |
| + app = app_prefix[len(account_prefix):].removesuffix("/") |
| + try: |
| + segment(app) |
| + except argparse.ArgumentTypeError: |
| + raise ReadError() from None |
| + if not app_prefix.endswith("/"): |
| + raise ReadError() |
| + if app_prefix in seen_apps: |
| + continue |
| + seen_apps.add(app_prefix) |
| + instance_prefix = app_prefix + "instances/" |
| + try: |
| + for objects in reads.pages(args.deployment_bucket, instance_prefix): |
| + for obj in objects.get("Contents", []): |
| + key = obj["Key"] |
| + suffix = key[len(instance_prefix):] |
| + if not suffix.endswith(".json"): |
| + continue |
| + try: |
| + segment(suffix[:-5]) |
| + except argparse.ArgumentTypeError: |
| + raise ReadError() from None |
| + if key in seen_keys: |
| + continue |
| + seen_keys.add(key) |
| + row = inspect_record(args, reads, key, account, app, now) |
| + if row is not None: |
| + totals["hosts"] += 1 |
| + totals[row["verdict"]] += 1 |
| + print(json.dumps(row, sort_keys=True), file=out) |
| + except ReadError: |
| + errors.append("read_error") |
| + except ReadError: |
| + errors.append("read_error") |
| + state = "unknown" if errors or totals["unknown"] else "not_ready" if totals["not_ready"] else "ready" |
| + summary = {"type": "summary", "pool": args.pool, "region": args.region, "accounts": args.account, |
| + "description": TEXT["summary"] + " " + TEXT["scope"], |
| + "files_published_at_proxy": TEXT["proxy"], "totals": totals, "verdict": state, |
| + "reasons": reasons(errors), "reads": reads.counts, |
| + "request_count": sum(reads.counts.values())} |
| + print(json.dumps(summary, sort_keys=True), file=out) |
| + return 1 if args.strict and state != "ready" else 0 |
| + |
| + |
| +if __name__ == "__main__": |
| + sys.exit(main()) |
diff --git a/scripts/region_ha_g3_pool_readiness_test.py b/scripts/region_ha_g3_pool_readiness_test.py| new file mode 100644 |
| index 000000000..476d8442e |
| --- /dev/null |
| +++ b/scripts/region_ha_g3_pool_readiness_test.py |
| @@ -0,0 +1,359 @@ |
| +"""Offline readiness tests. Every request is answered by fixture data.""" |
| +import copy |
| +from datetime import datetime |
| +import importlib.util |
| +import io |
| +import json |
| +from pathlib import Path |
| +import unittest |
| +from unittest.mock import patch |
| + |
| +SCRIPT = Path(__file__).parent / "region-ha-g3/pool-readiness.py" |
| +SPEC = importlib.util.spec_from_file_location("pool_readiness", SCRIPT) |
| +readiness = importlib.util.module_from_spec(SPEC) |
| +SPEC.loader.exec_module(readiness) |
| +FIXTURE = json.loads((Path(__file__).parent / "testdata/region-ha-locks.json").read_text()) |
| +NOW = datetime.fromisoformat(FIXTURE["now"].replace("Z", "+00:00")) |
| +ARGS = ["--profile", "fixture", "--region", "eu-west-1", "--deployment-bucket", "records", |
| + "--data-bucket", "data", "--pool", "pool-one", "--account", "account-one"] |
| + |
| + |
| +class FakeRunner: |
| + def __init__(self): |
| + self.objects = {} |
| + self.calls = [] |
| + self.page_size = 1000 |
| + self.errors = {} |
| + |
| + def __call__(self, verb, **params): |
| + self.calls.append((verb, params)) |
| + assert verb in {"get-object", "list-objects-v2"}, verb |
| + bucket = params["bucket"] |
| + target = params.get("key", params.get("prefix")) |
| + if (verb, target) in self.errors: |
| + raise readiness.ReadError() from None |
| + if verb == "get-object": |
| + value = self.objects.get((bucket, target)) |
| + return value if isinstance(value, bytes) or value is None else json.dumps(value).encode() |
| + keys = sorted(key for b, key in self.objects if b == bucket and key.startswith(target)) |
| + entries = set() |
| + for key in keys: |
| + suffix = key[len(target):] |
| + if params.get("delimiter") and "/" in suffix: |
| + entries.add(("prefix", target + suffix.split("/")[0] + "/")) |
| + else: |
| + entries.add(("key", key)) |
| + entries = sorted(entries) |
| + offset = int(params.get("continuation_token") or "0") |
| + count = min(params.get("max_keys", 1000), self.page_size) |
| + page = entries[offset:offset + count] |
| + result = {"Contents": [{"Key": key} for kind, key in page if kind == "key"], |
| + "CommonPrefixes": [{"Prefix": key} for kind, key in page if kind == "prefix"], |
| + "IsTruncated": offset + count < len(entries)} |
| + if result["IsTruncated"]: |
| + result["NextContinuationToken"] = str(offset + count) |
| + return result |
| + |
| + def host(self, lock="marker_clean", replica=True, manifest=None, **changes): |
| + record = {"schema": 1, "host": "host.example.invalid", "account": "account-one", |
| + "app": "app-one", "pool": "pool-one", "region": "eu-west-1", "ha": True} |
| + record.update(changes) |
| + key = f'apps/{record["account"]}/{record["app"]}/instances/{record["host"]}.json' |
| + self.objects["records", key] = record |
| + base = "instances/" + record["host"] + "/" |
| + if lock != "absent": |
| + self.objects["data", base + "lock.json"] = copy.deepcopy(FIXTURE["locks"][lock]) |
| + if replica: |
| + self.objects["data", base + "0000/0000000000000001-000000000000002a.ltx"] = b"fixture" |
| + self.objects["data", base + "files/0/manifest.json"] = ( |
| + {"v": 2, "seq": 8, "entries": {}, "platform": {}} if manifest is None else manifest) |
| + return key, base |
| + |
| + |
| +class PoolReadinessTests(unittest.TestCase): |
| + def setUp(self): |
| + self.fake = FakeRunner() |
| + # Even a regression in injection cannot contact a cloud service. |
| + self.no_process = patch.object(readiness.subprocess, "run", side_effect=AssertionError("Real runner used.")) |
| + self.no_process.start() |
| + self.addCleanup(self.no_process.stop) |
| + |
| + def run_check(self, *extra, args=None): |
| + out = io.StringIO() |
| + status = readiness.main((ARGS if args is None else args) + list(extra), |
| + runner=self.fake, now=NOW, out=out) |
| + lines = [json.loads(line) for line in out.getvalue().splitlines()] |
| + return status, lines[:-1], lines[-1] |
| + |
| + def codes(self, row): |
| + return [reason["code"] for reason in row["reasons"]] |
| + |
| + def test_awake_is_unknown_never_ready(self): |
| + self.fake.host(lock="held") |
| + status, rows, summary = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "unknown") |
| + self.assertIn("awake", self.codes(rows[0])) |
| + self.assertEqual(summary["verdict"], "unknown") |
| + self.assertEqual(status, 0) |
| + |
| + def test_shared_lock_classes(self): |
| + cases = {"absent": ("not_ready", "lock_absent"), |
| + "legacy": ("not_ready", "lock_old_format"), |
| + "marker_clean": ("ready", None), |
| + "marker_unclean": ("not_ready", "marker_unclean"), |
| + "held": ("unknown", "awake"), |
| + "expired": ("not_ready", "lock_expired_unreleased"), |
| + "no_iid": ("not_ready", "lock_old_format")} |
| + self.assertEqual(set(cases), set(FIXTURE["locks"])) |
| + for name, (verdict, code) in cases.items(): |
| + with self.subTest(name=name): |
| + self.fake = FakeRunner() |
| + self.fake.host(lock=name, replica=name != "absent") |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], verdict) |
| + self.assertEqual(rows[0]["lock"]["state"], code or "marker_clean") |
| + if code: |
| + self.assertIn(code, self.codes(rows[0])) |
| + |
| + def test_never_woken_is_not_ready(self): |
| + self.fake.host(lock="absent", replica=False) |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "not_ready") |
| + self.assertIn("no_replica", self.codes(rows[0])) |
| + |
| + def test_socket_defaults_and_exemptions(self): |
| + for changes, refused in [({"hibernate": False}, True), ({}, False), |
| + ({"hibernate": None}, False), |
| + ({"hibernate": False, "runtime": "rootfs"}, False), |
| + ({"hibernate": False, "addr": "127.0.0.1:9000"}, False), |
| + ({"hibernate": False, "addrs": ["127.0.0.1:9000"]}, False), |
| + ({"hibernate": False, "kind": "static"}, False)]: |
| + with self.subTest(changes=changes): |
| + self.fake = FakeRunner() |
| + self.fake.host(**changes) |
| + _, rows, _ = self.run_check() |
| + self.assertEqual("socket_non_hibernating" in self.codes(rows[0]), refused) |
| + |
| + def test_incomplete_files(self): |
| + manifests = [{"v": 1}, {"v": 2, "entries": {"file": {"torn": True}}}, |
| + {"v": 2, "entries": {"file": {"skipped": "x"}}}, |
| + {"v": 2, "platform": {"item": {"torn": True}}}, |
| + {"v": 2, "platform": {"item": {"skipped": "x"}}}, |
| + {"v": 2, "entries": []}, b"not json", b"null"] |
| + for manifest in manifests: |
| + with self.subTest(manifest=manifest): |
| + self.fake = FakeRunner() |
| + self.fake.host(manifest=manifest) |
| + _, rows, _ = self.run_check() |
| + self.assertIn("files_incomplete", self.codes(rows[0])) |
| + self.assertEqual(rows[0]["verdict"], "not_ready") |
| + |
| + def test_missing_files_and_proxy(self): |
| + _, base = self.fake.host() |
| + _, rows, summary = self.run_check() |
| + self.assertIn("clean marker", summary["files_published_at_proxy"]) |
| + del self.fake.objects["data", base + "files/0/manifest.json"] |
| + _, rows, _ = self.run_check() |
| + self.assertIn("files_incomplete", self.codes(rows[0])) |
| + |
| + def test_bad_record_and_identity_mismatch_are_unknown(self): |
| + for value in [b"{", b"null", b"[]", {"host": "other.example.invalid"}, |
| + {"account": "other-account"}, {"app": "other-app"}, {"ha": "true"}, |
| + {"hibernate": "false"}, {"addrs": "127.0.0.1:9000"}]: |
| + with self.subTest(value=value): |
| + self.fake = FakeRunner() |
| + key, _ = self.fake.host() |
| + if isinstance(value, dict): |
| + self.fake.objects["records", key].update(value) |
| + else: |
| + self.fake.objects["records", key] = value |
| + _, rows, summary = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "unknown") |
| + self.assertTrue(set(self.codes(rows[0])) & {"record_invalid", "record_identity_mismatch"}) |
| + self.assertEqual(summary["verdict"], "unknown") |
| + self.assertFalse(any(p["bucket"] == "data" for _, p in self.fake.calls)) |
| + |
| + def test_scope_and_read_counts(self): |
| + for a in range(2): |
| + for app in range(2): |
| + for h in range(5): |
| + self.fake.host(host=f"h{a}{app}{h}.example.invalid", account=f"account-{a}", |
| + app=f"app-{app}", pool="pool-one" if h < 2 or (app == 0 and h == 2) else "elsewhere") |
| + # An account not requested must never be enumerated. |
| + self.fake.host(account="unlisted") |
| + args = ARGS[:-2] + ["--account", "account-0", "--account", "account-1"] |
| + _, rows, summary = self.run_check(args=args) |
| + self.assertEqual(len(rows), 10) |
| + self.assertEqual(summary["reads"], {"list": 16, "get": 40}) |
| + self.assertEqual(summary["request_count"], 56) |
| + self.assertEqual(summary["totals"], {"hosts": 10, "ready": 10, "not_ready": 0, "unknown": 0}) |
| + self.assertEqual(summary["accounts"], ["account-0", "account-1"]) |
| + self.assertIn("Only the named accounts were read.", summary["description"]) |
| + self.assertTrue(all(row["reads"] == {"list": 1, "get": 3} for row in rows)) |
| + |
| + def test_filters_ha_pool_and_region(self): |
| + for changes in ({"ha": False}, {"pool": "elsewhere"}, {"region": "eu-north-1"}): |
| + self.fake = FakeRunner() |
| + self.fake.host(**changes) |
| + _, rows, summary = self.run_check() |
| + self.assertEqual(rows, []) |
| + self.assertEqual(summary["reads"], {"list": 2, "get": 1}) |
| + |
| + def test_read_errors_are_unknown_not_missing(self): |
| + key, base = self.fake.host() |
| + for verb, target in [("get-object", key), ("get-object", base + "lock.json"), |
| + ("get-object", base + "files/0/manifest.json"), |
| + ("list-objects-v2", "apps/account-one/")]: |
| + with self.subTest(target=target): |
| + self.fake.errors = {(verb, target): True} |
| + status, rows, summary = self.run_check("--strict") |
| + self.assertEqual(summary["verdict"], "unknown") |
| + self.assertEqual(status, 1) |
| + if rows: |
| + self.assertEqual(rows[0]["verdict"], "unknown") |
| + |
| + def test_malformed_lock_is_unknown(self): |
| + for body in [b"{", b"null", {"owner": "legacy:1"}, |
| + {"expires_at": "bad", "owner": "legacy:1"}, |
| + {"expires_at": "1970-01-01T00:00:00Z", "owner": "released/v1;ref=fixture-box"}]: |
| + self.fake = FakeRunner() |
| + _, base = self.fake.host() |
| + self.fake.objects["data", base + "lock.json"] = body |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "unknown") |
| + self.assertIn("lock_invalid", self.codes(rows[0])) |
| + |
| + def test_malformed_release_fields_are_unknown(self): |
| + for field, value in [("at", "bad"), ("txid", -1), ("box", []), ("clean", "true")]: |
| + with self.subTest(field=field): |
| + self.fake = FakeRunner() |
| + _, base = self.fake.host() |
| + self.fake.objects["data", base + "lock.json"]["carlos_release"][field] = value |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "unknown") |
| + self.assertIn("lock_invalid", self.codes(rows[0])) |
| + |
| + def test_owner_parser_is_strict_and_expiry_boundary_is_expired(self): |
| + for owner in ["box/v1;ref=x;iid=i-x;pid=01;ha=1", "box/v1;ref=x;iid=i-x;pid=1;ha=0", |
| + "box/v1;ref=x;iid=i-x;pid=1;boot=b;ha=1", "box/v1;ref=x;iid=i-x;pid=1;ha=1;extra=x", |
| + "box/v1;ref=x;iid=i-x;pid=99999999999999999999999999;ha=1"]: |
| + self.fake = FakeRunner() |
| + _, base = self.fake.host(lock="held") |
| + self.fake.objects["data", base + "lock.json"]["owner"] = owner |
| + _, rows, _ = self.run_check() |
| + self.assertIn("lock_old_format", self.codes(rows[0])) |
| + _, base = self.fake.host(lock="held") |
| + self.fake.objects["data", base + "lock.json"]["expires_at"] = FIXTURE["now"] |
| + _, rows, _ = self.run_check() |
| + self.assertIn("lock_expired_unreleased", self.codes(rows[0])) |
| + |
| + def test_strict_and_diagnostic_exit_codes(self): |
| + self.fake.host(replica=False) |
| + self.assertEqual(self.run_check()[0], 0) |
| + self.assertEqual(self.run_check("--strict")[0], 1) |
| + self.fake.host() |
| + self.assertEqual(self.run_check("--strict")[0], 0) |
| + |
| + def test_real_replica_layout_and_snapshot_only(self): |
| + _, base = self.fake.host(replica=False) |
| + # The stale ltx/ comment, files objects and the lock are not replicas. |
| + self.fake.objects["data", base + "ltx/0000000000000001-000000000000002a.ltx"] = b"old" |
| + self.fake.objects["data", base + "0000/not-a-replica"] = b"other" |
| + _, rows, _ = self.run_check() |
| + self.assertIn("no_replica", self.codes(rows[0])) |
| + self.fake.objects["data", base + "0009/0000000000000001-000000000000002a.ltx"] = b"snapshot" |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "ready") |
| + calls = [p for verb, p in self.fake.calls if verb == "list-objects-v2" and p["bucket"] == "data"] |
| + self.assertTrue(all(p["prefix"] == base for p in calls)) |
| + |
| + def test_pagination_and_custom_prefix(self): |
| + for n in range(3): |
| + self.fake.host(host=f"h{n}.example.invalid", app=f"app-{n}") |
| + for (bucket, key), body in list(self.fake.objects.items()): |
| + if bucket == "data": |
| + del self.fake.objects[bucket, key] |
| + self.fake.objects[bucket, key.replace("instances/", "custom/", 1)] = body |
| + self.fake.page_size = 1 |
| + _, rows, summary = self.run_check("--prefix", "custom") |
| + self.assertEqual(len(rows), 3) |
| + self.assertEqual(summary["totals"]["ready"], 3) |
| + self.assertEqual(summary["reads"], {"list": 9, "get": 9}) |
| + |
| + def test_replica_pagination_does_not_stop_at_unrelated_object(self): |
| + _, base = self.fake.host(replica=False) |
| + self.fake.objects["data", base + "0000/0000000000000001-0000000000000001.index"] = b"index" |
| + self.fake.objects["data", base + "0009/0000000000000001-000000000000002a.ltx"] = b"snapshot" |
| + self.fake.page_size = 1 |
| + _, rows, summary = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "ready") |
| + self.assertEqual(summary["reads"], {"list": 4, "get": 3}) |
| + |
| + def test_bad_listing_is_unknown_and_cannot_escape_scope(self): |
| + self.fake.host() |
| + original = self.fake |
| + for listing in [{"CommonPrefixes": [{"Prefix": "apps/unlisted/app/"}]}, |
| + {"CommonPrefixes": [], "IsTruncated": True}, |
| + {"Contents": "broken"}, None]: |
| + def bad(verb, **params): |
| + if verb == "list-objects-v2": |
| + return listing |
| + return original(verb, **params) |
| + self.fake = bad |
| + _, _, summary = self.run_check() |
| + self.assertEqual(summary["verdict"], "unknown") |
| + self.assertEqual(original.calls, []) |
| + |
| + def test_replica_list_error_is_unknown(self): |
| + _, base = self.fake.host() |
| + self.fake.errors["list-objects-v2", base] = True |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "unknown") |
| + self.assertIn("read_error", self.codes(rows[0])) |
| + |
| + def test_replica_listing_must_stay_inside_host(self): |
| + _, base = self.fake.host() |
| + original = self.fake |
| + |
| + def outside(verb, **params): |
| + if verb == "list-objects-v2" and params["bucket"] == "data": |
| + key = base.replace("host.", "evil.") + "0000/0000000000000001-000000000000002a.ltx" |
| + return {"Contents": [{"Key": key}]} |
| + return original(verb, **params) |
| + |
| + self.fake = outside |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["verdict"], "unknown") |
| + self.assertIn("read_error", self.codes(rows[0])) |
| + |
| + def test_repeated_pagination_token_is_unknown(self): |
| + def repeated(verb, **params): |
| + return {"IsTruncated": True, "NextContinuationToken": "same"} |
| + self.fake = repeated |
| + _, _, summary = self.run_check() |
| + self.assertEqual(summary["verdict"], "unknown") |
| + self.assertEqual(summary["reads"]["list"], 2) |
| + |
| + def test_no_account_refuses_before_any_request(self): |
| + with patch("sys.stderr", new=io.StringIO()), self.assertRaises(SystemExit) as error: |
| + self.run_check(args=ARGS[:-2]) |
| + self.assertEqual(error.exception.code, 2) |
| + self.assertEqual(self.fake.calls, []) |
| + |
| + def test_bad_scope_arguments_refuse_before_any_request(self): |
| + for option, value in [("--account", "../unlisted"), ("--prefix", "../other"), |
| + ("--prefix", "/instances"), ("--prefix", ""), ("--pool", "")]: |
| + with self.subTest(option=option, value=value): |
| + with patch("sys.stderr", new=io.StringIO()), self.assertRaises(SystemExit): |
| + self.run_check(option, value) |
| + self.assertEqual(self.fake.calls, []) |
| + |
| + def test_runner_refuses_non_read_verbs(self): |
| + runner = readiness.AWSRunner("fixture", "eu-west-1") |
| + for verb in ["put-object", "delete-object", "delete-objects", "copy-object", "cp", "--recursive"]: |
| + with self.subTest(verb=verb), self.assertRaises(ValueError): |
| + runner(verb, bucket="fixture") |
| + |
| + |
| +if __name__ == "__main__": |
| + unittest.main() |
diff --git a/scripts/testdata/region-ha-locks.json b/scripts/testdata/region-ha-locks.json| new file mode 100644 |
| index 000000000..f7e5c3406 |
| --- /dev/null |
| +++ b/scripts/testdata/region-ha-locks.json |
| @@ -0,0 +1,57 @@ |
| +{ |
| + "_comment": "Synthetic lock bodies from internal/hafresh/lock.go:17-34,55-75 (Marker, Lock, MarkerBody), internal/hafresh/owner.go:32-111 (OwnerFor and strict ParseOwner), internal/lease/legacytake.go:109-115 (generation and expiry), and internal/lease/release.go:26-38,88-90 (release timestamp and unclean marker). The legacy host:pid owner follows github.com/benbjohnson/litestream@v0.5.14/s3/leaser.go:53-57. Null represents NoSuchKey, not a JSON null object. Classify relative to now. All identities are fixtures.", |
| + "now": "2026-11-05T12:00:00Z", |
| + "locks": { |
| + "absent": null, |
| + "legacy": { |
| + "generation": 3, |
| + "expires_at": "2026-11-05T12:15:00Z", |
| + "owner": "fixture-box:2417" |
| + }, |
| + "marker_clean": { |
| + "generation": 7, |
| + "expires_at": "1970-01-01T00:00:00Z", |
| + "owner": "released/v1;ref=fixture-box;iid=i-0123456789abcdef0", |
| + "carlos_release": { |
| + "v": 1, |
| + "box": "fixture-box", |
| + "iid": "i-0123456789abcdef0", |
| + "lifetime": "fixture-lifetime-7", |
| + "txid": 42, |
| + "files_gen": "8:0123456789abcdef", |
| + "at": "2026-11-05T11:59:00Z", |
| + "clean": true |
| + } |
| + }, |
| + "marker_unclean": { |
| + "generation": 8, |
| + "expires_at": "1970-01-01T00:00:00Z", |
| + "owner": "released/v1;ref=fixture-box;iid=i-0123456789abcdef0", |
| + "carlos_release": { |
| + "v": 1, |
| + "box": "fixture-box", |
| + "iid": "i-0123456789abcdef0", |
| + "lifetime": "fixture-lifetime-8", |
| + "txid": 43, |
| + "files_gen": "", |
| + "at": "2026-11-05T11:59:30Z", |
| + "clean": false |
| + } |
| + }, |
| + "held": { |
| + "generation": 9, |
| + "expires_at": "2026-11-05T12:15:00Z", |
| + "owner": "box/v1;ref=fixture-box;iid=i-0123456789abcdef0;pid=2417;ha=1" |
| + }, |
| + "expired": { |
| + "generation": 9, |
| + "expires_at": "2026-11-05T11:59:59Z", |
| + "owner": "box/v1;ref=fixture-box;iid=i-0123456789abcdef0;pid=2417;ha=1" |
| + }, |
| + "no_iid": { |
| + "generation": 9, |
| + "expires_at": "2026-11-05T12:15:00Z", |
| + "owner": "box/v1;ref=fixture-box;pid=2417;ha=1" |
| + } |
| + } |
| +} |