From 952b0af131c7639e94d6f5c6a7ad64468b010765 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sat, 28 Nov 2026 14:41:30 +0100 Subject: [PATCH] Start a refused retry timer again instead of failing the workflow on replay When on_task_failure asks for a delayed retry, the executor starts the timer __simpleflow_task_ and, on later replays, looks at it in do_handle_failure. That method decoded timer["control"] before looking at timer["state"]. If SWF refused the timer (StartTimerFailed, e.g. TIMER_CREATION_RATE_EXCEEDED), History.parse_timer_event records a start_failed entry with no "control", so every replay raised KeyError and the executor failed the execution with "Cannot replay the workflow: KeyError('control')". The start_failed branch below was never reached, and it would have failed the execution all the same: it raised a bare TaskFailed, which replay also turns into "Cannot replay the workflow". Read "control" only where it is used, for a fired or canceled timer. For a refusal SWF may accept later (TIMER_CREATION_RATE_EXCEEDED, OPEN_TIMERS_LIMIT_EXCEEDED), fall through to the normal failure handling: on_task_failure decides again and the executor starts the retry timer again, under the same id. SWF only refuses an id while a timer with it is open, the refused one never opened, and successive retries already reuse that id once the previous timer fired. This mirrors ActivityTaskScheduleFailed, whose activity is scheduled again on the next decision. For any other cause (TIMER_ID_ALREADY_IN_USE, OPERATION_NOT_PERMITTED), treat the task as failed the way an abort decision does: raise the task's exception with TaskFailed(timer_id, cause) when it raises on failure, else return its failed future. History.parse_timer_event kept the decision_task_completed_event_id of an existing entry when a start_failed arrived for the same id. On a second or later retry the entry still held the first timer's decision, which is older than the latest failure, so find_timer_associated_with ignored the refused timer and the executor started it again whatever the cause. A start_failed now records its own decision, as a started timer already does. The two new replay tests (an activity that fails with a delayed retry, then a refused retry timer) run with no earlier retry and with one. On the previous code, a refusal of the first retry timer fails with KeyError('control') for both causes, and a permanent refusal on the second retry starts the timer again. Co-Authored-By: Claude Opus 5.5 --- simpleflow/history.py | 2 +- simpleflow/swf/executor.py | 20 +++--- tests/test_simpleflow/swf/test_executor.py | 72 +++++++++++++++++++++- 3 files changed, 85 insertions(+), 9 deletions(-) diff --git a/simpleflow/history.py b/simpleflow/history.py index a055cfa7..2e0589a6 100644 --- a/simpleflow/history.py +++ b/simpleflow/history.py @@ -728,13 +728,13 @@ def parse_timer_event(self, events: list[Event], event: TimerEvent): timer = { "type": "timer", "id": event.timer_id, - "decision_task_completed_event_id": event.decision_task_completed_event_id, } self._timers[event.timer_id] = timer timer.update( { "state": event.state, "cause": event.cause, + "decision_task_completed_event_id": event.decision_task_completed_event_id, "start_failed_event_id": event.id, "start_failed_event_timestamp": event.timestamp, } diff --git a/simpleflow/swf/executor.py b/simpleflow/swf/executor.py index 5edec4ca..63a0b6b9 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -45,6 +45,8 @@ NOTSET = object() +TRANSIENT_START_TIMER_FAILED_CAUSES = frozenset({"TIMER_CREATION_RATE_EXCEEDED", "OPEN_TIMERS_LIMIT_EXCEEDED"}) + # if "poll_for_activity_task" doesn't contain a "taskToken" # key, then retry; it happens (not often) that the decider @@ -594,23 +596,27 @@ def do_handle_failure( exception_class: type[Exception], ) -> futures.Future | tuple[futures.Future | None, ActivityTask | WorkflowTask | TimerTask] | None: timer = self.find_timer_associated_with(event, swf_task) + if timer and timer["state"] == "start_failed" and timer["cause"] in TRANSIENT_START_TIMER_FAILED_CAUSES: + logger.info(f"handle_failure: retry timer {timer['id']} refused ({timer['cause']}), starting it again") + timer = None if timer: - if isinstance(timer["control"], str): # FIXME unconditional? - control = format.decode(timer["control"]) - else: - control = timer["control"] - if not isinstance(control, dict): - control = {} if timer["state"] == "started": logger.debug(f'handle_failure: timer {timer["id"]} started, "pending" future') return futures.Future(), swf_task # mark as pending elif timer["state"] in ("fired", "canceled"): logger.debug(f"handle_failure: timer {timer['id']} fired or canceled, retrying") + control = timer["control"] + if isinstance(control, str): + control = format.decode(control) + if not isinstance(control, dict): + control = {} swf_task.args = control.get("args", ()) swf_task.kwargs = control.get("kwargs", {}) return None, swf_task elif timer["state"] == "start_failed": - raise exceptions.TaskFailed("timer", timer["id"], timer["cause"]) + if swf_task.payload.raises_on_failure: + raise exception_class(swf_task, exceptions.TaskFailed(timer["id"], timer["cause"])) + return future, swf_task else: # TODO: handle logger.warning(f'Unexpected timer state for timer "{timer["id"]}": {timer["state"]}') diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index 0a974fdf..3e88ee09 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -8,7 +8,7 @@ from simpleflow.swf.executor import Executor from simpleflow.swf.mapper.models.history import builder from simpleflow.swf.mapper.responses import Response -from tests.data.activities import increment +from tests.data.activities import increment, raise_on_failure from tests.data.constants import DOMAIN from tests.data.workflows import BaseTestWorkflow from tests.utils import MockSWFTestCase @@ -81,7 +81,77 @@ def run(self): type(self).future = self.submit(self.cancel_timer("a_timer")) +class RetryLaterWorkflow(BaseTestWorkflow): + def run(self): + futures.wait(self.submit(raise_on_failure)) + + def on_task_failure(self, failure_context): + return failure_context.decide_retry(retry_wait_timeout=30) + + +def replay_decisions(workflow, history): + return Executor(DOMAIN, workflow).replay(Response(history=history, execution=None)).decisions + + +RETRIED_ACTIVITY_ID = "activity-tests.data.activities.raise_on_failure-1" + + +def history_with_a_refused_retry_timer(cause, earlier_retries): + history = builder.History(RetryLaterWorkflow, input={}) + history.add_decision_task_completed() + for attempt in range(earlier_retries + 1): + history.add_activity_task( + raise_on_failure, decision_id=history.last_id, last_state="failed", activity_id=RETRIED_ACTIVITY_ID + ) + history.add_decision_task() + (retry_timer,) = replay_decisions(RetryLaterWorkflow, history) + assert retry_timer["decisionType"] == "StartTimer" + timer_id = retry_timer["startTimerDecisionAttributes"]["timerId"] + if attempt < earlier_retries: + history.add_timer_started(timer_id, 30, decision_id=history.last_id) + history.add_timer_fired(timer_id) + history.add_decision_task() + history.add_timer_start_failed(timer_id, cause, decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + return history, retry_timer + + class TestCaseNotNeedingDomain(unittest.TestCase): + def test_a_retry_timer_refused_for_rate_is_started_again(self): + for earlier_retries in (0, 1): + with self.subTest(earlier_retries=earlier_retries): + history, retry_timer = history_with_a_refused_retry_timer( + "TIMER_CREATION_RATE_EXCEEDED", earlier_retries + ) + + assert replay_decisions(RetryLaterWorkflow, history) == [retry_timer] + + timer_id = retry_timer["startTimerDecisionAttributes"]["timerId"] + history.add_decision_task_completed() + history.add_timer_started(timer_id, 30, decision_id=history.last_id) + history.add_timer_fired(timer_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + (decision,) = replay_decisions(RetryLaterWorkflow, history) + assert decision["decisionType"] == "ScheduleActivityTask" + assert decision["scheduleActivityTaskDecisionAttributes"]["activityId"] == RETRIED_ACTIVITY_ID + + def test_a_retry_timer_refused_for_good_fails_the_task(self): + for earlier_retries in (0, 1): + with self.subTest(earlier_retries=earlier_retries): + history, _ = history_with_a_refused_retry_timer("OPERATION_NOT_PERMITTED", earlier_retries) + + (decision,) = replay_decisions(RetryLaterWorkflow, history) + + assert decision["decisionType"] == "FailWorkflowExecution" + reason = decision["failWorkflowExecutionDecisionAttributes"]["reason"] + assert reason == ( + "Workflow execution error in activity-tests.data.activities.raise_on_failure:" + ' "OPERATION_NOT_PERMITTED"' + ) + def test_a_refused_timer_start_replays_as_a_failed_future(self): history = builder.History(StartTimerWorkflow, input={}) history.add_timer_start_failed("a_timer", "TIMER_CREATION_RATE_EXCEEDED", decision_id=2)