region HA P3b-2: fix client iid wiring; argv tests for every verb
B-SMOKE S5 (fourth live defect): client.py main() passed iid twice to send(), so arm-fault, arm-pause and fault-now crashed with a TypeError before any session. send() now takes target. Adds argv-level tests for every verb of the fault client (real subprocess, fake aws/plugin emitting the captured live frame), roll (8 verbs) and probe (4). Opus review READY; Paul's go 2026-11-05 19:20Z via 8a3d302. Squashed from region-ha-p3b2-cli-argv into main.
4 files changed,
+338
−5
scripts/region-group-fault/client.py+2 −2scripts/region_group_fault_test.py+114 −0scripts/region_group_probe_test.py+51 −2scripts/region_group_roll_test.py+171 −1
CI passed — run details
diff --git a/scripts/region-group-fault/client.py b/scripts/region-group-fault/client.py| index d95f1769d..3c0042095 100644 |
| --- a/scripts/region-group-fault/client.py |
| +++ b/scripts/region-group-fault/client.py |
| @@ -30,12 +30,12 @@ def result(output, nonce): |
| return rows[0][0] |
| -def send(config, iid, verb, **fields): |
| +def send(config, target, verb, **fields): |
| nonce = uuid.uuid4().hex |
| cmd = command(verb, nonce, **fields) |
| adapter = frames.roll.AWS(config) |
| try: |
| - output = adapter.invoke('ssm', 'start-session', ['--target', iid, |
| + output = adapter.invoke('ssm', 'start-session', ['--target', target, |
| '--document-name', config['document'], '--parameters', json.dumps({'command': [cmd]})], |
| timeout=120, raw=True) |
| except BaseException: |
diff --git a/scripts/region_group_fault_test.py b/scripts/region_group_fault_test.py| index ebec23311..33ecf80e3 100644 |
| --- a/scripts/region_group_fault_test.py |
| +++ b/scripts/region_group_fault_test.py |
| @@ -528,6 +528,120 @@ class StaticTests(unittest.TestCase): |
| client.result(nonce + ':BEGIN\n{}\n' + nonce + ':END:1\n', nonce) |
| +class ClientArgvTests(unittest.TestCase): |
| + def setUp(self): |
| + base = os.environ.get('TMPDIR') or str(Path.home() / '.cache') |
| + tmp = tempfile.TemporaryDirectory(prefix='fault-argv-', dir=base) |
| + self.addCleanup(tmp.cleanup) |
| + self.root = Path(tmp.name) |
| + self.calls = self.root / 'calls.jsonl' |
| + (self.root / 'frame.txt').write_text(live.frame()) |
| + aws = self.root / 'aws' |
| + aws.write_text('#!' + sys.executable + '\n' + '''import os, pathlib, sys |
| +os.execv(str(pathlib.Path(__file__).with_name('session-manager-plugin')), sys.argv) |
| +''') |
| + plugin = self.root / 'session-manager-plugin' |
| + plugin.write_text('#!' + sys.executable + '\n' + r'''import json, pathlib, re, sys |
| +root = pathlib.Path(__file__).parent |
| +args = sys.argv[1:] |
| +with (root / 'calls.jsonl').open('a') as out: |
| + out.write(json.dumps(args) + '\n') |
| +assert args[12:14] == ['ssm', 'start-session'], args |
| +command = json.loads(args[args.index('--parameters') + 1])['command'][0] |
| +nonce = re.search(r'([0-9a-f]{32}):BEGIN', command)[1] |
| +print((root / 'frame.txt').read_text().replace('0' * 32, nonce), end='') |
| +''') |
| + aws.chmod(0o700) |
| + plugin.chmod(0o700) |
| + # A closed PATH cannot fall through to a real AWS CLI or plugin. |
| + self.env = dict(os.environ, PATH=str(self.root), PYTHONDONTWRITEBYTECODE='1') |
| + # -I omits the script directory; restore only that trusted path, as |
| + # Python does for the card's ordinary script invocation. |
| + launcher = ('import pathlib, runpy, sys; ' |
| + 'sys.argv = sys.argv[1:]; ' |
| + 'sys.path.insert(0, str(pathlib.Path(sys.argv[0]).parent)); ' |
| + 'runpy.run_path(sys.argv[0], run_name="__main__")') |
| + self.argv = [sys.executable, '-I', '-B', '-c', launcher, str(DIR / 'client.py'), |
| + '--profile', 'example', '--region', 'eu-west-1', |
| + '--document', 'example-document', '--target', IID] |
| + self.grammar = pattern(hashlib.sha256(bundle.build()).hexdigest()) |
| + |
| + def check_verb(self, verb, dry_run=False): |
| + args = ARGS if verb in {'arm-fault', 'arm-pause', 'fault-now'} else [] |
| + result = subprocess.run(self.argv + [verb, *args] + (['--dry-run'] if dry_run else []), |
| + env=self.env, cwd=self.root, capture_output=True, |
| + text=True, timeout=15) |
| + self.assertEqual(result.returncode, 0, result.stderr) |
| + self.assertEqual(result.stderr, '') |
| + if dry_run: |
| + self.assertFalse(self.calls.exists()) |
| + command = result.stdout.rstrip('\n') |
| + else: |
| + self.assertEqual(result.stdout, live.frame().splitlines()[1] + '\n') |
| + calls = [json.loads(line) for line in self.calls.read_text().splitlines()] |
| + self.assertEqual(len(calls), 1) |
| + call = calls[0] |
| + self.assertEqual(call[:14], ['--profile', 'example', '--region', 'eu-west-1', |
| + '--output', 'json', '--no-cli-pager', '--no-paginate', |
| + '--cli-connect-timeout', '2', '--cli-read-timeout', '2', 'ssm', 'start-session']) |
| + self.assertEqual(call[14:18], ['--target', IID, '--document-name', 'example-document']) |
| + self.assertEqual(call[18], '--parameters') |
| + self.assertEqual(len(call), 20) |
| + parameters = json.loads(call[19]) |
| + self.assertEqual(list(parameters), ['command']) |
| + self.assertEqual(len(parameters['command']), 1) |
| + command = parameters['command'][0] |
| + self.assertIsNotNone(self.grammar.fullmatch(command), command[:200]) |
| + self.assertIsNone(pattern().fullmatch(command)) |
| + inner = '/bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh ' + verb |
| + if args: |
| + inner += ' ' + ' '.join(args) |
| + self.assertIn(inner + '); result=$?;', shlex.split(command)[-1]) |
| + |
| + def test_install(self): |
| + self.check_verb('install') |
| + |
| + def test_status(self): |
| + self.check_verb('status') |
| + |
| + def test_arm_fault(self): |
| + self.check_verb('arm-fault') |
| + |
| + def test_arm_pause(self): |
| + self.check_verb('arm-pause') |
| + |
| + def test_fault_now(self): |
| + self.check_verb('fault-now') |
| + |
| + def test_disarm(self): |
| + self.check_verb('disarm') |
| + |
| + def test_remove(self): |
| + self.check_verb('remove') |
| + |
| + def test_uninstall(self): |
| + self.check_verb('uninstall') |
| + |
| + def test_every_verb_dry_run(self): |
| + for verb in ('install', 'status', 'arm-fault', 'arm-pause', 'fault-now', |
| + 'disarm', 'remove', 'uninstall'): |
| + with self.subTest(verb=verb): |
| + self.check_verb(verb, dry_run=True) |
| + |
| + def test_target_must_match_iid(self): |
| + for verb in ('arm-fault', 'arm-pause', 'fault-now'): |
| + for dry_run in (False, True): |
| + with self.subTest(verb=verb, dry_run=dry_run): |
| + args = ['--iid', 'i-11111111111111111', *ARGS[2:]] |
| + result = subprocess.run(self.argv + [verb, *args] + |
| + (['--dry-run'] if dry_run else []), env=self.env, cwd=self.root, |
| + capture_output=True, text=True, timeout=15) |
| + self.assertEqual(result.returncode, 2) |
| + self.assertEqual(result.stdout, '') |
| + self.assertIn(client.TEXT['required'], result.stderr) |
| + self.assertFalse(self.calls.exists()) |
| + |
| + |
| class ClientFixtureTests(unittest.TestCase): |
| def test_client_parses_live_frame_and_refuses_nonzero_or_missing_end(self): |
| raw = live.frame() |
diff --git a/scripts/region_group_probe_test.py b/scripts/region_group_probe_test.py| index 725c7227d..8823dc700 100644 |
| --- a/scripts/region_group_probe_test.py |
| +++ b/scripts/region_group_probe_test.py |
| @@ -11,9 +11,9 @@ import textwrap |
| import sys |
| import unittest |
| from unittest.mock import patch |
| -from contextlib import redirect_stdout, redirect_stderr |
| +from contextlib import closing, redirect_stdout, redirect_stderr |
| -from scripts.region_group_roll_test import Fake, Death, IID, PEER, OLD, NEW, test_config |
| +from scripts.region_group_roll_test import CLIHarness, Fake, Death, IID, PEER, OLD, NEW, test_config |
| SPEC = importlib.util.spec_from_file_location( |
| "region_group_probe", Path(__file__).with_name("region-group-probe.py")) |
| @@ -41,6 +41,55 @@ class ProbeFake(Fake): |
| raise |
| +class ProbeArgvTests(CLIHarness, unittest.TestCase): |
| + roll_module = roll |
| + entry = probe |
| + |
| + def assert_minimum_refused(self, tx): |
| + self.assert_first_group() |
| + self.assert_refusal("api") |
| + self.assertEqual(self.calls[-1][:2], ("autoscaling", "update-auto-scaling-group")) |
| + with closing(self.store.load(tx, readonly=True)) as journal: |
| + self.assertEqual(journal.events[0]["iid"], IID) |
| + self.assertEqual(journal.events[0]["header"]["kind"], "probe") |
| + self.assertEqual(journal.events[0]["attended_by"], "argv operator") |
| + self.assertEqual(journal.last("intent")["args"], {"value": 1}) |
| + self.assertEqual(journal.last("validated")["old"], OLD) |
| + |
| + def test_probe(self): |
| + self.assertEqual(self.cli("probe", "--member", IID), 1) |
| + tx = self.store.active_id() |
| + self.assertRegex(tx, r"^probe-[0-9a-f]{32}$") |
| + self.assert_minimum_refused(tx) |
| + |
| + def test_resume(self): |
| + tx = self.seed(kind="probe") |
| + self.assertEqual(self.cli("resume", "--transaction", tx), 1) |
| + self.assert_minimum_refused(tx) |
| + |
| + def test_status(self): |
| + tx = self.seed(kind="probe") |
| + before = {p.name: p.read_bytes() for p in self.store.directory.iterdir()} |
| + with self.store.lock(): |
| + self.assertEqual(self.cli("status", "--transaction", tx), 0) |
| + self.assertEqual(self.calls, []) |
| + self.assertEqual(self.stderr.getvalue(), "") |
| + status = json.loads(self.stdout.getvalue()) |
| + self.assertEqual((status["transaction"], status["iid"], status["new_sha256"]), (tx, IID, OLD)) |
| + self.assertEqual(before, {p.name: p.read_bytes() for p in self.store.directory.iterdir()}) |
| + |
| + def test_abandon(self): |
| + tx = self.seed(kind="probe", validated=False) |
| + self.assertEqual(self.cli("abandon", "--transaction", tx), 0) |
| + self.assertEqual(self.calls, []) |
| + self.assertEqual(self.stderr.getvalue(), "") |
| + self.assertIsNone(self.store.active_id()) |
| + with closing(self.store.load(tx, readonly=True)) as journal: |
| + self.assertEqual(journal.last("done")["outcome"], "abandoned") |
| + self.assertEqual(journal.last("abandoned")["attended_by"], "argv operator") |
| + self.assertIn(roll.TEXT["abandoned"], self.stdout.getvalue()) |
| + |
| + |
| class ProbeTests(unittest.TestCase): |
| def setUp(self): |
| self.tmp = tempfile.TemporaryDirectory(prefix="b1-test-") |
diff --git a/scripts/region_group_roll_test.py b/scripts/region_group_roll_test.py| index 737bcdfc2..79ce5f8ff 100644 |
| --- a/scripts/region_group_roll_test.py |
| +++ b/scripts/region_group_roll_test.py |
| @@ -1,6 +1,6 @@ |
| """Offline witnesses for the attended group maintenance transaction.""" |
| import copy |
| -from contextlib import closing |
| +from contextlib import closing, redirect_stderr, redirect_stdout |
| import importlib.util |
| import io |
| import json |
| @@ -285,6 +285,176 @@ class Fake: |
| raise AssertionError((op, a)) |
| +class CLIHarness: |
| + def setUp(self): |
| + base = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| + tmp = tempfile.TemporaryDirectory(prefix="region-argv-", dir=base) |
| + self.addCleanup(tmp.cleanup) |
| + self.config = test_config(tmp.name) |
| + self.config["document"] = "example-document" |
| + self.config_path = Path(tmp.name) / "config.json" |
| + self.config_path.write_text(json.dumps(self.config)) |
| + self.store = self.roll_module.State(self.config, owner=os.getuid()) |
| + self.fake = Fake(self.config) |
| + self.fake.now = time.time() |
| + self.fake.boxes = {iid: self.fake.box(iid) for iid in (IID, PEER)} |
| + self.fake.published = {iid: self.fake.now - 5 for iid in (IID, PEER)} |
| + self.template = self.fake.fixture("describe-auto-scaling-groups.json")["AutoScalingGroups"][0]["LaunchTemplate"] |
| + self.calls = [] |
| + self.stdout, self.stderr = io.StringIO(), io.StringIO() |
| + |
| + def invoke(self, adapter, service, verb, args, **kwargs): |
| + self.assertEqual(adapter.c, self.config) |
| + self.calls.append((service, verb, copy.deepcopy(args), kwargs)) |
| + if (service, verb) == ("ssm", "start-session"): |
| + iid = args[1] |
| + self.assertIn(iid, (IID, PEER)) |
| + self.assertEqual(args[:4], ["--target", iid, "--document-name", "example-document"]) |
| + self.assertEqual(args[4], "--parameters") |
| + self.assertEqual(len(args), 6) |
| + command = json.loads(args[5])["command"][0] |
| + nonce = re.search(r"([0-9a-f]{32}):BEGIN", command)[1] |
| + if "group-maintenance prepare " in command: |
| + self.assertEqual(iid, IID) |
| + self.assertIn("group-maintenance prepare --sha256 " + NEW, shlex.split(command)[-1]) |
| + self.assertEqual(kwargs, dict(timeout=360, raw=True)) |
| + raise self.roll_module.Refusal(self.roll_module.TEXT["api"]) |
| + self.assertIn("group-maintenance status); result=$?;", shlex.split(command)[-1]) |
| + self.assertEqual(kwargs, dict(timeout=15, raw=True)) |
| + return live.frame().replace(live.NONCE, nonce).replace( |
| + live.frame().splitlines()[1], json.dumps(self.fake.boxes[iid])) |
| + if (service, verb) == ("autoscaling", "update-auto-scaling-group"): |
| + self.assertEqual(args, ["--auto-scaling-group-name", self.config["group"], "--min-size", "1"]) |
| + raise self.roll_module.Refusal(self.roll_module.TEXT["api"]) |
| + self.assertIn((service, verb), { |
| + ("autoscaling", "describe-auto-scaling-groups"), |
| + ("autoscaling", "describe-auto-scaling-instances"), |
| + ("autoscaling", "describe-lifecycle-hooks"), |
| + ("autoscaling", "describe-scaling-activities"), |
| + ("elbv2", "describe-target-health"), |
| + ("ssm", "describe-instance-information"), |
| + ("s3api", "get-object"), |
| + }) |
| + return self.fake.invoke(service, verb, args, **kwargs) |
| + |
| + def cli(self, *args): |
| + state_class = self.roll_module.State |
| + with patch.object(self.roll_module.os, "geteuid", return_value=0), \ |
| + patch.object(self.roll_module, "State", side_effect=lambda c, **kw: |
| + state_class(c, owner=os.getuid(), **kw)), \ |
| + patch.object(self.roll_module.AWS, "invoke", autospec=True, side_effect=self.invoke), \ |
| + redirect_stdout(self.stdout), redirect_stderr(self.stderr): |
| + return self.entry.main(["--config", str(self.config_path), |
| + "--attended-by", "argv operator", *args]) |
| + |
| + def seed(self, kind="roll", validated=True): |
| + tx = "probe-argv-test" if kind == "probe" else "argv-test" |
| + with self.store.lock(), closing(self.store.create(dict( |
| + kind=kind, transaction=tx, config=self.config, iid=IID, |
| + new=NEW, attended_by="argv operator"))) as journal: |
| + if validated: |
| + status = self.fake.boxes[IID] |
| + journal.add("validated", old=OLD, new=OLD if kind == "probe" else NEW, |
| + n=2, members=sorted((IID, PEER)), template=self.template, |
| + original_process=status["edge"]["identity"], |
| + identity={k: status[k] for k in |
| + ("iid", "boot_id", "account", "region", "group", "config_digest", "box_ref")}) |
| + return tx |
| + |
| + def assert_first_group(self): |
| + self.assertEqual(self.calls[0], ("autoscaling", "describe-auto-scaling-groups", |
| + ["--auto-scaling-group-names", self.config["group"]], {})) |
| + |
| + def assert_refusal(self, reason): |
| + self.assertEqual(self.stderr.getvalue(), |
| + self.roll_module.TEXT["refused"].format(reason=self.roll_module.TEXT[reason]) + "\n") |
| + |
| + |
| +class RollArgvTests(CLIHarness, unittest.TestCase): |
| + roll_module = entry = roll |
| + |
| + def setUp(self): |
| + super().setUp() |
| + with self.store.lock(): |
| + self.store.write(self.store.observation, dict(v=1, group_arn=self.config["group_arn"], |
| + hook=self.config["hook"], template=self.template, documented_no_hook=True)) |
| + |
| + def test_plan(self): |
| + self.assertEqual(self.cli("plan", "--member", IID, "--to-sha256", NEW), 0) |
| + self.assert_first_group() |
| + self.assertEqual(self.stderr.getvalue(), "") |
| + paths = list(self.store.directory.glob("plan-*.log")) |
| + self.assertEqual(len(paths), 1) |
| + with closing(roll.Journal(paths[0], os.getuid(), readonly=True)) as journal: |
| + self.assertEqual(journal.last("done")["refusals"], []) |
| + self.assertEqual(journal.events[0]["attended_by"], "argv operator") |
| + |
| + def check_roll(self, transaction=None): |
| + args = ["roll", "--member", IID, "--to-sha256", NEW] |
| + if transaction is not None: |
| + args += ["--transaction", transaction] |
| + self.assertEqual(self.cli(*args), 1) |
| + self.assert_first_group() |
| + self.assert_refusal("api") |
| + tx = self.store.active_id() |
| + if transaction is None: |
| + self.assertRegex(tx, r"^[0-9a-f]{32}$") |
| + else: |
| + self.assertEqual(tx, transaction) |
| + with closing(self.store.load(tx, readonly=True)) as journal: |
| + self.assertEqual(journal.events[0]["iid"], IID) |
| + self.assertEqual(journal.events[0]["new"], NEW) |
| + self.assertEqual(journal.events[0]["attended_by"], "argv operator") |
| + self.assertIsNotNone(journal.last("validated")) |
| + self.assertEqual(journal.last("intent")["args"], dict(iid=IID, verb="prepare", sha256=NEW)) |
| + |
| + def test_roll_generated_transaction(self): |
| + self.check_roll() |
| + |
| + def test_roll_chosen_transaction(self): |
| + self.check_roll("B6_fault-2026_11_05") |
| + |
| + def test_resume(self): |
| + tx = self.seed() |
| + self.assertEqual(self.cli("resume", "--transaction", tx), 1) |
| + self.assertEqual(len(self.calls), 1) |
| + self.assertEqual(self.calls[0][:2], ("ssm", "start-session")) |
| + self.assert_refusal("api") |
| + |
| + def test_status(self): |
| + tx = self.seed() |
| + before = {p.name: p.read_bytes() for p in self.store.directory.iterdir()} |
| + with self.store.lock(): |
| + self.assertEqual(self.cli("status", "--transaction", tx), 0) |
| + self.assertEqual(self.calls, []) |
| + self.assertEqual(self.stderr.getvalue(), "") |
| + status = json.loads(self.stdout.getvalue()) |
| + self.assertEqual((status["transaction"], status["iid"], status["new_sha256"]), (tx, IID, NEW)) |
| + self.assertEqual(before, {p.name: p.read_bytes() for p in self.store.directory.iterdir()}) |
| + |
| + def test_return(self): |
| + tx = self.seed() |
| + self.assertEqual(self.cli("return", "--transaction", tx), 1) |
| + self.assert_first_group() |
| + self.assert_refusal("return_intent") |
| + |
| + def test_rollback(self): |
| + tx = self.seed() |
| + self.assertEqual(self.cli("rollback", "--member", IID, "--transaction", tx), 1) |
| + self.assertEqual(self.calls[0][:2], ("ssm", "start-session")) |
| + self.assert_refusal("held") |
| + |
| + def test_abandon(self): |
| + tx = self.seed(validated=False) |
| + self.assertEqual(self.cli("abandon", "--transaction", tx), 0) |
| + self.assertEqual(self.calls, []) |
| + self.assertEqual(self.stderr.getvalue(), "") |
| + self.assertIsNone(self.store.active_id()) |
| + with closing(self.store.load(tx, readonly=True)) as journal: |
| + self.assertEqual(journal.last("done")["outcome"], "abandoned") |
| + self.assertEqual(journal.last("abandoned")["attended_by"], "argv operator") |
| + |
| + |
| class StandbyTests(unittest.TestCase): |
| def setUp(self): |
| base = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |