region HA: a terminate attempt is decided by its own activity
Fix round 3 (N2). The recovery decision counted activities from up to 5 s before the latest intent, so a previous attempt's Failed or Cancelled could override an answered retry, spend its resend budget or stop it early. - An answered attempt is tied to the activity ID its response named; until that activity is listed it gets its settlement allowance. - Otherwise the 5 s skew allowance applies only to activities whose ID no earlier attempt owns (named in an earlier response, or listed when an earlier attempt was decided). - Tests: the table now covers named and unnamed answers and previous activities 1 s and 60 s before the intent, known or not (over 30,000 rows), plus the boundary case (answered at 1000, now 1001, only a previous Failed at 999: wait) and a flow test of a quick failure then an accepted retry whose activity lags.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
scripts/region-group-roll.py+42 −12scripts/region_group_held_test.py+61 −13
CI failed — run details
Intent
<task-notification> <task-id>a8303ed4bc3147d03</task-id> <tool-use-id>toolu_01EMG9Bd5pUF5qkggybKrJ3L</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. N1 is fixed with a single recovery decision for every terminate after its intent. Commit: `206f097f` region HA: one terminate recovery decision for replace and remove (not pushed). There is no census commit this round: the Python scripts aren't census units, so the propose changed nothing (seal still deec6fc8…) and the census test passes. The fix: - **Status kept:** the activity parser now keeps `StatusCode`. - **One decision:** a new function, `terminate_decision()`, makes every post-intent call on every pass, both fresh runs and resumes. It returns exactly one of done, wait, retry, or an explicit recoverable fail that tells the operator to fix the provider and run resume. - **Failed or Cancelled** now leads to a retry, with at most 2 resends per run. A third failure is the explicit fail. - **Old activities don't count:** only activities newer than the latest intent decide, so an earlier failed attempt can no longer block recovery forever. - **Checks on retry:** a retry always re-runs the stop proof, the fence read and the lock sweep before the provider call. Tests: - 286 Python tests pass. - The exhaustive table test covers more than 10,000 combinations, including Failed and Cancelled after an unanswered intent. New witnesses cover recovery after Failed/Cancelled and a persistent failure followed by a successful resume. - 36 of 36 mutations are caught, including dropping `StatusCode`. Concerns: none new. Still owed: the live dev call (it needs the operator policy applied first) and the runbook. Report (fix round 2 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>439521</subagent_tokens><tool_uses>27</tool_uses><duration_ms>2467510</duration_ms></usage> </task-notification>
Attributed to this commit: 19.8 g CO₂e (2,566,365 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 2ae2b3007..1b5429e8c 100755 |
| --- a/scripts/region-group-roll.py |
| +++ b/scripts/region-group-roll.py |
| @@ -376,13 +376,20 @@ 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).""" |
| + answered (the latest intent got a response); activity_id (the activity |
| + that response named, or None); previous_ids (activity IDs known from |
| + earlier attempts); activities (A's terminate activities, each with id, |
| + 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. |
| + |
| + Which activity decides: for an answered attempt that named its |
| + activity, only that activity (until it is listed, the attempt gets its |
| + settlement allowance). Otherwise an activity that started no earlier |
| + than 5 s before the latest intent (clock skew) and whose ID no earlier |
| + attempt owns. So an old attempt's failure never decides 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") |
| @@ -390,8 +397,13 @@ def terminate_decision(f) -> Decision: |
| 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)) |
| + previous = set(f.get("previous_ids") or ()) |
| + if f.get("activity_id"): |
| + mine = [a for a in f["activities"] if a.get("id") == f["activity_id"]] |
| + else: |
| + mine = [a for a in f["activities"] if a.get("time", 0) >= f["intent_at"] - 5 and |
| + a.get("id") not in previous] |
| + current = sorted(mine, key=lambda a: a.get("time", 0)) |
| if current: |
| status = current[-1].get("status") |
| if status in ACTIVITY_FAILED: |
| @@ -2123,6 +2135,20 @@ class Operator: |
| except Uncertain: |
| pass |
| + def previous_terminate_activities(self, seq): |
| + """Activity IDs earlier terminate attempts own: those their responses |
| + named, and those listed when an earlier attempt was decided.""" |
| + ids = set() |
| + for r in self.j.events: |
| + if r.get("seq", 0) >= seq: |
| + break |
| + if r["kind"] == "response" and r.get("op") == "terminate" and isinstance(r.get("result"), dict): |
| + if r["result"].get("activity"): |
| + ids.add(r["result"]["activity"]) |
| + if r["kind"] == "terminate-decision": |
| + ids.update(a.get("id") for a in r["facts"].get("activities", []) if a.get("id")) |
| + return sorted(ids) |
| + |
| def stop_sent(self): |
| return any(r["kind"] == "intent" and r.get("op") == "session" and |
| r["args"].get("verb") == "edge-stop" for r in self.j.events) |
| @@ -2143,9 +2169,13 @@ class Operator: |
| # 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), |
| + response = next((r for r in self.j.events if r["kind"] == "response" and |
| + r.get("intent") == intent["seq"]), None) |
| + result = response.get("result") if response else None |
| + facts = dict(phase=phase, intent_at=intent["at"], intent_seq=intent["seq"], now=self.clock(), |
| + retries=retries, answered=response is not None, |
| + activity_id=result.get("activity") if isinstance(result, dict) else None, |
| + previous_ids=self.previous_terminate_activities(intent["seq"]), |
| 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) |
diff --git a/scripts/region_group_held_test.py b/scripts/region_group_held_test.py| index 993a25205..2f6056faa 100644 |
| --- a/scripts/region_group_held_test.py |
| +++ b/scripts/region_group_held_test.py |
| @@ -271,6 +271,11 @@ class HeldFake(base.Fake): |
| if "--should-decrement-desired-capacity" in args: |
| self.violate("terminate with decrement") |
| self.desired -= 1 |
| + if self.terminate_outcomes and self.terminate_outcomes[0] == "lagging": |
| + # Accepted, but the activity and the group lag for 20 s. |
| + self.terminate_outcomes.pop(0) |
| + self.lagging_until = self.now + 20 |
| + return dict(Activity=dict(ActivityId="terminate-lagging")) |
| if self.terminate_outcomes: |
| # The provider accepts the request, and its activity then ends |
| # Failed or Cancelled: the member stays in Standby. |
| @@ -282,7 +287,7 @@ class HeldFake(base.Fake): |
| self.tg.pop(iid, None) |
| self.terminated_at = self.now |
| self.departure_at = self.now + self.departure_delay |
| - return dict(Activity=dict(ActivityId="terminate-1")) |
| + return dict(Activity=dict(ActivityId="terminate-ok-%d" % len(self.activity))) |
| if verb == "describe-scaling-activities": |
| result = super().invoke(service, verb, args, **kwargs) |
| for row, a in zip(result["Activities"], self.activity): |
| @@ -732,6 +737,27 @@ class ReplaceTests(HeldBase): |
| ["status"], status) |
| self.assert_h4() |
| + def test_quick_failure_then_accepted_retry_is_not_resent(self): |
| + # N2 in the flow: the first attempt fails at once; the retry, inside |
| + # the 5 s skew allowance, is accepted but its activity is not listed |
| + # for 20 s. The old Failed activity must not resend or stop it. |
| + self.fake.terminate_outcomes = ["Failed", "lagging"] |
| + self.depart() |
| + self.assertEqual(self.fake.writes.count("terminate"), 2) |
| + self.assertEqual(self.fake.states[IID], "Terminated") |
| + with self.journal() as journal: |
| + intents = [r for r in journal.events if r["kind"] == "intent" and r["op"] == "terminate"] |
| + self.assertLess(intents[1]["at"] - intents[0]["at"], 5) |
| + waits = [r for r in journal.events if r["kind"] == "terminate-decision" and r["action"] == "wait"] |
| + self.assertTrue(waits) |
| + self.assertEqual(waits[0]["facts"]["activity_id"], "terminate-lagging") |
| + # The first attempt's Failed activity is known as a previous one. |
| + failed = journal.last("terminate-decision", action="retry")["facts"]["activities"][-1] |
| + self.assertEqual(failed["status"], "Failed") |
| + self.assertIn(failed["id"], waits[0]["facts"]["previous_ids"]) |
| + self.assertEqual(journal.last("response", op="terminate")["result"]["activity"], "terminate-lagging") |
| + 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: |
| @@ -1054,6 +1080,7 @@ class TerminateDecisionTests(unittest.TestCase): |
| @staticmethod |
| def expected(phase, answered, current, age, retries): |
| + """current is the status of the activity that decides (None: none).""" |
| retry = ("retry", "") if retries < roll.TERMINATE_RETRIES else ("fail", "terminate_failed") |
| if phase is None or phase.startswith("Terminat"): |
| return ("done", "") |
| @@ -1075,30 +1102,51 @@ class TerminateDecisionTests(unittest.TestCase): |
| intent = 1000.0 |
| rows = 0 |
| for phase in self.PHASES: |
| - for answered in (False, True): |
| + for answered, named in ((False, False), (True, False), (True, True)): |
| for current in [None] + self.STATUSES: |
| - for old in (None, "Failed", "InProgress"): |
| - for age in (0, 119, 120, 599, 600, 3600): |
| + # An earlier attempt's activity: none, or one at 60 s or at |
| + # 1 s before the intent (inside the 5 s skew allowance), |
| + # with its ID known to the journal or not. |
| + for old, old_at, known in ((None, None, False), ("Failed", -60, True), ("Failed", -1, True), |
| + ("Cancelled", -1, True), ("InProgress", -1, True), |
| + ("Failed", -60, False), ("Failed", -1, False)): |
| + for age in (0, 1, 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)) |
| + activities.append(dict(id="old", time=intent + old_at, status=old)) |
| if current is not None: |
| - activities.append(dict(time=intent + 1, |
| + activities.append(dict(id="new", time=intent + 1, |
| status=None if current == "missing" else current)) |
| got = roll.terminate_decision(dict( |
| - phase=phase, answered=answered, activities=activities, |
| + phase=phase, answered=answered, activity_id="new" if named else None, |
| + previous_ids=["old"] if known else [], 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): |
| + deciding = current |
| + if current is None and old and not named and not known and old_at >= -5: |
| + # An unowned activity inside the skew allowance |
| + # may be this attempt's: it decides. |
| + deciding = old |
| + want = self.expected(phase, answered, deciding, age, retries) |
| + with self.subTest(phase=phase, answered=answered, named=named, current=current, |
| + old=old, old_at=old_at, known=known, 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) |
| + self.assertGreater(rows, 30000) |
| + |
| + def test_previous_failure_never_decides_an_answered_attempt(self): |
| + # N2: answered at 1000, now 1001, only the previous attempt's Failed |
| + # activity (999) is listed. The new attempt gets its settlement time. |
| + for facts in (dict(activity_id="new", previous_ids=[]), dict(activity_id="new", previous_ids=["old"]), |
| + dict(activity_id=None, previous_ids=["old"])): |
| + with self.subTest(**facts): |
| + d = roll.terminate_decision(dict(phase="Standby", answered=True, intent_at=1000, now=1001, |
| + retries=0, activities=[dict(id="old", time=999, status="Failed")], |
| + **facts)) |
| + self.assertEqual(d.action, "wait") |
| 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, |
| @@ -1164,7 +1212,7 @@ class AdapterH4Tests(unittest.TestCase): |
| self.fake.states[IID] = "Standby" |
| self.fake.minimum = self.fake.desired = 1 |
| self.assertEqual(self.adapter.request("terminate", dict(iid=IID, decrement=False)), |
| - {"activity": "terminate-1"}) |
| + {"activity": "terminate-ok-0"}) |
| self.assertEqual(self.cli[-1], "terminate-instance-in-auto-scaling-group") |
| self.assertEqual(self.fake.desired, 1) |
| self.assertEqual(self.fake.h4_violations, []) |