carlos / platform Public

scripts: ppv2-step round 2: health to the record, reverify fixes

Re-review round 2 (Astra, Fable) and the controller's S3 guard:
- health stays on its 10 s schedule through the final trust wait and
  must cover the anchor to record publication, no gap over 15 s.
- reverify keeps the step's own target set (apply, earlier reverify
  or intent) and refuses a different --targets or registration.
- a pending intent newer than a step's evidence makes it stale.
- a reverify record is a basis for the next reverify, so a failed
  adopted-intent window is not a dead end.
- a not-armed answer (exit 2) at any trust poll fails A and B steps.
- reverify refuses after an S3 signal unless --incident-cleared.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2b69706628a02cf34beabbd8374f777b0e910206 parent a47ca6b
2 files changed, +298 −46
  • scripts/ppv2-step.py +135 −42
  • scripts/ppv2_step_test.py +163 −4
diff --git a/scripts/ppv2-step.py b/scripts/ppv2-step.py
index dc4ce944c..83ad1bfc2 100755
--- a/scripts/ppv2-step.py
+++ b/scripts/ppv2-step.py
@@ -32,8 +32,12 @@ them changes PPv2 while preservation is off, so no node can pass through S3.
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.
+ changed the attribute, it adopts <step>-intent.json. It keeps
+ the step's own targets, and refuses after an S3 signal
+ (marker_trusted or no_client_refused moved) unless given
+ --incident-cleared. Each step binds to the latest of its
+ predecessor's apply, reverify and intent: an intent newer than
+ the evidence makes it stale until a reverify passes.
Steps: A80, A443 (PPv2 on), B80, B443 (preservation off), R443, R80
(preservation back on). Nothing turns PPv2 off; there is no step for it.
@@ -271,15 +275,27 @@ def parse_trust(text):
def trust_of(iid, code, stdout, stderr):
- """A target's trust-status answer as a dict, or a string saying why there is none."""
+ """A target's trust-status answer: the status line (a dict with counters);
+ {'armed': False, 'detail': ...} when the box says it is not armed (exit 2),
+ which is an observation, not a missing one; or a string saying why there
+ is no answer at all (an SSM or parse failure)."""
if code == 2:
- return f'{iid} is not armed: {one_line(stderr)}'
+ return {'armed': False, 'detail': f'{iid} is not armed: {one_line(stderr)}'}
if code != 0:
return f'{iid}: trust-status failed ({code}): {one_line(stderr)}'
doc = parse_trust(stdout)
return doc if doc else f'{iid}: trust-status answered something that is not a status line'
+def is_status(s):
+ """A full trust-status line (armed or not, with counters)."""
+ return isinstance(s, dict) and 'counters' in s
+
+
+def is_unarmed(s):
+ return isinstance(s, dict) and s.get('armed') is False
+
+
def first_json(stdout, key):
"""The JSON document in stdout carrying key: the whole output, or one of its lines."""
try:
@@ -491,6 +507,13 @@ def record_refusal(name, record_dir, 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)})")
+ # An apply of that step that started after its evidence and wrote no
+ # -applied.json may have changed the attribute: the evidence is stale
+ # until a reverify of that step passes.
+ intent = intent_pending(record_dir, name)
+ if intent and intent.get('nlb_arn') == nlb_arn and (epoch(intent.get('started_at')) or 0) > (epoch(record_anchor(record)) or 0):
+ return (f"{name}-intent.json records an apply of {name} started at {intent.get('started_at')}, newer than "
+ f"{name}.json; reverify {name} first")
return None
@@ -614,7 +637,7 @@ def collect_baseline(cloud, step, targets):
if isinstance(status, str):
raise Refused(status)
if not status['armed']:
- raise Refused(f'{iid} is not armed')
+ raise Refused(status.get('detail') or 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':
@@ -649,16 +672,37 @@ def cmd_reverify(args, cloud):
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
+ made = {'nlb_arn': args.nlb_arn, 'port': args.port, 'tg_arn': args.tg_arn, 'step': args.step}
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()):
+ if intent and any(intent.get(k) != v for k, v in made.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')
+ # What the step was made with: its apply, an earlier reverify (which may
+ # itself have adopted an intent), or a pending intent. The latest is the basis.
+ basis = {}
+ for kind, record in (('applied', load_record(record_dir / f'{args.step}-applied.json')),
+ ('verified', load_record(record_dir / f'{args.step}-verified.json')),
+ ('intent', intent)):
+ if record and all(record.get(k) == v for k, v in made.items()):
+ basis[kind] = record
+ if not basis:
+ raise Refused(f'nothing to reverify: no {args.step}-applied.json, {args.step}-verified.json or '
+ f'{args.step}-intent.json for this target group')
+ when = lambda r: epoch(r.get('started_at') if r is intent else record_anchor(r)) or 0
+ latest = max(basis.values(), key=when)
+ # The step's targets are the ones it was made with; none may leave it unobserved.
+ made_with = latest.get('targets')
+ if not made_with:
+ raise Refused(f'the latest record of {args.step} names no targets; reverify cannot tell what to observe')
+ if sorted(targets) != sorted(made_with):
+ raise Refused(f"--targets must be the step's targets ({', '.join(made_with)}); a target cannot leave "
+ 'a step before it converges')
+ # A trust-violation signal in this step's evidence is S3 on some node (spec 6.4).
+ prior = load_record(record_dir / f'{args.step}.json') or {}
+ signals = [h for h in [prior] + list(prior.get('history') or []) if h.get('s3_signal')]
+ if signals and not args.incident_cleared:
+ raise Refused(f'{args.step}.json records an S3 signal (marker_trusted or no_client_refused moved); '
+ 'run the S3 incident procedure (runbook) first, then reverify with --incident-cleared')
+ applied = basis.get('applied')
try:
doc = json.loads((root / TFVARS_FILE).read_bytes())
except (OSError, ValueError) as err:
@@ -676,8 +720,9 @@ def cmd_reverify(args, cloud):
'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)}
+ 'intent_started_at': intent['started_at'] if intent else latest.get('intent_started_at'),
+ 'adopted_intent': bool(intent) or bool(latest.get('adopted_intent')),
+ 'incident_cleared': bool(signals) and args.incident_cleared}
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}.")
@@ -746,7 +791,8 @@ def cmd_apply(args, cloud):
intent = {'step': args.step, 'nlb_arn': args.nlb_arn, 'port': args.port, 'tg_arn': args.tg_arn,
'tg_address': args.tg_address, 'attribute': step.attribute, 'before': live[step.attribute],
'after': step.value, 'from': step.source, 'to': step.target, 'started_at': iso(cloud.clock.time()),
- 'planfile': planfile, 'tfvars_before': original.decode(), 'tfvars_after': edited.decode()}
+ 'planfile': planfile, 'tfvars_before': original.decode(), 'tfvars_after': edited.decode(),
+ 'targets': targets, 'baseline': baseline, 'baseline_at': iso(baseline_at)}
write_record(intent_path, intent)
PHASE['name'] = 'apply'
except BaseException as err:
@@ -804,7 +850,7 @@ 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', f'{forward}-verified.json'):
+ for name in (f'{forward}.json', f'{forward}-applied.json', f'{forward}-verified.json', f'{forward}-intent.json'):
path = record_dir / name
if path.exists():
os.replace(path, record_dir / name.replace('.json', f'.superseded-{stamp}.json'))
@@ -922,15 +968,21 @@ def converge(cloud, record_dir, applied, paths, timeout):
log.add({'kind': 'state', 'at': iso(t), 'error': str(err)})
deadline = clock.time() + timeout
- next_health = next_trust = clock.time()
+ schedule = {'health': clock.time()}
+
+ def health_due():
+ """Health keeps its own 10 s schedule through every wait, until the record is written."""
+ now = clock.time()
+ if now >= schedule['health']:
+ poll_health()
+ schedule['health'] = now + HEALTH_EVERY
+
+ next_trust = clock.time()
job = None
try:
while True:
- now = clock.time()
- if now >= next_health:
- poll_health()
- next_health = now + HEALTH_EVERY
- if job is None and now >= next_trust:
+ health_due()
+ if job is None and clock.time() >= next_trust:
job = TrustJob(cloud, targets)
if job is not None and job.check():
log.add(job.entry())
@@ -938,27 +990,32 @@ def converge(cloud, record_dir, applied, paths, timeout):
if probes_ready(paths, clock) or clock.time() >= deadline:
break
clock.sleep(TICK)
- # The last look, after the probes finished: health, the counters
- # (retried, since this one is required), and the target group's state.
- poll_health()
+ # The last look, after the probes finished: the counters (retried while
+ # SSM gives no answer, since this one is required) and the target group's
+ # state, with health still on its schedule, then health once more.
for _ in range(3):
job = TrustJob(cloud, targets)
while not job.check():
- clock.sleep(2)
+ health_due()
+ clock.sleep(TICK)
entry = log.add(job.entry())
- if all(isinstance(s, dict) for s in entry['status'].values()):
+ if not any(isinstance(s, str) for s in entry['status'].values()):
break
+ health_due()
poll_state()
+ poll_health()
except Interrupted as err:
raise Interrupted(f'{err} during convergence of {step}; no verdict written; the polls so far are kept in '
f'{log.path.name}; resume with converge')
- reasons, summary = evaluate(step, applied, log.read(), load_probes(paths), prereq, prior)
+ published = clock.time()
+ reasons, summary = evaluate(step, applied, log.read(), load_probes(paths), prereq, prior, published)
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')})
+ history.append({k: prior.get(k) for k in ('applied_at', 'verified_at', 'converged_at', 'passed', 'reasons',
+ 's3_signal')})
record = dict(summary, nlb_arn=applied['nlb_arn'], port=applied['port'], step=step, tg_arn=applied['tg_arn'],
applied_at=applied.get('applied_at'), verified_at=applied.get('verified_at'),
converged_at=iso(clock.time()), passed=passed, reasons=reasons, history=history,
@@ -1055,15 +1112,38 @@ def coverage_reasons(times, window, gap, what):
return reasons
+def continuous_reasons(times, start, end, gap, what, start_label):
+ """Observations (this host's clock) from start to end, never more than gap apart."""
+ points = sorted(t for t in times if start <= t <= end)
+ reasons = []
+ edges = [start] + points + [end]
+ for i, (a, b) in enumerate(zip(edges, edges[1:])):
+ if b - a > gap:
+ if i == 0:
+ reasons.append(f'{what} was not observed for {b - a:.0f} s after the {start_label} at {iso(a)} '
+ f'(at most {gap:g} s allowed)')
+ elif i == len(edges) - 2:
+ reasons.append(f'{what} was not observed in the last {b - a:.0f} s before the record was written '
+ f'(from {iso(a)}; at most {gap:g} s allowed)')
+ else:
+ reasons.append(f'{what} was not observed for {b - a:.0f} s, from {iso(a)} to {iso(b)} '
+ f'(at most {gap:g} s allowed)')
+ return reasons
+
+
def trust_findings(status, base, iid, step):
if isinstance(status, str):
- return []
+ return [] # no answer at all (SSM): not an observation; the final poll must have one
reasons = []
- if not status['armed']:
- reasons.append(f'{iid} is not armed')
- if status['barrier'] and step.startswith('B'):
+ # A box that says it is not armed, at any poll, fails A and B steps; only
+ # reverse steps keep their exception (rollback is the safe direction).
+ if not status['armed'] and not step.startswith('R'):
+ reasons.append(status.get('detail') or f'{iid} is not armed')
+ if status.get('barrier') and step.startswith('B'):
reasons.append(f'{iid}: barrier is up')
- if not isinstance(base, dict):
+ if not is_status(status):
+ return reasons
+ if not is_status(base):
return reasons + [f'{iid}: the apply recorded no baseline ({base})']
for counter in COUNTERS:
if status['counters'][counter] < base['counters'][counter]:
@@ -1075,8 +1155,9 @@ def trust_findings(status, base, iid, step):
return reasons
-def evaluate(step, applied, polls, docs, prereq, prior):
- """(reasons, summary): the whole verdict, from the apply, every poll and the probe records."""
+def evaluate(step, applied, polls, docs, prereq, prior, published):
+ """(reasons, summary): the whole verdict, from the apply, every poll and the probe
+ records, for a record written at `published`."""
reasons = []
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 [])
@@ -1091,14 +1172,21 @@ def evaluate(step, applied, polls, docs, prereq, prior):
for poll in health:
if 'health' in poll:
reasons.extend(f"health poll at {poll['at']}: {r}" for r in registered_refusals(poll['health'], targets))
- reasons.extend(coverage_reasons([epoch(p['at']) for p in health if 'health' in p], window, HEALTH_GAP_MAX, 'target health'))
+ health_times = [epoch(p['at']) for p in health if 'health' in p]
+ reasons.extend(coverage_reasons(health_times, window, HEALTH_GAP_MAX, 'target health'))
+ # And all along, from the apply (or reverify) to this record (spec 6.4:
+ # every target healthy from the start of the step until its record is written).
+ anchor = epoch(record_anchor(applied))
+ if anchor is not None:
+ reasons.extend(continuous_reasons(health_times, anchor, published, HEALTH_GAP_MAX, 'target health',
+ anchor_kind(applied)))
for poll in trust:
for iid in targets:
for r in trust_findings(poll['status'].get(iid, ''), baseline.get(iid), iid, step):
reasons.append(f"trust poll at {poll['at']}: {r}")
- complete = [p for p in trust if all(isinstance(p['status'].get(i), dict) for i in targets)]
+ complete = [p for p in trust if all(is_status(p['status'].get(i)) for i in targets)]
trust_times = [epoch(p['at']) for p in complete]
- if all(isinstance(baseline.get(i), dict) for i in targets) and applied.get('baseline_at'):
+ if all(is_status(baseline.get(i)) for i in targets) and applied.get('baseline_at'):
trust_times.append(epoch(applied['baseline_at']))
reasons.extend(coverage_reasons(trust_times, window, None, 'trust-status on every target'))
final = max(trust, key=lambda p: p['at']) if trust else None
@@ -1109,7 +1197,7 @@ def evaluate(step, applied, polls, docs, prereq, prior):
if step.startswith('B') and final is not None:
for iid in targets:
status, base = final['status'].get(iid), baseline.get(iid)
- if not isinstance(status, dict) or not isinstance(base, dict):
+ if not is_status(status) or not is_status(base):
continue
for node in prereq['sources']:
was, now = base['proxied_by_node'].get(node, 0), status['proxied_by_node'].get(node, 0)
@@ -1121,7 +1209,10 @@ def evaluate(step, applied, polls, docs, prereq, prior):
elif last_state['state'] != STEPS[step].target:
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),
+ # A rise of either is S3 on some node (spec 6.4): a reverify then needs the
+ # incident procedure first. Earlier runs' signals carry forward.
+ s3_signal = any(re.search(r': (marker_trusted|no_client_refused) moved ', r) for r in unique)
+ summary = {'s3_signal': s3_signal, 'probes': probes, 'health_polls': len(health), 'trust_polls': len(trust),
'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; '
@@ -1244,6 +1335,8 @@ def parser():
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')
+ v.add_argument('--incident-cleared', action='store_true',
+ help='the S3 incident procedure has been run for an S3 signal this step recorded')
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')
diff --git a/scripts/ppv2_step_test.py b/scripts/ppv2_step_test.py
index d7e06abd5..4c66ad7c6 100644
--- a/scripts/ppv2_step_test.py
+++ b/scripts/ppv2_step_test.py
@@ -345,12 +345,15 @@ 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', command='apply'):
+ def apply_args(self, step, port=None, targets=None, nlb=NLB, probes=None, timeout='60', command='apply',
+ incident_cleared=False):
port = port or STEP_PLAN.get(step, ('80',))[0]
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 incident_cleared:
+ args.append('--incident-cleared')
if probes is None:
probes = command == 'reverify' or not step.startswith('R')
if probes:
@@ -387,6 +390,12 @@ class Harness(unittest.TestCase):
"""The fake tofu apply moves target groups in the world file; take that up."""
self.world = json.loads(self.world_path.read_text())
+ def restart_sequences(self):
+ """The fake's health and trust answers start again from the first of each list."""
+ seq = self.world_path.with_suffix('.seq')
+ if seq.exists():
+ seq.unlink()
+
def record(self, name, **values):
(self.records / (name + '.json')).write_text(json.dumps(values))
@@ -734,8 +743,8 @@ class StepGateTests(Harness):
self.world['ssm_fail'] = True
self.apply('R80', expect=0)
baseline = json.loads((self.records / 'R80-applied.json').read_text())['baseline']
- self.assertIsInstance(baseline[TARGETS[0]], str)
- self.assertIn('not armed' if fault == 'not armed' else 'not collected', baseline[TARGETS[0]])
+ # Recorded, not refused: a not-armed answer (exit 2) or the SSM error.
+ self.assertIn('not armed' if fault == 'not armed' else 'not collected', json.dumps(baseline[TARGETS[0]]))
self.assertIn('apply', self.tofu_ops())
# The same SSM error refuses every forward step.
for step in ('A80', 'B80'):
@@ -993,6 +1002,95 @@ class ReverifyTests(Harness):
started_at='2026-11-12T10:00:00.000000Z')
self.assert_refused(self.reverify('A80'), 'not for this step and target group')
+ def failing_first_window(self, step='A80'):
+ """Health answers for: the run's own check, then one unhealthy poll, then healthy."""
+ self.world['health'][TG[STEP_PLAN[step][0]]] = [
+ [[t, 'healthy'] for t in TARGETS], [[TARGETS[0], 'healthy'], [TARGETS[1], 'unhealthy']],
+ [[t, 'healthy'] for t in TARGETS]]
+
+ def test_reverify_keeps_the_steps_targets(self):
+ # A80's window fails on TARGETS[1]; that target is then deregistered.
+ self.ready_for('A80')
+ self.failing_first_window()
+ self.apply_converging('A80', expect=1)
+ self.reload_world()
+ self.restart_sequences()
+ self.world['health'][TG['80']] = [[[TARGETS[0], 'healthy']]]
+ # Reverifying the survivors only is refused: the step was made with both.
+ self.assert_refused(self.reverify('A80', targets=TARGETS[:1]), "must be the step's targets")
+ # With both named, the missing one is refused as not registered.
+ self.assert_refused(self.reverify('A80'), TARGETS[1] + ' is not registered')
+ self.assertNotIn('A80-verified.json', [p.name for p in self.records.iterdir()])
+
+ def test_newer_intent_stales_evidence(self):
+ # A80 and A443 converged; then a repeated A80 apply changed the attribute
+ # and exited without -applied.json. Its intent is newer than A80.json.
+ for step, port, stale in (('B80', '80', 'A80'), ('B443', '443', 'A443')):
+ with self.subTest(step=step):
+ self.setUp()
+ self.ready_for(step)
+ self.record(stale + '-intent', step=stale, nlb_arn=NLB, port=STEP_PLAN[stale][0],
+ tg_arn=TG[STEP_PLAN[stale][0]], targets=TARGETS, started_at='2026-11-12T10:30:00.000000Z')
+ original = self.tfvars.read_bytes()
+ self.assert_refused(self.apply(step), f'{stale}-intent.json records an apply of {stale}')
+ self.assert_not_changed(original)
+ # A passing reverify of A80 takes the intent up, and B80 goes through.
+ self.setUp()
+ self.ready_for('B80')
+ self.record('A80-intent', step='A80', nlb_arn=NLB, port='80', tg_arn=TG['80'], targets=TARGETS,
+ started_at='2026-11-12T10:30:00.000000Z')
+ self.apply_converging('A80', command='reverify')
+ self.assertTrue(self.record_of('A80')['passed'])
+ self.restart_sequences()
+ self.apply_converging('B80')
+ self.assertTrue(self.record_of('B80')['passed'])
+
+ def test_failed_adopted_reverify_stays_reverifiable(self):
+ # tofu apply failed after changing the attribute: no -applied.json.
+ self.ready_for('A80')
+ self.world['apply_rc'] = 1
+ self.assert_refused(self.apply('A80'), 'failed after it started')
+ self.world['apply_rc'] = 0
+ self.live({'80': 'S1'}, tfvars=False)
+ # The first reverify adopts the intent, and its window fails.
+ self.restart_sequences()
+ self.failing_first_window()
+ self.apply_converging('A80', command='reverify', expect=1)
+ self.assertFalse(self.record_of('A80')['passed'])
+ # A second reverify starts from that adopted record, and passes.
+ self.restart_sequences()
+ self.world['health'][TG['80']] = [[[t, 'healthy'] for t in TARGETS]]
+ self.apply_converging('A80', command='reverify')
+ record = self.record_of('A80')
+ self.assertTrue(record['passed'], record['reasons'])
+ self.assertTrue(self.record_of('A80-verified')['adopted_intent'])
+ self.assertFalse(record['history'][0]['passed'])
+ # And the next step is unblocked.
+ self.restart_sequences()
+ self.world['plan'] = plan_for_step('A443')
+ self.world['on_apply'] = {TG['443']: attributes('S1')}
+ self.apply_converging('A443')
+ self.assertTrue(self.record_of('A443')['passed'])
+
+ def test_reverify_refuses_after_s3_signal(self):
+ # A80's window sees marker_trusted move on one target: an S3 signal.
+ self.ready_for('A80')
+ self.world['trust'][TARGETS[1]] = [trust('baseline'), trust('marker_trusted_moved')]
+ self.apply_converging('A80', expect=1)
+ self.assertTrue(self.record_of('A80')['s3_signal'])
+ self.reload_world()
+ result = self.reverify('A80')
+ self.assert_refused(result, 'run the S3 incident procedure (runbook) first')
+ self.assertFalse((self.records / 'A80-verified.json').exists())
+ # Once the incident procedure has been run, the operator says so.
+ self.apply_converging('A80', command='reverify', incident_cleared=True)
+ record = self.record_of('A80')
+ self.assertTrue(record['passed'], record['reasons'])
+ self.assertTrue(self.record_of('A80-verified')['incident_cleared'])
+ self.assertTrue(record['history'][0]['s3_signal'])
+ # The signal stays in history, so a later reverify needs the flag again.
+ self.assert_refused(self.reverify('A80'), 'run the S3 incident procedure')
+
class FakeClock:
def __init__(self, t):
@@ -1050,7 +1148,11 @@ class FakeCloud:
out = {}
for iid in targets:
name = [n for since, n in self.samples[iid] if since <= sent - T0][-1]
- out[iid] = ('Success', 0, json.dumps(self.override.get(iid) or trust(name)) + '\n', '')
+ sample = self.override.get(iid) or trust(name)
+ if 'rc' in sample: # the box answers exit 2: not armed
+ out[iid] = ('Failed', sample['rc'], '', sample['stderr'])
+ else:
+ out[iid] = ('Success', 0, json.dumps(sample) + '\n', '')
return out
def attributes(self, tg):
@@ -1241,6 +1343,63 @@ class ConvergeTests(unittest.TestCase):
self.assertEqual(1, code)
self.assert_reason(record, 'target health was not observed before the earliest probe started')
+ def test_health_polled_through_final_trust_wait(self):
+ # The probes finish at 65 s; the final trust poll then takes 40 s. A
+ # target unhealthy from 80 s to 100 s, inside that wait, must be seen.
+ self.fresh()
+ self.cloud.trust_delay = 40
+ self.cloud.unhealthy.append((80, 100, TARGETS[1]))
+ self.probes(at=T0 + 70)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, TARGETS[1] + ' is unhealthy')
+ self.assertTrue(any(80 <= t <= 100 for t in self.cloud.health_calls), self.cloud.health_calls)
+
+ def test_health_covered_from_anchor_to_record(self):
+ # Nothing watched health for the first 20 s after the apply.
+ self.fresh()
+ self.clock.t = T0 + 20
+ self.probes(at=T0 + 90, started=T0 + 25, finished=T0 + 85)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, 'target health was not observed for 20 s after the apply')
+ # Health answers stop after 72 s and the final trust poll takes 40 s:
+ # the record is written with the last 40 s unobserved.
+ self.fresh()
+ self.cloud.trust_delay = 40
+ answer = self.cloud.health
+
+ def failing(tg):
+ if self.clock.t - T0 > 72:
+ raise gate.Refused('aws elbv2 describe-target-health failed: throttled')
+ return answer(tg)
+ self.cloud.health = failing
+ self.probes(at=T0 + 70)
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, 'before the record was written')
+
+ def test_unarmed_mid_window_fails(self):
+ # One target answers "not armed" (exit 2) at the 31 s poll only.
+ timeline = [(0, 'after_a'), (25, 'not_armed'), (40, 'after_a')]
+ self.fresh('A80')
+ self.cloud.samples[TARGETS[1]] = timeline
+ self.probes()
+ code, record = self.run_converge()
+ self.assertEqual(1, code)
+ self.assert_reason(record, TARGETS[1] + ' is not armed')
+ # The same in a B step.
+ self.fresh('B80')
+ self.cloud.samples[TARGETS[1]] = [(0, 'b_both_nodes'), (25, 'not_armed'), (40, 'b_both_nodes')]
+ self.probes()
+ self.assert_reason(self.run_converge()[1], TARGETS[1] + ' is not armed')
+ # Reverse steps keep their exception.
+ self.fresh('R80')
+ self.cloud.samples[TARGETS[1]] = timeline
+ self.probes()
+ code, record = self.run_converge()
+ self.assertEqual(0, code, record['reasons'])
+
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.