Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions simpleflow/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand All @@ -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(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
184 changes: 143 additions & 41 deletions simpleflow/swf/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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":
Expand All @@ -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}")
Expand All @@ -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.
Expand All @@ -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":
Expand Down Expand Up @@ -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"],
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions simpleflow/swf/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 5 additions & 1 deletion simpleflow/swf/mapper/models/event/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading