From 88ccc954912c8f39e41725d92fcaf9f2eeddd64e Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sat, 28 Nov 2026 19:07:04 +0100 Subject: [PATCH 01/12] Send a directed signal even if a signal of the same name was received find_signal_event looked a SignalTask up in history.signals first, by name only. history.signals holds the signals this workflow received, so it says nothing about a signal this workflow sends to another one. Failure scenario: a workflow receives "a_signal" and then submits signal("a_signal", workflow_id="other"). The received signal was taken for the task's event, the future was finished with the received input, and no SignalExternalWorkflowExecution decision was ever made. The other workflow never got the signal. The received signals are now consulted only for a signal the workflow sends to itself: no workflow_id, or its own workflow_id with no run_id or its own run_id. Anything else is matched against the deliveries and the in-flight or refused sends, as before. A signal to another run of the same workflow_id is a directed signal. Co-Authored-By: Claude Fable 5.2 --- simpleflow/swf/executor.py | 9 ++- tests/test_simpleflow/swf/test_executor.py | 64 ++++++++++++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/simpleflow/swf/executor.py b/simpleflow/swf/executor.py index a4f5d8b1..3cd0f255 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -476,10 +476,13 @@ def find_signal_event(self, a_task: SignalTask, history: History) -> dict[str, A """ Get the event corresponding to a signal, if any. """ - # FIXME could look directly in signaled_workflows? - event = history.signals.get(a_task.name) + # history.signals holds the signals this workflow received: they only answer for a signal sent to itself. + to_self = a_task.workflow_id is None or ( + a_task.workflow_id == self._workflow_id and a_task.run_id in (None, self._run_id) + ) + event = history.signals.get(a_task.name) if to_self else None if not event: - if a_task.workflow_id is None: # Broadcast, should be in signals + if a_task.workflow_id is None: return None signaled_workflows = history.signaled_workflows.get(a_task.name, []) for w in signaled_workflows: diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index eb9226d6..23ab7909 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -302,6 +302,15 @@ def run(self): futures.wait(type(self).future) +class SignalItselfWorkflow(BaseTestWorkflow): + future = None + target = None + + def run(self): + type(self).future = self.submit(self.signal("a_signal", **(type(self).target or {}))) + futures.wait(type(self).future) + + class PropagateSignalsWorkflow(BaseTestWorkflow): def run(self): pass @@ -385,6 +394,61 @@ def test_a_rate_limited_signal_is_sent_again(self): assert decision["signalExternalWorkflowExecutionDecisionAttributes"]["workflowId"] == "target-wf" assert not future.done + def test_a_directed_signal_is_sent_despite_a_received_signal_of_the_same_name(self): + history = builder.History(SendSignalWorkflow, input={}) + history.add_signal("a_signal", {"args": [], "kwargs": {}}) + + _, decisions, future = self.replay(history) + + (decision,) = signal_decisions(decisions) + assert decision["signalExternalWorkflowExecutionDecisionAttributes"]["workflowId"] == "target-wf" + assert not future.done + + def test_a_delivered_directed_signal_is_not_sent_again_after_a_received_signal_of_the_same_name(self): + history, initiated_id = self.history_with_a_sent_signal() + history.add_external_workflow_signaled(initiated_id, "target-wf", "target-run") + history.add_signal("a_signal", {"args": [], "kwargs": {}}) + + _, decisions, future = self.replay(history) + + assert signal_decisions(decisions) == [] + assert future.finished + assert future.exception is None + + def replay_signal_to_itself(self, target, own_run_id="own-run", received=True): + history = builder.History(SignalItselfWorkflow, input={}) + if received: + history.add_signal("a_signal", {"args": [], "kwargs": {}}) + history.add_decision_task_scheduled() + history.add_decision_task_started() + SignalItselfWorkflow.future = None + SignalItselfWorkflow.target = target + executor = Executor(DOMAIN, SignalItselfWorkflow) + executor._run_context = {"workflow_id": "own-wf", "run_id": own_run_id} + decisions = executor.replay(Response(history=history, execution=None)).decisions + return signal_decisions(decisions), SignalItselfWorkflow.future + + def test_a_signal_to_itself_is_found_in_the_received_signals(self): + for target in (None, {"workflow_id": "own-wf"}, {"workflow_id": "own-wf", "run_id": "own-run"}): + with self.subTest(target=target): + decisions, future = self.replay_signal_to_itself(target) + + assert decisions == [] + assert future.finished + + def test_a_signal_to_itself_not_yet_received_is_sent(self): + (decision,) = self.replay_signal_to_itself(None, received=False)[0] + + attributes = decision["signalExternalWorkflowExecutionDecisionAttributes"] + assert (attributes["workflowId"], attributes["runId"]) == ("own-wf", "own-run") + + def test_a_signal_to_another_run_of_its_workflow_id_is_a_directed_signal(self): + decisions, future = self.replay_signal_to_itself({"workflow_id": "own-wf", "run_id": "previous-run"}) + + (decision,) = decisions + assert decision["signalExternalWorkflowExecutionDecisionAttributes"]["runId"] == "previous-run" + assert not future.done + def history_with_a_propagated_signal_in_flight(self): history = builder.History(PropagateSignalsWorkflow, input={}) history.add_child_workflow(PropagateSignalsWorkflow, last_state="started", workflow_id="child-wf") From 18ab13b0e2f2073979c29d18971ffa7fef621599 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sat, 28 Nov 2026 19:07:38 +0100 Subject: [PATCH 02/12] Fail the future of a refused marker instead of recording it again find_marker_event kept only "recorded" markers, so a marker SWF refused (RecordMarkerFailed, parsed as "record_failed") was never found. _get_future_from_marker_event did have a branch for it, but it tested state == "failed", a state the parser never writes. Failure scenario: the decider's IAM policy denies RecordMarker, the only documented cause (OPERATION_NOT_PERMITTED). Each replay found no event for the MarkerTask and issued RecordMarker again; each refusal schedules a new decision task, so the workflow looped on the same refused decision. find_marker_event now returns, in order: the latest recorded marker with the task's details, else the latest refusal for that marker name. The future branch tests "record_failed" and yields TaskFailed(name, cause). RecordMarkerFailed has no details, so a refusal cannot be tied to one MarkerTask: it stands for every not-yet-recorded marker of that name. The history builder gains add_marker_record_failed. Co-Authored-By: Claude Fable 5.2 --- simpleflow/swf/executor.py | 10 ++- .../swf/mapper/models/history/builder.py | 18 +++++ tests/test_simpleflow/swf/test_executor.py | 67 +++++++++++++++++++ 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/simpleflow/swf/executor.py b/simpleflow/swf/executor.py index 3cd0f255..dbc31844 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -371,7 +371,7 @@ def _get_future_from_marker_event(self, a_task, event: dict[str, Any]) -> future state = event["state"] if state == "recorded": future.set_finished(event["details"]) - elif state == "failed": + elif state == "record_failed": future.set_exception( exceptions.TaskFailed( name=event["name"], @@ -518,8 +518,12 @@ def find_marker_event(self, a_task: MarkerTask, history: History) -> dict[str, A marker_list = history.markers.get(a_task.name) if not marker_list: return None - marker_list = [m for m in marker_list if m["state"] == "recorded" and m["details"] == json_details] - return marker_list[-1] if marker_list else None + recorded = [m for m in marker_list if m["state"] == "recorded" and m["details"] == json_details] + if recorded: + return recorded[-1] + # RecordMarkerFailed carries no details: a refusal stands for every marker of that name. + refused = [m for m in marker_list if m["state"] == "record_failed"] + return refused[-1] if refused else None def find_timer_event(self, a_task: TimerTask | CancelTimerTask, history: History) -> dict[str, Any] | None: """ diff --git a/simpleflow/swf/mapper/models/history/builder.py b/simpleflow/swf/mapper/models/history/builder.py index 7a99b623..b6437984 100644 --- a/simpleflow/swf/mapper/models/history/builder.py +++ b/simpleflow/swf/mapper/models/history/builder.py @@ -778,6 +778,24 @@ def add_marker(self, name, details=None): return self + def add_marker_record_failed(self, name, cause="OPERATION_NOT_PERMITTED", decision_id=0): + self.events.append( + EventFactory( + { + "eventId": self.next_id, + "eventTimestamp": new_timestamp_string(), + "eventType": "RecordMarkerFailed", + "recordMarkerFailedEventAttributes": { + "cause": cause, + "decisionTaskCompletedEventId": decision_id, + "markerName": name, + }, + } + ) + ) + + return self + def add_timer_started(self, timer_id, timeout, control=None, decision_id=0): d = { "decisionTaskCompletedEventId": decision_id, diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index 23ab7909..a1a424cf 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -499,6 +499,73 @@ def test_a_refused_propagated_signal_is_sent_again_only_if_rate_limited(self): assert self.replay_propagation(history) == ([decision] if sent_again else []) +class RecordMarkerWorkflow(BaseTestWorkflow): + future = None + + def run(self): + type(self).future = self.submit(self.record_marker("a_marker", "some details")) + futures.wait(type(self).future) + + +class TestRefusedMarkerReplay(unittest.TestCase): + def history_with_a_refused_marker(self): + history = builder.History(RecordMarkerWorkflow, input={}) + (decision,) = self.replay(history)[0] + assert decision["recordMarkerDecisionAttributes"]["markerName"] == "a_marker" + history.add_decision_task_completed() + history.add_marker_record_failed("a_marker", decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + return history + + @staticmethod + def replay(history): + RecordMarkerWorkflow.future = None + decisions = replay_decisions(RecordMarkerWorkflow, history) + return [d for d in decisions if d["decisionType"] == "RecordMarker"], RecordMarkerWorkflow.future + + def test_a_refused_marker_is_not_recorded_again_and_fails_its_future(self): + history = self.history_with_a_refused_marker() + + decisions, future = self.replay(history) + + assert decisions == [] + assert future.finished + assert isinstance(future.exception, exceptions.TaskFailed) + assert future.exception.name == "a_marker" + assert future.exception.reason == "OPERATION_NOT_PERMITTED" + + def test_a_recorded_marker_wins_over_a_refusal_whatever_their_order(self): + for recorded_first in (True, False): + with self.subTest(recorded_first=recorded_first): + history = builder.History(RecordMarkerWorkflow, input={}) + history.add_decision_task_completed() + if recorded_first: + history.add_marker("a_marker", "some details") + history.add_marker_record_failed("a_marker", decision_id=history.last_id) + if not recorded_first: + history.add_marker("a_marker", "some details") + history.add_decision_task_scheduled() + history.add_decision_task_started() + + decisions, future = self.replay(history) + + assert decisions == [] + assert future.finished + assert future.exception is None + + def test_a_refusal_does_not_stand_for_another_marker_name(self): + history = builder.History(RecordMarkerWorkflow, input={}) + history.add_decision_task_completed() + history.add_marker_record_failed("another_marker", decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + (decision,) = self.replay(history)[0] + + assert decision["recordMarkerDecisionAttributes"]["markerName"] == "a_marker" + + @activity.with_attributes(raises_on_failure=True) def print_me_n_times(s, n, raises=False): if raises: From 59eafd6acee9c612924ed02eddbe69b8852a75c4 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sat, 28 Nov 2026 19:08:35 +0100 Subject: [PATCH 03/12] Parse ActivityTaskCanceled and WorkflowExecutionCanceled events Event states are the SWF event type name minus its prefix, snake_cased: ActivityTaskCanceled and WorkflowExecutionCanceled both give "canceled". Two parser branches in history.py tested "cancelled", so they never ran and both events were dropped. Failure scenario, activity: an activity is canceled (cancel requested, then ActivityTaskCanceled). The entry stayed "cancel_requested", or "started"/"scheduled" without a request, so the executor's own state == "canceled" branch was unreachable: the future stayed pending, the activity kept counting as open, and a workflow waiting on it blocked until its own timeout. Failure scenario, workflow: History.workflow kept state "started" for a canceled execution (visible in the CLI's history dump). Both branches now test "canceled". The activity branch wrote a "cancelled_timestamp" key that no reader could find: stats and the CLI read f"{state}_timestamp". It now writes "canceled_timestamp" and "canceled_id", like the other terminal states, and ActivityTaskEventDict follows. The workflow branch already derived its keys from the state. The history builder gains add_activity_task_cancel_requested, add_activity_task_canceled and add_workflow_execution_canceled. Co-Authored-By: Claude Fable 5.2 --- simpleflow/history.py | 7 ++- simpleflow/swf/mapper/models/event/task.py | 3 +- .../swf/mapper/models/history/builder.py | 55 +++++++++++++++++ tests/test_simpleflow/swf/test_executor.py | 61 +++++++++++++++++++ 4 files changed, 122 insertions(+), 4 deletions(-) diff --git a/simpleflow/history.py b/simpleflow/history.py index de1bc071..da5ef7bf 100644 --- a/simpleflow/history.py +++ b/simpleflow/history.py @@ -254,13 +254,14 @@ def get_activity(): activity["retry"] = 0 else: activity["retry"] += 1 - elif event.state == "cancelled": + elif event.state == "canceled": activity = get_activity() activity.update( { "state": event.state, "details": getattr(event, "details", ""), - "cancelled_timestamp": event.timestamp, + "canceled_id": event.id, + "canceled_timestamp": event.timestamp, } ) elif event.state == "cancel_requested": @@ -486,7 +487,7 @@ def parse_workflow_event(self, events: list[Event], event: WorkflowExecutionEven "result": getattr(event, "result", None), } ) - elif event.state == "cancelled": + elif event.state == "canceled": self._workflow.update( { "state": event.state, diff --git a/simpleflow/swf/mapper/models/event/task.py b/simpleflow/swf/mapper/models/event/task.py index d4224113..7f7fe609 100644 --- a/simpleflow/swf/mapper/models/event/task.py +++ b/simpleflow/swf/mapper/models/event/task.py @@ -58,7 +58,8 @@ class ActivityTaskEventDict(TypedDict): result: Any reason: str | None details: str | None - cancelled_timestamp: datetime + canceled_id: int + canceled_timestamp: datetime class CompiledActivityTaskEvent(CompiledEvent): diff --git a/simpleflow/swf/mapper/models/history/builder.py b/simpleflow/swf/mapper/models/history/builder.py index b6437984..9c0fc126 100644 --- a/simpleflow/swf/mapper/models/history/builder.py +++ b/simpleflow/swf/mapper/models/history/builder.py @@ -333,6 +333,44 @@ def add_activity_task_timed_out(self, timeout_type, scheduled=None, started=None ) ) + def add_activity_task_cancel_requested(self, activity_id, decision_id=0): + self.events.append( + EventFactory( + { + "eventId": self.next_id, + "eventTimestamp": new_timestamp_string(), + "eventType": "ActivityTaskCancelRequested", + "activityTaskCancelRequestedEventAttributes": { + "activityId": activity_id, + "decisionTaskCompletedEventId": decision_id, + }, + } + ) + ) + + return self + + def add_activity_task_canceled(self, scheduled, started=None, cancel_requested=None, details=None): + d = {"scheduledEventId": scheduled} + if started is not None: + d["startedEventId"] = started + if cancel_requested is not None: + d["latestCancelRequestedEventId"] = cancel_requested + if details is not None: + d["details"] = details + self.events.append( + EventFactory( + { + "eventId": self.next_id, + "eventTimestamp": new_timestamp_string(), + "eventType": "ActivityTaskCanceled", + "activityTaskCanceledEventAttributes": d, + } + ) + ) + + return self + def add_activity_task( self, activity, @@ -681,6 +719,23 @@ def add_request_cancel(self, cause=None, external_event_id=0): return self + def add_workflow_execution_canceled(self, decision_id=0, details=None): + d = {"decisionTaskCompletedEventId": decision_id} + if details is not None: + d["details"] = details + self.events.append( + EventFactory( + { + "eventId": self.next_id, + "eventTimestamp": new_timestamp_string(), + "eventType": "WorkflowExecutionCanceled", + "workflowExecutionCanceledEventAttributes": d, + } + ) + ) + + return self + def add_signal(self, name, input=None, external_event_id=0): self.events.append( EventFactory( diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index a1a424cf..bd5e8b7b 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -5,6 +5,7 @@ from unittest import mock from simpleflow import activity, exceptions, format, futures +from simpleflow.history import History from simpleflow.swf.executor import Executor from simpleflow.swf.mapper.models.history import builder from simpleflow.swf.mapper.responses import Response @@ -566,6 +567,66 @@ def test_a_refusal_does_not_stand_for_another_marker_name(self): assert decision["recordMarkerDecisionAttributes"]["markerName"] == "a_marker" +class OneActivityWorkflow(BaseTestWorkflow): + future = None + + def run(self): + type(self).future = self.submit(increment, 1) + futures.wait(type(self).future) + + +class TestCanceledReplay(unittest.TestCase): + ACTIVITY_ID = "activity-tests.data.activities.increment-1" + + def test_a_canceled_activity_cancels_its_future(self): + for started in (True, False): + with self.subTest(started=started): + history = builder.History(OneActivityWorkflow, input={}) + history.add_decision_task_completed() + history.add_activity_task( + increment, + decision_id=history.last_id, + last_state="started" if started else "scheduled", + activity_id=self.ACTIVITY_ID, + ) + scheduled_id = history.last_id - 1 if started else history.last_id + started_id = history.last_id if started else None + history.add_activity_task_cancel_requested(self.ACTIVITY_ID) + history.add_activity_task_canceled( + scheduled_id, started=started_id, cancel_requested=history.last_id, details="given up" + ) + canceled_id = history.last_id + history.add_decision_task_scheduled() + history.add_decision_task_started() + + OneActivityWorkflow.future = None + executor = Executor(DOMAIN, OneActivityWorkflow) + decisions = executor.replay(Response(history=history, execution=None)).decisions + + assert OneActivityWorkflow.future.cancelled + assert [d["decisionType"] for d in decisions] == ["CompleteWorkflowExecution"] + details = executor._history.activities[self.ACTIVITY_ID] + assert details["state"] == "canceled" + assert details["canceled_id"] == canceled_id + assert details["canceled_timestamp"] == history.events[-3].timestamp + assert details["details"] == "given up" + assert details["name"] == "tests.data.activities.increment" + + def test_a_canceled_workflow_execution_is_parsed(self): + swf_history = builder.History(OneActivityWorkflow, input={}) + swf_history.add_decision_task_completed() + swf_history.add_workflow_execution_canceled(decision_id=swf_history.last_id, details="given up") + history = History(swf_history) + + history.parse() + + assert history.workflow["state"] == "canceled" + assert history.workflow["canceled_id"] == swf_history.last_id + assert history.workflow["canceled_timestamp"] == swf_history.events[-1].timestamp + assert history.workflow["decision_task_completed_event_id"] == swf_history.last_id - 1 + assert history.workflow["details"] == "given up" + + @activity.with_attributes(raises_on_failure=True) def print_me_n_times(s, n, raises=False): if raises: From d0102ae8a527789409c5d230a2b0f1a91cd52537 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sat, 28 Nov 2026 19:09:50 +0100 Subject: [PATCH 04/12] Let the CLI read activities that were never scheduled Two kinds of activity entries lack the keys of a scheduled one: - a refused schedule (ScheduleActivityTaskFailed) with no earlier ActivityTaskScheduled has state, cause and activity_type, but no id, name, version, input nor scheduled_id; - a cancel request for an activity id the history does not know has an id, but no name, version, input nor scheduled_id. Failure scenario: on a workflow whose history holds such an entry, `simpleflow workflow.tasks` raised KeyError('name') (pretty.status), `workflow.info` raised KeyError('input') when the entry was the first task (pretty.info), `task.info` raised KeyError('id') (pretty.get_task) and `activity.rerun` raised KeyError('scheduled_id') before reaching the activity asked for (helpers.find_activity). The readers now tolerate the missing keys, rather than the parser inventing them: these entries feed the decider too, and it was not worth changing what it sees for a display problem. - status shows the name, else the refused activity type's name, else the activity id; - get_task falls back on the task id and the refused activity type, and on None for the input; - info reports no input instead of raising; - find_activity skips entries that were never scheduled: there is nothing to run again, so asking for one gives the usual "Couldn't find activity." Co-Authored-By: Claude Fable 5.2 --- simpleflow/swf/helpers.py | 2 + simpleflow/swf/stats/pretty.py | 18 +++-- .../test_simpleflow/swf/stats/test_pretty.py | 67 +++++++++++++++++++ tests/test_simpleflow/test_helpers.py | 21 ++++++ 4 files changed, 102 insertions(+), 6 deletions(-) diff --git a/simpleflow/swf/helpers.py b/simpleflow/swf/helpers.py index eb494062..2b5ea41b 100644 --- a/simpleflow/swf/helpers.py +++ b/simpleflow/swf/helpers.py @@ -140,6 +140,8 @@ def find_activity(history, scheduled_id=None, activity_id=None, input=None): """ found_activity = None for params in history.activities.values(): + if "scheduled_id" not in params: # never scheduled: refused, or only a cancel request + continue if params["scheduled_id"] == scheduled_id: found_activity = params if params["id"] == activity_id: diff --git a/simpleflow/swf/stats/pretty.py b/simpleflow/swf/stats/pretty.py index 4e11d461..3b86e68a 100644 --- a/simpleflow/swf/stats/pretty.py +++ b/simpleflow/swf/stats/pretty.py @@ -96,6 +96,11 @@ def get_timestamps(task: dict[str, Any]) -> tuple: return last_state, timestamp, scheduled_timestamp +def get_name(task: dict[str, Any]) -> str | None: + # A refused schedule only has its activity_type, a cancel request only the activity id. + return task.get("name") or task.get("activity_type", {}).get("name") or task.get("id") + + def info(workflow_execution: WorkflowExecution) -> tuple[Sequence, Sequence]: history = History(workflow_execution.history()) history.parse() @@ -105,7 +110,7 @@ def info(workflow_execution: WorkflowExecution) -> tuple[Sequence, Sequence]: first_timestamp = first_event[first_event["state"] + "_timestamp"] last_event = history.tasks[-1] last_timestamp = last_event.get("timestamp") or last_event[last_event["state"] + "_timestamp"] - workflow_input = first_event["input"] + workflow_input = first_event.get("input") else: first_event = history.events[0] first_timestamp = first_event.timestamp @@ -189,7 +194,7 @@ def status(workflow_execution, nb_tasks=None) -> tuple[Sequence, Sequence]: history.parse() header = ["Tasks", "Last State", "Last State Time", "Scheduled Time"] - rows = [(task["name"], *get_timestamps(task)) for task in history.tasks[::-1]] + rows = [(get_name(task), *get_timestamps(task)) for task in history.tasks[::-1]] if nb_tasks: rows = rows[:nb_tasks] @@ -299,15 +304,16 @@ def get_task( if details: header.append("details") state = task["state"] + activity_type = task.get("activity_type", {}) rows = [ [ task["type"], - task["id"], - task["name"], - task["version"], + task.get("id", task_id), + task.get("name") or activity_type.get("name"), + task.get("version") or activity_type.get("version"), state, task[state + "_timestamp"], - task["input"], + task.get("input"), task.get("result"), # Absent for failed tasks task.get("reason"), ] diff --git a/tests/test_simpleflow/swf/stats/test_pretty.py b/tests/test_simpleflow/swf/stats/test_pretty.py index 8c0c74f2..2a79d995 100644 --- a/tests/test_simpleflow/swf/stats/test_pretty.py +++ b/tests/test_simpleflow/swf/stats/test_pretty.py @@ -2,10 +2,15 @@ import json import unittest +from unittest import mock from simpleflow.history import History +from simpleflow.swf.mapper.models.history import builder from simpleflow.swf.mapper.models.history.base import History as BasicHistory +from simpleflow.swf.stats import pretty from simpleflow.swf.stats.pretty import dump_history_to_json +from tests.data.activities import increment +from tests.data.workflows import BaseTestWorkflow def fake_history(): @@ -38,3 +43,65 @@ def test_dump_history_to_json(self): ], [t[0] for t in parsed], ) + + +REFUSED_ID = "activity-tests.data.activities.double-1" +SCHEDULED_ID = "activity-tests.data.activities.increment-1" + + +def history_with_a_refused_schedule_and_an_unknown_cancel_request(): + """ + Activity entries without the keys of a scheduled one: no id, name nor input for + the refused schedule, no name nor input for the cancel request. + """ + history = builder.History(BaseTestWorkflow, input={}) + history.add_decision_task_completed() + decision_id = history.last_id + history.add_activity_task_schedule_failed( + REFUSED_ID, + decision_id, + {"name": "tests.data.activities.double", "version": "example"}, + "ACTIVITY_TYPE_DOES_NOT_EXIST", + ) + history.add_activity_task_cancel_requested("activity-unknown-1", decision_id) + history.add_activity_task(increment, decision_id, last_state="scheduled", activity_id=SCHEDULED_ID) + return history + + +class TestPrettyWithIncompleteActivityEntries(unittest.TestCase): + def setUp(self): + self.swf_history = history_with_a_refused_schedule_and_an_unknown_cancel_request() + self.execution = mock.Mock(tag_list=[]) + self.execution.history.return_value = self.swf_history + + def test_status(self): + _, rows = pretty.status(self.execution) + + assert [row[:2] for row in rows] == [ + ("tests.data.activities.increment", "scheduled"), + ("activity-unknown-1", "cancel_requested"), + ("tests.data.activities.double", "schedule_failed"), + ] + assert all(row[2] is not None for row in rows) + + def test_get_task(self): + header, rows = pretty.get_task(self.execution, REFUSED_ID) + + row = dict(zip(header, rows[0])) + assert row["id"] == REFUSED_ID + assert row["name"] == "tests.data.activities.double" + assert row["version"] == "example" + assert row["state"] == "schedule_failed" + assert row["timestamp"] is not None + assert row["input"] is None + + header, rows = pretty.get_task(self.execution, "activity-unknown-1") + + row = dict(zip(header, rows[0])) + assert (row["id"], row["name"], row["version"]) == ("activity-unknown-1", None, None) + assert row["state"] == "cancel_requested" + + def test_info(self): + header, rows = pretty.info(self.execution) + + assert dict(zip(header, rows[0]))["input"] is None diff --git a/tests/test_simpleflow/test_helpers.py b/tests/test_simpleflow/test_helpers.py index f1b70e31..2cfcb769 100644 --- a/tests/test_simpleflow/test_helpers.py +++ b/tests/test_simpleflow/test_helpers.py @@ -41,3 +41,24 @@ def test_find_activity(self): def test_find_activity_with_overriden_input(self): _, args, _, _, _ = find_activity(FakeHistory(), scheduled_id=5, input={"args": [4]}) assert args == [4] + + def test_find_activity_skips_entries_without_scheduled_id_or_id(self): + history = FakeHistory() + history.activities = { + "refused": {"type": "activity", "state": "schedule_failed", "cause": "ACTIVITY_TYPE_DOES_NOT_EXIST"}, + "unknown": {"type": "activity", "id": "unknown", "state": "cancel_requested"}, + **history.activities, + } + + _, _, _, _, params = find_activity(history, scheduled_id=5) + assert params["id"] == "activity-tests.integration.workflow.sleep-1" + + _, _, _, _, params = find_activity(history, activity_id="activity-tests.integration.workflow.sleep-1") + assert params["scheduled_id"] == 5 + + with self.assertRaisesRegex(ValueError, "Couldn't find activity"): + find_activity(history, activity_id="refused") + with self.assertRaisesRegex(ValueError, "Couldn't find activity"): + find_activity(history, activity_id="unknown") + with self.assertRaisesRegex(ValueError, "Couldn't find activity"): + find_activity(history) From d05779ba28e79c2db5304bed7ab90dd2d604c299 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sat, 28 Nov 2026 23:39:06 +0100 Subject: [PATCH 05/12] Let `simpleflow workflow.info` read histories whose first or last task has no state timestamp pretty.info computed the execution time from the first and last entries of history.tasks, reading f"{state}_timestamp" from them. Two kinds of task have no such key: - a received signal ("signaled") carries a plain `timestamp`; - a child workflow not started yet ("start_initiated") carries `initiated_event_timestamp`. So a history whose first task is a signal raised KeyError('signaled_timestamp'), and one whose first or last task is a child workflow still waiting to start raised KeyError('start_initiated_timestamp'). The last task already fell back to `timestamp`; the first did not. get_task_timestamp reads the state timestamp, then `timestamp`, then `initiated_event_timestamp`, and info uses it for both ends. The execution time keeps its meaning: last task minus first task. Co-Authored-By: Claude Opus 5.5 --- simpleflow/swf/stats/pretty.py | 9 ++++- .../test_simpleflow/swf/stats/test_pretty.py | 38 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/simpleflow/swf/stats/pretty.py b/simpleflow/swf/stats/pretty.py index 3b86e68a..fe5e743b 100644 --- a/simpleflow/swf/stats/pretty.py +++ b/simpleflow/swf/stats/pretty.py @@ -96,6 +96,11 @@ def get_timestamps(task: dict[str, Any]) -> tuple: return last_state, timestamp, scheduled_timestamp +def get_task_timestamp(task: dict[str, Any]) -> datetime: + # A signal has a plain timestamp, a child workflow not started yet only its initiation's. + return task.get(task["state"] + "_timestamp") or task.get("timestamp") or task["initiated_event_timestamp"] + + def get_name(task: dict[str, Any]) -> str | None: # A refused schedule only has its activity_type, a cancel request only the activity id. return task.get("name") or task.get("activity_type", {}).get("name") or task.get("id") @@ -107,9 +112,9 @@ def info(workflow_execution: WorkflowExecution) -> tuple[Sequence, Sequence]: if history.tasks: first_event = history.tasks[0] - first_timestamp = first_event[first_event["state"] + "_timestamp"] + first_timestamp = get_task_timestamp(first_event) last_event = history.tasks[-1] - last_timestamp = last_event.get("timestamp") or last_event[last_event["state"] + "_timestamp"] + last_timestamp = get_task_timestamp(last_event) workflow_input = first_event.get("input") else: first_event = history.events[0] diff --git a/tests/test_simpleflow/swf/stats/test_pretty.py b/tests/test_simpleflow/swf/stats/test_pretty.py index 2a79d995..f7bb747b 100644 --- a/tests/test_simpleflow/swf/stats/test_pretty.py +++ b/tests/test_simpleflow/swf/stats/test_pretty.py @@ -105,3 +105,41 @@ def test_info(self): header, rows = pretty.info(self.execution) assert dict(zip(header, rows[0]))["input"] is None + + +class TestPrettyInfoTimestamps(unittest.TestCase): + def info(self, swf_history): + execution = mock.Mock(tag_list=[]) + execution.history.return_value = swf_history + header, rows = pretty.info(execution) + return dict(zip(header, rows[0])) + + def test_a_signal_as_first_and_last_task(self): + swf_history = builder.History(BaseTestWorkflow, input={}) + swf_history.add_signal("a_signal", input={"x": 1}) + + assert self.info(swf_history)["execution_time"] == 0 + + def test_a_signal_before_an_activity(self): + swf_history = builder.History(BaseTestWorkflow, input={}) + swf_history.add_signal("a_signal") + swf_history.add_decision_task_completed() + swf_history.add_activity_task(increment, swf_history.last_id, last_state="scheduled", activity_id=SCHEDULED_ID) + history = History(swf_history) + history.parse() + signal, activity = history.tasks + + expected = (activity["scheduled_timestamp"] - signal["timestamp"]).total_seconds() + assert self.info(swf_history)["execution_time"] == expected + + def test_a_child_workflow_only_initiated(self): + swf_history = builder.History(BaseTestWorkflow, input={}) + swf_history.add_decision_task_completed() + swf_history.add_activity_task(increment, swf_history.last_id, last_state="scheduled", activity_id=SCHEDULED_ID) + swf_history.add_child_workflow_start_initiated(BaseTestWorkflow, workflow_id="a-child") + history = History(swf_history) + history.parse() + activity, child = history.tasks + + expected = (child["initiated_event_timestamp"] - activity["scheduled_timestamp"]).total_seconds() + assert self.info(swf_history)["execution_time"] == expected From f1cef1fc91059fc9017a2e8902ca41772eefb31a Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sun, 29 Nov 2026 01:01:04 +0100 Subject: [PATCH 06/12] Show the workflow's own input in `simpleflow workflow.info` pretty.info filled its `input` column from the first task of the history: the first activity's or child workflow's input, or the first received signal's. Only a history with no task fell back to the workflow's input, from the first event. The input now always comes from the first event, WorkflowExecutionStarted. The parser already relies on it being first (event ids start at 1). An absent SWF input decodes to {}. The existing test_info pinned the first task's input (None); it now expects the workflow's ({}). Co-Authored-By: Claude Opus 5.5 --- simpleflow/swf/stats/pretty.py | 15 ++++------ .../test_simpleflow/swf/stats/test_pretty.py | 30 ++++++++++++++++++- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/simpleflow/swf/stats/pretty.py b/simpleflow/swf/stats/pretty.py index fe5e743b..6d4d636e 100644 --- a/simpleflow/swf/stats/pretty.py +++ b/simpleflow/swf/stats/pretty.py @@ -109,19 +109,14 @@ def get_name(task: dict[str, Any]) -> str | None: def info(workflow_execution: WorkflowExecution) -> tuple[Sequence, Sequence]: history = History(workflow_execution.history()) history.parse() + workflow_input = history.events[0].input if history.tasks: - first_event = history.tasks[0] - first_timestamp = get_task_timestamp(first_event) - last_event = history.tasks[-1] - last_timestamp = get_task_timestamp(last_event) - workflow_input = first_event.get("input") + first_timestamp = get_task_timestamp(history.tasks[0]) + last_timestamp = get_task_timestamp(history.tasks[-1]) else: - first_event = history.events[0] - first_timestamp = first_event.timestamp - last_event = history.events[-1] - last_timestamp = last_event.timestamp - workflow_input = first_event.input + first_timestamp = history.events[0].timestamp + last_timestamp = history.events[-1].timestamp execution_time = (last_timestamp - first_timestamp).total_seconds() diff --git a/tests/test_simpleflow/swf/stats/test_pretty.py b/tests/test_simpleflow/swf/stats/test_pretty.py index f7bb747b..63711542 100644 --- a/tests/test_simpleflow/swf/stats/test_pretty.py +++ b/tests/test_simpleflow/swf/stats/test_pretty.py @@ -104,7 +104,7 @@ def test_get_task(self): def test_info(self): header, rows = pretty.info(self.execution) - assert dict(zip(header, rows[0]))["input"] is None + assert dict(zip(header, rows[0]))["input"] == {} class TestPrettyInfoTimestamps(unittest.TestCase): @@ -143,3 +143,31 @@ def test_a_child_workflow_only_initiated(self): expected = (child["initiated_event_timestamp"] - activity["scheduled_timestamp"]).total_seconds() assert self.info(swf_history)["execution_time"] == expected + + +class TestPrettyInfoInput(unittest.TestCase): + def info_input(self, swf_history): + execution = mock.Mock(tag_list=[]) + execution.history.return_value = swf_history + header, rows = pretty.info(execution) + return dict(zip(header, rows[0]))["input"] + + def test_the_workflow_input_not_the_first_activity_input(self): + swf_history = builder.History(BaseTestWorkflow, input={"args": [1]}) + swf_history.add_decision_task_completed() + swf_history.add_activity_task( + increment, swf_history.last_id, last_state="scheduled", activity_id=SCHEDULED_ID, input={"args": [2]} + ) + + assert self.info_input(swf_history) == {"args": [1]} + + def test_the_workflow_input_not_the_first_signal_input(self): + swf_history = builder.History(BaseTestWorkflow, input={"args": [1]}) + swf_history.add_signal("a_signal", input={"x": 3}) + + assert self.info_input(swf_history) == {"args": [1]} + + def test_the_workflow_input_without_tasks(self): + swf_history = builder.History(BaseTestWorkflow, input={"args": [1]}) + + assert self.info_input(swf_history) == {"args": [1]} From f7983b853b424e9b4e789adc1f113e6292e1bd09 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sun, 29 Nov 2026 01:10:51 +0100 Subject: [PATCH 07/12] Back off on a transient refused activity schedule, fail a permanent one A ScheduleActivityTaskFailed entry made the executor schedule the activity again in the next decision, whatever the cause. SWF answers a failed decision with a new decision task, so a refusal that does not go away (deprecated type, missing default timeout or task list, OPERATION_NOT_PERMITTED) looped until the execution hit its event cap, and a rate or limit refusal was retried at full speed. Transient causes (ACTIVITY_CREATION_RATE_EXCEEDED, OPEN_ACTIVITIES_LIMIT_EXCEEDED, ACTIVITY_ID_ALREADY_IN_USE, ACTIVITY_TYPE_DOES_NOT_EXIST) now start a timer, and the activity is scheduled again once it fires. The delay is 2^n seconds for the n-th refusal in a row, capped at 300 s; a successful schedule resets n. The first ACTIVITY_TYPE_DOES_NOT_EXIST still creates the type and schedules again at once, as before; later ones create it and wait. The timer id, __simpleflow_schedule__, is distinct per refusal and from the failure-retry timer (__simpleflow_task_), so a fired timer from an earlier refusal never stands for a later one. Any other cause is a failed attempt: the task's future fails with TaskFailed(, ) and goes through handle_failure, so raises_on_failure, `retry` and on_task_failure apply. Refusals do not increment the history's `retry`, so the failure context's event gets `retry` = earlier failures + refusals in a row - 1, the value a failed execution would have had. Each retry that is refused again raises it, so the default handling stops after `retry` attempts and attempt-based stop strategies in on_task_failure stop too. Before, a deprecated type or a missing default was rescheduled until the event cap; a mandatory activity now fails its workflow. History: a schedule_failed entry now carries id (the activity id), schedule_failed_id, schedule_failed_count and the refusal's decision_task_completed_event_id. schedule_failed_id lets handled_failures key a never-scheduled entry (get_event_id returned None for all of them, so two refused activities in one replay shared one outcome). The decision id is what do_handle_failure's timer lookup reads; it raised KeyError on a never-scheduled entry. on_task_failure implementations read event["id"]. If the backoff timer itself is refused (e.g. OPEN_TIMERS_LIMIT_EXCEEDED), the activity is scheduled again at once. Not changed: a child workflow's refused start still goes through the default retry handling without incrementing `retry`. Co-Authored-By: Claude Opus 5.5 --- simpleflow/history.py | 7 + simpleflow/swf/executor.py | 62 +++++- simpleflow/swf/mapper/models/event/task.py | 3 + tests/test_simpleflow/swf/test_executor.py | 220 ++++++++++++++++++++- 4 files changed, 281 insertions(+), 11 deletions(-) diff --git a/simpleflow/history.py b/simpleflow/history.py index da5ef7bf..6d96ea94 100644 --- a/simpleflow/history.py +++ b/simpleflow/history.py @@ -181,13 +181,19 @@ def get_activity(): # in ``retry``. As the state of the event mutates, it # corresponds to the last execution. self._activities[event.activity_id].update(activity) + self._activities[event.activity_id].pop("schedule_failed_count", None) elif event.state == "schedule_failed": + previous = self._activities.get(event.activity_id, {}) activity = { "type": "activity", + "id": event.activity_id, "state": event.state, "cause": event.cause, "activity_type": event.activity_type.copy(), + "schedule_failed_id": event.id, "schedule_failed_timestamp": event.timestamp, + "schedule_failed_count": previous.get("schedule_failed_count", 0) + 1, + "decision_task_completed_event_id": event.decision_task_completed_event_id, } if event.activity_id not in self._activities: @@ -808,6 +814,7 @@ def get_event_id(event: dict[str, Any]) -> int | None: "event_id", "started_event_id", "cancel_failed_event_id", + "schedule_failed_id", ): event_id = event.get(event_id_key) if event_id: diff --git a/simpleflow/swf/executor.py b/simpleflow/swf/executor.py index dbc31844..ff9fcd4a 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -46,6 +46,15 @@ NOTSET = object() TRANSIENT_START_TIMER_FAILED_CAUSES = frozenset({"TIMER_CREATION_RATE_EXCEEDED", "OPEN_TIMERS_LIMIT_EXCEEDED"}) +TRANSIENT_SCHEDULE_ACTIVITY_FAILED_CAUSES = frozenset( + { + "ACTIVITY_CREATION_RATE_EXCEEDED", + "ACTIVITY_ID_ALREADY_IN_USE", + "ACTIVITY_TYPE_DOES_NOT_EXIST", + "OPEN_ACTIVITIES_LIMIT_EXCEEDED", + } +) +SCHEDULE_ACTIVITY_RETRY_MAX_DELAY = 300 # if "poll_for_activity_task" doesn't contain a "taskToken" @@ -247,14 +256,6 @@ def _get_future_from_activity_event(self, event: dict[str, Any]) -> futures.Futu if state == "scheduled": pass - elif state == "schedule_failed": - name = event["activity_type"]["name"] - version = event["activity_type"]["version"] - if event["cause"] == "ACTIVITY_TYPE_DOES_NOT_EXIST" and (name, version) not in self.created_activity_types: - self.create_activity_type(name, version) - return None - logger.info(f"failed to schedule {name}: {event['cause']}") - return None elif state == "started": future.set_running() elif state == "completed": @@ -564,9 +565,10 @@ def resume_activity(self, a_task: ActivityTask, event: dict[str, Any]) -> future """ Resume an activity task. """ + if event["state"] == "schedule_failed": + return self.resume_refused_activity(a_task, event) + future = self._get_future_from_activity_event(event) - if not future: # schedule failed, maybe OK later. - return None if not future.finished: # Still pending or running... return future @@ -576,6 +578,46 @@ def resume_activity(self, a_task: ActivityTask, event: dict[str, Any]) -> future return self.handle_failure(event, future, a_task, exceptions.TaskException) + def resume_refused_activity( + self, a_task: ActivityTask, event: dict[str, Any] + ) -> futures.Future | tuple[futures.Future | None, SwfTask] | None: + """ + A transient refusal schedules the activity again after a timer, whose delay doubles with each + refusal in a row. Any other refusal is a failed attempt: earlier failures and the refusals in a + row count towards its `retry`. + """ + name = event["activity_type"]["name"] + cause = event["cause"] + if cause not in TRANSIENT_SCHEDULE_ACTIVITY_FAILED_CAUSES: + logger.info(f"failed to schedule {name}: {cause}") + future = futures.Future() + future.set_exception(exceptions.TaskFailed(name=a_task.id, reason=cause)) + attempt = {**event, "retry": event.get("retry", -1) + event["schedule_failed_count"]} + return self.handle_failure(attempt, future, a_task, exceptions.TaskException) + + timer = self._history.timers.get(self.get_schedule_retry_timer_id(a_task, event)) + if timer is None: + count = event["schedule_failed_count"] + if cause == "ACTIVITY_TYPE_DOES_NOT_EXIST": + version = event["activity_type"]["version"] + if (name, version) not in self.created_activity_types: + self.create_activity_type(name, version) + if count == 1: + return None + delay = min(2**count, SCHEDULE_ACTIVITY_RETRY_MAX_DELAY) + logger.info(f"failed to schedule {name}: {cause}, scheduling it again in {delay}s") + return None, TimerTask(self.get_schedule_retry_timer_id(a_task, event), delay, None) + if timer["state"] == "started": + return futures.Future() + return None + + @staticmethod + def get_schedule_retry_timer_id(a_task: ActivityTask, event: dict[str, Any]) -> str: + timer_id = f"__simpleflow_schedule_{event['schedule_failed_id']}_{a_task.id}" + if len(timer_id) > 256: + timer_id = timer_id[0:223] + "-" + hashlib.md5(timer_id.encode()).hexdigest() # nosec + return timer_id + def resume_child_workflow(self, a_workflow: WorkflowTask, event: dict[str, Any]) -> futures.Future | None: """ Resume a child workflow. diff --git a/simpleflow/swf/mapper/models/event/task.py b/simpleflow/swf/mapper/models/event/task.py index 7f7fe609..90f4a14c 100644 --- a/simpleflow/swf/mapper/models/event/task.py +++ b/simpleflow/swf/mapper/models/event/task.py @@ -60,6 +60,9 @@ class ActivityTaskEventDict(TypedDict): details: str | None canceled_id: int canceled_timestamp: datetime + schedule_failed_id: int + schedule_failed_timestamp: datetime + schedule_failed_count: int class CompiledActivityTaskEvent(CompiledEvent): diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index bd5e8b7b..f39fe257 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -2,6 +2,7 @@ import re import unittest +from typing import ClassVar from unittest import mock from simpleflow import activity, exceptions, format, futures @@ -10,7 +11,7 @@ from simpleflow.swf.mapper.models.history import builder from simpleflow.swf.mapper.responses import Response from tests.data.activities import increment, raise_on_failure -from tests.data.constants import DOMAIN +from tests.data.constants import DEFAULT_VERSION, DOMAIN from tests.data.workflows import BaseTestWorkflow from tests.utils import MockSWFTestCase @@ -627,6 +628,223 @@ def test_a_canceled_workflow_execution_is_parsed(self): assert history.workflow["details"] == "given up" +@activity.with_attributes(version=DEFAULT_VERSION, raises_on_failure=True, retry=2) +def mandatory_with_retries(x): + return x + + +class TwoActivitiesWorkflow(BaseTestWorkflow): + futures = None + + def run(self): + type(self).futures = [self.submit(increment, 1), self.submit(increment, 2)] + futures.wait(*type(self).futures) + + +class MandatoryActivityWorkflow(BaseTestWorkflow): + activity = raise_on_failure + + def run(self): + futures.wait(self.submit(type(self).activity)) + + +class MandatoryWithRetriesWorkflow(MandatoryActivityWorkflow): + activity = mandatory_with_retries + + +class IgnoreFailuresWorkflow(MandatoryActivityWorkflow): + contexts: ClassVar[list] = [] + + def on_task_failure(self, failure_context): + type(self).contexts.append( + (failure_context.exception.reason, failure_context.event["id"], failure_context.attempt_number) + ) + return failure_context.decide_ignore() + + +def decision_types(decisions): + return [d["decisionType"] for d in decisions] + + +def timer_attributes(decisions): + (timer,) = [d for d in decisions if d["decisionType"] == "StartTimer"] + return timer["startTimerDecisionAttributes"] + + +@mock.patch.object(Executor, "create_activity_type") +class TestRefusedScheduleReplay(unittest.TestCase): + ACTIVITY_ID = "activity-tests.data.activities.increment-1" + TRANSIENT_CAUSES = ( + "ACTIVITY_CREATION_RATE_EXCEEDED", + "OPEN_ACTIVITIES_LIMIT_EXCEEDED", + "ACTIVITY_ID_ALREADY_IN_USE", + ) + + @staticmethod + def refuse(history, cause, activity_id=ACTIVITY_ID, activity=increment): + history.add_decision_task_completed() + history.add_activity_task_schedule_failed( + activity_id, history.last_id, {"name": activity.name, "version": activity.version}, cause + ) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + @staticmethod + def replay(history, workflow=OneActivityWorkflow): + OneActivityWorkflow.future = None + TwoActivitiesWorkflow.futures = None + return replay_decisions(workflow, history) + + @staticmethod + def wait_for(history, timer): + history.add_decision_task_completed() + history.add_timer_started(timer["timerId"], timer["startToFireTimeout"], decision_id=history.last_id) + history.add_timer_fired(timer["timerId"], history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + def test_a_first_missing_type_is_created_and_scheduled_again_at_once(self, create_activity_type): + history = builder.History(OneActivityWorkflow, input={}) + self.refuse(history, "ACTIVITY_TYPE_DOES_NOT_EXIST") + + assert decision_types(self.replay(history)) == ["ScheduleActivityTask"] + create_activity_type.assert_called_once_with(increment.name, increment.version) + + def test_a_transient_refusal_waits_for_a_timer(self, create_activity_type): + for causes in [(c,) for c in self.TRANSIENT_CAUSES] + [("ACTIVITY_TYPE_DOES_NOT_EXIST",) * 2]: + with self.subTest(causes=causes): + history = builder.History(OneActivityWorkflow, input={}) + for cause in causes: + self.refuse(history, cause) + + decisions = self.replay(history) + + assert decision_types(decisions) == ["StartTimer"] + assert timer_attributes(decisions)["startToFireTimeout"] == str(2 ** len(causes)) + + def test_a_missing_type_is_created_again_on_every_refusal(self, create_activity_type): + history = builder.History(OneActivityWorkflow, input={}) + self.refuse(history, "ACTIVITY_TYPE_DOES_NOT_EXIST") + self.refuse(history, "ACTIVITY_TYPE_DOES_NOT_EXIST") + + self.replay(history) + + create_activity_type.assert_called_once_with(increment.name, increment.version) + + def test_the_activity_is_scheduled_once_its_timer_fired(self, create_activity_type): + history = builder.History(OneActivityWorkflow, input={}) + self.refuse(history, "ACTIVITY_CREATION_RATE_EXCEEDED") + timer = timer_attributes(self.replay(history)) + history.add_decision_task_completed() + history.add_timer_started(timer["timerId"], timer["startToFireTimeout"], decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert self.replay(history) == [] + assert not OneActivityWorkflow.future.finished + + history.add_decision_task_completed() + history.add_timer_fired(timer["timerId"], history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert decision_types(self.replay(history)) == ["ScheduleActivityTask"] + + def test_the_delay_doubles_up_to_a_cap_and_restarts_after_a_schedule(self, create_activity_type): + history = builder.History(OneActivityWorkflow, input={}) + delays = [] + timer_ids = set() + for _ in range(10): + self.refuse(history, "OPEN_ACTIVITIES_LIMIT_EXCEEDED") + timer = timer_attributes(self.replay(history)) + delays.append(int(timer["startToFireTimeout"])) + timer_ids.add(timer["timerId"]) + self.wait_for(history, timer) + assert decision_types(self.replay(history)) == ["ScheduleActivityTask"] + + assert delays == [2, 4, 8, 16, 32, 64, 128, 256, 300, 300] + assert len(timer_ids) == 10 + + history.add_decision_task_completed() + history.add_activity_task_scheduled(increment, history.last_id, activity_id=self.ACTIVITY_ID) + history.add_activity_task_timed_out("SCHEDULE_TO_START", scheduled=history.last_id) + self.refuse(history, "OPEN_ACTIVITIES_LIMIT_EXCEEDED") + + assert timer_attributes(self.replay(history))["startToFireTimeout"] == "2" + + def test_a_permanent_refusal_fails_the_future_without_scheduling_again(self, create_activity_type): + history = builder.History(OneActivityWorkflow, input={}) + self.refuse(history, "DEFAULT_TASK_LIST_UNDEFINED") + + assert decision_types(self.replay(history)) == ["CompleteWorkflowExecution"] + exception = OneActivityWorkflow.future.exception + assert isinstance(exception, exceptions.TaskFailed) + assert (exception.name, exception.reason) == (self.ACTIVITY_ID, "DEFAULT_TASK_LIST_UNDEFINED") + + def test_a_permanent_refusal_of_a_mandatory_activity_fails_the_workflow(self, create_activity_type): + history = builder.History(MandatoryActivityWorkflow, input={}) + self.refuse( + history, + "ACTIVITY_TYPE_DEPRECATED", + activity_id=f"activity-{raise_on_failure.name}-1", + activity=raise_on_failure, + ) + + assert decision_types(self.replay(history, MandatoryActivityWorkflow)) == ["FailWorkflowExecution"] + + def test_permanent_refusals_use_up_the_retries(self, create_activity_type): + history = builder.History(MandatoryWithRetriesWorkflow, input={}) + outcomes = [] + for _ in range(mandatory_with_retries.retry + 1): + self.refuse( + history, + "ACTIVITY_TYPE_DEPRECATED", + activity_id=f"activity-{mandatory_with_retries.name}-1", + activity=mandatory_with_retries, + ) + outcomes.append(decision_types(self.replay(history, MandatoryWithRetriesWorkflow))) + + assert outcomes == [["ScheduleActivityTask"], ["ScheduleActivityTask"], ["FailWorkflowExecution"]] + + def test_a_permanent_refusal_reaches_on_task_failure(self, create_activity_type): + IgnoreFailuresWorkflow.contexts = [] + activity_id = f"activity-{raise_on_failure.name}-1" + history = builder.History(IgnoreFailuresWorkflow, input={}) + self.refuse(history, "OPERATION_NOT_PERMITTED", activity_id=activity_id, activity=raise_on_failure) + + assert decision_types(self.replay(history, IgnoreFailuresWorkflow)) == ["CompleteWorkflowExecution"] + assert IgnoreFailuresWorkflow.contexts == [("OPERATION_NOT_PERMITTED", activity_id, 1)] + + def test_a_refused_backoff_timer_schedules_the_activity_at_once(self, create_activity_type): + history = builder.History(OneActivityWorkflow, input={}) + self.refuse(history, "OPEN_ACTIVITIES_LIMIT_EXCEEDED") + timer = timer_attributes(self.replay(history)) + history.add_decision_task_completed() + history.add_timer_start_failed(timer["timerId"], "OPEN_TIMERS_LIMIT_EXCEEDED", decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert decision_types(self.replay(history)) == ["ScheduleActivityTask"] + + def test_each_refused_activity_gets_its_own_outcome(self, create_activity_type): + history = builder.History(TwoActivitiesWorkflow, input={}) + history.add_decision_task_completed() + decision_id = history.last_id + causes = { + "activity-tests.data.activities.increment-1": "OPERATION_NOT_PERMITTED", + "activity-tests.data.activities.increment-2": "ACTIVITY_TYPE_DEPRECATED", + } + for activity_id, cause in causes.items(): + history.add_activity_task_schedule_failed( + activity_id, decision_id, {"name": increment.name, "version": increment.version}, cause + ) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert decision_types(self.replay(history, TwoActivitiesWorkflow)) == ["CompleteWorkflowExecution"] + assert [f.exception.reason for f in TwoActivitiesWorkflow.futures] == list(causes.values()) + + @activity.with_attributes(raises_on_failure=True) def print_me_n_times(s, n, raises=False): if raises: From c335a591d99168292c407bbb09cfaf86207ab977 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sun, 29 Nov 2026 01:31:35 +0100 Subject: [PATCH 08/12] Handle a refused child workflow start like a refused activity schedule A StartChildWorkflowExecutionFailed other than WORKFLOW_TYPE_DOES_NOT_EXIST became a TaskFailed future through handle_failure, and the default handling compared the history's `retry` with the child's: refusals never incremented `retry`, so a child with retry > 0 was started again on every decision until the execution hit its event cap. A rate or limit refusal failed the attempt instead of waiting, and a missing type was created and started again at once, for ever if the refusal persisted. Two children refused before being initiated (initiatedEventId is 0 for every cause but WORKFLOW_ALREADY_RUNNING) also shared one handled_failures entry: get_event_id returned None for both. resume_refused_activity becomes resume_refused_task, used by both resume_activity and resume_child_workflow: - transient causes (CHILD_CREATION_RATE_EXCEEDED, OPEN_CHILDREN_LIMIT_EXCEEDED, OPEN_WORKFLOWS_LIMIT_EXCEEDED, WORKFLOW_TYPE_DOES_NOT_EXIST for children) start a timer __simpleflow___, delay 2^n s capped at 300 s; the first missing type is created and tried again at once; - any other cause is a failed attempt, with `retry` = earlier failures + refusals in a row - 1. WORKFLOW_ALREADY_RUNNING stays a failed attempt: the running execution may be another one, for an unbounded time. History: a child start_failed entry gains start_failed_count, reset when the child starts, and get_event_id knows start_failed_id. The type creation moves to create_workflow_type; create_activity_type skips a type already created in this replay. The activity backoff timer is now named __simpleflow_schedule_failed__. Co-Authored-By: Claude Opus 5.5 --- simpleflow/history.py | 4 + simpleflow/swf/executor.py | 117 +++++++------ .../swf/mapper/models/history/builder.py | 23 +++ tests/test_simpleflow/swf/test_executor.py | 163 ++++++++++++++++++ 4 files changed, 259 insertions(+), 48 deletions(-) diff --git a/simpleflow/history.py b/simpleflow/history.py index 6d96ea94..4408b26b 100644 --- a/simpleflow/history.py +++ b/simpleflow/history.py @@ -349,6 +349,7 @@ def get_workflow(): ) self._child_workflows[event.workflow_id].update(workflow) elif event.state == "start_failed": + previous = self._child_workflows.get(event.workflow_id, {}) workflow = { "type": "child_workflow", "id": event.workflow_id, @@ -359,6 +360,7 @@ def get_workflow(): "control": event.control, "start_failed_id": event.id, "start_failed_timestamp": event.timestamp, + "start_failed_count": previous.get("start_failed_count", 0) + 1, "decision_task_completed_event_id": event.decision_task_completed_event_id, } if event.workflow_id not in self._child_workflows: @@ -377,6 +379,7 @@ def get_workflow(): "started_timestamp": event.timestamp, } ) + workflow.pop("start_failed_count", None) elif event.state == "completed": workflow = get_workflow() workflow.update( @@ -815,6 +818,7 @@ def get_event_id(event: dict[str, Any]) -> int | None: "started_event_id", "cancel_failed_event_id", "schedule_failed_id", + "start_failed_id", ): event_id = event.get(event_id_key) if event_id: diff --git a/simpleflow/swf/executor.py b/simpleflow/swf/executor.py index ff9fcd4a..9647caa5 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -54,7 +54,15 @@ "OPEN_ACTIVITIES_LIMIT_EXCEEDED", } ) -SCHEDULE_ACTIVITY_RETRY_MAX_DELAY = 300 +TRANSIENT_START_CHILD_WORKFLOW_FAILED_CAUSES = frozenset( + { + "CHILD_CREATION_RATE_EXCEEDED", + "OPEN_CHILDREN_LIMIT_EXCEEDED", + "OPEN_WORKFLOWS_LIMIT_EXCEEDED", + "WORKFLOW_TYPE_DOES_NOT_EXIST", + } +) +REFUSED_TASK_RETRY_MAX_DELAY = 300 # if "poll_for_activity_task" doesn't contain a "taskToken" @@ -279,6 +287,8 @@ def _get_future_from_activity_event(self, event: dict[str, Any]) -> futures.Futu return future def create_activity_type(self, name: str, version: str) -> None: + if (name, version) in self.created_activity_types: + return self.created_activity_types.add((name, version)) activity_type = simpleflow.swf.mapper.models.ActivityType(self.domain, name=name, version=version) logger.info(f"creating activity type {activity_type.name} in domain {self.domain.name}") @@ -290,6 +300,15 @@ def create_activity_type(self, name: str, version: str) -> None: f" creation failed, continuing..." ) + def create_workflow_type(self, name: str, version: str) -> None: + workflow_type = simpleflow.swf.mapper.models.WorkflowType(self.domain, name=name, version=version) + logger.info(f"Creating workflow type {workflow_type.name} in domain {self.domain.name}") + try: + workflow_type.save() + except simpleflow.swf.mapper.exceptions.AlreadyExistsError: + # Could have be created by a concurrent workflow execution. + pass + def _get_future_from_child_workflow_event(self, event: dict[str, Any]) -> futures.Future | None: """Maps a child workflow event to a Future with the corresponding state. @@ -302,27 +321,6 @@ def _get_future_from_child_workflow_event(self, event: dict[str, Any]) -> future if state == "start_initiated": pass # future._state = futures.PENDING - elif state == "start_failed": - if event["cause"] == "WORKFLOW_TYPE_DOES_NOT_EXIST": - workflow_type = simpleflow.swf.mapper.models.WorkflowType( - self.domain, - name=event["name"], - version=event["version"], - ) - logger.info(f"Creating workflow type {workflow_type.name} in domain {self.domain.name}") - try: - workflow_type.save() - except simpleflow.swf.mapper.exceptions.AlreadyExistsError: - # Could have be created by a concurrent workflow execution. - pass - return None - future.set_exception( - exceptions.TaskFailed( - name=event["id"], - reason=event["cause"], - details=event.get("details"), - ) - ) elif state == "started": future.set_running() elif state == "completed": @@ -566,7 +564,15 @@ def resume_activity(self, a_task: ActivityTask, event: dict[str, Any]) -> future Resume an activity task. """ if event["state"] == "schedule_failed": - return self.resume_refused_activity(a_task, event) + return self.resume_refused_task( + a_task, + event, + event["activity_type"], + TRANSIENT_SCHEDULE_ACTIVITY_FAILED_CAUSES, + "ACTIVITY_TYPE_DOES_NOT_EXIST", + self.create_activity_type, + exceptions.TaskException, + ) future = self._get_future_from_activity_event(event) @@ -578,42 +584,50 @@ def resume_activity(self, a_task: ActivityTask, event: dict[str, Any]) -> future return self.handle_failure(event, future, a_task, exceptions.TaskException) - def resume_refused_activity( - self, a_task: ActivityTask, event: dict[str, Any] + def resume_refused_task( + self, + a_task: ActivityTask | WorkflowTask, + event: dict[str, Any], + task_type: dict[str, str], + transient_causes: frozenset[str], + type_missing_cause: str, + create_type: Callable[[str, str], None], + exception_class: type[Exception], ) -> futures.Future | tuple[futures.Future | None, SwfTask] | None: """ - A transient refusal schedules the activity again after a timer, whose delay doubles with each - refusal in a row. Any other refusal is a failed attempt: earlier failures and the refusals in a - row count towards its `retry`. + SWF refused to schedule an activity or start a child workflow. A transient refusal tries again + after a timer, whose delay doubles with each refusal in a row. Any other refusal is a failed + attempt: earlier failures and the refusals in a row count towards the task's `retry`. """ - name = event["activity_type"]["name"] + refusal = event["state"] + name = task_type["name"] cause = event["cause"] - if cause not in TRANSIENT_SCHEDULE_ACTIVITY_FAILED_CAUSES: - logger.info(f"failed to schedule {name}: {cause}") + count = event[f"{refusal}_count"] + if cause not in transient_causes: + logger.info(f"{refusal}: {name}: {cause}") future = futures.Future() future.set_exception(exceptions.TaskFailed(name=a_task.id, reason=cause)) - attempt = {**event, "retry": event.get("retry", -1) + event["schedule_failed_count"]} - return self.handle_failure(attempt, future, a_task, exceptions.TaskException) + attempt = {**event, "retry": event.get("retry", -1) + count} + return self.handle_failure(attempt, future, a_task, exception_class) - timer = self._history.timers.get(self.get_schedule_retry_timer_id(a_task, event)) + timer_id = self.get_refused_task_timer_id(a_task, event) + timer = self._history.timers.get(timer_id) if timer is None: - count = event["schedule_failed_count"] - if cause == "ACTIVITY_TYPE_DOES_NOT_EXIST": - version = event["activity_type"]["version"] - if (name, version) not in self.created_activity_types: - self.create_activity_type(name, version) + if cause == type_missing_cause: + create_type(name, task_type["version"]) if count == 1: return None - delay = min(2**count, SCHEDULE_ACTIVITY_RETRY_MAX_DELAY) - logger.info(f"failed to schedule {name}: {cause}, scheduling it again in {delay}s") - return None, TimerTask(self.get_schedule_retry_timer_id(a_task, event), delay, None) + delay = min(2**count, REFUSED_TASK_RETRY_MAX_DELAY) + logger.info(f"{refusal}: {name}: {cause}, trying again in {delay}s") + return None, TimerTask(timer_id, delay, None) if timer["state"] == "started": return futures.Future() return None @staticmethod - def get_schedule_retry_timer_id(a_task: ActivityTask, event: dict[str, Any]) -> str: - timer_id = f"__simpleflow_schedule_{event['schedule_failed_id']}_{a_task.id}" + def get_refused_task_timer_id(a_task: ActivityTask | WorkflowTask, event: dict[str, Any]) -> str: + refusal = event["state"] + timer_id = f"__simpleflow_{refusal}_{event[f'{refusal}_id']}_{a_task.id}" if len(timer_id) > 256: timer_id = timer_id[0:223] + "-" + hashlib.md5(timer_id.encode()).hexdigest() # nosec return timer_id @@ -622,11 +636,18 @@ def resume_child_workflow(self, a_workflow: WorkflowTask, event: dict[str, Any]) """ Resume a child workflow. """ - future = self._get_future_from_child_workflow_event(event) + if event["state"] == "start_failed": + return self.resume_refused_task( + a_workflow, + event, + event, + TRANSIENT_START_CHILD_WORKFLOW_FAILED_CAUSES, + "WORKFLOW_TYPE_DOES_NOT_EXIST", + self.create_workflow_type, + exceptions.WorkflowException, + ) - if not future: - # WORKFLOW_TYPE_DOES_NOT_EXIST, will be created - return None + future = self._get_future_from_child_workflow_event(event) if not future.finished: # Still pending or running... return future diff --git a/simpleflow/swf/mapper/models/history/builder.py b/simpleflow/swf/mapper/models/history/builder.py index 9c0fc126..08b73790 100644 --- a/simpleflow/swf/mapper/models/history/builder.py +++ b/simpleflow/swf/mapper/models/history/builder.py @@ -456,6 +456,29 @@ def add_child_workflow_start_initiated( return self + def add_child_workflow_start_failed(self, workflow, workflow_id, cause, decision_id=0, initiated_id=0): + self.events.append( + EventFactory( + { + "eventId": self.next_id, + "eventType": "StartChildWorkflowExecutionFailed", + "eventTimestamp": new_timestamp_string(), + "startChildWorkflowExecutionFailedEventAttributes": { + "cause": cause, + "decisionTaskCompletedEventId": decision_id, + "initiatedEventId": initiated_id, + "workflowId": workflow_id, + "workflowType": { + "name": workflow.name, + "version": workflow.version, + }, + }, + } + ) + ) + + return self + def add_child_workflow_started(self, initiated_id): initiated_event = self.events[initiated_id - 1] workflow_id = initiated_event.workflow_id diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index f39fe257..0522dc42 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -845,6 +845,169 @@ def test_each_refused_activity_gets_its_own_outcome(self, create_activity_type): assert [f.exception.reason for f in TwoActivitiesWorkflow.futures] == list(causes.values()) +class ChildWorkflow(BaseTestWorkflow): + name = "child_workflow" + + def run(self, x=0): + return x + + +class ChildWithRetriesWorkflow(ChildWorkflow): + name = "child_with_retries" + retry = 2 + + +class OptionalChildWorkflow(ChildWorkflow): + name = "optional_child" + raises_on_failure = False + + +class ParentWorkflow(BaseTestWorkflow): + child = ChildWorkflow + futures = None + contexts: ClassVar[list] = [] + + def run(self): + type(self).futures = [self.submit(type(self).child)] + futures.wait(*type(self).futures) + + +class ParentWithRetriesWorkflow(ParentWorkflow): + child = ChildWithRetriesWorkflow + + +class TwoOptionalChildrenWorkflow(ParentWorkflow): + def run(self): + type(self).futures = [self.submit(OptionalChildWorkflow, 1), self.submit(OptionalChildWorkflow, 2)] + futures.wait(*type(self).futures) + + +class IgnoreChildFailuresWorkflow(ParentWorkflow): + def on_task_failure(self, failure_context): + type(self).contexts.append( + (failure_context.exception.reason, failure_context.event["id"], failure_context.attempt_number) + ) + return failure_context.decide_ignore() + + +def child_ids(decisions): + return [ + d["startChildWorkflowExecutionDecisionAttributes"]["workflowId"] + for d in decisions + if d["decisionType"] == "StartChildWorkflowExecution" + ] + + +@mock.patch("simpleflow.swf.mapper.models.WorkflowType.save") +class TestRefusedChildStartReplay(unittest.TestCase): + TRANSIENT_CAUSES = ("CHILD_CREATION_RATE_EXCEEDED", "OPEN_CHILDREN_LIMIT_EXCEEDED", "OPEN_WORKFLOWS_LIMIT_EXCEEDED") + + @staticmethod + def replay(history, workflow): + workflow.futures = None + return replay_decisions(workflow, history) + + def refuse(self, history, workflow, cause, children=None): + child = children or workflow.child + (workflow_id,) = child_ids(self.replay(builder.History(workflow, input={}), workflow)) + history.add_decision_task_completed() + history.add_child_workflow_start_failed(child, workflow_id, cause, decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + return workflow_id + + def test_a_first_missing_type_is_created_and_started_again_at_once(self, save): + history = builder.History(ParentWorkflow, input={}) + self.refuse(history, ParentWorkflow, "WORKFLOW_TYPE_DOES_NOT_EXIST") + + assert decision_types(self.replay(history, ParentWorkflow)) == ["StartChildWorkflowExecution"] + save.assert_called_once_with() + + def test_a_transient_refusal_waits_for_a_timer(self, save): + for causes in [(c,) for c in self.TRANSIENT_CAUSES] + [("WORKFLOW_TYPE_DOES_NOT_EXIST",) * 2]: + with self.subTest(causes=causes): + history = builder.History(ParentWorkflow, input={}) + for cause in causes: + self.refuse(history, ParentWorkflow, cause) + + decisions = self.replay(history, ParentWorkflow) + + assert decision_types(decisions) == ["StartTimer"] + assert timer_attributes(decisions)["startToFireTimeout"] == str(2 ** len(causes)) + + def test_the_child_is_started_once_its_timer_fired(self, save): + history = builder.History(ParentWorkflow, input={}) + self.refuse(history, ParentWorkflow, "CHILD_CREATION_RATE_EXCEEDED") + timer = timer_attributes(self.replay(history, ParentWorkflow)) + history.add_decision_task_completed() + history.add_timer_started(timer["timerId"], timer["startToFireTimeout"], decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert self.replay(history, ParentWorkflow) == [] + + history.add_decision_task_completed() + history.add_timer_fired(timer["timerId"], history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert decision_types(self.replay(history, ParentWorkflow)) == ["StartChildWorkflowExecution"] + + def test_the_delay_restarts_after_the_child_started(self, save): + history = builder.History(ParentWithRetriesWorkflow, input={}) + workflow_id = self.refuse(history, ParentWithRetriesWorkflow, "CHILD_CREATION_RATE_EXCEEDED") + self.refuse(history, ParentWithRetriesWorkflow, "CHILD_CREATION_RATE_EXCEEDED") + assert timer_attributes(self.replay(history, ParentWithRetriesWorkflow))["startToFireTimeout"] == "4" + + history.add_decision_task_completed() + history.add_child_workflow(ChildWithRetriesWorkflow, last_state="failed", workflow_id=workflow_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + assert decision_types(self.replay(history, ParentWithRetriesWorkflow)) == ["StartChildWorkflowExecution"] + self.refuse(history, ParentWithRetriesWorkflow, "CHILD_CREATION_RATE_EXCEEDED") + + assert timer_attributes(self.replay(history, ParentWithRetriesWorkflow))["startToFireTimeout"] == "2" + + def test_permanent_refusals_use_up_the_retries(self, save): + history = builder.History(ParentWithRetriesWorkflow, input={}) + outcomes = [] + for _ in range(ChildWithRetriesWorkflow.retry + 1): + self.refuse(history, ParentWithRetriesWorkflow, "WORKFLOW_TYPE_DEPRECATED") + outcomes.append(decision_types(self.replay(history, ParentWithRetriesWorkflow))) + + assert outcomes == [ + ["StartChildWorkflowExecution"], + ["StartChildWorkflowExecution"], + ["FailWorkflowExecution"], + ] + + def test_a_permanent_refusal_reaches_on_task_failure(self, save): + IgnoreChildFailuresWorkflow.contexts = [] + history = builder.History(IgnoreChildFailuresWorkflow, input={}) + workflow_id = self.refuse(history, IgnoreChildFailuresWorkflow, "OPERATION_NOT_PERMITTED") + + assert decision_types(self.replay(history, IgnoreChildFailuresWorkflow)) == ["CompleteWorkflowExecution"] + assert IgnoreChildFailuresWorkflow.contexts == [("OPERATION_NOT_PERMITTED", workflow_id, 1)] + + def test_each_refused_child_gets_its_own_outcome(self, save): + history = builder.History(TwoOptionalChildrenWorkflow, input={}) + workflow_ids = child_ids( + self.replay(builder.History(TwoOptionalChildrenWorkflow, input={}), TwoOptionalChildrenWorkflow) + ) + causes = ["OPERATION_NOT_PERMITTED", "WORKFLOW_TYPE_DEPRECATED"] + history.add_decision_task_completed() + decision_id = history.last_id + for workflow_id, cause in zip(workflow_ids, causes): + history.add_child_workflow_start_failed(OptionalChildWorkflow, workflow_id, cause, decision_id=decision_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + decisions = self.replay(history, TwoOptionalChildrenWorkflow) + + assert decision_types(decisions) == ["CompleteWorkflowExecution"] + assert [f.exception.reason for f in TwoOptionalChildrenWorkflow.futures] == causes + + @activity.with_attributes(raises_on_failure=True) def print_me_n_times(s, n, raises=False): if raises: From f4a10d3a66bfe56859047ddfa39533d86431d1ec Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sun, 29 Nov 2026 01:38:30 +0100 Subject: [PATCH 09/12] Don't hot-loop when the backoff timer of a refused task is itself refused When SWF refused the StartTimer of a refused activity or child workflow, resume_refused_task scheduled the task again at once. Under OPEN_ACTIVITIES_LIMIT_EXCEEDED plus OPEN_TIMERS_LIMIT_EXCEEDED that is a loop: task refused, timer refused, task refused..., two decisions per turn, until a limit clears or the execution hits its event cap. Now, by the timer's cause: - OPEN_TIMERS_LIMIT_EXCEEDED: the limit is per execution (1,000 open timers), so this execution's own timers will fire. The decision that the refusal brings waits (pending future, no decision); a later decision, i.e. one after a DecisionTaskCompleted that follows the refusal, starts the same timer again. A decision task timeout adds no DecisionTaskCompleted, so it waits again. - TIMER_CREATION_RATE_EXCEEDED: start the same timer again at once. This is an account-wide token bucket (StartTimer: 2,000, refilled at 200/s); nothing else is sure to wake the execution, so this stays a loop paced by decision round trips while SWF throttles. Same choice as the failure-retry timer (#484). - anything else (OPERATION_NOT_PERMITTED, TIMER_ID_ALREADY_IN_USE): a failed attempt, through the same path and attempt count as a permanent refusal. TaskFailed keeps the task's refusal cause as reason; details name the timer and its cause. Co-Authored-By: Claude Opus 5.5 --- simpleflow/swf/executor.py | 39 +++++-- tests/test_simpleflow/swf/test_executor.py | 119 +++++++++++++++++++-- 2 files changed, 141 insertions(+), 17 deletions(-) diff --git a/simpleflow/swf/executor.py b/simpleflow/swf/executor.py index 9647caa5..5c01421f 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -598,6 +598,9 @@ def resume_refused_task( SWF refused to schedule an activity or start a child workflow. A transient refusal tries again after a timer, whose delay doubles with each refusal in a row. Any other refusal is a failed attempt: earlier failures and the refusals in a row count towards the task's `retry`. + + If that timer is refused too: too many open timers waits for the next decision, which one of + them firing brings; a throttled one starts again; any other cause fails the attempt. """ refusal = event["state"] name = task_type["name"] @@ -605,24 +608,48 @@ def resume_refused_task( count = event[f"{refusal}_count"] if cause not in transient_causes: logger.info(f"{refusal}: {name}: {cause}") - future = futures.Future() - future.set_exception(exceptions.TaskFailed(name=a_task.id, reason=cause)) - attempt = {**event, "retry": event.get("retry", -1) + count} - return self.handle_failure(attempt, future, a_task, exception_class) + return self.fail_refused_attempt(a_task, event, exceptions.TaskFailed(a_task.id, cause), exception_class) timer_id = self.get_refused_task_timer_id(a_task, event) + delay = min(2**count, REFUSED_TASK_RETRY_MAX_DELAY) timer = self._history.timers.get(timer_id) if timer is None: if cause == type_missing_cause: create_type(name, task_type["version"]) if count == 1: return None - delay = min(2**count, REFUSED_TASK_RETRY_MAX_DELAY) logger.info(f"{refusal}: {name}: {cause}, trying again in {delay}s") return None, TimerTask(timer_id, delay, None) if timer["state"] == "started": return futures.Future() - return None + if timer["state"] != "start_failed": + return None + + timer_cause = timer["cause"] + if timer_cause == "TIMER_CREATION_RATE_EXCEEDED" or ( + timer_cause == "OPEN_TIMERS_LIMIT_EXCEEDED" and self.decided_since(timer["start_failed_event_id"]) + ): + logger.info(f"{refusal}: {name}: timer {timer_id} refused ({timer_cause}), starting it again") + return None, TimerTask(timer_id, delay, None) + if timer_cause == "OPEN_TIMERS_LIMIT_EXCEEDED": + return futures.Future() + exception = exceptions.TaskFailed(a_task.id, cause, f"backoff timer {timer_id} refused: {timer_cause}") + return self.fail_refused_attempt(a_task, event, exception, exception_class) + + def fail_refused_attempt( + self, + a_task: ActivityTask | WorkflowTask, + event: dict[str, Any], + exception: exceptions.TaskFailed, + exception_class: type[Exception], + ) -> futures.Future | tuple[futures.Future | None, SwfTask] | None: + future = futures.Future() + future.set_exception(exception) + attempt = {**event, "retry": event.get("retry", -1) + event[f"{event['state']}_count"]} + return self.handle_failure(attempt, future, a_task, exception_class) + + def decided_since(self, event_id: int) -> bool: + return any(e.type == "DecisionTask" and e.state == "completed" for e in self._history.events[event_id:]) @staticmethod def get_refused_task_timer_id(a_task: ActivityTask | WorkflowTask, event: dict[str, Any]) -> str: diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index 0522dc42..1c6e6aca 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -815,17 +815,6 @@ def test_a_permanent_refusal_reaches_on_task_failure(self, create_activity_type) assert decision_types(self.replay(history, IgnoreFailuresWorkflow)) == ["CompleteWorkflowExecution"] assert IgnoreFailuresWorkflow.contexts == [("OPERATION_NOT_PERMITTED", activity_id, 1)] - def test_a_refused_backoff_timer_schedules_the_activity_at_once(self, create_activity_type): - history = builder.History(OneActivityWorkflow, input={}) - self.refuse(history, "OPEN_ACTIVITIES_LIMIT_EXCEEDED") - timer = timer_attributes(self.replay(history)) - history.add_decision_task_completed() - history.add_timer_start_failed(timer["timerId"], "OPEN_TIMERS_LIMIT_EXCEEDED", decision_id=history.last_id) - history.add_decision_task_scheduled() - history.add_decision_task_started() - - assert decision_types(self.replay(history)) == ["ScheduleActivityTask"] - def test_each_refused_activity_gets_its_own_outcome(self, create_activity_type): history = builder.History(TwoActivitiesWorkflow, input={}) history.add_decision_task_completed() @@ -1008,6 +997,114 @@ def test_each_refused_child_gets_its_own_outcome(self, save): assert [f.exception.reason for f in TwoOptionalChildrenWorkflow.futures] == causes +def refuse_timer(history, timer, cause): + history.add_decision_task_completed() + history.add_timer_start_failed(timer["timerId"], cause, decision_id=history.last_id) + history.add_decision_task_scheduled() + history.add_decision_task_started() + + +def wake_up(history): + history.add_decision_task_completed() + history.add_signal("wake_up") + history.add_decision_task_scheduled() + history.add_decision_task_started() + + +@mock.patch.object(Executor, "create_activity_type") +class TestRefusedBackoffTimerReplay(unittest.TestCase): + @staticmethod + def refused_activity(workflow=OneActivityWorkflow, activity_=increment): + history = builder.History(workflow, input={}) + TestRefusedScheduleReplay.refuse( + history, "OPEN_ACTIVITIES_LIMIT_EXCEEDED", activity_id=f"activity-{activity_.name}-1", activity=activity_ + ) + return history + + @staticmethod + def refused_child(): + history = builder.History(ParentWorkflow, input={}) + (workflow_id,) = child_ids(replay_decisions(ParentWorkflow, builder.History(ParentWorkflow, input={}))) + history.add_decision_task_completed() + history.add_child_workflow_start_failed( + ChildWorkflow, workflow_id, "OPEN_CHILDREN_LIMIT_EXCEEDED", decision_id=history.last_id + ) + history.add_decision_task_scheduled() + history.add_decision_task_started() + return history + + def cases(self): + return ( + ("activity", OneActivityWorkflow, self.refused_activity), + ("child workflow", ParentWorkflow, self.refused_child), + ) + + def test_too_many_open_timers_waits_for_another_event(self, create_activity_type): + for kind, workflow, refused in self.cases(): + with self.subTest(kind): + history = refused() + timer = timer_attributes(replay_decisions(workflow, history)) + refuse_timer(history, timer, "OPEN_TIMERS_LIMIT_EXCEEDED") + + assert replay_decisions(workflow, history) == [] + + wake_up(history) + + assert timer_attributes(replay_decisions(workflow, history)) == timer + + def test_waiting_survives_a_decision_timeout(self, create_activity_type): + history = self.refused_activity() + timer = timer_attributes(replay_decisions(OneActivityWorkflow, history)) + refuse_timer(history, timer, "OPEN_TIMERS_LIMIT_EXCEEDED") + history.add_decision_task_timed_out() + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert replay_decisions(OneActivityWorkflow, history) == [] + assert not OneActivityWorkflow.future.finished + + def test_a_throttled_timer_starts_again_at_once(self, create_activity_type): + for kind, workflow, refused in self.cases(): + with self.subTest(kind): + history = refused() + timer = timer_attributes(replay_decisions(workflow, history)) + refuse_timer(history, timer, "TIMER_CREATION_RATE_EXCEEDED") + + assert timer_attributes(replay_decisions(workflow, history)) == timer + + def test_an_otherwise_refused_timer_fails_the_attempt(self, create_activity_type): + history = self.refused_activity() + timer = timer_attributes(replay_decisions(OneActivityWorkflow, history)) + refuse_timer(history, timer, "OPERATION_NOT_PERMITTED") + + assert decision_types(replay_decisions(OneActivityWorkflow, history)) == ["CompleteWorkflowExecution"] + exception = OneActivityWorkflow.future.exception + assert exception.reason == "OPEN_ACTIVITIES_LIMIT_EXCEEDED" + assert "OPERATION_NOT_PERMITTED" in str(exception.details) + + history = self.refused_activity(MandatoryActivityWorkflow, raise_on_failure) + timer = timer_attributes(replay_decisions(MandatoryActivityWorkflow, history)) + refuse_timer(history, timer, "OPERATION_NOT_PERMITTED") + + assert decision_types(replay_decisions(MandatoryActivityWorkflow, history)) == ["FailWorkflowExecution"] + + def test_otherwise_refused_timers_use_up_the_retries(self, create_activity_type): + history = builder.History(MandatoryWithRetriesWorkflow, input={}) + outcomes = [] + for _ in range(mandatory_with_retries.retry + 1): + TestRefusedScheduleReplay.refuse( + history, + "OPEN_ACTIVITIES_LIMIT_EXCEEDED", + activity_id=f"activity-{mandatory_with_retries.name}-1", + activity=mandatory_with_retries, + ) + timer = timer_attributes(replay_decisions(MandatoryWithRetriesWorkflow, history)) + refuse_timer(history, timer, "OPERATION_NOT_PERMITTED") + outcomes.append(decision_types(replay_decisions(MandatoryWithRetriesWorkflow, history))) + + assert outcomes == [["ScheduleActivityTask"], ["ScheduleActivityTask"], ["FailWorkflowExecution"]] + + @activity.with_attributes(raises_on_failure=True) def print_me_n_times(s, n, raises=False): if raises: From 4dd1e0b50ffefa417ef5a2714787d16aa08ec1c5 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sun, 29 Nov 2026 01:42:40 +0100 Subject: [PATCH 10/12] Wait for the next decision when a failure-retry timer hits the open-timers limit do_handle_failure treats a refused failure-retry timer (__simpleflow_task_) with a cause in TRANSIENT_START_TIMER_FAILED_CAUSES as never started, and asks on_task_failure again, which starts the same timer again in the same decision. For OPEN_TIMERS_LIMIT_EXCEEDED that is a loop, timer refused, timer started again, refused..., until a timer of the execution happens to fire between two turns. The limit is per execution (1,000 open timers), so this execution's own timers will fire and bring a decision. Now the decision that the refusal brings returns a pending future and no decision; a later one, i.e. after a DecisionTaskCompleted that follows the refusal, starts the timer again as before. A decision task timeout adds no DecisionTaskCompleted, so it waits again. TIMER_CREATION_RATE_EXCEEDED still starts it again at once, as #484 chose. Same rule as for the backoff timer of a refused task, through the same decided_since helper. Co-Authored-By: Claude Opus 5.5 --- simpleflow/swf/executor.py | 5 +++++ tests/test_simpleflow/swf/test_executor.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/simpleflow/swf/executor.py b/simpleflow/swf/executor.py index 5c01421f..b8129f14 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -720,6 +720,11 @@ def do_handle_failure( ) -> 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: + if timer["cause"] == "OPEN_TIMERS_LIMIT_EXCEEDED" and not self.decided_since( + timer["start_failed_event_id"] + ): + logger.info(f"handle_failure: retry timer {timer['id']} refused ({timer['cause']}), waiting") + return futures.Future(), swf_task logger.info(f"handle_failure: retry timer {timer['id']} refused ({timer['cause']}), starting it again") timer = None if timer: diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index 1c6e6aca..b14395bb 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -140,6 +140,23 @@ def test_a_retry_timer_refused_for_rate_is_started_again(self): assert decision["decisionType"] == "ScheduleActivityTask" assert decision["scheduleActivityTaskDecisionAttributes"]["activityId"] == RETRIED_ACTIVITY_ID + def test_a_retry_timer_refused_for_too_many_open_timers_waits_for_the_next_decision(self): + for earlier_retries in (0, 1): + with self.subTest(earlier_retries=earlier_retries): + history, retry_timer = history_with_a_refused_retry_timer("OPEN_TIMERS_LIMIT_EXCEEDED", earlier_retries) + + assert replay_decisions(RetryLaterWorkflow, history) == [] + + history.add_decision_task_timed_out() + history.add_decision_task_scheduled() + history.add_decision_task_started() + + assert replay_decisions(RetryLaterWorkflow, history) == [] + + wake_up(history) + + assert replay_decisions(RetryLaterWorkflow, history) == [retry_timer] + 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): From e784a94d5df06460baa83bcdbb46c7a91f990353 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sun, 29 Nov 2026 02:16:57 +0100 Subject: [PATCH 11/12] Tests: import moto before any test module creates a boto3 client tests.data.constants builds DOMAIN = Domain("TestDomain") at import, which creates the SWF boto3 client and caches it for the process (boto3_utils.get_or_create_boto3_client). moto 4 hooks into botocore when it is imported and only stubs clients created after that. When the first test module imports tests.data.constants before anything imports moto, every later @mock_swf test reuses an unstubbed client and calls the real SWF endpoint, failing with UnrecognizedClientException (with the fake keys from pytest's env) or worse with real credentials. Two orders hit it: test_executor.py run alone (3 MockSWFTestCase tests), and test_executor.py with test_dataflow.py under -k "Refused or schedule_failed" (test_activity_not_found_schedule_failed). The full run passed only because an earlier module imported moto first. tests/conftest.py imports moto, and pytest loads it before any test module. Co-Authored-By: Claude Opus 5.5 --- tests/conftest.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 tests/conftest.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..20f50125 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,4 @@ +from __future__ import annotations + +# moto only stubs boto3 clients created after its import, and tests.data.constants creates one at import. +import moto # noqa: F401 From 130497c6366d6c75a405e2be5f2f3a67ee1800a8 Mon Sep 17 00:00:00 2001 From: Yves Bastide Date: Sun, 29 Nov 2026 02:16:58 +0100 Subject: [PATCH 12/12] Tests: restore simpleflow.settings after TestSettings test_overriding_a_setting left METROLOGY_PATH_PREFIX = "123" (and test_change_multiple_settings left FOO and BAR) in simpleflow.settings for the rest of the process. test_metrology, run after it, uploaded under 123/local/local/ and read local/local/activity.0.json back: HeadObject 404. The default order runs test_metrology.py before test_simpleflow/, which is why it passed. setUp patches the module's namespace with mock.patch.dict and swaps _keys for a copy, since put_setting adds to it in place. Co-Authored-By: Claude Opus 5.5 --- tests/test_simpleflow/test_settings.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/test_simpleflow/test_settings.py b/tests/test_simpleflow/test_settings.py index 6a7ca218..41253b5d 100644 --- a/tests/test_simpleflow/test_settings.py +++ b/tests/test_simpleflow/test_settings.py @@ -1,11 +1,19 @@ from __future__ import annotations import unittest +from unittest import mock from simpleflow import settings class TestSettings(unittest.TestCase): + def setUp(self): + patcher = mock.patch.dict(vars(settings)) + patcher.start() + self.addCleanup(patcher.stop) + # put_setting adds to _keys in place: give it a copy, which the patch restores. + settings._keys = set(settings._keys) + def test_overriding_a_setting(self): assert settings.METROLOGY_PATH_PREFIX is None