Centralize group return decisions and simulate recovery
Enforce the acknowledged-return invariant through one pure decision table for resume and return. Preserve the R16 hold across stale observations and operator loss, and wait for root status before rollback inspection. Add table cases, journal-boundary witnesses and a seeded provider simulation. All 3000 serial seeds and all 12 mutations pass.
scripts/region-group-roll.py+369 −180scripts/region_group_roll_test.py+569 −14
Intent
<task-notification> <task-id>bem3s1902</task-id> <tool-use-id>toolu_01FWDU8ynqXr2ouYdrHZqg4f</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/bem3s1902.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b3g" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>abf5e0c58419eb314</task-id> <tool-use-id>toolu_014t3d4s2mkyNYHWyQMPBDtE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/abf5e0c58419eb314.output</output-file> <status>completed</status> <summary>Agent "Re-review B3 fix round 2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Five of the six items are fixed. Item 2 is only partly fixed: I reproduced two paths where an acknowledged CONTINUE still ends as a failed probe with the member InService. That is a T1/I4 return-contract finding, so stopping rule 2 applies. The full suite passed in my one run: 66 tests, exit 0, and all 8 plan mutations were caught. I also ran three extra scenarios from a scratch script that loaded the test fixtures; it has since been deleted. Nothing in the worktree changed. ## Per-item verdicts **1. [T1/I4 liveness] warming targets after Exit/CONTINUE — ADDRESSED.** - `scripts/region-group-roll.py:1203-1206`: on the no-hook InService path, targets that are not yet healthy now cause a 5-second sleep and another poll, inside the 900-second bound. - When that bound runs out, `:1101` raises a plain ALERT. It does not record a failed probe or restore min, and the journal and permit stay in place. Resume then continues without a second Exit (test at `region_group_roll_test.py:991`). - The fake leaves the target `initial` for 30 seconds by default after Exit (`test.py:161-162`) and after CONTINUE (`:173-174`). No test sets the warmup to 0, so every return test goes through warming. - In the hook case the target stays `initial` until CONTINUE. **2. [T1/I4 R16] after an acknowledged CONTINUE, always the R16 hold — PARTLY ADDRESSED.** - **Fixed:** the InService path (`:1189-1201`) now checks for an observed return hook before checking targets or readiness. With an acknowledged CONTINUE it skips readiness, requires min N-1, calls EnterStandby with decrement, and ends in DivergenceHeld. A describe blip after the hold has started stays resumable (`:1108`). - **Still open (Important, T1/I4: failed-probe vs hold classification after an acknowledged CONTINUE).** Two paths after `return-acknowledged` still record a failed probe: - **(a) Describe still shows Pending:Wait for a moment after the acknowledgement.** AWS moves through Pending:Wait, Pending:Proceed, Pending and InService asynchronously after CompleteLifecycleAction, so this is realistic. In the Pending:Wait branch, three checks run before the acknowledgement check at `:1163`: the 120-second deadline check (`:1153-1154`), `exit_activity()`, and the readiness check (`:1156-1160`). So if admission drops after CONTINUE, the result is a failed probe. - Reproduced: FailedProbe is raised with `return-acknowledged` present and `failed-probe` recorded. The member ends InService at min 1 / desired 2, and it is not held in Standby. - Item 2 limits FailedProbe to "Pending:Wait with admission dropped **before** CONTINUE". - **(b) Describe blip in the gap between `return-acknowledged` and the `divergence-hold` event.** The guard at `:1108` checks for `divergence-hold`, not `return-acknowledged`, so a describe failure on the next poll after the acknowledgement is a failed probe. - Reproduced with the same outcome: FailedProbe, member InService at min 1 / desired 2. - This is also the R19 case that a describe blip must not be classified as a failed probe. - In both cases a later `resume` does reach the hold, because the member is InService and a return hook was observed. But the run stops with a false FAIL record and the member InService and unready, instead of held in Standby. - The fake moves straight to InService on `complete`, so the tests never exercise either path. - Likely fix: check `return-acknowledged` before the deadline, activity and readiness checks in the Pending:Wait branch, and use it in the `:1108` guard. **3. [recovery] rollback after a failed apply readback — ADDRESSED.** - `rollback()` (`:1052-1068`) reads status first, before any group describe, without re-verifying the apply. - New sha installed: the R12 sequence runs as before (revoke, new rollback permit, rollback verb). - Old sha already installed: `already_restored=True` is journaled and `mutation()` is skipped (`:1046`). Readiness still requires the old digest, fresh admission, and this transaction's consumed apply permit (`:729-735`). - Any other digest: refused with `rollback_digest` and no writes. - All three cases are tested (`test.py:1028`), plus resume after recording the decision and a one-off bad digest readback. - Minor (recovery, not T1/I4): if a cut session's apply is still running, `rollback` can record `already_restored` while the binary is still old. When the apply then finishes on the new binary, readiness keeps refusing with "process" and no command will issue the box rollback verb. Hand-editing the journal is the only way out. The member stays safely in Standby, and this rests on the known deferred minor about catching a still-running apply. **4. Pending:Wait classified before the exit-intent / desired checks — ADDRESSED.** - `:1119-1121` records the return hook and writes the block flag right after describe, before the lost-member, invariant, `return_intent` and desired checks. Tested at `test.py:1059`. - A direct `return` with no exit-intent now ends as FailedProbe through `:1240`. That is reasonable, since no CONTINUE is possible. **5. R20 unparseable pointer version — ADDRESSED.** - `:930-932` refuses before any group write, with the comment explaining why it is stricter than BelowFloor. Tested with six versions; only `prepare` was written. **6. R21 `abandon --transaction` — ADDRESSED.** - `abandon()` at `:848-862` runs under the group lock from `main`. It refuses on any `minimum`, `enter`, `exit`, `complete` or `desired` intent, any `permit`, `revoke`, `apply` or `rollback` session, or an exit-intent, and points the operator at resume, rollback or return. - It journals `abandoned` and `done`, makes no provider calls, and never sends a lifecycle ABANDON. - Both outcomes are tested, plus the CLI after an interrupted preflight. ## Focused checks - **Warming within the 15-minute bound:** yes for the no-hook path and after an acknowledged CONTINUE on the InService path. The exceptions are the two item 2 paths above. - **Every post-CONTINUE path ends in the R16 hold:** no. Paths (a) and (b) above end in FailedProbe. - **Rollback cases:** new-sha, already-old-sha and other-digest all work. - **Pending:Wait ordering:** correct. - **Abandon refusal:** refuses once any write intent exists. - **8 plan mutations:** all still caught. - **Unchanged rules:** Exit and CONTINUE ownership and their preconditions, no completion while unready, no ABANDON, min never restored in the divergence hold, and the N-HA14 shape (hold at min N-1 / desired N-1 / max N). New breakage: - **Important, T1/I4 (failed-probe vs hold after an acknowledged CONTINUE):** paths (a) and (b) under item 2. They are the residue of the item 2 finding rather than a new kind of fault: (b) is in the guard this diff changed at `:1108`, and (a) is in check ordering that was left unchanged at `:1151-1163`. - **Minor, T1/I4-adjacent:** an ambiguous CONTINUE followed by InService with admission lost gives a resumable Refusal, and no hold until admission comes back. Reproduced: Refusal, no failed-probe record, member InService at min 1. It is safe and matches the contract's "resolved by InService plus fresh admission". I am noting it, not grading it up. - **Minor, recovery:** the stuck already-restored rollback under item 3. Verdict: open: item 2 (T1/I4 return-contract family: a stale Pending:Wait after the acknowledgement plus admission loss, and a describe blip before `divergence-hold`, both record a failed probe instead of the R16 hold). Under stopping rule 2, that is the third round with a T1/I4 finding.</result> <usage><subagent_tokens>107660</subagent_tokens><tool_uses>20</tool_uses><duration_ms>418161</duration_ms></usage> </task-notification>
<task-notification> <task-id>be85p0o91</task-id> <tool-use-id>toolu_01L8fnhLMadMhKtHTjkMeyK2</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/be85p0o91.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-luna.sh" completed (exit code 0)</summary> </task-notification>
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py| index a1cb07970..6d331082c 100755 |
| --- a/scripts/region-group-roll.py |
| +++ b/scripts/region-group-roll.py |
| @@ -31,6 +31,15 @@ An uncertain consumed box action stays in Standby for operator investigation. |
| The command never replays it, restarts a unit by hand, terminates a member, |
| sends ABANDON, or sets desired capacity. A Standby wait alerts after 15 minutes. |
| +Once return-acknowledged is journaled for this transaction+iid, the only |
| +outcomes are the R16 Standby hold (EnterStandby with decrement at min N-1, |
| +deregistration verified, DivergenceHeld) or a resumable state. FailedProbe is |
| +possible only before acknowledgement (Pending:Wait with current-process |
| +admission dropped before CONTINUE, member terminated/replaced, or completion |
| +ambiguity resolving to ABANDON). classify() owns this decision for both return |
| +and resume. Only return_member sends Exit/CONTINUE. It never completes while |
| +unready, sends ABANDON, restores minimum in the hold, or raises desired. |
| + |
| Sessions can be cut during apply or rollback. Both remote commands have a |
| 15-minute transport bound, with 30 seconds for TERM before KILL. Their local |
| session bound is 990 seconds. Prepare has a five-minute box bound and a |
| @@ -62,6 +71,7 @@ import subprocess |
| import sys |
| import tempfile |
| import time |
| +from typing import NamedTuple |
| import tty |
| import uuid |
| @@ -141,6 +151,157 @@ WAIT = 900 |
| SESSION_TIMEOUTS = {"prepare": 360, "apply": 990, "rollback": 990} |
| +class Decision(NamedTuple): |
| + action: str |
| + reason: str = "" |
| + delay: float = 0 |
| + |
| + |
| +def classify(facts) -> Decision: |
| + """Pure, ordered decision table. Journal facts outlive observations. |
| + |
| + Once acknowledged, every observation leads to hold or resumable state. |
| + In particular, a stale Pending:Wait cannot reopen a completed action. |
| + No executor or exception handler may choose FailedProbe independently. |
| + """ |
| + f = facts |
| + context, phase = f.get("context", "return"), f.get("phase") |
| + acknowledged = f.get("acknowledged") or f.get("hold_started") |
| + n = f.get("n", 0) |
| + minimum, desired = f.get("minimum"), f.get("desired") |
| + ready = f.get("readiness", "unknown") |
| + if context == "rollback": |
| + if f.get("timed_out"): |
| + return Decision("resumable", "uncertain_action") |
| + if f.get("status_error"): |
| + return Decision("wait", delay=5) |
| + return Decision("inspect-rollback" if f.get("status_checked") else "observe-status") |
| + if context == "resume": |
| + if f.get("done"): |
| + return Decision("finish") |
| + if f.get("exit_intent") or f.get("hook") or acknowledged: |
| + return Decision("return") |
| + if f.get("operation_error") or f.get("describe_error"): |
| + return Decision("resumable", f.get("error_reason", "api")) |
| + if not f.get("pending_checked"): |
| + return Decision("observe-action") |
| + if not f.get("prepared"): |
| + return Decision("prepare") |
| + if context == "return" and f.get("completion_response") and not acknowledged: |
| + return Decision("acknowledge") |
| + if f.get("describe_error") or f.get("operation_error"): |
| + if context == "return" and f.get("hook") and not acknowledged: |
| + return Decision("failed", "return_failed") |
| + return Decision("resumable", f.get("error_reason", "api")) |
| + if not f.get("observed"): |
| + return Decision("describe") |
| + if context == "return" and phase == "Pending:Wait" and not f.get("hook"): |
| + return Decision("record-hook") |
| + |
| + # This precedence is the acknowledgement invariant. Even termination or |
| + # stale capacity after acknowledgement cannot turn it into FailedProbe. |
| + shape = (f.get("members_match") and f.get("template_match") and |
| + f.get("maximum") == n and n >= 2) |
| + if context == "return" and acknowledged: |
| + if not shape or phase is None or phase.startswith("Terminat"): |
| + return Decision("resumable", "members") |
| + if f.get("timed_out"): |
| + return Decision("resumable", "return_phase") |
| + if phase in {"Standby", "EnteringStandby"} and f.get("hold_started"): |
| + if minimum != n - 1 or desired != n - 1: |
| + return Decision("resumable", "held") |
| + if phase == "Standby" and f.get("deregistered"): |
| + return Decision("held") |
| + return Decision("wait", delay=5) |
| + if phase == "InService": |
| + if minimum == n - 1 and desired == n: |
| + return Decision("hold") |
| + return Decision("resumable", "held") |
| + if phase in {"Pending:Wait", "Pending:Proceed", "Pending", "PreInService"}: |
| + return Decision("wait", delay=2) |
| + return Decision("resumable", "return_phase") |
| + |
| + sent = f.get("exit_state", "none") != "none" |
| + if context == "return" and sent: |
| + if phase is None or phase.startswith("Terminat") or not f.get("members_match"): |
| + return Decision("failed", "lost_member") |
| + if phase not in {"Standby", "EnteringStandby", "Pending", "PreInService", |
| + "Pending:Wait", "Pending:Proceed", "InService"}: |
| + return Decision("failed", "unknown_phase") |
| + if not shape: |
| + return Decision("resumable", "members") |
| + if f.get("timed_out"): |
| + return Decision("resumable", "timeout" if phase == "Standby" else "return_phase") |
| + |
| + if context == "resume": |
| + if phase == "InService": |
| + if (desired != n or minimum not in (n - 1, n) or |
| + (minimum == n - 1 and not f.get("minimum_intent"))): |
| + return Decision("resumable", "shape") |
| + if not f.get("peers_checked"): |
| + return Decision("check-peers") |
| + return Decision("lower-minimum" if minimum == n else "enter") |
| + if phase in {"Standby", "EnteringStandby"}: |
| + if minimum != n - 1 or desired != n - 1: |
| + return Decision("resumable", "held") |
| + if phase != "Standby" or not f.get("deregistered"): |
| + return Decision("wait", delay=5) |
| + if not f.get("action_verified") and not f.get("already_restored"): |
| + return Decision("mutate") |
| + if ready == "unknown": |
| + return Decision("observe-ready") |
| + return Decision("return") if ready == "ok" else Decision("wait", delay=5) |
| + return Decision("resumable", "held") |
| + |
| + if phase == "Standby": |
| + if minimum != n - 1 or desired != n - 1: |
| + return Decision("resumable", "held") |
| + if not f.get("deregistered"): |
| + return Decision("wait", delay=5) |
| + if ready == "unknown": |
| + return Decision("observe-ready") |
| + return Decision("exit") if ready == "ok" else Decision("wait", delay=5) |
| + if not f.get("exit_intent"): |
| + return Decision("resumable", "return_intent") |
| + if desired != n or minimum not in (n - 1, n): |
| + return Decision("resumable", "members") |
| + if phase == "Pending:Wait": |
| + if f.get("deadline_close"): |
| + return Decision("failed", "return_failed") |
| + if f.get("attempts", 0) >= 4: |
| + return Decision("failed", "return_attempts") |
| + if not f.get("activity_ready"): |
| + return Decision("activity") |
| + if f.get("attempts", 0) and not f.get("backoff_done"): |
| + return Decision("backoff", delay=(1, 2, 4)[f["attempts"] - 1]) |
| + if ready == "unknown": |
| + return Decision("observe-ready") |
| + if ready != "ok": |
| + return Decision("failed", "return_failed") |
| + return Decision("complete") |
| + if phase in {"Pending", "PreInService", "Pending:Proceed"}: |
| + return Decision("wait", delay=5) |
| + if phase == "InService": |
| + if f.get("hook"): |
| + if not f.get("activity_ready"): |
| + return Decision("activity") |
| + if ready == "unknown": |
| + return Decision("observe-ready") |
| + if ready != "ok": |
| + return Decision("wait", delay=5) |
| + if not f.get("attempts"): |
| + return Decision("resumable", "return_intent") |
| + return Decision("acknowledge") |
| + if not f.get("targets_healthy"): |
| + return Decision("wait", delay=5) |
| + if ready == "unknown": |
| + return Decision("observe-ready") |
| + if ready != "ok": |
| + return Decision("wait", delay=5) |
| + return Decision("restore-minimum" if minimum != n else "finish-return") |
| + return Decision("resumable", "return_phase") |
| + |
| + |
| class Refusal(Exception): |
| pass |
| @@ -901,19 +1062,6 @@ class Operator: |
| raise DivergenceHeld(TEXT[key]) |
| raise Refusal(TEXT[key]) |
| - def wait_standby(self, check): |
| - end = self.clock() + WAIT |
| - while True: |
| - try: |
| - g = self.snapshot() |
| - self.standby(g, deregistered=False) |
| - result = check(g) |
| - return result |
| - except (Refusal, Uncertain): |
| - if self.clock() >= end: |
| - self.alert("timeout") |
| - self.sleep(min(5, end - self.clock())) |
| - |
| def prepare(self): |
| if self.j.last("prepared"): |
| return |
| @@ -1003,58 +1151,156 @@ class Operator: |
| raise |
| self.verify_action(self.box(h["iid"])) |
| + def decision_facts(self, context, group=None, **observation): |
| + h = self.header |
| + intent = self.j.last("exit-intent") |
| + exit_call = self.j.last("intent", op="exit") |
| + exit_error = self.j.last("error", op="exit") |
| + exit_response = self.j.last("response", op="exit") |
| + exit_state = "none" |
| + if exit_call: |
| + exit_state = "dispatched" |
| + if exit_response and exit_response["intent"] == exit_call["seq"]: |
| + exit_state = "acknowledged" |
| + elif exit_error and exit_error["intent"] == exit_call["seq"]: |
| + exit_state = "ambiguous" if exit_error.get("dispatched") else "none" |
| + activity = self.j.last("exit-activity") |
| + key = ([h["transaction"], h["iid"], h["identity"]["boot_id"], |
| + intent["process"], activity["activity"]] if intent and activity else None) |
| + attempts = [r for r in self.j.events if r["kind"] == "return-action" and r["key"] == key] |
| + acknowledged = any(r["kind"] == "return-acknowledged" and |
| + r.get("key", [])[:2] == [h["transaction"], h["iid"]] |
| + for r in self.j.events) |
| + complete_response = self.j.last("response", op="complete") |
| + # Death between the API response journal entry and acknowledgement |
| + # must not make a successful action eligible for another CONTINUE. |
| + completion_response = bool(attempts and complete_response and |
| + complete_response["seq"] > attempts[-1]["seq"]) |
| + facts = dict(context=context, done=bool(self.j.last("done")), |
| + exit_intent=bool(intent), exit_state=exit_state, |
| + hook=bool(self.j.last("return-hook")), acknowledged=acknowledged, |
| + completion_response=completion_response, |
| + hold_started=bool(self.j.last("divergence-hold")), |
| + attempts=len(attempts), key=key, activity_ready=bool(activity), |
| + prepared=bool(self.j.last("prepared")), |
| + minimum_intent=bool(self.j.last("intent", op="minimum")), |
| + action_verified=bool(self.j.last("box-action-verified", action=self.action())), |
| + already_restored=bool(self.j.last("rollback-requested", already_restored=True)), |
| + deadline_close=bool(intent and self.clock() + 120 >= intent["at"] + 900), |
| + observed=group is not None, n=h["n"]) |
| + if group is not None: |
| + facts.update(phase=group["members"].get(h["iid"]), |
| + minimum=group["minimum"], desired=group["desired"], maximum=group["maximum"], |
| + members_match=sorted(group["members"]) == h["members"], |
| + template_match=group["template"] == h["template"], |
| + deregistered=all(t.get(h["iid"], "unused") == "unused" for t in group["targets"]), |
| + targets_healthy=all(group["members"].get(m) == "InService" and |
| + group["healthy"].get(m) is True and |
| + all(t.get(m) == "healthy" for t in group["targets"]) for m in h["members"])) |
| + facts.update(observation) |
| + return facts |
| + |
| + def stop_decision(self, decision, error=None): |
| + if decision.action == "failed": |
| + self.alert(decision.reason, failed=True) |
| + if error is not None: |
| + self.event("alert", reason=TEXT[decision.reason]) |
| + self.say("ALERT", TEXT[decision.reason]) |
| + raise error |
| + self.alert(decision.reason) |
| + |
| def resume(self): |
| self.restore_header() |
| h = self.header |
| - if self.j.last("done"): |
| - self.state.finish() |
| - return |
| - self.observe_pending_action() |
| - if self.j.last("exit-intent"): |
| - return self.return_member() |
| - self.prepare() |
| - g = self.snapshot() |
| - self.invariant(g) |
| - phase = g["members"][h["iid"]] |
| - if phase == "InService": |
| - require(g["desired"] == h["n"] and g["minimum"] in (h["n"], h["n"] - 1), "shape") |
| - require(g["minimum"] == h["n"] or self.j.last("intent", op="minimum"), "shape") |
| - # Recheck peers and identity before the first group write, including |
| - # resume after preparation or an ambiguous minimum update. |
| - for member in h["members"]: |
| - require(self.call("online", iid=member) is True, "offline") |
| - require(g["members"][member] == "InService" and |
| - g["healthy"].get(member) is True and |
| - all(t.get(member) == "healthy" for t in g["targets"]), "peer") |
| - self.readiness(member) |
| - if g["minimum"] == h["n"]: |
| - self.event("phase", phase="lower-minimum") |
| - self.call("minimum", value=h["n"] - 1) |
| - if self.j.last("intent", op="enter"): |
| - # An attended resume may retry only from the observed original |
| - # InService/desired-N shape. EnteringStandby/Standby instead go |
| - # straight to readback below. No desired-capacity repair exists. |
| - self.event("enter-retry", observed=g) |
| - self.event("phase", phase="enter-standby") |
| - if not self.j.last("enter-activity-baseline"): |
| - self.event("enter-activity-baseline", activities=self.call("activities", iid=h["iid"])) |
| - result = self.call("enter", iid=h["iid"], decrement=True) |
| - if result.get("activity"): |
| - self.event("enter-activity", activity=result["activity"]) |
| - self.wait_standby(lambda g: self.standby(g)) |
| - self.say("Standby", h["iid"]) |
| - if not self.j.last("rollback-requested", already_restored=True): |
| - self.mutation() |
| - self.event("phase", phase="local-verification", action=self.action()) |
| - self.wait_standby(lambda g: self.readiness(h["iid"], maintenance=True)) |
| - return self.return_member() |
| + end = self.clock() + WAIT |
| + group, error = None, None |
| + observed = dict(pending_checked=False, peers_checked=False) |
| + while True: |
| + facts = self.decision_facts("resume", group, timed_out=self.clock() >= end, **observed) |
| + decision = classify(facts) |
| + action = decision.action |
| + if action in {"failed", "resumable"}: |
| + self.stop_decision(decision, error) |
| + if action == "finish": |
| + self.state.finish() |
| + return |
| + if action == "return": |
| + return self.return_member() |
| + try: |
| + if action == "observe-action": |
| + self.observe_pending_action() |
| + observed["pending_checked"] = True |
| + elif action == "prepare": |
| + self.prepare() |
| + elif action == "describe": |
| + group = self.snapshot() |
| + elif action == "check-peers": |
| + for member in h["members"]: |
| + require(self.call("online", iid=member) is True, "offline") |
| + require(group["members"][member] == "InService" and |
| + group["healthy"].get(member) is True and |
| + all(t.get(member) == "healthy" for t in group["targets"]), "peer") |
| + self.readiness(member) |
| + observed["peers_checked"] = True |
| + elif action == "lower-minimum": |
| + self.event("phase", phase="lower-minimum") |
| + self.call("minimum", value=h["n"] - 1) |
| + group = None |
| + elif action == "enter": |
| + self.event("phase", phase="enter-standby") |
| + if not self.j.last("enter-activity-baseline"): |
| + self.event("enter-activity-baseline", activities=self.call("activities", iid=h["iid"])) |
| + result = self.call("enter", iid=h["iid"], decrement=True) |
| + if result.get("activity"): |
| + self.event("enter-activity", activity=result["activity"]) |
| + group = None |
| + end = self.clock() + WAIT |
| + elif action == "mutate": |
| + self.mutation() |
| + self.event("phase", phase="local-verification", action=self.action()) |
| + group = None |
| + # Bound the readiness wait, not time spent running apply. |
| + end = self.clock() + WAIT |
| + elif action == "observe-ready": |
| + try: |
| + self.readiness(h["iid"], maintenance=True) |
| + observed["readiness"] = "ok" |
| + except (Refusal, Uncertain): |
| + observed["readiness"] = "dropped" |
| + elif action == "wait": |
| + self.sleep(max(0, min(decision.delay, end - self.clock()))) |
| + group = None |
| + observed.pop("readiness", None) |
| + else: |
| + raise AssertionError(decision) |
| + except (Refusal, Uncertain) as exc: |
| + error = exc |
| + observed["operation_error"] = True |
| def rollback(self, iid): |
| self.restore_header() |
| require(iid == self.header["iid"] and not self.j.last("exit-intent"), "rollback_refused") |
| # Failed apply verification is a reason to roll back. Read installed |
| # state first instead of demanding that the failed apply verify again. |
| - s = self.box(iid) |
| + # The root status verb refuses while apply holds its lock. A cut |
| + # session is not proof that apply stopped; wait for a successful read. |
| + end, status_checked, status_error = self.clock() + WAIT, False, False |
| + while True: |
| + decision = classify(dict(context="rollback", status_checked=status_checked, |
| + status_error=status_error, timed_out=self.clock() >= end)) |
| + if decision.action == "resumable": |
| + self.stop_decision(decision) |
| + if decision.action == "inspect-rollback": |
| + break |
| + if decision.action == "wait": |
| + self.sleep(max(0, min(decision.delay, end - self.clock()))) |
| + status_error = False |
| + elif decision.action == "observe-status": |
| + try: |
| + s = self.box(iid) |
| + status_checked = True |
| + except (Refusal, Uncertain): |
| + status_error = True |
| self.identity(s, iid) |
| self.standby(self.snapshot()) |
| if not self.j.last("rollback-requested"): |
| @@ -1091,50 +1337,45 @@ class Operator: |
| return matches[0] |
| def return_member(self): |
| - """The only owner of ExitStandby and defensive return CONTINUE.""" |
| + """Execute classify() decisions. Sole owner of Exit and CONTINUE.""" |
| self.restore_header() |
| - self.observe_pending_action() |
| h, iid = self.header, self.header["iid"] |
| self.event("phase", phase="return") |
| end = self.clock() + WAIT |
| + group, ready, error = None, None, None |
| + observed = {} |
| + backed_off = 0 |
| while True: |
| - if self.clock() >= end: |
| - self.alert("return_phase") |
| - g, phase = None, None |
| + facts = self.decision_facts("return", group, timed_out=self.clock() >= end, **observed) |
| + facts["backoff_done"] = backed_off == facts["attempts"] |
| + decision = classify(facts) |
| + action = decision.action |
| + if action in {"failed", "resumable"}: |
| + self.stop_decision(decision, error) |
| + if action == "held": |
| + self.event("divergence-held", iid=iid) |
| + self.alert("divergence") |
| try: |
| - try: |
| - g = self.snapshot() |
| - except (Refusal, Uncertain): |
| - if self.j.last("return-hook") and not self.j.last("divergence-hold"): |
| - self.alert("return_failed", failed=True) |
| - # No observed hook: a failed read is resumable. It does |
| - # not establish an unknown lifecycle state or divergence. |
| - raise |
| - exit_call = self.j.last("intent", op="exit") |
| - exit_error = self.j.last("error", op="exit") |
| - sent = exit_call and not (exit_error and exit_error["intent"] == exit_call["seq"] and |
| - exit_error.get("dispatched") is False) |
| - phase = g["members"].get(iid) |
| - intent = self.j.last("exit-intent") |
| - if phase == "Pending:Wait": |
| + if action == "describe": |
| + group = self.snapshot() |
| + elif action == "record-hook": |
| + intent = self.j.last("exit-intent") |
| + self.state.write(self.state.blocked, dict(transaction=h["transaction"], phase="Pending:Wait")) |
| self.event("return-hook", deadline=intent["at"] + 900 if intent else None) |
| - self.state.write(self.state.blocked, dict(transaction=h["transaction"], phase=phase)) |
| - if sent and (phase is None or phase.startswith("Terminat") or |
| - sorted(g["members"]) != h["members"]): |
| - self.alert("lost_member", failed=True) |
| - if sent and phase not in {"Standby", "EnteringStandby", "Pending", "PreInService", |
| - "Pending:Wait", "Pending:Proceed", "InService"}: |
| - self.alert("unknown_phase", failed=True) |
| - self.invariant(g) |
| - if self.j.last("divergence-hold") and phase in {"Standby", "EnteringStandby"}: |
| - self.wait_standby(lambda current: self.standby(current)) |
| - self.event("divergence-held", iid=iid) |
| - self.alert("divergence") |
| - if phase == "Standby": |
| - self.standby(g) |
| - if intent: |
| - self.sleep(1) |
| - ready = self.readiness(iid, maintenance=True) |
| + elif action == "observe-ready": |
| + try: |
| + ready = self.readiness(iid, maintenance=not bool(self.j.last("returned"))) |
| + intent = self.j.last("exit-intent") |
| + if intent and group["members"][iid] != "Standby": |
| + require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| + expected = h["old"] if self.action() == "rollback" else h["new"] |
| + require(ready["status"]["binary_sha256"] == expected, "process") |
| + observed["readiness"] = "ok" |
| + except (Refusal, Uncertain): |
| + observed["readiness"] = "dropped" |
| + elif action == "activity": |
| + self.exit_activity() |
| + elif action == "exit": |
| self.event("exit-intent", transaction=h["transaction"], iid=iid, |
| boot_id=h["identity"]["boot_id"], process=ready["status"]["edge"]["identity"], |
| observed=ready["observed"], generation=ready["generation"]) |
| @@ -1144,79 +1385,41 @@ class Operator: |
| self.event("exit-activity", activity=result["activity"]) |
| except Uncertain: |
| pass |
| - # Always describe after a response, including a lost one. |
| - continue |
| - require(intent is not None, "return_intent") |
| - require(g["desired"] == h["n"] and g["minimum"] in (h["n"] - 1, h["n"]), "members") |
| - if phase == "Pending:Wait": |
| - # Leave room for the bounded status sessions and completion. |
| - if self.clock() + 120 >= intent["at"] + 900: |
| - self.alert("return_failed", failed=True) |
| - activity = self.exit_activity() |
| - try: |
| - ready = self.readiness(iid, maintenance=True) |
| - require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| - except (Refusal, Uncertain): |
| - self.alert("return_failed", failed=True) |
| - key = [h["transaction"], iid, h["identity"]["boot_id"], intent["process"], activity] |
| - attempts = [r for r in self.j.events if r["kind"] == "return-action" and r["key"] == key] |
| - if self.j.last("return-acknowledged", key=key): |
| - self.sleep(2) |
| - continue |
| - if len(attempts) >= 4: |
| - self.alert("return_attempts", failed=True) |
| - if attempts: |
| - self.sleep((1, 2, 4)[len(attempts) - 1]) |
| - # The next iteration describes before another write and |
| - # then obtains a new readiness observation. |
| - g = self.snapshot() |
| - if g["members"][iid] != "Pending:Wait": |
| - continue |
| - ready = self.readiness(iid, maintenance=True) |
| - require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| - self.event("return-action", key=key, attempt=len(attempts) + 1, |
| - deadline=intent["at"] + 900, result="CONTINUE") |
| + group, observed = None, {} |
| + elif action == "complete": |
| + key, attempt = facts["key"], facts["attempts"] + 1 |
| + self.event("return-action", key=key, attempt=attempt, |
| + deadline=self.j.last("exit-intent")["at"] + 900, result="CONTINUE") |
| try: |
| self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE", |
| freshness=ready["observed"]) |
| - self.event("return-outcome", key=key, attempt=len(attempts) + 1, outcome="acknowledged") |
| + self.event("return-outcome", key=key, attempt=attempt, outcome="acknowledged") |
| self.event("return-acknowledged", key=key) |
| except Uncertain: |
| - self.event("return-outcome", key=key, attempt=len(attempts) + 1, outcome="uncertain") |
| - continue |
| - if phase == "InService": |
| - if self.j.last("return-hook"): |
| - # An acknowledged CONTINUE plus InService ends the |
| - # hook. R16 must hold the member even if health drops |
| - # or the targets are still warming. An ambiguous |
| - # completion still needs current admission to resolve. |
| - if not (self.j.last("return-acknowledged") or self.j.last("divergence-hold")): |
| - ready = self.readiness(iid, maintenance=True) |
| - require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| - require(g["minimum"] == h["n"] - 1, "held") |
| - self.event("divergence-hold", iid=iid) |
| - try: |
| - self.call("enter", iid=iid, decrement=True) |
| - except Uncertain: |
| - pass |
| - continue |
| - if not all(g["members"][member] == "InService" and g["healthy"].get(member) is True and |
| - all(t.get(member) == "healthy" for t in g["targets"]) for member in h["members"]): |
| - self.sleep(max(0, min(5, end - self.clock()))) |
| - continue |
| - # Once revoked, use the saved observation plus a fresh |
| - # identity/readiness read; a consumed permit may be absent. |
| - if not self.j.last("returned"): |
| - ready = self.readiness(iid, maintenance=True) |
| - require(ready["status"]["edge"]["identity"] == intent["process"], "admission") |
| - self.event("returned", process=intent["process"]) |
| - if g["minimum"] != h["n"]: |
| - self.event("phase", phase="restore-minimum") |
| - self.call("minimum", value=h["n"]) |
| - continue |
| - s = self.box(iid) |
| - self.identity(s, iid) |
| - require(s["edge"]["identity"] == intent["process"] and s["health"]["state"] == "healthy", "admission") |
| + self.event("return-outcome", key=key, attempt=attempt, outcome="uncertain") |
| + group, observed = None, {} |
| + elif action == "acknowledge": |
| + self.event("return-acknowledged", key=facts["key"], |
| + evidence="response" if facts["completion_response"] else "InService-admitted") |
| + elif action == "hold": |
| + self.event("divergence-hold", iid=iid) |
| + try: |
| + self.call("enter", iid=iid, decrement=True) |
| + except Uncertain: |
| + pass |
| + group, observed = None, {} |
| + elif action in {"wait", "backoff"}: |
| + self.sleep(max(0, min(decision.delay, end - self.clock()))) |
| + if action == "backoff": |
| + backed_off = facts["attempts"] |
| + group, observed = None, {} |
| + elif action == "restore-minimum": |
| + self.event("returned", process=self.j.last("exit-intent")["process"]) |
| + self.event("phase", phase="restore-minimum") |
| + self.call("minimum", value=h["n"]) |
| + group, observed = None, {} |
| + elif action == "finish-return": |
| + s = ready["status"] |
| if s["permit"].get("state") != "absent": |
| require(s["permit"].get("transaction") == h["transaction"], "permit") |
| self.event("phase", phase="revocation") |
| @@ -1226,26 +1429,12 @@ class Operator: |
| provider_divergence=self.state.blocked.exists()) |
| self.state.finish() |
| self.say("done", TEXT["done"]) |
| - if self.state.blocked.exists(): |
| - self.say("ALERT", TEXT["divergence"]) |
| return |
| - require(phase in {"Pending", "PreInService", "Pending:Proceed"}, "return_phase") |
| - except (FailedProbe, DivergenceHeld): |
| - raise |
| - except ObservationExpired: |
| - if phase == "Pending:Wait": |
| - self.alert("return_failed", failed=True) |
| - raise |
| - except (Refusal, Uncertain): |
| - if phase == "Pending:Wait": |
| - self.alert("return_failed", failed=True) |
| - if g is None or phase != "Standby": |
| - raise |
| - if self.clock() >= end: |
| - self.alert("timeout" if locals().get("phase") == "Standby" else "return_phase") |
| - if self.clock() >= end: |
| - self.alert("return_phase") |
| - self.sleep(5) |
| + else: |
| + raise AssertionError(decision) |
| + except (Refusal, Uncertain) as exc: |
| + error = exc |
| + observed["describe_error" if action == "describe" else "operation_error"] = True |
| def main(argv=None): |
diff --git a/scripts/region_group_roll_test.py b/scripts/region_group_roll_test.py| index de1e3259b..a80bcc3fb 100644 |
| --- a/scripts/region_group_roll_test.py |
| +++ b/scripts/region_group_roll_test.py |
| @@ -4,6 +4,9 @@ import importlib.util |
| import io |
| import json |
| import os |
| +import random |
| +import time |
| +from collections import Counter |
| from pathlib import Path |
| import shlex |
| import subprocess |
| @@ -22,6 +25,19 @@ OLD, NEW = "a" * 64, "b" * 64 |
| IID, PEER = "i-" + "1" * 17, "i-" + "2" * 17 |
| +def test_config(state_dir): |
| + account_scope = "eu-west-1:" + "0" * 12 |
| + return dict( |
| + deployment="example", account="0" * 12, region="eu-west-1", |
| + group="example-group", hook="example-launch", |
| + group_arn="arn:aws:autoscaling:" + account_scope + |
| + ":autoScalingGroup:example:autoScalingGroupName/example-group", |
| + target_groups=["arn:aws:elasticloadbalancing:" + account_scope + |
| + ":targetgroup/example-" + p + "/" + p * 16 for p in ("8", "4")], |
| + bucket="example-deployment", document="AWS-StartNonInteractiveCommand", |
| + state_dir=state_dir, profile="example", min_release="v0.34.0") |
| + |
| + |
| class Death(BaseException): |
| pass |
| @@ -219,14 +235,7 @@ class StandbyTests(unittest.TestCase): |
| base = os.environ.get("TMPDIR") or str(Path.home() / ".cache") |
| self.tmp = tempfile.TemporaryDirectory(prefix="region-roll-test-", dir=base) |
| self.addCleanup(self.tmp.cleanup) |
| - self.config = dict(deployment="example", account="0" * 12, region="eu-west-1", |
| - group="example-group", hook="example-launch", |
| - group_arn="arn:aws:autoscaling:eu-west-1:" + "0" * 12 + |
| - ":autoScalingGroup:example:autoScalingGroupName/example-group", |
| - target_groups=["arn:aws:elasticloadbalancing:eu-west-1:" + "0" * 12 + |
| - ":targetgroup/example-" + p + "/" + p * 16 for p in ("8", "4")], |
| - bucket="example-deployment", document="AWS-StartNonInteractiveCommand", |
| - state_dir=self.tmp.name, profile="example", min_release="v0.34.0") |
| + self.config = test_config(self.tmp.name) |
| self.fake = Fake(self.config) |
| self.output = io.StringIO() |
| self.store = roll.State(self.config, owner=os.geteuid()) |
| @@ -1407,21 +1416,564 @@ class AdapterTests(unittest.TestCase): |
| op.j.close() |
| +class RoundThreeTests(unittest.TestCase): |
| + setUp = StandbyTests.setUp |
| + engine = StandbyTests.engine |
| + run_roll = StandbyTests.run_roll |
| + resume = StandbyTests.resume |
| + assert_retained = StandbyTests.assert_retained |
| + journal = RoundTwoTests.journal |
| + |
| + def test_box_action_time_does_not_consume_readiness_wait(self): |
| + self.fake.after = lambda name: self.fake.sleep(901) if name == "apply" else None |
| + self.run_roll() |
| + self.assertIsNone(self.store.active_id()) |
| + self.assert_retained() |
| + |
| + def test_acknowledgement_reconstructed_after_death_during_journaling(self): |
| + for boundary in ("response", "return-outcome", "return-acknowledged"): |
| + with self.subTest(boundary=boundary): |
| + self.setUp() |
| + self.fake.hook = True |
| + add = roll.Journal.add |
| + cut = False |
| + def die(journal, kind, **data): |
| + nonlocal cut |
| + row = add(journal, kind, **data) |
| + if not cut and kind == boundary and (kind != "response" or data.get("op") == "complete"): |
| + cut = True |
| + raise Death(boundary) |
| + return row |
| + with patch.object(roll.Journal, "add", die): |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + # Readback remains stale and admission is now unavailable. |
| + perform = self.fake.perform |
| + stale = 0 |
| + def read(op, args): |
| + nonlocal stale |
| + result = perform(op, args) |
| + if op == "group" and self.fake.writes.count("enter") == 1 and stale < 2: |
| + result["members"][IID] = "Pending:Wait" |
| + stale += 1 |
| + return result |
| + self.fake.perform = read |
| + self.fake.admitted = False |
| + with self.assertRaises(roll.DivergenceHeld): |
| + self.resume() |
| + self.assertEqual(self.fake.continues, 1) |
| + self.assertIsNone(self.journal().last("failed-probe")) |
| + |
| + def test_rollback_waits_for_cut_apply_lock_before_inspecting_digest(self): |
| + self.fake.fault, self.fake.fault_at = "death", 5 |
| + with self.assertRaises(Death): |
| + self.run_roll() |
| + self.fake.boxes[IID]["binary_sha256"] = OLD |
| + request = self.fake.request |
| + reads = 0 |
| + def busy(op, args): |
| + nonlocal reads |
| + if op == "session" and args["verb"] == "status": |
| + reads += 1 |
| + if reads < 3: |
| + raise roll.Refusal("apply lock busy") |
| + if reads == 3: |
| + self.fake.boxes[IID]["binary_sha256"] = NEW |
| + if reads < 3: |
| + self.assertEqual((op, args["verb"]), ("session", "status")) |
| + return request(op, args) |
| + self.fake.request = busy |
| + with self.store.lock(): |
| + j = self.journal() |
| + start = self.fake.now |
| + self.engine(j).rollback(IID) |
| + self.assertFalse(j.last("rollback-requested")["already_restored"]) |
| + self.assertGreaterEqual(self.fake.now - start, 10) |
| + self.assertEqual(self.fake.writes.count("rollback"), 1) |
| + self.assert_retained() |
| + |
| + def test_acknowledged_stale_wait_ignores_dropped_admission(self): |
| + self.fake.hook = True |
| + perform = self.fake.perform |
| + stale = 0 |
| + def transition(op, args): |
| + nonlocal stale |
| + if op == "group" and self.fake.continues and self.fake.writes.count("enter") == 1: |
| + stale += 1 |
| + self.fake.states[IID] = "Pending:Wait" if stale < 4 else "InService" |
| + self.fake.admitted = False |
| + return perform(op, args) |
| + self.fake.perform = transition |
| + with self.assertRaises(roll.DivergenceHeld): |
| + self.run_roll() |
| + self.assertIsNone(self.journal().last("failed-probe")) |
| + self.assertEqual(self.fake.continues, 1) |
| + self.assert_retained() |
| + |
| + def test_acknowledged_describe_blip_before_hold_is_resumable(self): |
| + self.fake.hook = True |
| + perform = self.fake.perform |
| + def transition(op, args): |
| + if op == "group" and self.fake.continues: |
| + raise roll.Uncertain("describe blip after acknowledgement") |
| + return perform(op, args) |
| + self.fake.perform = transition |
| + with self.assertRaises(roll.Uncertain): |
| + self.run_roll() |
| + self.assertIsNone(self.journal().last("failed-probe")) |
| + self.fake.perform = perform |
| + with self.assertRaises(roll.DivergenceHeld): |
| + self.resume() |
| + self.assertEqual(self.fake.continues, 1) |
| + |
| + |
| +class ClassifyTests(unittest.TestCase): |
| + def test_acknowledgement_dominates_every_observation(self): |
| + for phase in ("Pending:Wait", "Pending:Proceed", "Pending", "PreInService", |
| + "InService", "Standby", "Terminated", None): |
| + for readiness in ("ok", "dropped", "unknown"): |
| + for error in (False, True): |
| + with self.subTest(phase=phase, readiness=readiness, error=error): |
| + decision = roll.classify(dict(context="return", acknowledged=True, |
| + hook=True, phase=phase, readiness=readiness, describe_error=error, |
| + observed=True, members_match=True, template_match=True, |
| + n=2, minimum=1, desired=2, maximum=2, exit_intent=True)) |
| + self.assertIn(decision.action, {"hold", "wait", "resumable", "held"}) |
| + |
| + |
| +# Each row becomes a separate unittest case so failures identify the table cell. |
| +CLASSIFY_BASE = dict(context="return", observed=True, n=2, minimum=1, desired=2, |
| + maximum=2, members_match=True, template_match=True, phase="InService", |
| + exit_intent=True, exit_state="acknowledged", targets_healthy=True, |
| + readiness="ok", deregistered=True, prepared=True, pending_checked=True, |
| + peers_checked=True, action_verified=True) |
| +CLASSIFY_ROWS = [ |
| + ("rollback_observe", dict(context="rollback"), "observe-status"), |
| + ("rollback_busy", dict(context="rollback", status_error=True), "wait"), |
| + ("rollback_observed", dict(context="rollback", status_checked=True), "inspect-rollback"), |
| + ("rollback_timeout", dict(context="rollback", status_error=True, timed_out=True), "resumable"), |
| + ("describe", dict(observed=False), "describe"), |
| + ("ordinary_describe_error", dict(describe_error=True), "resumable"), |
| + ("hook_describe_error", dict(hook=True, describe_error=True), "failed"), |
| + ("ack_describe_error", dict(hook=True, acknowledged=True, describe_error=True), "resumable"), |
| + ("ack_operation_error", dict(acknowledged=True, operation_error=True), "resumable"), |
| + ("durable_completion_response", dict(completion_response=True, observed=False), "acknowledge"), |
| + ("discover_hook_before_missing_intent", dict(phase="Pending:Wait", exit_intent=False), "record-hook"), |
| + ("ack_stale_wait", dict(phase="Pending:Wait", hook=True, acknowledged=True, readiness="dropped"), "wait"), |
| + ("ack_inservice_unready", dict(hook=True, acknowledged=True, readiness="dropped", targets_healthy=False), "hold"), |
| + ("ack_terminated", dict(phase="Terminated", acknowledged=True), "resumable"), |
| + ("ack_absent", dict(phase=None, acknowledged=True, members_match=False), "resumable"), |
| + ("ack_wrong_capacity", dict(acknowledged=True, minimum=2), "resumable"), |
| + ("ack_unknown", dict(acknowledged=True, phase="Unknown"), "resumable"), |
| + ("ack_timeout", dict(acknowledged=True, timed_out=True), "resumable"), |
| + ("hold_still_draining", dict(hold_started=True, phase="Standby", desired=1, deregistered=False), "wait"), |
| + ("hold_entering", dict(hold_started=True, phase="EnteringStandby", desired=1), "wait"), |
| + ("hold_verified", dict(hold_started=True, phase="Standby", desired=1), "held"), |
| + ("hold_capacity_wrong", dict(hold_started=True, phase="Standby", desired=2), "resumable"), |
| + ("terminated_before_ack", dict(phase="Terminated"), "failed"), |
| + ("absent_before_ack", dict(phase=None), "failed"), |
| + ("replaced_before_ack", dict(members_match=False), "failed"), |
| + ("unknown_before_ack", dict(phase="Unknown"), "failed"), |
| + ("unsent_unknown", dict(phase="Unknown", exit_state="none"), "resumable"), |
| + ("wrong_template", dict(template_match=False), "resumable"), |
| + ("standby_unobserved", dict(phase="Standby", desired=1, readiness="unknown"), "observe-ready"), |
| + ("standby_unready", dict(phase="Standby", desired=1, readiness="dropped"), "wait"), |
| + ("standby_ready", dict(phase="Standby", desired=1), "exit"), |
| + ("standby_not_drained", dict(phase="Standby", desired=1, deregistered=False), "wait"), |
| + ("standby_wrong_minimum", dict(phase="Standby", desired=1, minimum=2), "resumable"), |
| + ("pending_wait_activity", dict(phase="Pending:Wait", hook=True), "activity"), |
| + ("pending_wait_readiness", dict(phase="Pending:Wait", hook=True, activity_ready=True, readiness="unknown"), "observe-ready"), |
| + ("pending_wait_drop", dict(phase="Pending:Wait", hook=True, activity_ready=True, readiness="dropped"), "failed"), |
| + ("pending_wait_complete", dict(phase="Pending:Wait", hook=True, activity_ready=True), "complete"), |
| + ("pending_wait_backoff", dict(phase="Pending:Wait", hook=True, activity_ready=True, attempts=1), "backoff"), |
| + ("pending_wait_retry", dict(phase="Pending:Wait", hook=True, activity_ready=True, attempts=3, backoff_done=True), "complete"), |
| + ("pending_wait_exhausted", dict(phase="Pending:Wait", hook=True, attempts=4), "failed"), |
| + ("pending_wait_deadline", dict(phase="Pending:Wait", hook=True, deadline_close=True), "failed"), |
| + ("pending_wait_wrong_desired", dict(phase="Pending:Wait", hook=True, desired=1), "resumable"), |
| + ("pending", dict(phase="Pending"), "wait"), |
| + ("proceed", dict(phase="Pending:Proceed"), "wait"), |
| + ("preinservice", dict(phase="PreInService"), "wait"), |
| + ("inservice_warming", dict(targets_healthy=False), "wait"), |
| + ("inservice_unknown_readiness", dict(readiness="unknown"), "observe-ready"), |
| + ("inservice_drop", dict(readiness="dropped"), "wait"), |
| + ("inservice_restore", {}, "restore-minimum"), |
| + ("inservice_finish", dict(minimum=2), "finish-return"), |
| + ("ambiguous_complete_resolved", dict(hook=True, attempts=1, activity_ready=True), "acknowledge"), |
| + ("ambiguous_complete_not_ready", dict(hook=True, attempts=1, activity_ready=True, readiness="dropped"), "wait"), |
| + ("no_intent", dict(exit_intent=False), "resumable"), |
| + ("resume_return", dict(context="resume"), "return"), |
| + ("resume_done", dict(context="resume", done=True), "finish"), |
| + ("resume_observe_cut_action", dict(context="resume", exit_intent=False, pending_checked=False), "observe-action"), |
| + ("resume_prepare", dict(context="resume", exit_intent=False, prepared=False), "prepare"), |
| + ("resume_peers", dict(context="resume", exit_intent=False, minimum=2, peers_checked=False), "check-peers"), |
| + ("resume_lower", dict(context="resume", exit_intent=False, minimum=2), "lower-minimum"), |
| + ("resume_unexplained_minimum", dict(context="resume", exit_intent=False), "resumable"), |
| + ("resume_enter", dict(context="resume", exit_intent=False, minimum_intent=True), "enter"), |
| + ("resume_mutate", dict(context="resume", exit_intent=False, phase="Standby", desired=1, action_verified=False), "mutate"), |
| + ("resume_readiness", dict(context="resume", exit_intent=False, phase="Standby", desired=1, readiness="unknown"), "observe-ready"), |
| + ("resume_verified", dict(context="resume", exit_intent=False, phase="Standby", desired=1), "return"), |
| + ("resume_entering", dict(context="resume", exit_intent=False, phase="EnteringStandby", desired=1), "wait"), |
| +] |
| + |
| + |
| +def classify_row(changes, expected): |
| + def test(self): |
| + facts = dict(CLASSIFY_BASE, **changes) |
| + before = copy.deepcopy(facts) |
| + decision = roll.classify(facts) |
| + self.assertEqual(decision.action, expected) |
| + self.assertEqual(facts, before) |
| + self.assertEqual(roll.classify(facts), decision) |
| + return test |
| + |
| + |
| +for row_name, row_changes, row_expected in CLASSIFY_ROWS: |
| + setattr(ClassifyTests, "test_table_" + row_name, classify_row(row_changes, row_expected)) |
| + |
| + |
| +class SimulationJournal: |
| + # Persistence/fcntl/fsync are exercised by the filesystem tests. Here each |
| + # load makes a new object from durable rows, with death before/after append. |
| + last = roll.Journal.last |
| + |
| + def __init__(self, state): |
| + self.state = state |
| + self.path = Path(state.tx + ".jsonl") |
| + self.events = copy.deepcopy(state.rows) |
| + |
| + def add(self, kind, **data): |
| + self.state.sim.journal_step("before", kind, data) |
| + row = dict(seq=len(self.events), kind=kind, **copy.deepcopy(data)) |
| + self.events.append(row) |
| + self.state.rows.append(copy.deepcopy(row)) |
| + self.state.sim.journal_step("after", kind, data) |
| + return row |
| + |
| + def close(self): |
| + pass |
| + |
| + |
| +class SimulationFlag: |
| + def __init__(self): |
| + self.present = False |
| + |
| + def exists(self): |
| + return self.present |
| + |
| + |
| +class SimulationState: |
| + def __init__(self, sim): |
| + self.sim, self.held = sim, True |
| + self.rows, self.tx, self.active = [], None, False |
| + self.blocked = SimulationFlag() |
| + self.observation = object() |
| + |
| + def read(self, path): |
| + assert path is self.observation |
| + c = self.sim.c |
| + return dict(v=1, group_arn=c["group_arn"], hook=c["hook"], |
| + template={"LaunchTemplateId": "lt-example", "Version": "1"}, documented_no_hook=True) |
| + |
| + def write(self, path, value): |
| + assert path is self.blocked |
| + self.blocked.present = True |
| + |
| + def active_id(self): |
| + return self.tx if self.active else None |
| + |
| + def create(self, header): |
| + self.tx, self.active = header["transaction"], True |
| + journal = SimulationJournal(self) |
| + journal.add("begin", **header) |
| + return journal |
| + |
| + def finish(self): |
| + self.active = False |
| + |
| + |
| +class SimulationFake(Fake): |
| + def __init__(self, sim): |
| + super().__init__(sim.c) |
| + self.sim = sim |
| + self.hook = sim.rng.choice((False, True)) |
| + self.target_warmup = sim.rng.randint(1, 80) |
| + self.transitions = [] |
| + self.stale_waits = 0 |
| + self.completed = False |
| + self.completed_key = None |
| + self.acknowledgements = Counter() |
| + |
| + def advance(self, seconds): |
| + self.sleep_base(seconds) |
| + while self.transitions and self.transitions[0][0] <= self.now: |
| + _, phase = self.transitions.pop(0) |
| + self.states[IID] = phase |
| + self.sim.coverage["phase:" + phase] += 1 |
| + self.sim.trace.append(("transition", phase)) |
| + |
| + def sleep_base(self, seconds): |
| + super().sleep(seconds) |
| + |
| + def sleep(self, seconds): |
| + self.advance(seconds) |
| + self.sim.environment("sleep") |
| + self.sim.audit("sleep") |
| + self.sim.maybe_die("sleep") |
| + |
| + def schedule(self, phases): |
| + at = self.now |
| + self.transitions = [] |
| + for phase in phases: |
| + at += self.sim.rng.randint(1, 8) |
| + self.transitions.append((at, phase)) |
| + |
| + def request(self, op, args): |
| + sim = self.sim |
| + write = op in {"minimum", "enter", "exit", "complete", "desired"} or ( |
| + op == "session" and args["verb"] != "status") |
| + self.calls.append((op, copy.deepcopy(args))) |
| + self.advance(0.05) |
| + # Admission changes at reads and waits, including both status reads. |
| + # A confirmed observation is stable through its immediate dispatch; |
| + # the operator cannot atomically fence a later independent box failure. |
| + if not write: |
| + sim.environment(op) |
| + sim.maybe_die("before-api:" + op) |
| + sim.audit("before-api:" + op) |
| + if sim.chaos and op in {"group", "targets"} and sim.rng.random() < 0.04: |
| + sim.coverage["describe-error"] += 1 |
| + if sim.acknowledged(): |
| + sim.coverage["describe-error-after-ack"] += 1 |
| + sim.trace.append(("describe-error", op)) |
| + raise roll.Uncertain("simulation describe failure") |
| + if op == "minimum" and args["value"] == 2: |
| + assert not sim.acknowledged() and not sim.last("return-hook") and not sim.last("divergence-hold"), "minimum restored in hold" |
| + assert self.states[IID] == "InService" and self.tg[IID] == "healthy" and self.admitted, "minimum restored before readiness" |
| + assert self.desired == 2, "minimum raised desired" |
| + if op == "complete": |
| + assert args["result"] == "CONTINUE", "ABANDON sent" |
| + assert self.admitted and self.boxes[IID]["health"]["state"] == "healthy", "CONTINUE while unready" |
| + assert sim.last("readiness"), "CONTINUE without observation" |
| + if self.completed: |
| + sim.coverage["duplicate-rejected"] += 1 |
| + raise roll.Uncertain("no lifecycle action remains") |
| + assert self.states[IID] == "Pending:Wait", "CONTINUE outside wait" |
| + self.completed_key = tuple(sim.last("return-action")["key"]) |
| + assert op not in {"desired", "terminate"}, "forbidden provider write" |
| + old_desired = self.desired |
| + result = self.perform(op, args) |
| + if op == "minimum": |
| + assert self.desired == old_desired, "minimum raised desired" |
| + if write: |
| + name = args["verb"] if op == "session" else op |
| + self.writes.append(name) |
| + sim.trace.append(("write", name, self.states[IID], self.minimum, self.desired)) |
| + sim.coverage["write:" + name] += 1 |
| + if op == "exit": |
| + if self.hook: |
| + self.states[IID] = "Pending" |
| + self.schedule(["Pending:Wait"]) |
| + else: |
| + self.states[IID] = "PreInService" |
| + self.schedule(["Pending", "InService"]) |
| + if op == "complete": |
| + self.completed = True |
| + self.deadline = None |
| + self.states[IID] = "Pending:Proceed" |
| + self.schedule(["Pending", "InService"]) |
| + self.stale_waits = sim.rng.randint(0, 5) |
| + if op == "enter": |
| + self.transitions = [] |
| + if op == "group" and self.completed and self.stale_waits and self.writes.count("enter") == 1: |
| + result["members"][IID] = "Pending:Wait" |
| + self.stale_waits -= 1 |
| + sim.coverage["stale-wait"] += 1 |
| + if sim.acknowledged(): |
| + sim.coverage["stale-wait-after-ack"] += 1 |
| + sim.audit("after-api:" + op) |
| + sim.maybe_die("after-api:" + op) |
| + if write and sim.chaos and sim.rng.random() < 0.12: |
| + sim.trace.append(("response-loss", op)) |
| + sim.coverage["loss:" + (args["verb"] if op == "session" else op)] += 1 |
| + raise roll.Uncertain("simulation lost write response") |
| + if op == "complete": |
| + self.acknowledgements[self.completed_key] += 1 |
| + return copy.deepcopy(result) |
| + |
| + |
| +class Simulation: |
| + def __init__(self, seed, classifier=None): |
| + self.seed, self.rng = seed, random.Random(seed) |
| + self.c = test_config("/simulation") |
| + self.coverage, self.trace = Counter(), [] |
| + self.store = SimulationState(self) |
| + self.fake = SimulationFake(self) |
| + self.classifier = classifier or roll.classify |
| + self.deaths = 0 |
| + self.chaos = False |
| + self.output = io.StringIO() |
| + |
| + def last(self, kind): |
| + return next((r for r in reversed(self.store.rows) if r["kind"] == kind), None) |
| + |
| + def acknowledged(self): |
| + return self.last("return-acknowledged") is not None |
| + |
| + def journal_step(self, when, kind, data): |
| + if kind == "validated" and when == "after": |
| + self.chaos = True |
| + if when == "after" and kind in {"failed-probe", "return-acknowledged", "divergence-held", "done"}: |
| + self.trace.append(("journal", kind)) |
| + self.audit(when + ":journal:" + kind) |
| + self.maybe_die(when + ":journal:" + kind) |
| + |
| + def maybe_die(self, boundary): |
| + if self.chaos and self.deaths < 3 and self.rng.random() < 0.007: |
| + self.deaths += 1 |
| + self.trace.append(("death", boundary)) |
| + self.coverage["death"] += 1 |
| + self.coverage["death:" + boundary] += 1 |
| + raise Death(boundary) |
| + |
| + def environment(self, boundary): |
| + if self.chaos and self.rng.random() < 0.08: |
| + self.fake.admitted = not self.fake.admitted |
| + self.fake.boxes[IID]["health"] = dict( |
| + state="healthy" if self.fake.admitted else "unhealthy", code=200 if self.fake.admitted else 503) |
| + self.trace.append(("admission", self.fake.admitted, boundary)) |
| + self.coverage["admission-recovery" if self.fake.admitted else "admission-drop"] += 1 |
| + |
| + def audit(self, boundary): |
| + f = self.fake |
| + assert set(f.states) == {IID, PEER} and f.states[IID] != "Terminated", "same iid lost" |
| + assert f.launches == f.abandons == 0, "provider replacement or ABANDON" |
| + assert f.exits <= 1 and f.continues <= 1, "duplicate accepted return write" |
| + assert all(count <= 1 for count in f.acknowledgements.values()), "duplicate acknowledged CONTINUE key" |
| + ack, fail = self.last("return-acknowledged"), self.last("failed-probe") |
| + assert not (ack and fail and fail["seq"] > ack["seq"]), "FailedProbe after acknowledgement" |
| + if self.last("divergence-hold"): |
| + assert f.minimum == 1, "minimum restored in hold" |
| + if self.last("divergence-held"): |
| + assert f.states[IID] == "Standby" and f.tg[IID] == "unused" and f.desired == f.minimum == 1, "hold not verified" |
| + assert self.store.blocked.exists(), "held group not blocked" |
| + self.coverage["steps"] += 1 |
| + |
| + def decide(self, facts): |
| + decision = self.classifier(facts) |
| + self.trace.append(("decision", facts.get("phase"), decision.action, |
| + facts.get("acknowledged"), facts.get("readiness", "unknown"))) |
| + if facts.get("context") == "return" and facts.get("acknowledged"): |
| + assert decision.action in {"describe", "record-hook", "hold", "held", "wait", "resumable"}, "post-ack decision: " + decision.action |
| + if decision.action == "complete": |
| + assert facts.get("readiness") == "ok", "CONTINUE decision while unready" |
| + if decision.action == "restore-minimum": |
| + assert not facts.get("hook") and not facts.get("acknowledged") and not facts.get("hold_started"), "minimum decision in hold" |
| + assert facts.get("phase") == "InService" and facts.get("targets_healthy") and facts.get("readiness") == "ok", "minimum decision before readiness" |
| + self.audit("classify") |
| + return decision |
| + |
| + def run(self): |
| + try: |
| + with patch.object(roll, "classify", self.decide): |
| + for turn in range(40): |
| + if turn >= 20: |
| + self.chaos = False |
| + self.fake.admitted = True |
| + self.fake.boxes[IID]["health"] = dict(state="healthy", code=200) |
| + journal = SimulationJournal(self.store) if self.store.rows else None |
| + op = roll.Operator(self.c, self.fake, self.store, journal=journal, |
| + clock=lambda: self.fake.now, sleep=self.fake.sleep, output=self.output, attended_by="simulation") |
| + try: |
| + op.resume() if journal else op.roll(IID, NEW) |
| + except roll.DivergenceHeld: |
| + assert self.last("divergence-held") |
| + break |
| + except (Death, roll.Refusal, roll.Uncertain): |
| + self.coverage["resume"] += 1 |
| + self.audit("operator-return") |
| + if not self.store.active: |
| + break |
| + # A failed probe is reported before its hook deadline. The |
| + # simulator recovers admission/API access and resumes the |
| + # saved transaction; it does not extend the provider timer. |
| + if self.last("failed-probe"): |
| + assert not self.fake.deadline or self.fake.now < self.fake.deadline, "late failed probe" |
| + self.fake.advance(0.1) |
| + else: |
| + raise AssertionError("did not converge after fault injection stopped") |
| + self.audit("end") |
| + if self.fake.hook: |
| + assert self.last("divergence-held") and self.fake.states[IID] == "Standby", "hook return did not hold" |
| + else: |
| + assert not self.store.active and self.fake.states[IID] == "InService", "ordinary return not finished" |
| + assert self.fake.minimum == self.fake.desired == self.fake.maximum == 2 |
| + return self.coverage |
| + except Exception as exc: |
| + raise AssertionError(f"seed={self.seed}: {exc}\ntrace={self.trace!r}") from exc |
| + |
| + |
| +class SimulationTests(unittest.TestCase): |
| + def test_seeded_return_simulation(self): |
| + count = int(os.environ.get("REGION_GROUP_ROLL_SIM_SEEDS", "50")) |
| + start = int(os.environ.get("REGION_GROUP_ROLL_SIM_START", "0")) |
| + began, coverage = time.monotonic(), Counter() |
| + for seed in range(start, start + count): |
| + coverage.update(Simulation(seed).run()) |
| + summary = {k: v for k, v in sorted(coverage.items()) if not k.startswith("death:")} |
| + print(f"simulation seeds={start}..{start + count - 1} wall={time.monotonic() - began:.3f}s coverage={summary}", file=sys.stderr) |
| + if count >= 50: |
| + for event in ("describe-error-after-ack", "stale-wait-after-ack", "death", "resume", |
| + "admission-drop", "admission-recovery", "loss:exit", "loss:complete", |
| + "phase:Pending:Wait", "phase:Pending", "phase:InService"): |
| + self.assertGreater(coverage[event], 0, event) |
| + |
| + def test_simulation_mutations(self): |
| + original = roll.classify |
| + def stale_wait(f): |
| + if f.get("acknowledged") and f.get("phase") == "Pending:Wait": |
| + return roll.Decision("failed", "return_failed") |
| + return original(f) |
| + def describe_blip(f): |
| + if f.get("acknowledged") and f.get("describe_error"): |
| + return roll.Decision("failed", "return_failed") |
| + return original(f) |
| + def minimum_in_hold(f): |
| + d = original(f) |
| + return roll.Decision("restore-minimum") if d.action == "hold" else d |
| + def unready_complete(f): |
| + if f.get("phase") == "Pending:Wait" and f.get("readiness") == "dropped" and not f.get("acknowledged"): |
| + return roll.Decision("complete") |
| + return original(f) |
| + for name, mutant in (("failed-after-stale-wait", stale_wait), ("failed-after-describe-blip", describe_blip), |
| + ("minimum-in-hold", minimum_in_hold), ("unready-continue", unready_complete)): |
| + with self.subTest(mutation=name): |
| + for seed in range(50): |
| + try: |
| + Simulation(seed, classifier=mutant).run() |
| + except AssertionError as exc: |
| + self.assertRegex(str(exc).splitlines()[0], |
| + "post-ack decision:|CONTINUE decision while unready") |
| + print(f"simulation mutation caught: {name}: {str(exc).splitlines()[0]}", file=sys.stderr) |
| + break |
| + else: |
| + self.fail(name + " survived simulation") |
| + |
| class MutationTests(unittest.TestCase): |
| def test_eight_required_mutations(self): |
| source = Path(roll.__file__).read_text() |
| cases = [ |
| ("decrement=false", [("decrement=True)", "decrement=False)")], "test_standby_roll_order"), |
| ("permit-before-Standby", [ |
| - ('self.call("enter", iid=h["iid"], decrement=True)', |
| - 'self.box(h["iid"], "permit", permit={})\n self.call("enter", iid=h["iid"], decrement=True)')], |
| + ('result = self.call("enter", iid=h["iid"], decrement=True)', |
| + 'self.box(h["iid"], "permit", permit={})\n result = self.call("enter", iid=h["iid"], decrement=True)')], |
| "test_standby_roll_order"), |
| ("blind desired reset", [ |
| ('result = self.call("exit", iid=iid, freshness=ready["observed"])', |
| 'result = self.call("exit", iid=iid, freshness=ready["observed"])\n self.call("desired", value=h["n"])')], |
| "test_standby_roll_order"), |
| ("exit-on-timeout", [ |
| - ('self.alert("timeout")', 'self.call("exit", iid=self.header["iid"])\n self.alert("timeout")')], |
| + ('self.alert(decision.reason)', |
| + 'self.call("exit", iid=self.header["iid"])\n self.alert(decision.reason)')], |
| "test_standby_shared_outage"), |
| ("ignored transaction lock", [ |
| ('fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)', 'pass')], "test_lock_refuses_second_writer"), |
| @@ -1429,10 +1981,13 @@ class MutationTests(unittest.TestCase): |
| ('self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE",\n freshness=ready["observed"])', 'self.sleep(901)')], |
| "test_standby_exit_pending_wait"), |
| ("completion before fresh admission", [ |
| - ('try:\n ready = self.readiness(iid, maintenance=True)', |
| - 'try:\n self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE")\n ready = self.readiness(iid, maintenance=True)')], |
| + ('elif action == "observe-ready":\n try:\n ready =', |
| + 'elif action == "observe-ready":\n try:\n self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE")\n ready =')], |
| "test_standby_exit_pending_wait_admission_loss"), |
| - ("PreInService as InService", [('== "InService"', 'in {"InService", "PreInService"}')], |
| + ("PreInService as InService", [ |
| + ('context, phase = f.get("context", "return"), f.get("phase")', |
| + 'context, phase = f.get("context", "return"), f.get("phase")\n if phase == "PreInService":\n phase = "InService"'), |
| + ('== "InService"', 'in {"InService", "PreInService"}')], |
| "test_standby_preinservice_is_not_inservice"), |
| ] |
| for name, replacements, test in cases: |