scripts: pool readiness filters by placement code, not AWS region
scripts/region-ha-g3/pool-readiness.py+51 −19scripts/region_ha_g3_pool_readiness_test.py+140 −6
Intent
<task-notification> <task-id>bvr3av5wt</task-id> <tool-use-id>toolu_016BojUZrVPLQ2UbJcwGwkGo</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/bvr3av5wt.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 7 implementer" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 19.8 g CO₂e (2,496,131 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| index d81e6febe..a28edb5b8 100755 |
| --- a/scripts/region-ha-g3/pool-readiness.py |
| +++ b/scripts/region-ha-g3/pool-readiness.py |
| @@ -31,6 +31,7 @@ REASONS = { |
| "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.", |
| + "no_hosts": "No host in the named accounts matched the pool and placement.", |
| } |
| 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") |
| @@ -52,14 +53,14 @@ def decode(body): |
| 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 __init__(self, profile, aws_region): |
| + self.profile, self.aws_region = profile, aws_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, |
| + command = ["aws", "--profile", self.profile, "--region", self.aws_region, |
| "--output", "json", "--no-cli-pager", "--no-paginate", |
| "--cli-connect-timeout", "2", "--cli-read-timeout", "10", |
| "s3api", verb, "--bucket", bucket] |
| @@ -103,13 +104,13 @@ class Reads: |
| self.counts["get"] += 1 |
| return self.runner("get-object", bucket=bucket, key=key) |
| - def pages(self, bucket, prefix, delimiter=None): |
| + def pages(self, bucket, prefix, delimiter=None, max_keys=1000): |
| 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) |
| + delimiter=delimiter, max_keys=max_keys, 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")): |
| @@ -140,9 +141,13 @@ def timestamp(value): |
| return parsed |
| +def lock_observation(state, generation=None, expires_at=None): |
| + return {"state": state, "generation": generation, "expires_at": expires_at} |
| + |
| + |
| def classify_lock(body, now): |
| if body is None: |
| - return {"state": "lock_absent"} |
| + return lock_observation("lock_absent") |
| try: |
| lock = decode(body) |
| expires = timestamp(lock.get("expires_at")) |
| @@ -174,10 +179,9 @@ def classify_lock(body, now): |
| 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"]} |
| + return lock_observation(state, lock.get("generation"), lock["expires_at"]) |
| except (ValueError, TypeError, UnicodeError): |
| - return {"state": "lock_invalid"} |
| + return lock_observation("lock_invalid") |
| def complete_files(body): |
| @@ -203,6 +207,9 @@ def complete_files(body): |
| def record_valid(record): |
| + # DecodeRecord decodes Schema as a Go int; rootrecord.go:78 requires version 1. |
| + if type(record.get("schema")) is not int or record["schema"] != 1: |
| + return False |
| for field in ("host", "account", "app", "pool", "region", "kind", "addr", "runtime"): |
| if field in record and not isinstance(record[field], str): |
| return False |
| @@ -225,8 +232,10 @@ def socket_non_hibernating(record): |
| 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): |
| + # %04x levels 0 through SnapshotLevel (9, compaction_level.go:9) share 000. |
| + # This is their narrowest common prefix and excludes files/, lock.json and ltx/. |
| + # Probe one key at a time, stopping at the first valid replica. |
| + for page in reads.pages(bucket, prefix + "000", max_keys=1): |
| 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): |
| @@ -247,8 +256,8 @@ def reasons(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"}} |
| + row = {"type": "host", "host": host, "account": account, "app": app, "pool": args.pool, |
| + "lock": lock_observation("not_read")} |
| codes = [] |
| try: |
| record = decode(reads.get(args.deployment_bucket, key)) |
| @@ -256,7 +265,11 @@ def inspect_record(args, reads, key, account, app, now): |
| 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: |
| + # server.go:598-610 and seedmove.go:33-40: home records store region "". |
| + # No console home-code mapping is available here; callers select home with "". |
| + # An omitted region also decodes to the empty Go string. |
| + elif (record.get("ha") is not True or record.get("pool") != args.pool |
| + or record.get("region", "") != args.placement): |
| return None |
| except ReadError: |
| codes.append("read_error") |
| @@ -271,7 +284,7 @@ def inspect_record(args, reads, key, account, app, now): |
| if row["lock"]["state"] != "marker_clean": |
| codes.append(row["lock"]["state"]) |
| except ReadError: |
| - row["lock"] = {"state": "read_error"} |
| + row["lock"] = lock_observation("read_error") |
| codes.append("read_error") |
| try: |
| if not has_replica(reads, args.data_bucket, prefix): |
| @@ -294,10 +307,24 @@ def segment(value): |
| return value |
| +def placement(value): |
| + if re.fullmatch(r"[a-z]{2}-[a-z]+-[0-9]", value): |
| + raise argparse.ArgumentTypeError( |
| + "Use a placement code such as ie, or an empty string for home. " |
| + "Pass the AWS region with --aws-region.") |
| + # provision.go:877 regionPoolRe, including the stored home-region value "". |
| + if not re.fullmatch(r"[a-z0-9-]{0,16}", value): |
| + raise argparse.ArgumentTypeError( |
| + "Use up to 16 lowercase letters, digits or hyphens, or an empty string for home.") |
| + return value |
| + |
| + |
| def parse_args(argv): |
| parser = argparse.ArgumentParser(description=TEXT["summary"]) |
| - for name in ("profile", "region", "deployment-bucket", "data-bucket", "pool"): |
| + for name in ("profile", "aws-region", "deployment-bucket", "data-bucket", "pool"): |
| parser.add_argument("--" + name, required=True, type=segment) |
| + parser.add_argument("--placement", required=True, type=placement, |
| + help="Match this placement code exactly; use an empty string for home.") |
| 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.") |
| @@ -316,7 +343,7 @@ 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) |
| + reads = Reads(AWSRunner(args.profile, args.aws_region) if runner is None else runner) |
| totals = {"hosts": 0, "ready": 0, "not_ready": 0, "unknown": 0} |
| errors = [] |
| seen_apps, seen_keys = set(), set() |
| @@ -342,7 +369,9 @@ def main(argv=None, *, runner=None, now=None, out=None): |
| for obj in objects.get("Contents", []): |
| key = obj["Key"] |
| suffix = key[len(instance_prefix):] |
| - if not suffix.endswith(".json"): |
| + # provision.recordHosts (provision.go:3045-3059) skips |
| + # nested keys, non-JSON keys and empty host names. |
| + if "/" in suffix or not suffix.endswith(".json") or suffix == ".json": |
| continue |
| try: |
| segment(suffix[:-5]) |
| @@ -360,8 +389,11 @@ def main(argv=None, *, runner=None, now=None, out=None): |
| errors.append("read_error") |
| except ReadError: |
| errors.append("read_error") |
| + if totals["hosts"] == 0: |
| + errors.append("no_hosts") |
| 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, |
| + summary = {"type": "summary", "pool": args.pool, "aws_region": args.aws_region, |
| + "placement": args.placement, "accounts": args.account, |
| "description": TEXT["summary"] + " " + TEXT["scope"], |
| "files_published_at_proxy": TEXT["proxy"], "totals": totals, "verdict": state, |
| "reasons": reasons(errors), "reads": reads.counts, |
diff --git a/scripts/region_ha_g3_pool_readiness_test.py b/scripts/region_ha_g3_pool_readiness_test.py| index 476d8442e..c79dd3c3e 100644 |
| --- a/scripts/region_ha_g3_pool_readiness_test.py |
| +++ b/scripts/region_ha_g3_pool_readiness_test.py |
| @@ -14,7 +14,8 @@ 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", |
| +ARGS = ["--profile", "fixture", "--aws-region", "eu-west-1", "--placement", "ie", |
| + "--deployment-bucket", "records", |
| "--data-bucket", "data", "--pool", "pool-one", "--account", "account-one"] |
| @@ -56,7 +57,7 @@ class FakeRunner: |
| 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} |
| + "app": "app-one", "pool": "pool-one", "region": "ie", "ha": True} |
| record.update(changes) |
| key = f'apps/{record["account"]}/{record["app"]}/instances/{record["host"]}.json' |
| self.objects["records", key] = record |
| @@ -112,6 +113,11 @@ class PoolReadinessTests(unittest.TestCase): |
| _, rows, _ = self.run_check() |
| self.assertEqual(rows[0]["verdict"], verdict) |
| self.assertEqual(rows[0]["lock"]["state"], code or "marker_clean") |
| + self.assertEqual(rows[0]["type"], "host") |
| + self.assertEqual(set(rows[0]["lock"]), {"state", "generation", "expires_at"}) |
| + if name == "absent": |
| + self.assertIsNone(rows[0]["lock"]["generation"]) |
| + self.assertIsNone(rows[0]["lock"]["expires_at"]) |
| if code: |
| self.assertIn(code, self.codes(rows[0])) |
| @@ -191,14 +197,130 @@ class PoolReadinessTests(unittest.TestCase): |
| 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"}): |
| + def test_filters_ha_pool_and_placement(self): |
| + for changes in ({"ha": False}, {"pool": "elsewhere"}, {"region": "se"}): |
| 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_placement_selects_real_records_without_vacuous_ready(self): |
| + # Both records disappeared under the old --region eu-west-1 filter. |
| + self.fake.host(host="ie.example.invalid", region="ie", replica=False) |
| + self.fake.host(host="home.example.invalid", region="", replica=False) |
| + for code, host in [("ie", "ie.example.invalid"), ("", "home.example.invalid")]: |
| + with self.subTest(placement=code): |
| + status, rows, summary = self.run_check("--placement", code, "--strict") |
| + self.assertEqual([row["host"] for row in rows], [host]) |
| + self.assertEqual(summary["totals"]["hosts"], 1) |
| + self.assertEqual(summary["placement"], code) |
| + self.assertEqual(summary["aws_region"], "eu-west-1") |
| + self.assertEqual(summary["verdict"], "not_ready") |
| + self.assertIn("no_replica", self.codes(rows[0])) |
| + self.assertEqual(status, 1) |
| + |
| + def test_omitted_record_region_is_home(self): |
| + key, _ = self.fake.host() |
| + del self.fake.objects["records", key]["region"] |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows, []) |
| + status, rows, summary = self.run_check("--placement", "", "--strict") |
| + self.assertEqual(len(rows), 1) |
| + self.assertEqual(summary["verdict"], "ready") |
| + self.assertEqual(status, 0) |
| + |
| + def test_placement_is_required_and_refuses_aws_region(self): |
| + start = ARGS.index("--placement") |
| + without_placement = ARGS[:start] + ARGS[start + 2:] |
| + for args, message in [(without_placement, "--placement"), |
| + (ARGS + ["--placement", "eu-west-1"], "--aws-region"), |
| + (ARGS + ["--placement", "us-east-2"], "placement code"), |
| + (ARGS + ["--placement", "IE"], "lowercase"), |
| + (ARGS + ["--placement", "ie/other"], "lowercase")]: |
| + with self.subTest(args=args): |
| + err = io.StringIO() |
| + with patch("sys.stderr", new=err), self.assertRaises(SystemExit) as error: |
| + self.run_check(args=args) |
| + self.assertEqual(error.exception.code, 2) |
| + self.assertIn(message, err.getvalue()) |
| + self.assertEqual(self.fake.calls, []) |
| + |
| + def test_aws_runner_receives_aws_region_only(self): |
| + self.fake.host() |
| + with patch.object(readiness, "AWSRunner", return_value=self.fake) as factory: |
| + status = readiness.main(ARGS, now=NOW, out=io.StringIO()) |
| + factory.assert_called_once_with("fixture", "eu-west-1") |
| + self.assertEqual(status, 0) |
| + |
| + def test_zero_hosts_is_unknown_and_strict_fails(self): |
| + for extra in [(), ("--pool", "missing"), ("--account", "missing"), |
| + ("--placement", "se")]: |
| + with self.subTest(extra=extra): |
| + self.fake = FakeRunner() |
| + if extra: |
| + self.fake.host() |
| + # Replace account rather than append it, since the flag is repeatable. |
| + args = ARGS[:-2] if extra and extra[0] == "--account" else ARGS |
| + status, rows, summary = self.run_check(*extra, args=args) |
| + self.assertEqual(status, 0) |
| + self.assertEqual(rows, []) |
| + self.assertEqual(summary["totals"]["hosts"], 0) |
| + self.assertEqual(summary["verdict"], "unknown") |
| + self.assertEqual(self.codes(summary), ["no_hosts"]) |
| + self.assertEqual(self.run_check(*extra, "--strict", args=args)[0], 1) |
| + |
| + def test_nested_instance_keys_are_skipped(self): |
| + key, _ = self.fake.host() |
| + prefix = key.rsplit("/", 1)[0] + "/" |
| + skipped = [prefix + name for name in ["a/nested.json", ".json", "note.txt"]] |
| + for name in skipped: |
| + self.fake.objects["records", name] = b"not a record" |
| + self.fake.page_size = 1 |
| + status, rows, summary = self.run_check("--strict") |
| + self.assertEqual(status, 0) |
| + self.assertEqual(len(rows), 1) |
| + self.assertEqual(summary["verdict"], "ready") |
| + self.assertEqual(summary["reasons"], []) |
| + gets = [params["key"] for verb, params in self.fake.calls if verb == "get-object"] |
| + self.assertTrue(set(skipped).isdisjoint(gets)) |
| + |
| + def test_record_requires_integer_schema_one(self): |
| + for schema in [None, 0, 2, True, 1.0, "1", "missing"]: |
| + with self.subTest(schema=schema): |
| + self.fake = FakeRunner() |
| + key, _ = self.fake.host(schema=schema) |
| + if schema == "missing": |
| + del self.fake.objects["records", key]["schema"] |
| + status, rows, summary = self.run_check("--strict") |
| + self.assertEqual(self.codes(rows[0]), ["record_invalid"]) |
| + self.assertEqual(summary["verdict"], "unknown") |
| + self.assertEqual(status, 1) |
| + self.assertFalse(any(p["bucket"] == "data" for _, p in self.fake.calls)) |
| + |
| + def test_unavailable_lock_fields_are_null(self): |
| + for state in ["not_read", "lock_invalid", "read_error"]: |
| + with self.subTest(state=state): |
| + self.fake = FakeRunner() |
| + key, base = self.fake.host() |
| + if state == "not_read": |
| + self.fake.objects["records", key] = b"not json" |
| + elif state == "lock_invalid": |
| + self.fake.objects["data", base + "lock.json"] = b"not json" |
| + else: |
| + self.fake.errors["get-object", base + "lock.json"] = True |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["type"], "host") |
| + self.assertEqual(rows[0]["lock"], |
| + {"state": state, "generation": None, "expires_at": None}) |
| + self.fake = FakeRunner() |
| + _, base = self.fake.host() |
| + del self.fake.objects["data", base + "lock.json"]["generation"] |
| + _, rows, _ = self.run_check() |
| + self.assertEqual(rows[0]["lock"]["state"], "marker_clean") |
| + self.assertIsNone(rows[0]["lock"]["generation"]) |
| + self.assertIsNotNone(rows[0]["lock"]["expires_at"]) |
| + |
| 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"), |
| @@ -265,7 +387,7 @@ class PoolReadinessTests(unittest.TestCase): |
| _, 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)) |
| + self.assertTrue(all(p["prefix"] == base + "000" and p["max_keys"] == 1 for p in calls)) |
| def test_pagination_and_custom_prefix(self): |
| for n in range(3): |
| @@ -289,6 +411,18 @@ class PoolReadinessTests(unittest.TestCase): |
| self.assertEqual(rows[0]["verdict"], "ready") |
| self.assertEqual(summary["reads"], {"list": 4, "get": 3}) |
| + def test_replica_probe_does_not_walk_file_objects(self): |
| + _, base = self.fake.host(replica=False) |
| + for n in range(2001): |
| + self.fake.objects["data", base + f"files/0/objects/{n}"] = b"file" |
| + _, rows, summary = self.run_check() |
| + self.assertIn("no_replica", self.codes(rows[0])) |
| + self.assertEqual(summary["reads"], {"list": 3, "get": 3}) |
| + calls = [p for verb, p in self.fake.calls if verb == "list-objects-v2" and p["bucket"] == "data"] |
| + self.assertEqual(len(calls), 1) |
| + self.assertEqual(calls[0]["prefix"], base + "000") |
| + self.assertEqual(calls[0]["max_keys"], 1) |
| + |
| def test_bad_listing_is_unknown_and_cannot_escape_scope(self): |
| self.fake.host() |
| original = self.fake |
| @@ -306,7 +440,7 @@ class PoolReadinessTests(unittest.TestCase): |
| def test_replica_list_error_is_unknown(self): |
| _, base = self.fake.host() |
| - self.fake.errors["list-objects-v2", base] = True |
| + self.fake.errors["list-objects-v2", base + "000"] = True |
| _, rows, _ = self.run_check() |
| self.assertEqual(rows[0]["verdict"], "unknown") |
| self.assertIn("read_error", self.codes(rows[0])) |