carlos / platform Public

scripts: ppv2-step reverify and a 5 s clock tolerance on spans

Controller rulings on fix round 1:
- reverify gives a step already made (TG in its target state) a full
  fresh convergence window anchored on verified_at, with the chain,
  lock, target set, NLB-bound probes and the step kind's barrier rule.
  Earlier verdicts stay in the record's history; downstream steps bind
  to the latest of applied_at and verified_at. It also adopts an
  intent left by a tofu apply that failed after changing the attribute.
- span checks allow 5 s between probe-host and operator-host clocks
  and record it; the probe-after-anchor check stays strict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a47ca6b5a19cc43ec474ddff2630bfc4b97d2ba7 parent 1077a2e
2 files changed, +344 −63
  • scripts/ppv2-step.py +194 −55
  • scripts/ppv2_step_test.py +150 −8
diff --git a/scripts/ppv2-step.py b/scripts/ppv2-step.py
index 244de4507..dc4ce944c 100755
--- a/scripts/ppv2-step.py
+++ b/scripts/ppv2-step.py
@@ -23,9 +23,17 @@ them changes PPv2 while preservation is off, so no node can pass through S3.
it polls target health every 10 s and trust counters every 30 s
until the probe records are in, and writes <step>.json, the next
step's evidence. Forward steps need --probe-records.
- converge resumes the convergence of the latest apply of a step, after an
- interrupted apply. Polls already made for that apply count, and a
- failure already seen is never cleared.
+ converge resumes the convergence of the latest apply (or reverify) of a
+ step, after an interruption. Polls already made for it count, and
+ a failure already seen is never cleared.
+ reverify a full fresh convergence window for a step already made: the
+ target group must already be in the step's target state. It
+ writes <step>-verified.json (verified_at plays the part of
+ applied_at) and a new <step>.json; earlier verdicts stay in its
+ history. After a failed convergence this is the way on (A steps
+ cannot be undone); after a tofu apply that failed once it had
+ changed the attribute, it adopts <step>-intent.json. Each step
+ binds to the latest of its predecessor's apply and reverify.
Steps: A80, A443 (PPv2 on), B80, B443 (preservation off), R443, R80
(preservation back on). Nothing turns PPv2 off; there is no step for it.
@@ -36,8 +44,8 @@ in the root directory, which this script owns:
"ppv2_proxy_protocol_v2":{"80":false,"443":false}}
Records, in --record-dir: prereq.json, <step>-intent.json (written before
-tofu apply starts), <step>-applied.json, <step>-polls.jsonl (every poll, as
-it is made) and <step>.json. A run holds .ppv2-step.lock in the root and in
+tofu apply starts), <step>-applied.json, <step>-verified.json (reverify),
+<step>-polls.jsonl (every poll, as it is made) and <step>.json. A run holds .ppv2-step.lock in the root and in
the record directory; a second run refuses while one is held.
Exit codes: 0 done or passed, 1 refused or failed, 2 invalid arguments,
@@ -99,6 +107,8 @@ HEALTH_EVERY = 10.0
# change a target's state, so a target reported unhealthy stays so for at
# least 20 s. Observations at most 15 s apart cannot miss one.
HEALTH_GAP_MAX = 15.0
+# The probe host's clock against this host's, in the span checks only.
+CLOCK_TOLERANCE = 5.0
TRUST_EVERY = 30.0
SSM_BOUND = 120.0
TICK = 1.0
@@ -477,13 +487,42 @@ def record_refusal(name, record_dir, nlb_arn):
return None
if record.get('step') != name:
return f"{name}.json is a record of {record.get('step')}"
- applied = load_record(record_dir / f'{name}-applied.json')
- if applied is None or applied.get('applied_at') != record.get('applied_at') or applied.get('nlb_arn') != nlb_arn:
- return (f"{name}.json is not for its latest apply ({name}-applied.json applied_at "
- f"{(applied or {}).get('applied_at')}, {name}.json {record.get('applied_at')})")
+ latest = latest_anchor(record_dir, name, nlb_arn)
+ if latest is None or record_anchor(latest) != record_anchor(record):
+ return (f"{name}.json is not for its latest apply or reverify (latest {record_anchor(latest or {})}, "
+ f"{name}.json {record_anchor(record)})")
return None
+def record_anchor(record):
+ """The moment a record's evidence counts from: its reverify, else its apply."""
+ return record.get('verified_at') or record.get('applied_at')
+
+
+def anchor_kind(record):
+ return 'reverify' if record.get('verified_at') else 'apply'
+
+
+def latest_anchor(record_dir, step, nlb_arn):
+ """The later of <step>-applied.json and <step>-verified.json for this NLB, or None."""
+ found = [r for r in (load_record(record_dir / f'{step}-applied.json'),
+ load_record(record_dir / f'{step}-verified.json'))
+ if r and r.get('nlb_arn') == nlb_arn and record_anchor(r)]
+ return max(found, key=lambda r: epoch(record_anchor(r)) or 0) if found else None
+
+
+def intent_pending(record_dir, step):
+ """<step>-intent.json when no apply or reverify record has taken it up yet."""
+ intent = load_record(record_dir / f'{step}-intent.json')
+ if not intent:
+ return None
+ for name in (f'{step}-applied.json', f'{step}-verified.json'):
+ record = load_record(record_dir / name)
+ if record and record.get('intent_started_at') == intent.get('started_at'):
+ return None
+ return intent
+
+
def chain_refusal(step, record_dir, nlb_arn):
"""Every record back to prereq.json: passed, this NLB, bound to its latest apply."""
name = PREDECESSOR[step]
@@ -551,14 +590,101 @@ def target_list(text):
def pending_intent(record_dir, step):
- intent = load_record(record_dir / f'{step}-intent.json')
- applied = load_record(record_dir / f'{step}-applied.json')
- if intent and (not applied or applied.get('intent_started_at') != intent.get('started_at')):
+ intent = intent_pending(record_dir, step)
+ if intent:
return (f' ({step}-intent.json records an apply started at {intent.get("started_at")} that wrote no '
- f'{step}-applied.json; see its tfvars_before)')
+ f'{step}-applied.json; see its tfvars_before, or adopt it with reverify if the live attribute changed)')
return ''
+def collect_baseline(cloud, step, targets):
+ """(time, {instance: trust-status or why none}), refused by the step kind's rules:
+ A and B need every target armed, B also every barrier down; R refuses nothing."""
+ baseline_at = cloud.clock.time()
+ try:
+ baseline = cloud.trust(targets)
+ except Refused as err:
+ if step.forward:
+ raise
+ # Rollback is the safe direction and is most needed when boxes are unwell.
+ baseline = {iid: f'trust-status not collected: {err}' for iid in targets}
+ if step.forward:
+ for iid in targets:
+ status = baseline[iid]
+ if isinstance(status, str):
+ raise Refused(status)
+ if not status['armed']:
+ raise Refused(f'{iid} is not armed')
+ # In S0 and S1 no client is trusted, so an A step is allowed behind a
+ # barrier: it is the way forward again after an S3 incident (spec 6.5).
+ if status['barrier'] and step.attribute == 'preserve_client_ip':
+ raise Refused(f'the trust barrier is up on {iid}; no B step while it is up (spec 4.7)')
+ return baseline_at, baseline
+
+
+def cmd_reverify(args, cloud):
+ """A fresh observation window for a step already made: the target group is
+ in the step's target state, and its latest evidence failed or is missing
+ (or tofu apply failed after it changed the attribute, and this adopts it)."""
+ step = STEPS[args.step]
+ if step.port != args.port:
+ raise Refused(f'step {args.step} is for port {step.port}, not {args.port}')
+ record_dir, root = Path(args.record_dir), Path(args.root)
+ for d, flag in ((record_dir, '--record-dir'), (root, '--root')):
+ if not d.is_dir():
+ raise Refused(f'{flag} {d} is not a directory')
+ targets = target_list(args.targets)
+ paths = split(args.probe_records)
+ with locked(root, record_dir):
+ check_state_address(cloud, args)
+ cloud.target_group(args.tg_arn, args.nlb_arn, args.port)
+ live = cloud.attributes(args.tg_arn)
+ state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])
+ if state != step.target:
+ raise Refused(f'reverify {args.step}: the target group is in {state}, not {step.target}; '
+ 'reverify only observes a step already made')
+ reason = chain_refusal(args.step, record_dir, args.nlb_arn)
+ if reason:
+ raise Refused(reason)
+ public = prereq_for(record_dir, args.nlb_arn)['public_addresses']
+ if len(paths) != len(public):
+ raise Refused(f'--probe-records needs one record per NLB address ({len(public)}: {", ".join(public)})')
+ made = {'nlb_arn': args.nlb_arn, 'port': args.port, 'tg_arn': args.tg_arn}
+ applied = load_record(record_dir / f'{args.step}-applied.json')
+ if applied and any(applied.get(k) != v for k, v in made.items()):
+ applied = None
+ intent = intent_pending(record_dir, args.step)
+ if intent and any(intent.get(k) != v for k, v in dict(made, step=args.step).items()):
+ raise Refused(f'{args.step}-intent.json is not for this step and target group; reconcile it by hand')
+ if not applied and not intent:
+ raise Refused(f'nothing to reverify: no {args.step}-applied.json or {args.step}-intent.json for '
+ 'this target group')
+ try:
+ doc = json.loads((root / TFVARS_FILE).read_bytes())
+ except (OSError, ValueError) as err:
+ raise Refused(f'cannot read {root / TFVARS_FILE}: {err}')
+ reason = tfvars_check(doc, args.port, live)
+ if reason:
+ raise Refused(reason)
+ reasons = registered_refusals(cloud.health(args.tg_arn), targets)
+ if reasons:
+ raise Refused('every target must be registered and healthy: ' + '; '.join(reasons))
+ baseline_at, baseline = collect_baseline(cloud, step, targets)
+ verified_at = cloud.clock.time()
+ verified = {
+ 'nlb_arn': args.nlb_arn, 'port': args.port, 'step': args.step, 'tg_arn': args.tg_arn,
+ 'tg_address': args.tg_address, 'targets': targets, 'from': step.source, 'to': step.target,
+ 'baseline': baseline, 'baseline_at': iso(baseline_at), 'verified_at': iso(verified_at),
+ 'applied_at': (applied or {}).get('applied_at'),
+ 'intent_started_at': intent['started_at'] if intent else (applied or {}).get('intent_started_at'),
+ 'adopted_intent': bool(intent)}
+ write_record(record_dir / f'{args.step}-verified.json', verified)
+ print(f'{args.step} reverify started at {iso(verified_at)}'
+ f"{' (adopting ' + args.step + '-intent.json)' if intent else ''}: the target group is in {step.target}.")
+ print(f'Converging: start the probes on {len(paths)} NLB addresses now; waiting for {", ".join(paths)}.')
+ return converge(cloud, record_dir, verified, paths, args.timeout)
+
+
def cmd_apply(args, cloud):
step = STEPS[args.step]
if step.port != args.port:
@@ -589,25 +715,7 @@ def cmd_apply(args, cloud):
reasons = registered_refusals(cloud.health(args.tg_arn), targets)
if step.forward and reasons:
raise Refused('every target must be registered and healthy: ' + '; '.join(reasons))
- baseline_at = cloud.clock.time()
- try:
- baseline = cloud.trust(targets)
- except Refused as err:
- if step.forward:
- raise
- # Rollback is the safe direction and is most needed when boxes are unwell.
- baseline = {iid: f'trust-status not collected: {err}' for iid in targets}
- if step.forward:
- for iid in targets:
- status = baseline[iid]
- if isinstance(status, str):
- raise Refused(status)
- if not status['armed']:
- raise Refused(f'{iid} is not armed')
- # In S0 and S1 no client is trusted, so an A step is allowed behind a
- # barrier: it is the way forward again after an S3 incident (spec 6.5).
- if status['barrier'] and step.attribute == 'preserve_client_ip':
- raise Refused(f'the trust barrier is up on {iid}; no B step while it is up (spec 4.7)')
+ baseline_at, baseline = collect_baseline(cloud, step, targets)
tfvars = root / TFVARS_FILE
try:
original = tfvars.read_bytes()
@@ -696,18 +804,19 @@ def supersede(record_dir, forward, applied_at):
if not forward:
return
stamp = re.sub(r'[^0-9]', '', applied_at)
- for name in (f'{forward}.json', f'{forward}-applied.json'):
+ for name in (f'{forward}.json', f'{forward}-applied.json', f'{forward}-verified.json'):
path = record_dir / name
if path.exists():
os.replace(path, record_dir / name.replace('.json', f'.superseded-{stamp}.json'))
class PollLog:
- """Every observation for one apply, appended as it is made, so an
- interrupted run's polls (and any failure they saw) survive into a resume."""
+ """Every observation for one apply or reverify (its anchor), appended as it
+ is made, so an interrupted run's polls (and any failure they saw) survive
+ into a resume."""
- def __init__(self, path, applied_at):
- self.path, self.applied_at = path, applied_at
+ def __init__(self, path, anchor):
+ self.path, self.anchor = path, anchor
def read(self):
try:
@@ -720,12 +829,12 @@ class PollLog:
entry = json.loads(line)
except ValueError:
continue # a line cut short by a kill
- if entry.get('applied_at') == self.applied_at:
+ if entry.get('anchor') == self.anchor:
out.append(entry)
return out
def add(self, entry):
- entry = dict(entry, applied_at=self.applied_at)
+ entry = dict(entry, anchor=self.anchor)
with open(self.path, 'a') as f:
f.write(json.dumps(entry, sort_keys=True) + '\n')
f.flush()
@@ -790,10 +899,11 @@ def converge(cloud, record_dir, applied, paths, timeout):
if len(paths) != len(prereq['public_addresses']):
raise Refused(f"converge needs one probe record per NLB address ({len(prereq['public_addresses'])}: "
f"{', '.join(prereq['public_addresses'])})")
+ anchor = record_anchor(applied)
prior = load_record(record_dir / f'{step}.json')
- if prior and prior.get('applied_at') == applied['applied_at'] and prior.get('passed') is True:
- raise Refused(f'{step}.json already passed for the apply at {applied["applied_at"]}; nothing to resume')
- log = PollLog(record_dir / f'{step}-polls.jsonl', applied['applied_at'])
+ if prior and record_anchor(prior) == anchor and prior.get('passed') is True:
+ raise Refused(f'{step}.json already passed for the {anchor_kind(applied)} at {anchor}; nothing to resume')
+ log = PollLog(record_dir / f'{step}-polls.jsonl', anchor)
targets = applied['targets']
def poll_health():
@@ -844,8 +954,14 @@ def converge(cloud, record_dir, applied, paths, timeout):
f'{log.path.name}; resume with converge')
reasons, summary = evaluate(step, applied, log.read(), load_probes(paths), prereq, prior)
passed = not reasons
+ # Earlier verdicts for this step (earlier applies or reverifies) are kept,
+ # never cleared; only this anchor's full window decides `passed`.
+ history = list((prior or {}).get('history') or [])
+ if prior and record_anchor(prior) != anchor:
+ history.append({k: prior.get(k) for k in ('applied_at', 'verified_at', 'converged_at', 'passed', 'reasons')})
record = dict(summary, nlb_arn=applied['nlb_arn'], port=applied['port'], step=step, tg_arn=applied['tg_arn'],
- applied_at=applied['applied_at'], converged_at=iso(clock.time()), passed=passed, reasons=reasons,
+ applied_at=applied.get('applied_at'), verified_at=applied.get('verified_at'),
+ converged_at=iso(clock.time()), passed=passed, reasons=reasons, history=history,
targets=targets, polls=log.path.name,
proxied_scope='proxied_by_node sums both listeners (:80 and :443)')
write_record(record_dir / f'{step}.json', record)
@@ -861,7 +977,8 @@ def probe_findings(docs, applied, step, public):
"""(reasons, summaries, window) for the probe records against the apply and the NLB."""
reasons, summaries, starts, finishes, addresses = [], [], [], [], []
expect = PROBE_EXPECT[step[0]]
- applied_at = epoch(applied['applied_at'])
+ applied_at = epoch(record_anchor(applied))
+ kind = anchor_kind(applied)
for path, doc in docs:
name = Path(path).name
if doc is None:
@@ -876,8 +993,10 @@ def probe_findings(docs, applied, step, public):
if doc.get('expect') != expect:
reasons.append(f"probe record {name} expected {doc.get('expect')}; step {step} needs {expect}")
started, finished = epoch(doc.get('started_at')), epoch(doc.get('finished_at'))
+ # Strict, no clock tolerance: in a B step S1 and S2 answer alike, so an
+ # attempt from before the change could otherwise count as evidence.
if started is None or started <= applied_at:
- reasons.append(f"probe record {name} started before the apply ({doc.get('started_at')})")
+ reasons.append(f"probe record {name} started before the {kind} ({doc.get('started_at')})")
if finished is None or (started is not None and finished < started):
reasons.append(f"probe record {name} has no usable finished_at ({doc.get('finished_at')})")
if started is not None:
@@ -917,13 +1036,16 @@ def coverage_reasons(times, window, gap, what):
return []
start, end = window
times = sorted(times)
- before = [t for t in times if t <= start]
- after = [t for t in times if t >= end]
+ # The window is in the probe host's clock, the observations in this host's.
+ before = [t for t in times if t <= start + CLOCK_TOLERANCE]
+ after = [t for t in times if t >= end - CLOCK_TOLERANCE]
reasons = []
if not before:
- reasons.append(f'{what} was not observed before the earliest probe started ({iso(start)})')
+ reasons.append(f'{what} was not observed before the earliest probe started ({iso(start)}, '
+ f'{CLOCK_TOLERANCE:g} s clock tolerance)')
if not after:
- reasons.append(f'{what} was not observed after the latest probe finished ({iso(end)})')
+ reasons.append(f'{what} was not observed after the latest probe finished ({iso(end)}, '
+ f'{CLOCK_TOLERANCE:g} s clock tolerance)')
if gap is not None and before and after:
span = [t for t in times if before[-1] <= t <= after[0]]
for a, b in zip(span, span[1:]):
@@ -956,7 +1078,7 @@ def trust_findings(status, base, iid, step):
def evaluate(step, applied, polls, docs, prereq, prior):
"""(reasons, summary): the whole verdict, from the apply, every poll and the probe records."""
reasons = []
- if prior and prior.get('applied_at') == applied['applied_at'] and prior.get('passed') is False:
+ if prior and record_anchor(prior) == record_anchor(applied) and prior.get('passed') is False:
reasons.extend(r if r.startswith('earlier run: ') else f'earlier run: {r}' for r in prior.get('reasons') or [])
targets, baseline = applied['targets'], applied.get('baseline') or {}
if set(baseline) != set(targets):
@@ -1000,7 +1122,10 @@ def evaluate(step, applied, polls, docs, prereq, prior):
reasons.append(f"the target group is in {last_state['state']}, not {STEPS[step].target}")
unique = list(dict.fromkeys(reasons))
summary = {'probes': probes, 'health_polls': len(health), 'trust_polls': len(trust),
- 'window': [iso(window[0]), iso(window[1])] if window else None}
+ 'window': [iso(window[0]), iso(window[1])] if window else None,
+ 'clock_tolerance_s': CLOCK_TOLERANCE,
+ 'clock_tolerance': 'span checks only: probe-host times against this host\'s polls; '
+ 'the probe-after-anchor check is strict'}
return unique, summary
@@ -1009,9 +1134,12 @@ def cmd_converge(args, cloud):
paths = split(args.probe_records)
targets = target_list(args.targets)
with locked(record_dir):
- applied = load_record(record_dir / f'{args.step}-applied.json')
+ # The latest of the step's apply and reverify: that is what a resume continues.
+ candidates = [r for r in (load_record(record_dir / f'{args.step}-applied.json'),
+ load_record(record_dir / f'{args.step}-verified.json')) if r and record_anchor(r)]
+ applied = max(candidates, key=lambda r: epoch(record_anchor(r)) or 0) if candidates else None
if applied is None:
- raise Refused(f'no {args.step}-applied.json in {record_dir}; run apply first')
+ raise Refused(f'no {args.step}-applied.json or {args.step}-verified.json in {record_dir}; run apply first')
if applied.get('step') != args.step or applied.get('tg_arn') != args.tg_arn:
raise Refused(f'{args.step}-applied.json is for {applied.get("step")} on {applied.get("tg_arn")}')
if sorted(targets) != sorted(applied.get('targets') or []):
@@ -1107,7 +1235,16 @@ def parser():
c.add_argument('--record-dir', required=True)
c.add_argument('--probe-records', required=True, help='one probe record path per NLB address, comma-separated')
c.add_argument('--tg-arn', required=True)
- for s in (a, c):
+ v = sub.add_parser('reverify', help='a fresh convergence window for a step already made')
+ v.add_argument('--root', required=True, help='the tofu root directory holding ppv2.auto.tfvars.json')
+ v.add_argument('--nlb-arn', required=True)
+ v.add_argument('--tg-arn', required=True)
+ v.add_argument('--tg-address', required=True, help='the target group\'s tofu address')
+ v.add_argument('--port', required=True, choices=['80', '443'])
+ v.add_argument('--step', required=True, choices=list(STEPS))
+ v.add_argument('--record-dir', required=True)
+ v.add_argument('--probe-records', required=True, help='one probe record path per NLB address, comma-separated')
+ for s in (a, c, v):
s.add_argument('--timeout', type=float, default=1800.0, help='seconds to wait for the probe records')
r = sub.add_parser('prereq', help='the automated prerequisite checks; writes prereq.json')
r.add_argument('--nlb-arn', required=True)
@@ -1116,7 +1253,7 @@ def parser():
r.add_argument('--sources', required=True, help='the ingress module\'s proxy_protocol_sources, comma-separated')
r.add_argument('--alarm', required=True, help='the proxy trust alarm name')
r.add_argument('--record-dir', required=True)
- for s in (a, c, r):
+ for s in (a, c, v, r):
s.add_argument('--profile', required=True)
s.add_argument('--region', required=True)
s.add_argument('--targets', required=True, help='every target instance id, comma-separated')
@@ -1133,6 +1270,8 @@ def main(argv=None):
return cmd_apply(args, cloud)
if args.command == 'converge':
return cmd_converge(args, cloud)
+ if args.command == 'reverify':
+ return cmd_reverify(args, cloud)
return cmd_prereq(args, cloud)
except Refused as err:
print(f'refused: {one_line(err)}', file=sys.stderr)
diff --git a/scripts/ppv2_step_test.py b/scripts/ppv2_step_test.py
index 936b7b903..d7e06abd5 100644
--- a/scripts/ppv2_step_test.py
+++ b/scripts/ppv2_step_test.py
@@ -345,14 +345,14 @@ class Harness(unittest.TestCase):
def ops(self):
return [c.get('op') or ' '.join(c['args'][:2]) for c in self.calls()]
- def apply_args(self, step, port=None, targets=None, nlb=NLB, probes=None, timeout='60'):
+ def apply_args(self, step, port=None, targets=None, nlb=NLB, probes=None, timeout='60', command='apply'):
port = port or STEP_PLAN.get(step, ('80',))[0]
- args = ['apply', '--root', str(self.root), '--profile', 'kass', '--region', 'eu-west-1',
+ args = [command, '--root', str(self.root), '--profile', 'kass', '--region', 'eu-west-1',
'--nlb-arn', nlb, '--tg-arn', TG[port], '--tg-address', ADDR[port],
'--port', port, '--step', step, '--targets', ','.join(targets or TARGETS),
'--record-dir', str(self.records), '--timeout', timeout]
if probes is None:
- probes = not step.startswith('R')
+ probes = command == 'reverify' or not step.startswith('R')
if probes:
args += ['--probe-records', ','.join(str(self.probes / n) for n in ('a.json', 'b.json'))]
return args
@@ -360,14 +360,16 @@ class Harness(unittest.TestCase):
def apply(self, step, expect=None, **kw):
return self.run_step(*self.apply_args(step, **kw), expect=expect)
- def apply_converging(self, step, expect=0, **kw):
- """apply, with both probes started once the apply is in, as an operator would."""
+ def apply_converging(self, step, expect=0, command='apply', **kw):
+ """apply (or reverify), with both probes started once its anchor record
+ is written, as an operator would."""
port = STEP_PLAN[step][0]
- applied = self.records / f'{step}-applied.json'
+ anchor = self.records / f"{step}-{'verified' if command == 'reverify' else 'applied'}.json"
+ was = anchor.stat().st_mtime_ns if anchor.exists() else None
stop = threading.Event()
def writer():
- while not applied.exists():
+ while not anchor.exists() or anchor.stat().st_mtime_ns == was:
if stop.wait(0.02):
return
start = time.time() + 1.0
@@ -376,11 +378,15 @@ class Harness(unittest.TestCase):
thread = threading.Thread(target=writer)
thread.start()
try:
- return self.apply(step, expect=expect, probes=True, **kw)
+ return self.apply(step, expect=expect, probes=True, command=command, **kw)
finally:
stop.set()
thread.join()
+ def reload_world(self):
+ """The fake tofu apply moves target groups in the world file; take that up."""
+ self.world = json.loads(self.world_path.read_text())
+
def record(self, name, **values):
(self.records / (name + '.json')).write_text(json.dumps(values))
@@ -876,6 +882,118 @@ class StepGateTests(Harness):
self.assert_refused(self.run_step(*args, '--targets', ','.join(TARGETS)), 'already passed')
+class ReverifyTests(Harness):
+ def reverify(self, step, expect=None, **kw):
+ return self.run_step(*self.apply_args(step, command='reverify', **kw), expect=expect)
+
+ def record_of(self, name):
+ return json.loads((self.records / (name + '.json')).read_text())
+
+ def test_reverify_unblocks_after_failed_convergence(self):
+ # A80 applies, then one health poll during its convergence is unhealthy: A80.json fails.
+ self.ready_for('A80')
+ self.world['health'][TG['80']] = [[[t, 'healthy'] for t in TARGETS],
+ [[TARGETS[0], 'healthy'], [TARGETS[1], 'unhealthy']],
+ [[t, 'healthy'] for t in TARGETS]]
+ self.apply_converging('A80', expect=1)
+ failed = self.record_of('A80')
+ self.assertFalse(failed['passed'])
+ self.reload_world()
+ # A80 cannot be undone, and A443 is blocked on it.
+ self.world['plan'] = plan_for_step('A443')
+ self.world['on_apply'] = {TG['443']: attributes('S1')}
+ self.assert_refused(self.apply('A443'), 'A80.json did not pass')
+ # A fresh window for A80, behind a barrier (allowed for an A step): passes.
+ self.world['trust'][TARGETS[1]] = [trust('barrier_up')]
+ self.apply_converging('A80', command='reverify')
+ record = self.record_of('A80')
+ verified = self.record_of('A80-verified')
+ self.assertTrue(record['passed'], record['reasons'])
+ self.assertEqual(verified['verified_at'], record['verified_at'])
+ self.assertEqual(failed['applied_at'], record['applied_at'])
+ self.assertGreater(record['verified_at'], record['applied_at'])
+ # The earlier failure is kept.
+ self.assertEqual(1, len(record['history']))
+ self.assertFalse(record['history'][0]['passed'])
+ self.assertTrue(any(TARGETS[1] + ' is unhealthy' in r for r in record['history'][0]['reasons']))
+ # Nothing about the target group changed: no tofu plan or apply in the reverify.
+ self.assertEqual(1, self.tofu_ops().count('apply'))
+ # A443 now binds to A80's reverify and goes through.
+ self.apply_converging('A443')
+ self.assertTrue(self.record_of('A443')['passed'])
+
+ def test_reverify_probes_before_verified_at_fail(self):
+ self.ready_for('A80')
+ self.apply_converging('A80')
+ self.reload_world()
+ # Probe records from before the reverify started: they are not its evidence.
+ start = time.time()
+ for name, ip in zip(('a.json', 'b.json'), PUBLIC):
+ (self.probes / name).write_text(json.dumps(probe_doc(ip, 80, 's1', start, start + 2.5)))
+ result = self.reverify('A80')
+ self.assertEqual(1, result.returncode, result.stderr)
+ record = self.record_of('A80')
+ self.assertFalse(record['passed'])
+ self.assertTrue(any('started before the reverify' in r for r in record['reasons']), record['reasons'])
+ # The passed apply window is history; the step is now held on its latest evidence.
+ self.assertTrue(record['history'][0]['passed'])
+ self.world['plan'] = plan_for_step('A443')
+ self.assert_refused(self.apply('A443'), 'A80.json did not pass')
+
+ def test_reverify_refuses_off_target_state(self):
+ # The target group is not in the step's target state: nothing was made to reverify.
+ self.ready_for('A80')
+ self.converged('A80', passed=False)
+ result = self.reverify('A80')
+ self.assert_refused(result, 'the target group is in S0, not S1')
+ self.assertNotIn('ssm send-command', self.ops())
+ # In the target state, but no apply or intent record for it.
+ self.setUp()
+ self.ready_for('A80')
+ self.live({'80': 'S1'})
+ self.assert_refused(self.reverify('A80'), 'nothing to reverify')
+ # A B step's reverify needs every barrier down, as its apply does.
+ self.setUp()
+ self.ready_for('B80')
+ self.live({'80': 'S2'})
+ self.converged('B80', passed=False)
+ self.world['trust'][TARGETS[1]] = [trust('barrier_up')]
+ self.assert_refused(self.reverify('B80'), 'no B step while it is up')
+ # The chain before the step must hold, as for apply.
+ self.setUp()
+ self.ready_for('A443')
+ self.live({'443': 'S1'})
+ self.converged('A443', passed=False)
+ (self.records / 'A80.json').unlink()
+ self.assert_refused(self.reverify('A443'), 'A80.json is missing')
+
+ def test_reverify_adopts_intent(self):
+ # tofu apply failed after it started, and the attribute did change.
+ self.ready_for('A80')
+ self.world['apply_rc'] = 1
+ self.assert_refused(self.apply('A80'), 'failed after it started')
+ intent = self.record_of('A80-intent')
+ self.world['apply_rc'] = 0
+ self.live({'80': 'S1'}, tfvars=False)
+ self.apply_converging('A80', command='reverify')
+ verified = self.record_of('A80-verified')
+ self.assertTrue(verified['adopted_intent'])
+ self.assertEqual(intent['started_at'], verified['intent_started_at'])
+ self.assertIsNone(verified['applied_at'])
+ self.assertTrue(self.record_of('A80')['passed'])
+ # The intent is taken up: no longer reported as pending.
+ result = self.apply('A80')
+ self.assert_refused(result, 'no change')
+ self.assertNotIn('A80-intent.json', result.stderr)
+ # An intent for another target group is not adopted.
+ self.setUp()
+ self.ready_for('A80')
+ self.live({'80': 'S1'})
+ self.record('A80-intent', step='A80', nlb_arn=NLB, port='80', tg_arn=TG['443'],
+ started_at='2026-11-12T10:00:00.000000Z')
+ self.assert_refused(self.reverify('A80'), 'not for this step and target group')
+
+
class FakeClock:
def __init__(self, t):
self.t = t
@@ -1123,6 +1241,30 @@ class ConvergeTests(unittest.TestCase):
self.assertEqual(1, code)
self.assert_reason(record, 'target health was not observed before the earliest probe started')
+ def test_span_clock_tolerance(self):
+ # The probe host's clock may run up to 5 s ahead of this host's: a first
+ # health poll 3 s after the probe's own start time still counts as before it.
+ self.fresh()
+ self.clock.t = T0 + 8
+ self.probes(started=T0 + 5)
+ code, record = self.run_converge()
+ self.assertEqual(0, code, record['reasons'])
+ self.assertEqual(5.0, record['clock_tolerance_s'])
+ self.assertIn('span checks only', record['clock_tolerance'])
+ # 7 s is beyond it.
+ self.fresh()
+ self.clock.t = T0 + 12
+ self.probes(started=T0 + 5)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, 'not observed before the earliest probe started', '5 s clock tolerance')
+ # No tolerance where it would let pre-change attempts count: a probe that
+ # started 1 s before the anchor is refused.
+ self.fresh()
+ self.probes(started=T0 - 1)
+ code, record = self.run_converge()
+ self.assert_reason(record, 'started before the apply')
+
def test_rerun_cannot_launder(self):
# A failed run, then a clean re-run for the same apply: still failed.
self.fresh()