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
140 changes: 140 additions & 0 deletions src/durable_workflow/_condition_input_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""Canonical input positions for condition predicate replay."""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any

CAPABILITY = "condition_wait_input_order"
AUTHORING = "condition_wait_input_order_authoring"
ORDER = "durable_receipt_order"
PENDING_INPUT = "condition_wait_pending_input_sequence"


def marked(payload: Mapping[str, Any]) -> bool:
return payload.get(CAPABILITY) == ORDER


def positive_sequence(value: Any) -> int | None:
return value if type(value) is int and value > 0 else None


@dataclass(frozen=True)
class CompetingSelection:
terminal_id: str
sequence: int


def competing_selection(events: Sequence[Mapping[str, Any]], group_id: str) -> CompetingSelection | None:
candidates = [
(event, payload) for event in events
if event.get("event_type", event.get("type")) == "SelectionCandidateReady"
and isinstance(payload := event.get("payload"), Mapping)
and payload.get("selection_group_id") == group_id
]
if not candidates:
return None
if len(candidates) != 1:
raise ValueError("an ordered selection has more than one competing terminal event")
candidate, payload = candidates[0]
terminal_id = payload.get("resolution_event_id")
sequence = positive_sequence(payload.get("resolution_event_sequence"))
if (not isinstance(terminal_id, str) or not terminal_id or sequence is None
or sequence >= (positive_sequence(candidate.get("sequence")) or 0)
or not any(
event.get("sequence") == sequence
and (event.get("id") or event.get("event_id")) == terminal_id
and event.get("event_type", event.get("type")) == payload.get("resolution_event_type")
for event in events
)):
raise ValueError("ordered selection candidate does not match its terminal history event")
return CompetingSelection(terminal_id, sequence)


@dataclass
class Wait:
opening_sequence: int
scheduled_sequence: int | None = None
timer_id: str | None = None
fired_sequence: int | None = None
settled: bool | None = None
satisfying_receipt: int | None = None


@dataclass(frozen=True)
class History:
waits: dict[str, Wait]
applied_signal_receipts: frozenset[int]
update_receipts: dict[int, int]


def read(events: Sequence[Mapping[str, Any]]) -> History:

Check failure on line 72 in src/durable_workflow/_condition_input_order.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 57 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-python&issues=AaIKsTqePWUT3T_M538a&open=AaIKsTqePWUT3T_M538a&pullRequest=375
if not any(
event.get("event_type", event.get("type")) == "ConditionWaitOpened"
and isinstance(event.get("payload"), Mapping) and marked(event["payload"])
for event in events
):
return History({}, frozenset(), {})
waits: dict[str, Wait] = {}
receipts: dict[tuple[str, str], int] = {}
applied_signals: set[int] = set()
update_receipts: dict[int, int] = {}
for event in events:
kind = event.get("event_type", event.get("type"))
payload = event.get("payload")
if not isinstance(payload, Mapping):
continue
sequence = positive_sequence(event.get("sequence"))
command_id = event.get("workflow_command_id") or payload.get("workflow_command_id")
if sequence is not None and isinstance(command_id, str) and command_id:
if kind in ("SignalReceived", "UpdateAccepted"):
receipts.setdefault((kind, command_id), sequence)
elif kind == "SignalApplied":
receipt = receipts.get(("SignalReceived", command_id))
if receipt is not None:
applied_signals.add(receipt)
elif kind == "UpdateApplied":
receipt = receipts.get(("UpdateAccepted", command_id))
if receipt is not None:
update_receipts[sequence] = receipt
wait_id = payload.get("condition_wait_id")
if not isinstance(wait_id, str) or not wait_id:
continue
if kind == "ConditionWaitOpened" and marked(payload):
if sequence is None or wait_id in waits:
raise ValueError("ordered condition has an invalid opening sequence or repeated identity")
waits[wait_id] = Wait(sequence)
wait = waits.get(wait_id)
if wait is None:
continue
if kind == "TimerScheduled":
timer = payload.get("timer_id")
if (not marked(payload) or payload.get("timer_kind") != "condition_timeout"
or sequence is None or sequence <= wait.opening_sequence or not isinstance(timer, str)
or not timer or wait.scheduled_sequence is not None):
raise ValueError("ordered condition timer does not match its opening")
wait.scheduled_sequence = sequence
wait.timer_id = timer
elif kind == "TimerFired":
if (not marked(payload) or payload.get("timer_id") != wait.timer_id
or payload.get("timer_kind") != "condition_timeout" or wait.scheduled_sequence is None
or sequence is None or sequence <= wait.scheduled_sequence or wait.fired_sequence is not None):
raise ValueError("ordered condition fire does not match its original timer")
wait.fired_sequence = sequence
elif kind in ("ConditionWaitSatisfied", "ConditionWaitTimedOut"):
satisfied = kind == "ConditionWaitSatisfied"
receipt = positive_sequence(payload.get("input_receipt_sequence"))
if (not marked(payload) or wait.settled is not None or sequence is None
or sequence <= (wait.fired_sequence or wait.opening_sequence)
or payload.get("timer_fired_sequence") != wait.fired_sequence
or (receipt is not None and receipt >= sequence)
or (not satisfied and (wait.fired_sequence is None or receipt is not None))
or (satisfied and wait.fired_sequence is not None
and (receipt is None or receipt >= wait.fired_sequence))):
raise ValueError("ordered condition outcome does not match its original input boundary")
wait.settled = satisfied
wait.satisfying_receipt = receipt
if any(wait.scheduled_sequence is None for wait in waits.values()):
raise ValueError("ordered condition is missing its original timer schedule")
return History(waits, frozenset(applied_signals), update_receipts)
27 changes: 26 additions & 1 deletion src/durable_workflow/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

import httpx

from . import _continue_as_new, serializer
from . import _condition_input_order, _continue_as_new, serializer
from ._activity_lease import (
ACTIVITY_LEASE_RENEWAL_EXHAUSTED,
ActivityLeaseAuthority,
Expand Down Expand Up @@ -1477,6 +1477,7 @@ def __init__(
self._query_tasks_supported = False
self._workflow_memo_updates_supported = False
self._signal_external_workflow_supported = False
self._ordered_condition_inputs_supported = False
self._update_validation_tasks_supported = False
self._query_thread_stop = threading.Event()
self._query_thread: threading.Thread | None = None
Expand Down Expand Up @@ -1711,6 +1712,9 @@ async def _register(self) -> None:
"Server query_task_authority=true before registration")
self._workflow_memo_updates_supported = _server_supports_workflow_memo_updates(info)
self._signal_external_workflow_supported = _server_supports_signal_external_workflow(info)
self._ordered_condition_inputs_supported = (
isinstance(server_capabilities, Mapping) and _condition_input_order.marked(server_capabilities)
)
has_update_validators = any(
contract["update_validators"] for contract in self.workflow_command_contracts.values()
)
Expand Down Expand Up @@ -1738,6 +1742,8 @@ async def _register(self) -> None:
if any(contract["updates"] for contract in self.workflow_command_contracts.values()):
capabilities.append(WORKFLOW_UPDATES_CAPABILITY)
capabilities.append(MESSAGE_STREAMS_CAPABILITY)
if self._ordered_condition_inputs_supported:
capabilities.append(_condition_input_order.CAPABILITY)
capabilities.extend(self.capabilities)
if self._nexus_cooperative_cancellation_supported and "nexus_cooperative_cancellation" not in capabilities:
capabilities.append("nexus_cooperative_cancellation")
Expand Down Expand Up @@ -2126,6 +2132,13 @@ async def _replay_workflow_claim(
self, cls: type, task: dict[str, Any], history: list[dict[str, Any]], start_input: list[Any],
*, payload_codec: str | None, execute_local: Callable[[RecordLocalActivity], Any],
) -> tuple[ReplayOutcome, list[dict[str, Any]]]:
pending_condition_input: tuple[int | None] | None = None
if _condition_input_order.PENDING_INPUT in task:
raw_sequence = task[_condition_input_order.PENDING_INPUT]
sequence = _condition_input_order.positive_sequence(raw_sequence)
if raw_sequence is not None and sequence is None:
raise LocalActivityExecutionAborted("invalid ordered condition input snapshot")
pending_condition_input = (sequence,)
observation = task.get("cancellation_request")
if observation is not None:
observed = self._observe_workflow_cancellation(task, observation)
Expand Down Expand Up @@ -2158,6 +2171,9 @@ async def _replay_workflow_claim(
allow_cancellation_scope_delivery=self._allow_cancellation_scope_delivery,
record_parallel_failure_order=self.record_parallel_failure_order,
allow_continue_as_new_target_build=self._continue_as_new_target_build_supported,
allow_ordered_condition_inputs=self._ordered_condition_inputs_supported,
author_ordered_condition_inputs=task.get(_condition_input_order.AUTHORING) is True,
pending_condition_input=pending_condition_input,
)
if outcome.cancellation_scope_delivery is not None:
if outcome.commands:
Expand Down Expand Up @@ -3199,6 +3215,15 @@ def execute_local(command: RecordLocalActivity) -> Any:
return None

workflow_commands = list(outcome.commands)
if not workflow_commands and _condition_input_order.PENDING_INPUT in task:
await self.client.fail_workflow_task(
task_id=task_id,
lease_owner=self.worker_id,
workflow_task_attempt=attempt,
message="Workflow task waiting for scheduled history.",
failure_type="WorkflowTaskWaitingForHistory",
)
return None

if (
any(isinstance(command, UpsertMemo) for command in workflow_commands)
Expand Down
Loading