carlos / platform Public

region HA: one terminate recovery decision for replace and remove

Fix round 2 (N1). A Failed or Cancelled termination activity vetoed
recovery forever: the activity parser dropped StatusCode, so every
resume waited 900 s and the group could stay at N-1 with A stopped.

- The parser keeps each activity's StatusCode.
- terminate_decision(), a pure function like classify(), owns every
  post-intent pass: from A's lifecycle state, whether the latest intent
  was answered, its terminate activities (only those after the latest
  intent) with their status, the time and this run's resends, it
  returns done, wait, retry or fail with a TEXT key.
- Failed or Cancelled retries; a running activity waits up to 10 min; a
  success not yet shown waits 2 min; an unknown status, a member that
  left Standby, or a third failure is an explicit recoverable FAIL that
  names the next step (resume after the provider is fixed).
- A retry re-runs the stop proof, the fence read and the lock sweep
  before the provider call. Each decision is journaled.

Tests: an exhaustive table over phase, answered, current and earlier
activity status, age and resends (over 10,000 rows); Failed and
Cancelled after an unanswered intent; persistent failure then resume.
Mutations, including dropping StatusCode, are all caught.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 206f097f8be5d284385debb283f11ca305d4faf1 parent a2e1b5b
3 files changed, +214 −18
  • scripts/region-group-roll.py +79 −16
  • scripts/region_group_held_test.py +134 −1
  • scripts/region_group_roll_test.py +1 −1

Intent

Human

<task-notification> <task-id>a8303ed4bc3147d03</task-id> <tool-use-id>toolu_018t315NDo1LtptCtRXWxAs2</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a8303ed4bc3147d03.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6: roll tool" 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>Status: DONE. Every P1, P2 and Important finding is fixed; four minors are listed, not done. Commits: `6d9c73f1` (fix round 1) and `a2e1b5b1` (census re-propose), on FIX_BASE 81877223. Not pushed. Tests: - **Python:** 281 tests pass (roll, probe, held, document, contract). - **Mutations:** 30 of 30 caught (the 19 earlier ones plus 11 for this round). - **Census:** re-proposed with NAME=region-ha-held-build; seal now deec6fc8…, census and Python-guard tests pass. - **Tofu:** document module tests pass, 12 of 12. The operator-policy tests pass 13 of 13, but only in a scratch copy with two changes for local tofu 1.12.5, which rejects keyed EIP override targets in every region-host test file. CI should run the committed file as-is. Concerns: - Listed, not done: a root `edge-stop &lt;txn&gt;` verb (a Go change, suggested for Task 8); run the first live replace on a 3-member group; a note for the runbook. - Open question for you: is the housekeeper lease a "lease naming A" under H5? The lock sweep doesn't read it. - Still owed: the live dev call, which needs the policy applied first, and the runbook. Report (fix round appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-6-report.md</result> <usage><subagent_tokens>401107</subagent_tokens><tool_uses>51</tool_uses><duration_ms>2004778</duration_ms></usage> </task-notification>

Attributed to this commit: 15.5 g CO₂e (2,035,606 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-held-build, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py
index 18437cc2a..2ae2b3007 100755
--- a/scripts/region-group-roll.py
+++ b/scripts/region-group-roll.py
@@ -204,6 +204,11 @@ TEXT = {
"remove_pools_unknown": "The member's served_pools are unknown",
"watch_timeout": "The replacement or the departure did not finish in time",
"lock_held_after_stop": "A lock still names the member after its edge stopped. The member is held in Standby",
+ "terminate_failed": "The member's termination failed, was cancelled or never arrived, and was retried. It stays in Standby with its edge stopped and its fence in place. Resolve the provider error, then run resume to try again",
+ "terminate_left_standby": "The member left Standby without being terminated. Its edge is stopped and its fence is in place. Investigate before running resume or close-lost",
+ "terminate_unsettled": "The termination activity succeeded but the group still shows the member in Standby. Check the group, then run resume",
+ "terminate_stuck": "The termination activity is still running after 10 minutes. Check it in the console, then run resume",
+ "terminate_status": "The termination activity has an unknown status. Check it in the console, then run resume",
"fence_moot": "The member is gone, so its start fence went with it. No fence-clear is needed.",
"replaced": "Member replaced.",
"removed": "Member removed. Set box_count to {n} in the region's tofu and apply; the plan should show no instance change.",
@@ -353,6 +358,54 @@ def classify(facts) -> Decision:
return Decision("resumable", "return_phase")
+# The terminate recovery decision (replace and remove, after the intent).
+# AWS ScalingActivityStatusCode values (API_Activity.html): three terminal,
+# the rest still running.
+ACTIVITY_FAILED = {"Failed", "Cancelled"}
+ACTIVITY_PENDING = {"PendingSpotBidPlacement", "WaitingForSpotInstanceRequestId", "WaitingForSpotInstanceId",
+ "WaitingForInstanceId", "PreInService", "InProgress", "WaitingForELBConnectionDraining",
+ "MidLifecycleAction", "WaitingForInstanceWarmup", "WaitingForConnectionDraining",
+ "WaitingForInPlaceUpdateToStart", "WaitingForInPlaceUpdateToFinalize",
+ "InPlaceUpdateInProgress"}
+TERMINATE_RETRIES = 2 # resends per tool run; a later resume starts again
+TERMINATE_SETTLE = 120 # seconds for the group to show a received terminate
+TERMINATE_PENDING = 600 # seconds a running terminate activity may take
+
+
+def terminate_decision(f) -> Decision:
+ """The one decision for a terminate after its durable intent.
+
+ Facts: phase (A's lifecycle state in the group, None when absent);
+ answered (the latest intent got a response); activities (A's terminate
+ activities, each with time and status); intent_at; now; retries (resends
+ in this run). Returns exactly one of done, wait, retry, or fail with the
+ TEXT key of an explicit, recoverable instruction. Only activities that
+ started after the latest intent count, so an old attempt's failure never
+ vetoes a new one. A retry re-runs the stop, fence and lock checks before
+ the provider call (Operator.stop_and_terminate)."""
+ phase = f["phase"]
+ if phase is None or phase.startswith("Terminat"):
+ return Decision("done")
+ if phase != "Standby":
+ return Decision("fail", "terminate_left_standby")
+ age = f["now"] - f["intent_at"]
+ retry = Decision("retry") if f["retries"] < TERMINATE_RETRIES else Decision("fail", "terminate_failed")
+ current = sorted((a for a in f["activities"] if a.get("time", 0) >= f["intent_at"] - 5),
+ key=lambda a: a.get("time", 0))
+ if current:
+ status = current[-1].get("status")
+ if status in ACTIVITY_FAILED:
+ return retry
+ if status == "Successful":
+ return Decision("wait", delay=5) if age < TERMINATE_SETTLE else Decision("fail", "terminate_unsettled")
+ if status in ACTIVITY_PENDING:
+ return Decision("wait", delay=5) if age < TERMINATE_PENDING else Decision("fail", "terminate_stuck")
+ return Decision("fail", "terminate_status")
+ if f["answered"] and age < TERMINATE_SETTLE:
+ return Decision("wait", delay=5)
+ return retry
+
+
class Refusal(Exception):
pass
@@ -865,7 +918,10 @@ class AWS:
"terminate" if description.startswith("Terminating EC2 instance") else None)
if re.search(r"\b" + re.escape(a["iid"]) + r"\b", description) and kind:
dt = datetime.fromisoformat(row["StartTime"].replace("Z", "+00:00"))
- result.append(dict(id=row["ActivityId"], iid=a["iid"], time=dt.timestamp(), kind=kind))
+ # StatusCode tells an activity still running from a
+ # terminal one (Successful, Failed, Cancelled).
+ result.append(dict(id=row["ActivityId"], iid=a["iid"], time=dt.timestamp(), kind=kind,
+ status=row.get("StatusCode")))
return result
if op == "edges":
require(re.fullmatch(r"g-[a-z0-9-]+", a["box_ref"]), "identity")
@@ -2077,28 +2133,35 @@ class Operator:
start = self.j.last("intent", op="terminate")["at"]
end = self.clock() + WAIT
departed_at = replacement = None
+ retries = 0
while True:
if self.clock() >= end:
self.alert("watch_timeout")
g = self.snapshot()
require(g["maximum"] == n and g["template"] == h["template"], "members")
phase = g["members"].get(iid)
- if phase is not None and not phase.startswith("Terminat"):
- # Still a member. A terminate the provider never answered (an
- # error, or a hard cut after the durable intent that left no
- # row at all) is sent again, unless the provider's activities
- # show it arrived; a received one is waited for.
- require(phase == "Standby", "members")
- intent = self.j.last("intent", op="terminate")
- answered = any(r["kind"] == "response" and r.get("intent") == intent["seq"]
- for r in self.j.events)
- if not answered and not any(
- a.get("kind") == "terminate" and a.get("time", 0) >= intent["at"] - 5
- for a in self.call("activities", iid=iid)):
- self.stop_and_terminate()
- continue
- self.sleep(max(0, min(5, end - self.clock())))
+ # Every pass, a fresh start or a resume, asks terminate_decision.
+ intent = self.j.last("intent", op="terminate")
+ settled = phase is None or phase.startswith("Terminat")
+ facts = dict(phase=phase, intent_at=intent["at"], now=self.clock(), retries=retries,
+ answered=any(r["kind"] == "response" and r.get("intent") == intent["seq"]
+ for r in self.j.events),
+ activities=[] if settled or phase != "Standby" else
+ [a for a in self.call("activities", iid=iid) if a.get("kind") == "terminate"])
+ decision = terminate_decision(facts)
+ if not settled:
+ self.event("terminate-decision", action=decision.action, reason=decision.reason, facts=facts)
+ if decision.action == "fail":
+ # An explicit, recoverable stop; the journal stays for resume.
+ self.alert(decision.reason or "terminate_status")
+ if decision.action == "retry":
+ retries += 1
+ self.stop_and_terminate()
+ continue
+ if decision.action == "wait":
+ self.sleep(max(0, min(decision.delay, end - self.clock())))
continue
+ require(decision.action == "done", "record")
others = sorted(m for m in g["members"] if m != iid)
if not self.j.last("terminate-checked"):
# The provider check behind H4: terminating the Standby member
diff --git a/scripts/region_group_held_test.py b/scripts/region_group_held_test.py
index 7b5e4c1e5..993a25205 100644
--- a/scripts/region_group_held_test.py
+++ b/scripts/region_group_held_test.py
@@ -80,6 +80,7 @@ class HeldFake(base.Fake):
self.entering_polls = 0
self.cancel_ok = True
self.starts = []
+ self.terminate_outcomes = []
def add_member(self, iid, state):
self.states[iid] = state
@@ -270,6 +271,13 @@ class HeldFake(base.Fake):
if "--should-decrement-desired-capacity" in args:
self.violate("terminate with decrement")
self.desired -= 1
+ if self.terminate_outcomes:
+ # The provider accepts the request, and its activity then ends
+ # Failed or Cancelled: the member stays in Standby.
+ status = self.terminate_outcomes.pop(0)
+ self.activity.append(dict(id="terminate-%d" % len(self.activity), iid=iid, time=self.now,
+ kind="terminate", status=status))
+ return dict(Activity=dict(ActivityId=self.activity[-1]["id"]))
self.states[iid] = "Terminating"
self.tg.pop(iid, None)
self.terminated_at = self.now
@@ -280,6 +288,7 @@ class HeldFake(base.Fake):
for row, a in zip(result["Activities"], self.activity):
if a["kind"] == "terminate":
row["Description"] = "Terminating EC2 instance: " + a["iid"]
+ row["StatusCode"] = a.get("status", "Successful")
return result
if verb == "describe-instance-information":
iid = json.loads(value("--filters"))[0]["Values"][0]
@@ -677,13 +686,67 @@ class ReplaceTests(HeldBase):
self.assertEqual(self.fake.writes.count("terminate"), 1)
self.fake.states[IID] = "Standby"
self.fake.terminated_at = None
- self.fake.activity.append(dict(id="terminate-1", iid=IID, time=self.fake.now, kind="terminate"))
+ self.fake.activity.append(dict(id="terminate-1", iid=IID, time=self.fake.now, kind="terminate",
+ status="InProgress"))
self.fake.lagging_until = self.fake.now + 20
self.resume()
self.assertEqual(self.fake.writes.count("terminate"), 1)
self.assertEqual(self.fake.states[IID], "Terminated")
self.assertIsNone(self.store.active_id())
+ def cut_terminate_rows(self):
+ add = roll.Journal.add
+
+ def cut(journal, kind, **data):
+ if kind == "error" and data.get("op") == "terminate":
+ raise base.Death("cut")
+ return add(journal, kind, **data)
+ return patch.object(roll.Journal, "add", cut)
+
+ def test_failed_or_cancelled_activity_after_unanswered_intent_is_retried(self):
+ for status in ("Failed", "Cancelled"):
+ with self.subTest(status=status):
+ self.setUp()
+ self.fake.terminate_outcomes = [status]
+ self.fake.fault, self.fake.fault_at = "death", 5
+ with self.cut_terminate_rows(), self.assertRaises(base.Death):
+ self.depart()
+ with self.journal() as journal:
+ self.assertIsNone(journal.last("response", op="terminate"))
+ self.assertIsNone(journal.last("error", op="terminate"))
+ self.assertEqual(self.fake.states[IID], "Standby")
+ start = len(self.fake.calls)
+ self.resume()
+ self.assertEqual(self.fake.states[IID], "Terminated")
+ self.assertEqual(self.fake.writes.count("terminate"), 2)
+ # The retry re-ran the stop proof, the fence read and the lock
+ # sweep before the provider call.
+ after = [(op, a.get("verb")) for op, a in self.fake.calls[start:]]
+ second = after.index(("terminate", None))
+ self.assertIn(("session", "edge-stop"), after[:second])
+ self.assertIn(("session", "status"), after[after.index(("session", "edge-stop")):second])
+ self.assertIn(("lock_hosts", None), after[after.index(("session", "edge-stop")):second])
+ self.assertEqual((self.fake.minimum, self.fake.desired), (2, 2))
+ with self.journal() as journal:
+ self.assertEqual(journal.last("terminate-decision", action="retry")["facts"]["activities"][-1]
+ ["status"], status)
+ self.assert_h4()
+
+ def test_persistent_failure_is_an_explicit_recoverable_fail(self):
+ self.fake.terminate_outcomes = ["Failed"] * (1 + roll.TERMINATE_RETRIES)
+ with self.assertRaises(roll.Refusal) as caught:
+ self.depart()
+ self.assertEqual(str(caught.exception), roll.TEXT["terminate_failed"])
+ self.assertEqual(self.fake.writes.count("terminate"), 1 + roll.TERMINATE_RETRIES)
+ self.assertEqual(self.fake.states[IID], "Standby")
+ self.assertEqual(self.store.active_id(), "t6-held")
+ self.assertLess(self.fake.now, 1800000000.0 + roll.WAIT)
+ # The provider is fixed: resume decides afresh and completes.
+ self.resume()
+ self.assertEqual(self.fake.states[IID], "Terminated")
+ self.assertEqual((self.fake.minimum, self.fake.desired), (2, 2))
+ self.assertIsNone(self.store.active_id())
+
def test_provider_changing_desired_on_terminate_fails(self):
invoke = self.fake.invoke
@@ -982,6 +1045,76 @@ class DrainedRollTests(HeldBase):
self.assert_h4()
+class TerminateDecisionTests(unittest.TestCase):
+ """The one terminate recovery decision, over every combination."""
+ # None stands for an activity whose StatusCode is missing.
+ STATUSES = sorted(roll.ACTIVITY_FAILED | roll.ACTIVITY_PENDING | {"Successful", "Unexpected"}) + ["missing"]
+ PHASES = (None, "Terminating", "Terminating:Wait", "Terminating:Proceed", "Terminated", "Standby",
+ "EnteringStandby", "InService", "Pending", "Pending:Wait", "Detaching")
+
+ @staticmethod
+ def expected(phase, answered, current, age, retries):
+ retry = ("retry", "") if retries < roll.TERMINATE_RETRIES else ("fail", "terminate_failed")
+ if phase is None or phase.startswith("Terminat"):
+ return ("done", "")
+ if phase != "Standby":
+ return ("fail", "terminate_left_standby")
+ if current is not None:
+ if current in ("Failed", "Cancelled"):
+ return retry
+ if current == "Successful":
+ return ("wait", "") if age < 120 else ("fail", "terminate_unsettled")
+ if current in roll.ACTIVITY_PENDING:
+ return ("wait", "") if age < 600 else ("fail", "terminate_stuck")
+ return ("fail", "terminate_status")
+ if answered and age < 120:
+ return ("wait", "")
+ return retry
+
+ def test_every_combination(self):
+ intent = 1000.0
+ rows = 0
+ for phase in self.PHASES:
+ for answered in (False, True):
+ for current in [None] + self.STATUSES:
+ for old in (None, "Failed", "InProgress"):
+ for age in (0, 119, 120, 599, 600, 3600):
+ for retries in range(roll.TERMINATE_RETRIES + 1):
+ activities = []
+ if old:
+ # An earlier attempt's activity never decides.
+ activities.append(dict(time=intent - 60, status=old))
+ if current is not None:
+ activities.append(dict(time=intent + 1,
+ status=None if current == "missing" else current))
+ got = roll.terminate_decision(dict(
+ phase=phase, answered=answered, activities=activities,
+ intent_at=intent, now=intent + age, retries=retries))
+ want = self.expected(phase, answered, current, age, retries)
+ with self.subTest(phase=phase, answered=answered, current=current, old=old,
+ age=age, retries=retries):
+ self.assertEqual((got.action, got.reason), want)
+ self.assertIn(got.action, {"done", "wait", "retry", "fail"})
+ if got.action == "fail":
+ self.assertIn(got.reason, roll.TEXT)
+ rows += 1
+ self.assertGreater(rows, 10000)
+
+ def test_activity_status_none_is_not_a_veto_of_its_own(self):
+ # An activity row whose status could not be read is an explicit fail,
+ # never an endless wait.
+ d = roll.terminate_decision(dict(phase="Standby", answered=False, activities=[dict(time=5, status=None)],
+ intent_at=0, now=10, retries=0))
+ self.assertEqual((d.action, d.reason), ("fail", "terminate_status"))
+
+ def test_adapter_keeps_status_code(self):
+ fake = HeldFake(held_config("/state"))
+ fake.activity.append(dict(id="t-1", iid=IID, time=fake.now, kind="terminate", status="Cancelled"))
+ rows = roll.AWS.request(fake, "activities", dict(iid=IID))
+ self.assertEqual([(r["kind"], r["status"]) for r in rows if r["kind"] == "terminate"],
+ [("terminate", "Cancelled")])
+
+
class AdapterH4Tests(unittest.TestCase):
"""H4 at the adapter: the real AWS adapter, with its CLI calls answered by
the provider that punishes any other desired-lowering call."""
diff --git a/scripts/region_group_roll_test.py b/scripts/region_group_roll_test.py
index add5820a4..fc3262520 100644
--- a/scripts/region_group_roll_test.py
+++ b/scripts/region_group_roll_test.py
@@ -1830,7 +1830,7 @@ class LiveFixtureTests(unittest.TestCase):
with patch.object(self.adapter, "invoke", return_value=raw):
result = self.adapter.request("activities", dict(iid=IID))
self.assertEqual(result, [dict(id=row["ActivityId"], iid=IID,
- time=1793891898.824, kind=kind)])
+ time=1793891898.824, kind=kind, status=status)])
def test_live_edges_and_root_frame(self):
for box in (live.BOX, live.PEER_BOX):