diff --git a/simpleflow/history.py b/simpleflow/history.py index de1bc071a..4408b26b5 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: @@ -254,13 +260,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": @@ -342,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, @@ -352,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: @@ -370,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( @@ -486,7 +496,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, @@ -807,6 +817,8 @@ def get_event_id(event: dict[str, Any]) -> int | None: "event_id", "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 a4f5d8b15..b8129f149 100644 --- a/simpleflow/swf/executor.py +++ b/simpleflow/swf/executor.py @@ -46,6 +46,23 @@ 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", + } +) +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" @@ -247,14 +264,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": @@ -278,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}") @@ -289,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. @@ -301,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": @@ -371,7 +370,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"], @@ -476,10 +475,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: @@ -515,8 +517,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: """ @@ -557,9 +563,18 @@ 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_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) - if not future: # schedule failed, maybe OK later. - return None if not future.finished: # Still pending or running... return future @@ -569,15 +584,97 @@ 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_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: + """ + 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"] + cause = event["cause"] + count = event[f"{refusal}_count"] + if cause not in transient_causes: + logger.info(f"{refusal}: {name}: {cause}") + 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 + 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() + 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: + 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 + def resume_child_workflow(self, a_workflow: WorkflowTask, event: dict[str, Any]) -> futures.Future | None: """ 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 @@ -623,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/simpleflow/swf/helpers.py b/simpleflow/swf/helpers.py index eb4940629..2b5ea41bd 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/mapper/models/event/task.py b/simpleflow/swf/mapper/models/event/task.py index d42241138..90f4a14c5 100644 --- a/simpleflow/swf/mapper/models/event/task.py +++ b/simpleflow/swf/mapper/models/event/task.py @@ -58,7 +58,11 @@ class ActivityTaskEventDict(TypedDict): result: Any reason: str | None details: str | None - cancelled_timestamp: datetime + canceled_id: int + canceled_timestamp: datetime + schedule_failed_id: int + schedule_failed_timestamp: datetime + schedule_failed_count: int class CompiledActivityTaskEvent(CompiledEvent): diff --git a/simpleflow/swf/mapper/models/history/builder.py b/simpleflow/swf/mapper/models/history/builder.py index 7a99b6230..08b737900 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, @@ -418,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 @@ -681,6 +742,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( @@ -778,6 +856,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/simpleflow/swf/stats/pretty.py b/simpleflow/swf/stats/pretty.py index 4e11d4613..6d4d636ee 100644 --- a/simpleflow/swf/stats/pretty.py +++ b/simpleflow/swf/stats/pretty.py @@ -96,22 +96,27 @@ 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") + + 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 = 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"] + 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() @@ -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/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..20f501259 --- /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 diff --git a/tests/test_simpleflow/swf/stats/test_pretty.py b/tests/test_simpleflow/swf/stats/test_pretty.py index 8c0c74f2e..637115424 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,131 @@ 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"] == {} + + +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 + + +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]} diff --git a/tests/test_simpleflow/swf/test_executor.py b/tests/test_simpleflow/swf/test_executor.py index 3baa01401..db96196a8 100644 --- a/tests/test_simpleflow/swf/test_executor.py +++ b/tests/test_simpleflow/swf/test_executor.py @@ -2,10 +2,12 @@ import re import unittest +from typing import ClassVar from unittest import mock from simpleflow import activity, exceptions, format, futures from simpleflow.canvas import Group +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 @@ -140,6 +142,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): @@ -304,6 +323,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 @@ -387,6 +415,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") @@ -505,6 +588,610 @@ def test_an_optional_use_elsewhere_leaves_the_child_workflow_mandatory(self): assert replay_after_a_failure(MandatoryChildUseWorkflow) == "FailWorkflowExecution" +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" + + +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(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_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()) + + +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 + + +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: diff --git a/tests/test_simpleflow/test_helpers.py b/tests/test_simpleflow/test_helpers.py index f1b70e31e..2cfcb7693 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) diff --git a/tests/test_simpleflow/test_settings.py b/tests/test_simpleflow/test_settings.py index 6a7ca2186..41253b5db 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