carlos / platform Public

Refuse lifecycle completion during group maintenance

Treat return hooks as provider divergence: journal, alert and block further rolls.
Record default-ABANDON termination or replacement as a failed probe.

Remove operator completion authority and document the cut. Validate with
132 Python tests, 3000 simulation seeds, 15 mutations, mock IAM tests and go build.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev e38fbb939f5ab1d6cca9b4c6d86b4fb0bb2dc1d2 parent 580a364
8 files changed, +345 −480
  • docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md +15 −8
  • docs/superpowers/notes/2026-11-05-region-ha-p3b2-standby-witness.md +19 −15
  • docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md +1 −0
  • infra/modules/region-host/README.md +6 −2
  • infra/modules/region-host/group_operator.tf +4 −3
  • infra/modules/region-host/tests/group_operator.tftest.hcl +3 −3
  • scripts/region-group-roll.py +44 −130
  • scripts/region_group_roll_test.py +253 −319

Intent

Human

<task-notification> <task-id>b56hsizc4</task-id> <tool-use-id>toolu_011EduEn7Uoo6Tfi9u27SFm1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/b56hsizc4.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b3h" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a4ec329a30dac296b</task-id> <tool-use-id>toolu_01LHTjS6C114otkFZNm5S1Xt</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/a4ec329a30dac296b.output</output-file> <status>completed</status> <summary>Agent "Re-review B3 invariant + sim" 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>**Verdict: not clean.** I found one more fault in the T1/I4 return-contract family. The tool can still record FailedProbe after AWS has accepted CONTINUE, when the success response was lost so `return-acknowledged` was never journaled. This round fixed the two literal paths only for the acknowledged case. The same failure outcome is reachable just before acknowledgement, so under your rule the build stops and goes to Paul. All paths below are under /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b2-build. "Script" is `scripts/region-group-roll.py`; "tests" is `scripts/region_group_roll_test.py`. ### Per-check verdicts 1. **Invariant text: PASS.** Script lines 34–41 match the brief word for word, apart from backticks. The other required invariants are stated too, and `classify()` restates the precedence rule (script lines 161–166, 200–202). 2. **classify() is pure and the only decider: PASS, structurally.** - `classify()` (script lines 160–302) reads only its input and has no side effects. - FailedProbe is raised only at script line 1060, through `alert(failed=True)`, which is called only from `stop_decision` (line 1205) on a `failed` decision. - DivergenceHeld is raised only at line 1062, from the `held` decision (line 1357). - Each provider write runs only under one decision: - Enter: line 1253 (`enter`) and line 1407 (`hold`) - Exit: line 1383 (`exit`) - CONTINUE: line 1394 (`complete`) - minimum: line 1247 (`lower-minimum`) and line 1419 (`restore-minimum`) - Other refusals (`require`, line 1089 `alert("process")`) are turned back into `operation_error` facts inside the resume/return loops. - The problem is what the table decides, not who decides it. 3. **Table coverage: PASS for the acknowledged state, gap for the ambiguous one.** Both previously open paths are rows, and their post-acknowledgement rows return wait/resumable (script lines 199–220). A 48-cell cross product also checks acknowledgement. But there is no row for "CONTINUE dispatched, outcome uncertain". With a hook and no acknowledgement: - line 194 (describe error) returns `failed` - line 280 (Pending:Wait with readiness dropped) returns `failed` - line 272 (attempts exhausted on stale Pending:Wait reads) returns `failed` 4. **The simulator is real: PASS, with one hole.** It is seeded and genuinely random (tests lines 1694–1913). It covers async phase lags, stale Pending:Wait after completion, describe failures, response loss on every write, admission drops and recoveries, warming durations, death plus resume with a fresh Operator and journal, and hook/no-hook. It audits at every provider, journal, decision and sleep boundary. The hole: the audit at tests line 1853 checks only "no FailedProbe after acknowledgement". It never checks the invariant's second sentence (pre-acknowledgement FailedProbe only for the three listed causes), even though the fake knows the truth (`fake.completed`). That is why it missed the finding below. 5. **Four simulation mutations: PASS.** All caught in seeds 0..49 (seeds 0, 9, 0, 0). They are caught by the decision-level checks in `Simulation.decide` (tests lines 1866–1872), not by provider-state checks. That is acceptable, though those checks partly restate the table. 6. **Eight plan mutations: PASS.** All eight still fail the suite. 7. **already_restored / cut-session minor: PASS within the available interface.** Rollback loops on status until it succeeds (script lines 1280–1306). The Go status verb returns "apply lock busy" while apply holds the lock (`internal/host/group_maintenance_verbs.go:116-127`). Status cannot show journal closure, which the report states honestly. Runs: the default `unittest` once (139 tests, OK, 229 s). Separately, simulation seeds 0..299 under a read-only probe, all passing. I did not repeat the 3000-seed sweep. ### Findings 1. **Important — T1/I4 return-contract family.** FailedProbe is recorded after AWS has accepted CONTINUE but before the acknowledgement is journaled. - **Where:** script line 194 (`hook_describe_error` row), line 280 (`pending_wait_drop`) and line 272 (`pending_wait_exhausted` via stale reads), reached from `return_member` lines 1392–1401. - **Which invariant:** "FailedProbe is possible only before acknowledgement (Pending:Wait with current-process admission dropped **before CONTINUE**, member terminated/replaced, or completion ambiguity **resolving to ABANDON**)". Here CONTINUE was sent and accepted, and the ambiguity has not resolved to ABANDON. - **Reproduction:** seed 23 in the existing simulator. 1. Ready Pending:Wait leads to `complete`. AWS accepts it, the response is lost, and the journal records the outcome as `uncertain` with attempts=1. 2. Describe shows a stale Pending:Wait, so the tool backs off. 3. The next describe fails on `targets`, so `classify` returns `failed`. 4. FailedProbe is journaled and the blocked flag written. At that moment the provider shows Pending:Proceed, min 1, desired 2, so the member is returning to service unheld. 5. On resume, a stale Pending:Wait plus an admission drop gives a second FailedProbe. Only a later resume reaches acknowledge, then hold, then held. - **Frequency:** in seeds 0..299, 26 of 147 hook seeds recorded a FailedProbe while the fake's CONTINUE had taken effect (21 via describe blip, 5 via stale Pending:Wait plus admission drop). - **Outcome:** the same end state as the round-2 open finding (FailedProbe instead of the R16 hold, member InService at min N-1, resume reaches the hold), shifted from "acknowledged" to "accepted but unacknowledged". The describe-blip variant is not admission loss at all. - **Counter-argument:** contract row 32 equates API loss with a failed probe, and the operator cannot tell a stale Pending:Wait from a real one. But the brief's binding invariant names completion ambiguity only when it resolves to ABANDON. - **Fix direction, for Paul:** after a dispatched CONTINUE, classify should keep a describe error or an admission drop as wait/resumable. It should hold once Pending:Proceed/Pending/InService is seen, and fail only when Pending:Wait persists to `deadline_close` or the member is terminated. The simulator should also assert that no FailedProbe is journaled while `fake.completed` is true. 2. **Minor — same family.** Before acknowledgement, a member that has already returned is left in service unheld while admission is down. - **Where:** script lines 286–294. With a hook, InService and attempts≥1 but readiness dropped, the table waits and then becomes resumable instead of holding. - **Why it matters:** the post-acknowledgement branch holds without readiness (row `ack_inservice_unready`). R16 says "if already returned … EnterStandby(decrement)". Seeing InService after a CONTINUE attempt proves the return is done. - **Outcome:** an unready member stays in both target groups at min N-1 until admission recovers. The result is resumable, not a FailedProbe. The scratch probe has been deleted. I also removed `scripts/__pycache__`, which my probe created by mistake; the worktree is clean and nothing is running. Verdict: open: [Important] FailedProbe after an accepted but unacknowledged CONTINUE (describe blip or stale Pending:Wait plus admission drop), and the simulator has no assertion for that case; [Minor] already-returned InService member not held before acknowledgement while admission is down. T1/I4 family finding: yes</result> <usage><subagent_tokens>116823</subagent_tokens><tool_uses>23</tool_uses><duration_ms>529823</duration_ms></usage> </task-notification>

diff --git a/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md b/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md
index 0bf4c4474..1cca4c4d0 100644
--- a/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md
+++ b/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md
@@ -112,14 +112,21 @@ both deregistrations, installs the permit, applies and verifies. Return restores
desired through ExitStandby; minimum is restored only after the same member and
both target groups are healthy. The permit is revoked last.
-The tool never terminates a member, sends ABANDON or explicitly sets/raises
-desired capacity. It never suspends HealthCheck or ReplaceUnhealthy. Before
-Exit, doubt leaves the member held in Standby. If Exit has already been sent,
-read the actual lifecycle state: an uncertain response cannot establish that
-the member is still protected by Standby. An unexpected return hook blocks
-rolls; recovery completes only while freshly admitted, then holds the same
-member in Standby. Admission loss there is a failed probe, not a 15-minute
-Standby wait. See the witness's return table.
+The tool never sends CompleteLifecycleAction or ABANDON. It never terminates
+a member, explicitly sets desired capacity, or suspends HealthCheck or
+ReplaceUnhealthy. Before Exit, doubt leaves the member held in Standby.
+After Exit, read the actual lifecycle state. An uncertain response cannot
+establish that the member is still protected by Standby.
+
+If Pending:Wait appears after Exit, the tool records `return-hook`, writes
+`provider-divergence.json`, prints an alert and stops. This applies at any
+readiness level. Resume observes the outcome without sending a completion.
+If AWS's default ABANDON terminates or replaces the member, resume records
+FAIL and further resumes retain that failure. Further rolls remain blocked.
+If AWS returns the same member to InService on its own, the tool enters
+Standby with decrement=true, verifies deregistration and keeps the record
+and permit. It does not restore minimum in that hold. See the witness's
+return table.
The IAM policy grants no direct termination action, but its
`UpdateAutoScalingGroup` permission can change more than minimum. Only this
diff --git a/docs/superpowers/notes/2026-11-05-region-ha-p3b2-standby-witness.md b/docs/superpowers/notes/2026-11-05-region-ha-p3b2-standby-witness.md
index 34c3ab253..6846920db 100644
--- a/docs/superpowers/notes/2026-11-05-region-ha-p3b2-standby-witness.md
+++ b/docs/superpowers/notes/2026-11-05-region-ha-p3b2-standby-witness.md
@@ -91,13 +91,15 @@ Standby transitions from lifecycle-hook availability:
An activity labelled PreInService is not an instance Pending:Wait observation
or proof of InService. Capture both API objects, not just activity text.
-If a return hook appears, stop the probe as a roll blocker. While freshly
-admitted, the serialized probe owner must handle any pending CONTINUE safely,
-verify same-iid InService, then EnterStandby with decrement=true and verify both
-deregistrations. Retain min=desired=1, max=2, the probe record and the same iid
-in Standby until the controller resolves the contract. Never pretend an iid
-in Pending:Wait is still in Standby. If readiness/API access drops, follow the
-failed-probe row below. Do not send ABANDON or invent a heartbeat extension.
+If a return hook appears, stop the probe and block further rolls. The tool
+never sends CompleteLifecycleAction or ABANDON. Record the exact iid, hook,
+transaction and deadline, restore reversible probe faults and retain the
+journal. Resume only to observe the outcome. If AWS's default ABANDON
+terminates the member and launches a replacement, record FAIL. If AWS moves
+the same member to InService on its own, enter Standby with decrement=true
+and verify both deregistrations. Retain min=desired=1, max=2, the probe record
+and the same iid until the controller resolves the contract. Pending:Wait
+has no Standby protection; elapsed time cannot make this probe a pass.
Only after a pass may the controller write root-owned 0600
`provider-observation.json` with the exact fields in the operator instructions.
@@ -246,8 +248,8 @@ can route to unhealthy targets. Retain ordinary lease, local-copy and duty
rules. Missing fixtures mean NOT RUN, not a pass for the entire gate.
Pass the hold only with the same iid and total member set, zero extra launches,
-replacements or terminations, zero lifecycle completions while unready in
-Standby, closed tenant starts and the healthy peer unaffected. Separately show
+replacements or terminations, zero operator lifecycle completions, closed
+tenant starts and the healthy peer unaffected. Separately show
that shared dependency loss on an already-admitted live process leaves its
health/startup latch intact until local shutdown. Use a separate short bounded
fault before the roll, restore access before
@@ -276,7 +278,7 @@ same identity, expected digest and edges generation at least two seconds after
`edge.started_at`, which is a lower bound. Measure the time from the first
status response through the second status, journal fsync and Exit dispatch.
The observation must still be at most five seconds old. The code permits
-60 seconds for ordinary readiness, but Exit/CONTINUE require five. Slow real
+60 seconds for ordinary readiness, but Exit requires five. Slow real
session startup is a refusal, not permission to widen that bound.
Use the tool's `return --transaction '<transaction>'` only when that state is
@@ -289,13 +291,15 @@ The single return controller handles these cases:
| Standby, freshly admitted | Persist current transaction/iid/boot/process/publication and intent, then Exit with observation age at most five seconds. |
| Lost Exit response | Describe group, exact member, targets and activity before any write. Retry only from observed Standby with fresh evidence. Never blindly restore desired. |
| Pending or PreInService | Observe transition; do not send another Exit or call it InService. |
-| Pending:Wait | Record provider divergence immediately. Only the serialized operator may send CONTINUE for this iid/hook after rechecking current-process admission. Journal transaction+iid+boot+process+Exit activity, each intent/outcome and at most four attempts with 1/2/4-second backoffs and two-second calls. Describe after an ambiguous response. The original launch receipt cannot suppress this action. |
-| Pending:Proceed | Observe; do not complete again. |
-| Admission/API access lost after a return hook | Record FAIL and alert immediately before the 900-second hook deadline. Send neither CONTINUE nor ABANDON. Restore reversible probe faults, stop all rolls and retain exact iid/hook/transaction/deadline. Default ABANDON may still terminate the disposable member; record that loss and replacement as a failed probe. Never use the ordinary 15-minute Standby wait here. |
-| InService, same iid, unchanged members, desired 2, both target groups healthy | On documented no-hook return, restore minimum 2, revoke permit last and verify absence. Zero return completions. On unexpected hook return, enter Standby again with decrement=true, verify deregistration, retain permit/record and block further rolls. |
+| Pending:Wait | At any readiness level, journal the return hook, alert, write the group block flag and stop. Send no completion and no ABANDON. Resume only to observe the outcome. |
+| Pending:Proceed | Observe; send no completion. After an observed hook, keep rolls blocked. |
+| API access lost after a return hook | Alert and retain the blocked transaction for observation when access returns. Restore reversible probe faults. Do not wait the ordinary 15-minute Standby interval or assume the hook deadline stopped. |
+| Terminated or replaced after Exit | Record FAIL, retain the block flag and journal, and stop. Resume observes the loss and stays FAIL. AWS default ABANDON is never a passing maintenance witness. |
+| InService, same iid, unchanged members, desired 2, both target groups healthy | On documented no-hook return, restore minimum 2, revoke permit last and verify absence. Zero return completions. If AWS returns the member after an observed hook, hold it in Standby with decrement=true even if admission or targets are unready. Verify deregistration, retain permit/record and block further rolls. |
A divergent hook is always a failed provider-contract observation, even if
-CONTINUE safely preserves the iid. The synthetic Pending:Wait tests remain
+AWS later returns the same iid without a completion. The synthetic Pending:Wait
+tests remain
required offline; do not deliberately manufacture a live hook. Never interpret
a lost session, elapsed time or old launch receipt as fresh admission.
diff --git a/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md b/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md
index d5b09c9a8..3b5d85838 100644
--- a/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md
+++ b/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md
@@ -25,6 +25,7 @@
| Author's call, B3b-B | **N1:** a hairpinned client's address is this box's IMDS-reported public IPv4, checked against root boot identity and public-address validation. It is not the NLB EIP, a bridge address or an HTTP header. Task 5 specifies the authenticated kernel path. |
| Author's call, B3b-C | **T1/A1:** the restart guard, immutable group marker and Restart=no drop-in ship with the first group, even though the attended roll drill is a later slice. An environment flag cannot disable them. |
| Author's call, B3b-D | **T1/I4:** AWS documents no Standby hook; Task 7 alone owns any defensive return CONTINUE. Observe the exact dev behavior before enabling rolls; divergence refuses the roll. |
+| Paul, 2026-11-05 (P3b-2 build, stopping rule 2) | **T1/I4:** replaces B3b-D's defensive return CONTINUE. The operator never completes a lifecycle action: Pending:Wait after ExitStandby is divergence (journal, alert, block further rolls, no completion, no ABANDON); a default ABANDON of the probe is FAIL, never a pass. Operator IAM drops CompleteLifecycleAction. Recorded on #421. |
| Author's call, B3b-E | **A1/I6/E1:** a distinct group queue uses competing consumers; a closed member journals but neither imports nor acknowledges. Tasks 2/3 preserve Started without granting duty authority. |
| Paul, **N-HA19**, 2026-11-04, via the agent manager under delegation — D1 | **S1/H4:** approved staging exception to spec §19 for the limited P3b-1 first-service experiment on the recorded G1 boxes. Full G2 still waits for P2b, drain and P1b-3b slice S. |
| Paul, N-HA19 — D2 | **R1/H4/I3:** groups start serve-only using the existing role reader; role transitions, drain and readiness remain blocked until their producers merge. Refuse an existing drain/platform/unknown role; do not rewrite it. |
diff --git a/infra/modules/region-host/README.md b/infra/modules/region-host/README.md
index 18bfa7d8a..195ec4447 100644
--- a/infra/modules/region-host/README.md
+++ b/infra/modules/region-host/README.md
@@ -154,8 +154,12 @@ fixed mode. `group_operator_session_document_arn` selects one approved session
document; its default is the regional AWS-managed
`AWS-StartNonInteractiveCommand`. A custom document must belong to this
account and region. The policy grants group-scoped maintenance actions and
-Session Manager access to this group's tagged instances. The operator tool
-must still enforce the instance, hook, transaction and `CONTINUE` result.
+Session Manager access to this group's tagged instances. It grants no
+`CompleteLifecycleAction`. The tool never sends CompleteLifecycleAction or
+ABANDON. A return hook is provider divergence: the tool journals it, alerts,
+blocks further rolls and stops. Resume observes the outcome. Default ABANDON
+termination or replacement is recorded as FAIL. If AWS returns the member on
+its own, the tool holds it in Standby with decrement and verified deregistration.
The policy grants no direct termination action, but `UpdateAutoScalingGroup`
can still lower capacity or set lifetime limits. Only the operator command
may use it, and only in the N-HA14 shape: minimum N-1 during Standby,
diff --git a/infra/modules/region-host/group_operator.tf b/infra/modules/region-host/group_operator.tf
index 04256bd70..686fd971e 100644
--- a/infra/modules/region-host/group_operator.tf
+++ b/infra/modules/region-host/group_operator.tf
@@ -20,8 +20,9 @@ locals {
}
# Attach this output to the attended operator identity, never the instance role.
-# IAM cannot bind iid, hook, CONTINUE-only or transaction state. return_member in
-# scripts/region-group-roll.py must enforce those before lifecycle completion.
+# The tool never completes lifecycle actions. A return hook blocks further
+# rolls; AWS's default result applies. The instance role's initial boot hook
+# permission is separate from this operator policy.
output "group_operator_policy_json" {
description = "IAM policy for the attended group roll operator. Empty in fixed mode. Creates no IAM resource."
value = !local.group_enabled ? "" : jsonencode({
@@ -30,7 +31,7 @@ output "group_operator_policy_json" {
{
Sid = "GroupMaintenance"
Effect = "Allow"
- Action = ["autoscaling:UpdateAutoScalingGroup", "autoscaling:EnterStandby", "autoscaling:ExitStandby", "autoscaling:CompleteLifecycleAction"]
+ Action = ["autoscaling:UpdateAutoScalingGroup", "autoscaling:EnterStandby", "autoscaling:ExitStandby"]
Resource = aws_autoscaling_group.group[0].arn
Condition = { StringEquals = {
"aws:ResourceTag/carlos:deployment" = var.group_config.deployment
diff --git a/infra/modules/region-host/tests/group_operator.tftest.hcl b/infra/modules/region-host/tests/group_operator.tftest.hcl
index 0d647c949..b787b2c4f 100644
--- a/infra/modules/region-host/tests/group_operator.tftest.hcl
+++ b/infra/modules/region-host/tests/group_operator.tftest.hcl
@@ -124,7 +124,7 @@ run "operator_policy" {
{
Sid = "GroupMaintenance"
Effect = "Allow"
- Action = ["autoscaling:UpdateAutoScalingGroup", "autoscaling:EnterStandby", "autoscaling:ExitStandby", "autoscaling:CompleteLifecycleAction"]
+ Action = ["autoscaling:UpdateAutoScalingGroup", "autoscaling:EnterStandby", "autoscaling:ExitStandby"]
Resource = aws_autoscaling_group.group[0].arn
Condition = { StringEquals = {
"aws:ResourceTag/carlos:deployment" = "dev"
@@ -179,9 +179,9 @@ run "operator_policy" {
}
assert {
condition = !anytrue([for s in jsondecode(output.group_operator_policy_json).Statement :
- anytrue([for a in s.Action : contains(["ec2:TerminateInstances", "autoscaling:TerminateInstanceInAutoScalingGroup", "autoscaling:SetDesiredCapacity", "autoscaling:SetInstanceHealth", "ssm:SendCommand"], a) || startswith(a, "ssm:GetParameter")])
+ anytrue([for a in s.Action : contains(["autoscaling:CompleteLifecycleAction", "ec2:TerminateInstances", "autoscaling:TerminateInstanceInAutoScalingGroup", "autoscaling:SetDesiredCapacity", "autoscaling:SetInstanceHealth", "ssm:SendCommand"], a) || startswith(a, "ssm:GetParameter")])
])
- error_message = "the roll policy must not grant termination, direct capacity or health changes, Run Command or parameter reads"
+ error_message = "the roll policy must not grant lifecycle completion, termination, direct capacity or health changes, Run Command or parameter reads"
}
}
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py
index 6d331082c..b16886715 100755
--- a/scripts/region-group-roll.py
+++ b/scripts/region-group-roll.py
@@ -31,14 +31,13 @@ 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.
+The tool never sends CompleteLifecycleAction or ABANDON. Pending:Wait after
+ExitStandby is provider divergence: journal it, alert, block further rolls and
+stop. Resume observes the outcome. A terminated or replaced member is FAIL,
+never a pass. If the provider returns the member to InService on its own,
+retain the R16 Standby hold with decrement and verified deregistration.
+classify() owns these decisions for return and resume. Only return_member
+sends ExitStandby. Never restore minimum in a hold or raise 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
@@ -129,12 +128,10 @@ TEXT = {
"timeout": "The 15-minute Standby wait expired",
"uncertain_action": "The consumed box action has no verified completion",
"return_intent": "A durable current-process return intent is required",
- "return_failed": "Admission or API access was lost during a return hook",
- "return_attempts": "The bounded return completion attempts are exhausted",
+ "return_hook": "The provider used a return hook. No lifecycle action will be completed; further rolls are blocked",
"return_phase": "The provider has not completed this member's return",
"lost_member": "member terminated or replaced: failed probe",
"unknown_phase": "The member's return phase is unknown: failed probe",
- "activity": "The ExitStandby activity cannot be bound to this transaction",
"hook": "The immutable launch hook must have a 900-second ABANDON default",
"remote": "The Session Manager command has no successful framed result",
"api": "An AWS response is unavailable or invalid",
@@ -158,15 +155,13 @@ class Decision(NamedTuple):
def classify(facts) -> Decision:
- """Pure, ordered decision table. Journal facts outlive observations.
+ """The tool never sends CompleteLifecycleAction or ABANDON.
- 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.
+ A return hook blocks success. A terminated or replaced member is FAIL.
+ Provider-driven InService goes to the R16 hold, even without readiness.
"""
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")
@@ -179,7 +174,7 @@ def classify(facts) -> Decision:
if context == "resume":
if f.get("done"):
return Decision("finish")
- if f.get("exit_intent") or f.get("hook") or acknowledged:
+ if f.get("exit_intent") or f.get("hook") or f.get("hold_started"):
return Decision("return")
if f.get("operation_error") or f.get("describe_error"):
return Decision("resumable", f.get("error_reason", "api"))
@@ -187,22 +182,25 @@ def classify(facts) -> Decision:
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 context == "return" and f.get("hook") and not f.get("divergence_recorded", True):
+ return Decision("diverged", "return_hook")
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")
+ if context == "return" and phase == "Pending:Wait":
+ return Decision("diverged", "return_hook")
- # This precedence is the acknowledgement invariant. Even termination or
- # stale capacity after acknowledgement cannot turn it into FailedProbe.
+ sent = f.get("exit_state", "none") != "none"
+ if context == "return" and (sent or f.get("hook")):
+ 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")
shape = (f.get("members_match") and f.get("template_match") and
f.get("maximum") == n and n >= 2)
- if context == "return" and acknowledged:
+ if context == "return" and (f.get("hook") or f.get("hold_started")):
if not shape or phase is None or phase.startswith("Terminat"):
return Decision("resumable", "members")
if f.get("timed_out"):
@@ -217,17 +215,8 @@ def classify(facts) -> Decision:
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"):
@@ -265,33 +254,9 @@ def classify(facts) -> Decision:
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":
@@ -759,11 +724,6 @@ class AWS:
if op == "terminate_session":
require(re.fullmatch(r"[A-Za-z0-9_-]+", a["session_id"]), "remote")
return self.invoke("ssm", "terminate-session", ["--session-id", a["session_id"]])
- if op == "complete":
- require(a["hook"] == self.c["hook"] and a["result"] == "CONTINUE", "hook")
- return self.invoke("autoscaling", "complete-lifecycle-action", group +
- ["--instance-id", a["iid"], "--lifecycle-hook-name", a["hook"],
- "--lifecycle-action-result", "CONTINUE"], timeout=2)
if op == "session":
self.last_session_id = None
nonce = uuid.uuid4().hex
@@ -1164,29 +1124,24 @@ class Operator:
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"])
+ hook = self.j.last("return-hook")
+ # Group responses are durable before target reads and decisions. Keep
+ # the hook evidence even if target reads fail or journaling is cut.
+ groups = (r.get("result") for r in self.j.events
+ if r["kind"] == "response" and r.get("op") == "group")
+ hook_observed = bool(hook) or any(isinstance(g, dict) and
+ g.get("arn") == self.c["group_arn"] and g.get("name") == self.c["group"] and
+ isinstance(g.get("members"), dict) and g["members"].get(h["iid"]) == "Pending:Wait"
+ for g in groups)
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,
+ hook=hook_observed,
+ divergence_recorded=bool(hook and self.state.blocked.exists()),
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"]),
@@ -1313,55 +1268,33 @@ class Operator:
binary_sha256=s["binary_sha256"])
return self.resume()
- def exit_activity(self):
- saved = self.j.last("exit-activity")
- if saved:
- return saved["activity"]
- rows = self.call("activities", iid=self.header["iid"])
- entered = self.j.last("enter-activity")
- if not entered:
- baseline = self.j.last("enter-activity-baseline")
- require(baseline is not None, "activity")
- known = {r["id"] for r in baseline["activities"]}
- candidates = [r for r in rows if r["iid"] == self.header["iid"] and
- r["kind"] == "enter" and r["id"] not in known]
- require(len(candidates) == 1, "activity")
- entered = self.event("enter-activity", activity=candidates[0]["id"])
- starts = [r for r in rows if r["id"] == entered["activity"] and
- r["kind"] == "enter" and r["iid"] == self.header["iid"]]
- require(len(starts) == 1, "activity")
- matches = [r["id"] for r in rows if r["iid"] == self.header["iid"] and
- r["kind"] == "exit" and r["time"] > starts[0]["time"]]
- require(len(matches) == 1, "activity")
- self.event("exit-activity", activity=matches[0])
- return matches[0]
-
def return_member(self):
- """Execute classify() decisions. Sole owner of Exit and CONTINUE."""
+ """Execute classify() decisions. Sole owner of ExitStandby."""
self.restore_header()
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:
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 == "diverged":
+ intent = self.j.last("exit-intent")
+ self.state.write(self.state.blocked, dict(transaction=h["transaction"], phase="Pending:Wait"))
+ if not self.j.last("return-hook"):
+ self.event("return-hook", iid=iid, hook=self.c["hook"],
+ transaction=h["transaction"], deadline=intent["at"] + 900 if intent else None)
+ self.alert("return_hook")
if action == "held":
self.event("divergence-held", iid=iid)
self.alert("divergence")
try:
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)
elif action == "observe-ready":
try:
ready = self.readiness(iid, maintenance=not bool(self.j.last("returned")))
@@ -1373,8 +1306,6 @@ class Operator:
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"],
@@ -1386,21 +1317,6 @@ class Operator:
except Uncertain:
pass
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=attempt, outcome="acknowledged")
- self.event("return-acknowledged", key=key)
- except Uncertain:
- 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:
@@ -1408,10 +1324,8 @@ class Operator:
except Uncertain:
pass
group, observed = None, {}
- elif action in {"wait", "backoff"}:
+ elif action == "wait":
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"])
diff --git a/scripts/region_group_roll_test.py b/scripts/region_group_roll_test.py
index a80bcc3fb..954c429cb 100644
--- a/scripts/region_group_roll_test.py
+++ b/scripts/region_group_roll_test.py
@@ -1,5 +1,6 @@
"""Offline witnesses for the attended group maintenance transaction."""
import copy
+from contextlib import closing
import importlib.util
import io
import json
@@ -339,48 +340,27 @@ class StandbyTests(unittest.TestCase):
self.assert_retained()
def test_standby_exit_pending_wait(self):
- self.fake.hook = True
- with self.assertRaises(roll.Refusal):
- self.run_roll()
- self.assertEqual(self.fake.continues, 1)
- self.assertTrue(self.store.blocked.exists())
- self.assertEqual(self.fake.states[IID], "Standby")
- self.assertEqual(self.fake.tg[IID], "unused")
- self.assertEqual((self.fake.minimum, self.fake.desired), (1, 1))
- self.assertEqual(self.fake.writes[-1], "enter")
- self.assertIsNotNone(self.store.active_id())
- self.assert_retained()
- with self.assertRaises(roll.Refusal):
- self.run_roll()
+ CutTests.test_hook_is_divergence_without_completion(self)
def test_standby_exit_pending_wait_resume_and_loss(self):
- for fault, boundary in (("death", 6), ("death", 7), ("loss", 6), ("loss", 7)):
- with self.subTest(fault=fault, boundary=boundary):
+ for before, fault in ((False, "death"), (True, "death"), (False, "loss")):
+ with self.subTest(before=before, fault=fault):
self.setUp()
self.fake.hook = True
- self.fake.fault, self.fake.fault_at = fault, boundary
- try:
+ self.fake.fail_before = before
+ self.fake.fault, self.fake.fault_at = fault, 6
+ with self.assertRaises((Death, roll.Refusal)):
self.run_roll()
- except (Death, roll.Refusal, roll.Uncertain):
- pass
- if self.store.active_id():
- with self.assertRaises(roll.Refusal):
- self.resume()
- self.assertEqual(self.fake.continues, 1)
+ with self.assertRaises(roll.Refusal):
+ self.resume()
+ self.assertEqual(self.fake.continues, 0)
self.assertEqual(self.fake.exits, 1)
+ self.assertEqual(self.fake.states[IID], "Pending:Wait")
+ self.assertTrue(self.store.blocked.exists())
self.assert_retained()
def test_standby_exit_pending_wait_admission_loss(self):
- self.fake.hook = self.fake.loss_after_exit = True
- with self.assertRaises(roll.Refusal):
- self.run_roll()
- self.assertLess(self.fake.now, self.fake.deadline)
- self.assertEqual(self.fake.continues, 0)
- self.assertIn("FAIL", self.output.getvalue())
- self.fake.sleep(901)
- self.assertEqual(self.fake.abandons, 1)
- with self.assertRaises(roll.Refusal):
- self.resume()
+ CutTests.test_default_abandon_and_resume_stay_failed(self)
def test_precheck_failures_before_minimum(self):
cases = (lambda: setattr(self.fake, "online", False),
@@ -465,27 +445,23 @@ class StandbyTests(unittest.TestCase):
self.assertGreaterEqual(polls, 9)
self.assertEqual(self.fake.exits, 1)
- def test_standby_pending_proceed_no_duplicate_completion(self):
- self.fake.hook = True
+ def test_standby_pending_proceed_without_completion(self):
perform = self.fake.perform
polls = 0
-
def delayed(op, a):
nonlocal polls
result = perform(op, a)
- if op == "complete":
+ if op == "exit":
self.fake.states[IID] = "Pending:Proceed"
if op == "group" and self.fake.states[IID] == "Pending:Proceed":
polls += 1
if polls == 3:
self.fake.states[IID] = "InService"
return result
-
self.fake.perform = delayed
- with self.assertRaises(roll.Refusal):
- self.run_roll()
+ self.run_roll()
self.assertGreaterEqual(polls, 3)
- self.assertEqual(self.fake.continues, 1)
+ self.assertEqual(self.fake.continues, 0)
def test_fake_abandon_terminates_and_replaces(self):
self.fake.hook = True
@@ -499,37 +475,7 @@ class StandbyTests(unittest.TestCase):
self.assertEqual(self.fake.states["i-" + "3" * 17], "Pending:Wait")
self.assertNotIn(IID, self.fake.request("group", {})["members"])
self.assertEqual(self.fake.launches, 1)
- # Mutation 6 is the real rev-1 witness: it changes the production
- # return path, suppresses CONTINUE, and must fail the retention test.
-
- def test_standby_completion_retry_budget_and_journal(self):
- self.fake.hook = True
- request = self.fake.request
- attempts = []
- def fail_completion(op, a):
- if op == "complete":
- attempts.append(self.fake.now)
- raise roll.Uncertain("response lost before acceptance")
- return request(op, a)
-
- self.fake.request = fail_completion
- with self.assertRaises(roll.Refusal):
- self.run_roll()
- self.assertEqual(len(attempts), 4)
- self.assertEqual([b - a for a, b in zip(attempts, attempts[1:])], [1, 2, 4])
- j = self.store.load(self.store.active_id())
- try:
- actions = [r for r in j.events if r["kind"] == "return-action"]
- self.assertEqual([r["attempt"] for r in actions], [1, 2, 3, 4])
- self.assertEqual(len(set(tuple(r["key"]) for r in actions)), 1)
- self.assertIsNotNone(j.last("failed-probe"))
- finally:
- j.close()
- with self.assertRaises(roll.Refusal):
- self.resume()
- self.assertEqual(len(attempts), 4)
- self.assertLess(self.fake.now, self.fake.deadline)
def test_standby_return_process_or_transaction_changes(self):
for kind in ("process", "transaction", "boot"):
@@ -549,22 +495,26 @@ class StandbyTests(unittest.TestCase):
self.assertEqual(self.fake.exits, 0)
self.assert_retained()
- def test_standby_post_exit_api_loss_fails_immediately(self):
+ def test_standby_post_exit_api_loss_is_resumable(self):
self.fake.hook = True
self.fake.fault, self.fake.fault_at = "loss", 6
request = self.fake.request
def fail_describe(op, a):
- if op == "activities" and self.fake.exits:
+ if op == "group" and self.fake.exits:
raise roll.Uncertain("API unavailable")
return request(op, a)
self.fake.request = fail_describe
- with self.assertRaises(roll.Refusal):
+ with self.assertRaises(roll.Uncertain):
self.run_roll()
self.assertLess(self.fake.now, self.fake.deadline)
self.assertEqual(self.fake.continues, 0)
- self.assertIn("FAIL", self.output.getvalue())
+ self.assertFalse(self.store.blocked.exists())
+ self.fake.request = request
+ with self.assertRaises(roll.Refusal):
+ self.resume()
+ self.assertTrue(self.store.blocked.exists())
def test_consumed_uncertain_action_never_replays(self):
self.fake.fault, self.fake.fault_at = "death", 5
@@ -663,6 +613,115 @@ class StandbyTests(unittest.TestCase):
self.assertIn(roll.TEXT["peer"], self.output.getvalue())
+class CutTests(unittest.TestCase):
+ setUp = StandbyTests.setUp
+ engine = StandbyTests.engine
+ run_roll = StandbyTests.run_roll
+ resume = StandbyTests.resume
+
+ def test_hook_is_divergence_without_completion(self):
+ for admitted in (True, False):
+ with self.subTest(admitted=admitted):
+ self.setUp()
+ self.fake.hook = True
+ self.fake.loss_after_exit = not admitted
+ with self.assertRaises(roll.Refusal):
+ self.run_roll()
+ self.assertEqual(self.fake.states[IID], "Pending:Wait")
+ self.assertEqual(self.fake.continues, 0)
+ self.assertFalse(any(op == "complete" for op, _ in self.fake.calls))
+ self.assertTrue(self.store.blocked.exists())
+ self.assertIn("ALERT", self.output.getvalue())
+ with closing(self.store.load(self.store.active_id())) as j:
+ self.assertIsNotNone(j.last("return-hook"))
+ self.assertIsNotNone(j.last("alert"))
+ self.assertIsNone(j.last("done"))
+ self.assertLess(self.fake.now, self.fake.deadline)
+ writes = list(self.fake.writes)
+ with self.assertRaises(roll.Refusal):
+ self.resume()
+ self.assertEqual(self.fake.writes, writes)
+
+ def test_default_abandon_and_resume_stay_failed(self):
+ self.fake.hook = True
+ with self.assertRaises(roll.Refusal):
+ self.run_roll()
+ self.fake.sleep(900)
+ self.assertEqual(self.fake.states[IID], "Terminated")
+ self.assertEqual((self.fake.abandons, self.fake.launches), (1, 1))
+ for _ in range(2):
+ with self.assertRaises(roll.FailedProbe):
+ self.resume()
+ with closing(self.store.load(self.store.active_id())) as j:
+ self.assertIsNotNone(j.last("failed-probe"))
+ self.assertIsNone(j.last("done"))
+ self.assertIn("FAIL", self.output.getvalue())
+ self.assertEqual(self.fake.continues, 0)
+ self.assertFalse(any(op == "complete" for op, _ in self.fake.calls))
+ writes = list(self.fake.writes)
+ with self.assertRaisesRegex(roll.Refusal, roll.TEXT["blocked"]):
+ self.engine().preflight(IID, NEW)
+ self.assertEqual(self.fake.writes, writes)
+
+ def test_hook_observed_before_target_describe_error_blocks(self):
+ self.fake.hook = True
+ request = self.fake.request
+ def unavailable(op, args):
+ if op == "targets" and self.fake.states[IID] == "Pending:Wait":
+ raise roll.Uncertain("targets unavailable")
+ return request(op, args)
+ self.fake.request = unavailable
+ with self.assertRaises(roll.Refusal):
+ self.run_roll()
+ self.assertTrue(self.store.blocked.exists())
+ self.assertEqual(self.fake.continues, 0)
+ with closing(self.store.load(self.store.active_id())) as j:
+ self.assertIsNotNone(j.last("return-hook"))
+ self.assertIsNone(j.last("done"))
+
+ def test_death_during_divergence_recording(self):
+ for boundary in ("response", "snapshot", "return-hook", "alert"):
+ with self.subTest(boundary=boundary):
+ self.setUp()
+ self.fake.hook = True
+ add = roll.Journal.add
+ def die(j, kind, **data):
+ row = add(j, kind, **data)
+ if kind == boundary and self.fake.states[IID] == "Pending:Wait" and (kind != "response" or data.get("op") == "group"):
+ raise Death(kind)
+ return row
+ with patch.object(roll.Journal, "add", die):
+ with self.assertRaises(Death):
+ self.run_roll()
+ self.fake.states[IID] = "InService"
+ self.fake.deadline = None
+ # A partial divergence record is repaired with an alert first.
+ for _ in range(2):
+ with self.assertRaises(roll.Refusal):
+ self.resume()
+ self.assertEqual(self.fake.states[IID], "Standby")
+ self.assertTrue(self.store.blocked.exists())
+ self.assertEqual(self.fake.continues, 0)
+ with closing(self.store.load(self.store.active_id())) as j:
+ self.assertIsNotNone(j.last("return-hook"))
+ self.assertIsNotNone(j.last("divergence-held"))
+ self.assertIsNone(j.last("done"))
+
+ def test_provider_return_without_tool_completion_is_held(self):
+ self.fake.hook = True
+ with self.assertRaises(roll.Refusal):
+ self.run_roll()
+ self.fake.states[IID] = "InService"
+ self.fake.admitted = False
+ self.fake.deadline = None
+ with self.assertRaises(roll.DivergenceHeld):
+ self.resume()
+ self.assertEqual(self.fake.states[IID], "Standby")
+ self.assertEqual(self.fake.tg[IID], "unused")
+ self.assertEqual((self.fake.minimum, self.fake.desired), (1, 1))
+ self.assertEqual(self.fake.continues, 0)
+
+
class RoundOneTests(unittest.TestCase):
setUp = StandbyTests.setUp
engine = StandbyTests.engine
@@ -762,19 +821,6 @@ class RoundOneTests(unittest.TestCase):
self.run_roll()
self.assertEqual(self.fake.exits, 1)
- def test_continue_checks_age_after_journal_flush(self):
- self.fake.hook = True
- original = roll.Operator.event
- def delayed(engine, kind, **data):
- result = original(engine, kind, **data)
- if kind == "intent" and data.get("op") == "complete":
- self.fake.sleep(6)
- return result
- with patch.object(roll.Operator, "event", delayed):
- with self.assertRaises(roll.FailedProbe):
- self.run_roll()
- self.assertEqual(self.fake.continues, 0)
- self.assertLess(self.fake.now, self.fake.deadline)
def test_observation_age_includes_first_response_journal_flush(self):
engine = self.engine()
@@ -798,17 +844,21 @@ class RoundOneTests(unittest.TestCase):
with self.subTest(before=before, fault=fault):
self.setUp()
self.fake.hook = True
+ with self.assertRaises(roll.Refusal):
+ self.run_roll()
+ self.fake.states[IID] = "InService"
+ self.fake.deadline = None
self.fake.fail_before = before
- self.fake.fault, self.fake.fault_at = fault, 8
+ self.fake.fault, self.fake.fault_at = fault, 7
with self.assertRaises((Death, roll.Refusal)):
- self.run_roll()
+ self.resume()
with self.assertRaises(roll.DivergenceHeld):
self.resume()
writes = list(self.fake.writes)
with self.assertRaises(roll.DivergenceHeld):
self.resume(returning=True)
self.assertEqual(writes, self.fake.writes)
- self.assertEqual(self.fake.continues, 1)
+ self.assertEqual(self.fake.continues, 0)
self.assertEqual(self.fake.states[IID], "Standby")
self.assertEqual((self.fake.minimum, self.fake.desired), (1, 1))
self.assertEqual(self.fake.writes.count("enter"), 2)
@@ -930,22 +980,6 @@ class RoundOneTests(unittest.TestCase):
self.fake.request("minimum", {"value": 2})
self.assertEqual(self.fake.desired, 2)
- def test_ambiguous_exit_activity_uses_enter_not_operator_clock(self):
- self.fake.hook = True
- request = self.fake.request
- def shifted(op, a):
- result = request(op, a)
- if op == "enter":
- self.fake.activity[-1]["time"] -= 100
- if op == "exit":
- self.fake.activity[-1]["time"] -= 100
- raise roll.Uncertain("lost response")
- return result
- self.fake.request = shifted
- with self.assertRaises(roll.Refusal):
- self.run_roll()
- self.assertEqual(self.fake.continues, 1)
- self.assertEqual(self.fake.states[IID], "Standby")
def test_resume_reads_status_first_after_cut_apply(self):
self.pause_after_apply()
@@ -1014,28 +1048,6 @@ class RoundTwoTests(unittest.TestCase):
self.assertEqual(self.fake.exits, 1)
self.assert_retained()
- def test_acknowledged_continue_holds_without_readiness_or_targets(self):
- for loss in (False, True):
- with self.subTest(loss=loss):
- self.setUp()
- self.fake.hook = True
- self.fake.target_warmup = 1000
- def after(name):
- if name == "complete" and loss:
- self.fake.admitted = False
- self.fake.boxes[IID]["health"] = dict(state="unhealthy", code=503)
- self.fake.after = after
- with self.assertRaises(roll.DivergenceHeld):
- self.run_roll()
- j = self.journal()
- self.assertIsNotNone(j.last("return-acknowledged"))
- self.assertIsNotNone(j.last("divergence-held"))
- self.assertIsNone(j.last("failed-probe"))
- self.assertEqual((self.fake.minimum, self.fake.desired), (1, 1))
- self.assertEqual(self.fake.tg[IID], "unused")
- self.assertEqual(self.fake.states[IID], "Standby")
- self.assertEqual(self.fake.continues, 1)
- self.assert_retained()
def test_rollback_after_failed_apply_readback(self):
for installed, unchanged in ((NEW, True), (OLD, False), (OLD, True), ("d" * 64, False)):
@@ -1134,7 +1146,7 @@ class RoundTwoTests(unittest.TestCase):
self.assertEqual(self.fake.boxes[IID]["binary_sha256"], OLD)
self.assert_retained()
- def test_hold_describe_blip_after_ack_is_resumable(self):
+ def test_hold_describe_blip_after_provider_return_is_resumable(self):
perform = self.fake.perform
def blip(op, args):
if op == "group" and self.fake.writes.count("enter") == 2:
@@ -1142,13 +1154,17 @@ class RoundTwoTests(unittest.TestCase):
return perform(op, args)
self.fake.perform = blip
self.fake.hook = True
- with self.assertRaises(roll.Uncertain):
+ with self.assertRaises(roll.Refusal):
self.run_roll()
+ self.fake.states[IID] = "InService"
+ self.fake.deadline = None
+ with self.assertRaises(roll.Uncertain):
+ self.resume()
self.assertIsNone(self.journal().last("failed-probe"))
self.fake.perform = perform
with self.assertRaises(roll.DivergenceHeld):
self.resume()
- self.assertEqual(self.fake.continues, 1)
+ self.assertEqual(self.fake.continues, 0)
self.assertEqual(self.fake.writes.count("enter"), 2)
self.assert_retained()
@@ -1285,20 +1301,20 @@ class AdapterTests(unittest.TestCase):
adapter.request("minimum", {"value": 1})
adapter.request("enter", {"iid": IID, "decrement": True})
adapter.request("exit", {"iid": IID})
- adapter.request("complete", {"iid": IID, "hook": self.config["hook"], "result": "CONTINUE"})
+ for result in ("CONTINUE", "ABANDON"):
+ with self.assertRaises(roll.Refusal):
+ adapter.request("complete", {"iid": IID, "hook": self.config["hook"], "result": result})
adapter.request("edges", {"box_ref": "g-example"})
for verb in ("status", "prepare", "permit", "revoke", "apply", "rollback"):
adapter.request("session", dict(iid=IID, verb=verb, sha256=NEW, permit={"v": 1}))
- self.assertEqual([(s, v) for s, v, _, _ in calls[:5]], [
+ self.assertEqual([(s, v) for s, v, _, _ in calls[:4]], [
("autoscaling", "update-auto-scaling-group"), ("autoscaling", "enter-standby"),
- ("autoscaling", "exit-standby"), ("autoscaling", "complete-lifecycle-action"),
+ ("autoscaling", "exit-standby"),
("s3api", "get-object")])
self.assertNotIn("--desired-capacity", calls[0][2])
- self.assertEqual(calls[3][3]["timeout"], 2)
- self.assertIn("--instance-id", calls[3][2])
- self.assertNotIn("--lifecycle-action-token", calls[3][2])
- self.assertIn("control/edges/g-example.json", calls[4][2])
- self.assertTrue(calls[4][3]["object_body"])
+ self.assertFalse(any(v == "complete-lifecycle-action" for _, v, _, _ in calls))
+ self.assertIn("control/edges/g-example.json", calls[3][2])
+ self.assertTrue(calls[3][3]["object_body"])
def test_remote_frame_and_root_failure_refuse(self):
adapter = roll.AWS(self.config)
@@ -1430,39 +1446,6 @@ class RoundThreeTests(unittest.TestCase):
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
@@ -1492,53 +1475,9 @@ class RoundThreeTests(unittest.TestCase):
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"})
+ pass
# Each row becomes a separate unittest case so failures identify the table cell.
@@ -1548,24 +1487,31 @@ CLASSIFY_BASE = dict(context="return", observed=True, n=2, minimum=1, desired=2,
readiness="ok", deregistered=True, prepared=True, pending_checked=True,
peers_checked=True, action_verified=True)
CLASSIFY_ROWS = [
+ ("hook_record_cut", dict(hook=True, divergence_recorded=False), "diverged"),
+ ("hook_targets_failed", dict(hook=True, divergence_recorded=False, describe_error=True, observed=False), "diverged"),
+ ("wait_ready", dict(phase="Pending:Wait"), "diverged"),
+ ("wait_unready", dict(phase="Pending:Wait", readiness="dropped"), "diverged"),
+ ("wait_unknown", dict(phase="Pending:Wait", readiness="unknown"), "diverged"),
+ ("wait_wrong_capacity", dict(phase="Pending:Wait", desired=1), "diverged"),
+ ("wait_already_journaled", dict(phase="Pending:Wait", hook=True), "diverged"),
+ ("hook_terminated", dict(hook=True, phase="Terminated"), "failed"),
+ ("hook_replaced", dict(hook=True, members_match=False), "failed"),
+ ("hook_unknown", dict(hook=True, phase="Unknown"), "failed"),
+ ("hook_provider_return", dict(hook=True, readiness="dropped", targets_healthy=False), "hold"),
+ ("hook_pending", dict(hook=True, phase="Pending"), "resumable"),
+ ("hook_preinservice", dict(hook=True, phase="PreInService"), "resumable"),
+ ("hook_proceed", dict(hook=True, phase="Pending:Proceed"), "resumable"),
+ ("hook_standby_no_hold", dict(hook=True, phase="Standby", desired=1), "resumable"),
+ ("hook_wrong_capacity", dict(hook=True, minimum=2), "resumable"),
+ ("hook_timeout", dict(hook=True, timed_out=True), "resumable"),
("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"),
+ ("hook_describe_error", dict(hook=True, describe_error=True), "resumable"),
+ ("discover_hook_before_missing_intent", dict(phase="Pending:Wait", exit_intent=False), "diverged"),
("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"),
@@ -1581,15 +1527,6 @@ CLASSIFY_ROWS = [
("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"),
@@ -1598,8 +1535,6 @@ CLASSIFY_ROWS = [
("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"),
@@ -1698,10 +1633,7 @@ class SimulationFake(Fake):
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()
+ self.provider_returns = sim.rng.choice((False, True))
def advance(self, seconds):
self.sleep_base(seconds)
@@ -1742,23 +1674,15 @@ class SimulationFake(Fake):
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
+ if sim.last("return-hook"):
+ sim.coverage["describe-error-after-hook"] += 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 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 != "complete", "lifecycle completion attempted"
assert op not in {"desired", "terminate"}, "forbidden provider write"
old_desired = self.desired
result = self.perform(op, args)
@@ -1776,28 +1700,14 @@ class SimulationFake(Fake):
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)
@@ -1816,13 +1726,10 @@ class Simulation:
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"}:
+ if when == "after" and kind in {"failed-probe", "return-hook", "divergence-held", "done"}:
self.trace.append(("journal", kind))
self.audit(when + ":journal:" + kind)
self.maybe_die(when + ":journal:" + kind)
@@ -1845,12 +1752,17 @@ class Simulation:
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"
+ assert f.continues == 0 and not any(op == "complete" for op, _ in f.calls), "lifecycle completion attempted"
+ assert f.exits <= 1, "duplicate accepted return write"
+ assert not any(op in {"desired", "terminate"} for op, _ in f.calls), "forbidden provider write"
+ if f.abandons:
+ assert f.hook and f.states[IID] == "Terminated" and f.launches == 1, "unexpected replacement"
+ assert not self.last("done"), "terminated member recorded as pass"
+ else:
+ assert set(f.states) == {IID, PEER} and f.states[IID] != "Terminated", "same iid lost"
+ if self.last("return-hook"):
+ assert self.store.blocked.exists(), "divergence not flagged"
+ assert not self.last("done"), "hook recorded as pass"
if self.last("divergence-hold"):
assert f.minimum == 1, "minimum restored in hold"
if self.last("divergence-held"):
@@ -1861,13 +1773,16 @@ class Simulation:
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"
+ facts.get("hook"), facts.get("readiness", "unknown")))
+ assert decision.action not in {"complete", "abandon"}, "lifecycle completion decision"
+ if facts.get("context") == "return" and facts.get("observed") and not facts.get("describe_error") and not facts.get("operation_error"):
+ if facts.get("phase") == "Pending:Wait":
+ assert decision.action == "diverged", "divergence decision bypassed"
+ if facts.get("phase") is None or str(facts.get("phase")).startswith("Terminat") or not facts.get("members_match"):
+ if facts.get("exit_state") != "none" or facts.get("hook"):
+ assert decision.action == "failed", "terminated member recorded as pass"
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 not facts.get("hook") 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
@@ -1893,17 +1808,34 @@ class Simulation:
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)
+ if self.last("return-hook") and not self.last("divergence-hold"):
+ assert self.store.blocked.exists(), "divergence not flagged"
+ if self.fake.states[IID] == "Pending:Wait":
+ self.coverage["diverged"] += 1
+ # The tool stopped. Only the provider moves next.
+ if self.fake.provider_returns:
+ self.fake.deadline = None
+ self.fake.states[IID] = "Pending:Proceed"
+ self.fake.schedule(["Pending", "InService"])
+ self.coverage["provider-return"] += 1
+ else:
+ self.fake.advance(901)
+ self.coverage["provider-abandon"] += 1
+ if self.last("failed-probe"):
+ assert self.fake.states[IID] == "Terminated", "unexpected failed probe"
+ self.coverage["failed"] += 1
+ break
+ self.fake.advance(3)
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"
+ if self.fake.provider_returns:
+ assert self.last("divergence-held") and self.fake.states[IID] == "Standby", "hook return did not hold"
+ else:
+ assert self.last("failed-probe") and self.fake.states[IID] == "Terminated", "provider loss not failed"
+ assert self.store.blocked.exists(), "divergence not flagged"
+ assert not self.last("done"), "hook recorded as pass"
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
@@ -1922,44 +1854,41 @@ class SimulationTests(unittest.TestCase):
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",
+ for event in ("describe-error", "diverged", "failed", "provider-return", "death", "resume",
+ "admission-drop", "admission-recovery", "loss:exit",
"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 completion(f):
+ return roll.Decision("complete") if original(f).action == "diverged" else original(f)
+ def abandon(f):
+ return roll.Decision("abandon") if original(f).action == "diverged" else original(f)
+ def ignore_hook(f):
+ return roll.Decision("wait", delay=5) if original(f).action == "diverged" else original(f)
+ def loss_passes(f):
+ return roll.Decision("finish-return") if original(f).action == "failed" else 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)):
+ return roll.Decision("restore-minimum") if original(f).action == "hold" else original(f)
+ for name, mutant in (("continue", completion), ("abandon", abandon),
+ ("divergence-not-flagged", ignore_hook), ("terminated-pass", loss_passes),
+ ("minimum-in-hold", minimum_in_hold)):
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")
+ "lifecycle completion decision|divergence decision bypassed|terminated member recorded as pass|minimum decision in hold")
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):
+ def test_ten_required_mutations(self):
source = Path(roll.__file__).read_text()
cases = [
("decrement=false", [("decrement=True)", "decrement=False)")], "test_standby_roll_order"),
@@ -1977,12 +1906,17 @@ class MutationTests(unittest.TestCase):
"test_standby_shared_outage"),
("ignored transaction lock", [
('fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)', 'pass')], "test_lock_refuses_second_writer"),
- ("original receipt suppresses return completion", [
- ('self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE",\n freshness=ready["observed"])', 'self.sleep(901)')],
+ ("tool sends CONTINUE on Pending:Wait", [
+ ('if action == "diverged":', 'if action == "diverged":\n self.call("complete", iid=iid, hook=self.c["hook"], result="CONTINUE")')],
+ "test_standby_exit_pending_wait"),
+ ("tool sends ABANDON", [
+ ('if action == "diverged":', 'if action == "diverged":\n self.call("complete", iid=iid, hook=self.c["hook"], result="ABANDON")')],
+ "test_standby_exit_pending_wait"),
+ ("divergence not flagged", [
+ ('self.state.write(self.state.blocked, dict(transaction=h["transaction"], phase="Pending:Wait"))', 'pass')],
"test_standby_exit_pending_wait"),
- ("completion before fresh admission", [
- ('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 =')],
+ ("terminated member recorded as pass", [
+ ('return Decision("failed", "lost_member")', 'return Decision("finish-return")')],
"test_standby_exit_pending_wait_admission_loss"),
("PreInService as InService", [
('context, phase = f.get("context", "return"), f.get("phase")',