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
6 changes: 4 additions & 2 deletions simpleflow/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,10 +758,12 @@ def parse_timer_event(self, events: list[Event], event: TimerEvent):
"cancel_decision_task_completed_event_id": event.decision_task_completed_event_id,
}
self._timers[event.timer_id] = timer
# A cancel that lost the race (TIMER_ID_UNKNOWN) must not hide a fire, cancel or start failure.
if timer.get("state", "started") == "started":
timer["state"] = event.state
timer.update(
{
"state": event.state,
"cause": event.cause,
"cancel_failed_cause": event.cause,
"cancel_failed_event_id": event.id,
"cancel_failed_event_timestamp": event.timestamp,
}
Expand Down
38 changes: 34 additions & 4 deletions simpleflow/swf/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ def get_future_from_external_workflow_event(self, a_task: WorkflowTask, event: d
elif state == "signal_execution_failed":
future.set_exception(
exceptions.TaskFailed(
name=event["name"],
name=event["signal_name"],
reason=event["cause"],
)
)
Expand All @@ -436,13 +436,20 @@ def _get_future_from_timer_event(self, a_task: TimerTask, event: dict[str, Any])
future.set_finished(None)
elif state == "canceled":
future.set_cancelled()
elif state in ("start_failed", "cancel_failed"):
elif state == "start_failed":
future.set_exception(
exceptions.TaskFailed(
name=event["id"],
reason=event["cause"],
)
)
elif state == "cancel_failed":
future.set_exception(
exceptions.TaskFailed(
name=event["id"],
reason=event["cancel_failed_cause"],
)
)

return future

Expand Down Expand Up @@ -477,8 +484,27 @@ def find_signal_event(self, a_task: SignalTask, history: History) -> dict[str, A
if w["workflow_id"] == a_task.workflow_id and (a_task.run_id is None or w["run_id"] == a_task.run_id):
event = w
break
else:
# Not delivered: the latest send still in flight or refused, if any
for w in history.external_workflows_signaling.values():
if (
w["signal_name"] == a_task.name
and w["id"] == a_task.workflow_id
and (a_task.run_id is None or w["run_id"] == a_task.run_id)
):
event = w
if event and self.is_transient_signal_failure(event):
return None
return event

TRANSIENT_SIGNAL_FAILED_CAUSES: ClassVar[frozenset[str]] = frozenset(
{"SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_RATE_EXCEEDED"}
)

@classmethod
def is_transient_signal_failure(cls, event: dict[str, Any]) -> bool:
return event["state"] == "signal_execution_failed" and event["cause"] in cls.TRANSIENT_SIGNAL_FAILED_CAUSES

def find_marker_event(self, a_task: MarkerTask, history: History) -> dict[str, Any] | None:
"""
Get the event corresponding to a marker, if any.
Expand Down Expand Up @@ -1214,7 +1240,7 @@ def wait_signal(self, name):
def propagate_signals(self):
"""
Send every signals we got to our parent and children.
Don't send to workflows present in history.signaled_workflows.
Don't send to workflows this one already signaled, is signaling or was refused.
"""
history = self._history
if not history.signals:
Expand Down Expand Up @@ -1248,7 +1274,11 @@ def propagate_signals(self):
args = input.get("args", ())
kwargs = input.get("kwargs", {})
sender = (signal["external_workflow_id"], signal["external_run_id"])
signaled_workflows_ids = {(w["workflow_id"], w["run_id"]) for w in history.signaled_workflows[name]}
signaled_workflows_ids = {
(w["id"], w["run_id"])
for w in history.external_workflows_signaling.values()
if w["signal_name"] == name and not self.is_transient_signal_failure(w)
}
not_signaled_workflows_ids = list(known_workflows_ids - signaled_workflows_ids - {sender})
extra_input = {"__propagate": propagate}
for workflow_id, run_id in not_signaled_workflows_ids:
Expand Down
65 changes: 64 additions & 1 deletion simpleflow/swf/mapper/models/history/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,68 @@ def add_signal(self, name, input=None, external_event_id=0):

return self

def add_signal_execution_initiated(
self, workflow_id, signal_name, input=None, run_id=None, control=None, decision_id=0
):
d = {
"decisionTaskCompletedEventId": decision_id,
"input": json_dumps(input) if input is not None else "{}",
"signalName": signal_name,
"workflowId": workflow_id,
}
if run_id is not None:
d["runId"] = run_id
if control is not None:
d["control"] = json_dumps(control)
self.events.append(
EventFactory(
{
"eventId": self.next_id,
"eventTimestamp": new_timestamp_string(),
"eventType": "SignalExternalWorkflowExecutionInitiated",
"signalExternalWorkflowExecutionInitiatedEventAttributes": d,
}
)
)
return self

def add_external_workflow_signaled(self, initiated_id, workflow_id, run_id):
self.events.append(
EventFactory(
{
"eventId": self.next_id,
"eventTimestamp": new_timestamp_string(),
"eventType": "ExternalWorkflowExecutionSignaled",
"externalWorkflowExecutionSignaledEventAttributes": {
"initiatedEventId": initiated_id,
"workflowExecution": {"workflowId": workflow_id, "runId": run_id},
},
}
)
)
return self

def add_signal_execution_failed(self, initiated_id, workflow_id, cause, run_id=None, decision_id=0):
d = {
"cause": cause,
"decisionTaskCompletedEventId": decision_id,
"initiatedEventId": initiated_id,
"workflowId": workflow_id,
}
if run_id is not None:
d["runId"] = run_id
self.events.append(
EventFactory(
{
"eventId": self.next_id,
"eventTimestamp": new_timestamp_string(),
"eventType": "SignalExternalWorkflowExecutionFailed",
"signalExternalWorkflowExecutionFailedEventAttributes": d,
}
)
)
return self

def add_marker(self, name, details=None):
self.events.append(
EventFactory(
Expand Down Expand Up @@ -786,7 +848,7 @@ def add_timer_cancel_failed(self, timer_id, cause, decision_id=0):
)
return self

def add_timer_canceled(self, timer_id, started_timer_id=0):
def add_timer_canceled(self, timer_id, started_timer_id=0, decision_id=0):
self.events.append(
EventFactory(
{
Expand All @@ -796,6 +858,7 @@ def add_timer_canceled(self, timer_id, started_timer_id=0):
"timerCanceledEventAttributes": {
"timerId": timer_id,
"startedEventId": started_timer_id,
"decisionTaskCompletedEventId": decision_id,
},
}
)
Expand Down
195 changes: 195 additions & 0 deletions tests/test_simpleflow/swf/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,60 @@ def test_a_failed_timer_cancel_replays_as_a_failed_future(self):
assert future.exception.name == "a_timer"
assert future.exception.reason == "TIMER_ID_UNKNOWN"

def test_a_timer_cancel_refused_after_the_fire_keeps_the_timer_fired(self):
history = builder.History(CancelTimerWorkflow, input={})
history.add_timer_started("a_timer", 10, decision_id=2)
history.add_timer_fired("a_timer")
history.add_decision_task()
history.add_timer_cancel_failed("a_timer", "TIMER_ID_UNKNOWN", decision_id=history.last_id)
history.add_decision_task_scheduled()
history.add_decision_task_started()

for workflow in (StartTimerWorkflow, CancelTimerWorkflow):
with self.subTest(workflow=workflow.__name__):
workflow.future = None
executor = Executor(DOMAIN, workflow)
decisions = executor.replay(Response(history=history, execution=None)).decisions

assert [d["decisionType"] for d in decisions] == ["CompleteWorkflowExecution"]
future = workflow.future
assert future.finished
assert future.exception is None
timer = executor.get_event_details("timer", "a_timer")
assert timer["state"] == "fired"
assert timer["cancel_failed_cause"] == "TIMER_ID_UNKNOWN"
assert "cause" not in timer

def test_a_second_timer_cancel_refused_keeps_the_timer_canceled(self):
history = builder.History(StartTimerWorkflow, input={})
history.add_timer_started("a_timer", 10, decision_id=2)
history.add_decision_task()
history.add_timer_canceled("a_timer", decision_id=history.last_id)
history.add_timer_cancel_failed("a_timer", "TIMER_ID_UNKNOWN", decision_id=history.last_id - 1)
history.add_decision_task_scheduled()
history.add_decision_task_started()

StartTimerWorkflow.future = None
executor = Executor(DOMAIN, StartTimerWorkflow)
executor.replay(Response(history=history, execution=None))

assert StartTimerWorkflow.future.cancelled
assert executor.get_event_details("timer", "a_timer")["state"] == "canceled"

def test_a_timer_cancel_refused_after_a_refused_start_keeps_the_start_failure(self):
history = builder.History(StartTimerWorkflow, input={})
history.add_timer_start_failed("a_timer", "OPEN_TIMERS_LIMIT_EXCEEDED", decision_id=2)
history.add_decision_task()
history.add_timer_cancel_failed("a_timer", "TIMER_ID_UNKNOWN", decision_id=history.last_id)

executor = Executor(DOMAIN, StartTimerWorkflow)
executor.replay(Response(history=history, execution=None))

timer = executor.get_event_details("timer", "a_timer")
assert timer["state"] == "start_failed"
assert timer["cause"] == "OPEN_TIMERS_LIMIT_EXCEEDED"
assert timer["cancel_failed_cause"] == "TIMER_ID_UNKNOWN"

def test_get_event_details(self):
history = builder.History(ExampleWorkflow, input={})
signal_input = {"x": 42, "foo": "bar", "__propagate": False}
Expand Down Expand Up @@ -170,6 +224,147 @@ def test_get_event_details(self):
assert details is None


class SendSignalWorkflow(BaseTestWorkflow):
future = None

def run(self):
type(self).future = self.submit(self.signal("a_signal", workflow_id="target-wf", run_id="target-run"))
futures.wait(type(self).future)


class PropagateSignalsWorkflow(BaseTestWorkflow):
def run(self):
pass


def signal_decisions(decisions):
return [d for d in decisions if d["decisionType"] == "SignalExternalWorkflowExecution"]


class TestSentSignalReplay(unittest.TestCase):
def history_with_a_sent_signal(self):
history = builder.History(SendSignalWorkflow, input={})
executor = Executor(DOMAIN, SendSignalWorkflow)
(decision,) = signal_decisions(executor.replay(Response(history=history, execution=None)).decisions)
attributes = decision["signalExternalWorkflowExecutionDecisionAttributes"]
history.add_decision_task_completed()
history.add_signal_execution_initiated(
attributes["workflowId"],
attributes["signalName"],
input=format.decode(attributes["input"]),
run_id=attributes["runId"],
decision_id=history.last_id,
)
return history, history.last_id

def replay(self, history):
history.add_decision_task_scheduled()
history.add_decision_task_started()
SendSignalWorkflow.future = None
executor = Executor(DOMAIN, SendSignalWorkflow)
decisions = executor.replay(Response(history=history, execution=None)).decisions
return executor, decisions, SendSignalWorkflow.future

def test_a_signal_in_flight_is_not_sent_again(self):
history, _ = self.history_with_a_sent_signal()

executor, decisions, future = self.replay(history)

assert [w["state"] for w in executor._history.external_workflows_signaling.values()] == [
"signal_execution_initiated"
]
assert signal_decisions(decisions) == []
assert not future.done

def test_a_refused_signal_is_not_sent_again_and_fails_its_future(self):
history, initiated_id = self.history_with_a_sent_signal()
history.add_signal_execution_failed(
initiated_id, "target-wf", "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION", run_id="target-run"
)

executor, decisions, future = self.replay(history)

assert [w["state"] for w in executor._history.external_workflows_signaling.values()] == [
"signal_execution_failed"
]
assert signal_decisions(decisions) == []
assert future.finished
assert isinstance(future.exception, exceptions.TaskFailed)
assert future.exception.name == "a_signal"
assert future.exception.reason == "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION"

def test_a_delivered_signal_finishes_its_future(self):
history, initiated_id = self.history_with_a_sent_signal()
history.add_external_workflow_signaled(initiated_id, "target-wf", "target-run")

_, decisions, future = self.replay(history)

assert signal_decisions(decisions) == []
assert future.finished
assert future.exception is None

def test_a_rate_limited_signal_is_sent_again(self):
history, initiated_id = self.history_with_a_sent_signal()
history.add_signal_execution_failed(
initiated_id, "target-wf", "SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_RATE_EXCEEDED", run_id="target-run"
)

_, decisions, future = self.replay(history)

(decision,) = signal_decisions(decisions)
assert decision["signalExternalWorkflowExecutionDecisionAttributes"]["workflowId"] == "target-wf"
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")
child_run_id = history.events[-1].workflow_execution["runId"]
history.add_signal("a_signal", {"args": [], "kwargs": {}, "__propagate": True})
history.add_decision_task_scheduled()
history.add_decision_task_started()

(decision,) = self.replay_propagation(history)
attributes = decision["signalExternalWorkflowExecutionDecisionAttributes"]
assert (attributes["workflowId"], attributes["runId"]) == ("child-wf", child_run_id)

history.add_decision_task_completed()
history.add_signal_execution_initiated(
"child-wf",
"a_signal",
input=format.decode(attributes["input"]),
run_id=child_run_id,
decision_id=history.last_id,
)
initiated_id = history.last_id
history.add_decision_task_scheduled()
history.add_decision_task_started()
return history, initiated_id, child_run_id, decision

@staticmethod
def replay_propagation(history):
executor = Executor(DOMAIN, PropagateSignalsWorkflow)
return signal_decisions(executor.replay(Response(history=history, execution=None)).decisions)

def test_a_propagated_signal_in_flight_is_not_sent_again(self):
history, _, _, _ = self.history_with_a_propagated_signal_in_flight()

assert self.replay_propagation(history) == []

def test_a_refused_propagated_signal_is_sent_again_only_if_rate_limited(self):
for cause, sent_again in (
("UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION", False),
("SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_RATE_EXCEEDED", True),
):
with self.subTest(cause=cause):
history, initiated_id, child_run_id, decision = self.history_with_a_propagated_signal_in_flight()
history.add_decision_task_completed()
history.add_signal_execution_failed(initiated_id, "child-wf", cause, run_id=child_run_id)
history.add_decision_task_scheduled()
history.add_decision_task_started()

assert self.replay_propagation(history) == ([decision] if sent_again else [])


@activity.with_attributes(raises_on_failure=True)
def print_me_n_times(s, n, raises=False):
if raises:
Expand Down