diff --git a/src/durable_workflow/_condition_input_order.py b/src/durable_workflow/_condition_input_order.py new file mode 100644 index 0000000..428f38e --- /dev/null +++ b/src/durable_workflow/_condition_input_order.py @@ -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: + 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) diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index 52458a1..6844ea5 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -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, @@ -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 @@ -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() ) @@ -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") @@ -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) @@ -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: @@ -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) diff --git a/src/durable_workflow/workflow.py b/src/durable_workflow/workflow.py index fc73ae1..0924c92 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -36,7 +36,7 @@ from pathlib import PureWindowsPath from typing import Any, TypeVar, cast -from . import replay_clock, serializer +from . import _condition_input_order, replay_clock, serializer from ._cancellation_scope import CancellationScopeHistory, scope_identity from ._cancellation_scope_history import ( CancellationScopeDeliveryIntent, @@ -1874,6 +1874,7 @@ class WaitCondition: condition_definition_fingerprint: str | None = None timeout_seconds: int | None = None condition_wait_occurrence_id: str | None = None + _ordered_inputs: bool = field(default=False, init=False, repr=False, compare=False) _cancellation_scope_id: str = field( default_factory=_authored_cancellation_scope, init=False, repr=False, compare=False, ) @@ -1899,6 +1900,10 @@ def to_server_command( cmd["condition_definition_fingerprint"] = self.condition_definition_fingerprint if self.timeout_seconds is not None: cmd["timeout_seconds"] = self.timeout_seconds + if self._ordered_inputs: + cmd[_condition_input_order.CAPABILITY] = _condition_input_order.ORDER + cmd["deadline_policy"] = "occurrence" + cmd["condition_wait_timeout_budget_seconds"] = self.timeout_seconds if self.condition_wait_occurrence_id is not None: cmd["condition_wait_occurrence_id"] = self.condition_wait_occurrence_id return cmd @@ -1992,6 +1997,24 @@ def to_server_command( } +@dataclass(frozen=True) +class _ResolveConditionWait: + wait_id: str + satisfied: bool + receipt: int | None + competing_resolution_event_id: str | None = None + + def to_server_command(self, task_queue: str, **_: Any) -> dict[str, Any]: + command: dict[str, Any] = { + "type": "resolve_condition_wait", "condition_wait_id": self.wait_id, "satisfied": self.satisfied, + } + if self.receipt is not None: + command["input_receipt_sequence"] = self.receipt + if self.competing_resolution_event_id is not None: + command["competing_resolution_event_id"] = self.competing_resolution_event_id + return command + + def _condition_predicate_fingerprint(predicate: Callable[[], bool]) -> str | None: """The stable v2 predicate fingerprint, or None without source (#258).""" return _stable_condition_fingerprint(predicate) @@ -2001,7 +2024,7 @@ def _condition_predicate_fingerprint(predicate: Callable[[], bool]) -> str | Non ScheduleActivity | RecordLocalActivity | StartTimer | CompleteWorkflow | FailWorkflow | CompleteUpdate | FailUpdate | ContinueAsNew | RecordSideEffect | StartChildWorkflow | NexusServiceCall | RecordVersionMarker | UpsertMemo | UpsertSearchAttributes | WaitCondition - | CancelDurableOperation | SignalExternalWorkflow + | CancelDurableOperation | SignalExternalWorkflow | _ResolveConditionWait ) @@ -3486,6 +3509,7 @@ class _PendingReceiver: args: list[Any] condition_wait_id: str | None = None after_cancellation_delivery: bool = False + receipt_sequence: int | None = None @dataclass(frozen=True) @@ -3803,6 +3827,9 @@ def replay( allow_cancellation_scope_delivery: bool = False, record_parallel_failure_order: bool = False, allow_continue_as_new_target_build: bool = False, + allow_ordered_condition_inputs: bool = False, + author_ordered_condition_inputs: bool = False, + pending_condition_input: tuple[int | None] | None = None, ) -> ReplayOutcome: """Replay ``history_events`` and return the next commands. @@ -3832,6 +3859,9 @@ def replay( allow_cancellation_scope_delivery=allow_cancellation_scope_delivery, record_parallel_failure_order=record_parallel_failure_order, allow_continue_as_new_target_build=allow_continue_as_new_target_build, + allow_ordered_condition_inputs=allow_ordered_condition_inputs, + author_ordered_condition_inputs=author_ordered_condition_inputs, + pending_condition_input=pending_condition_input, ).outcome @@ -5373,6 +5403,9 @@ def _replay_state( parallel_group_policies: tuple[str, ...] = (), record_parallel_failure_order: bool = False, allow_continue_as_new_target_build: bool = False, + allow_ordered_condition_inputs: bool = False, + author_ordered_condition_inputs: bool = False, + pending_condition_input: tuple[int | None] | None = None, ) -> _ReplayState: _validate_workflow_entrypoint(workflow_cls) _workflow_handler_registries(workflow_cls) @@ -5404,6 +5437,7 @@ def _replay_state( # an all() group and never supplies replay time: the workflow had closed # past it. Every history reader below sees the activity as still open. events = [event for event in retained_events if not _settled_at_close(event)] + ordered_condition_history = _condition_input_order.read(events) if len(events) != len(retained_events): recorded_group_policies = _read_parallel_group_policies(events, parallel_group_policies) # A malformed delivery span refuses replay before any history parser can @@ -6117,6 +6151,8 @@ def _receiver_binding_boundary_kind(event_type: str | None, payload: Mapping[str ) == "condition_timeout" ): + if _condition_input_order.marked(payload): + return None return "condition" if event_type in ( "WorkflowCompleted", @@ -6150,6 +6186,7 @@ def _receiver_binding_boundary_kind(event_type: str | None, payload: Mapping[str def _receiver_condition_wait_bindings() -> dict[int, str | None]: bindings: dict[int, str | None] = {} + active_ordered_waits: dict[str, None] = {} prefix_receivers: list[int] = [] prefix_can_bind_to_first_wait = True current_wait_id: str | None = None @@ -6166,6 +6203,8 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: if not isinstance(wait_id, str) or not wait_id: continue condition_wait_opened_indexes.setdefault(wait_id, index) + if wait_id in ordered_condition_history.waits: + active_ordered_waits[wait_id] = None if current_wait_id is None: for receiver_index in prefix_receivers: @@ -6188,6 +6227,9 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: continue if _is_external_receiver_event(event_type): + if active_ordered_waits: + bindings[index] = next(reversed(active_ordered_waits)) + continue explicit_sequence = _workflow_sequence(payload) explicit_selected_wait_id = ( selected_condition_wait_ids_by_sequence.get(explicit_sequence) @@ -6217,6 +6259,10 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: continue boundary_kind = _receiver_binding_boundary_kind(event_type, payload) + if event_type in ("ConditionWaitSatisfied", "ConditionWaitTimedOut", "ConditionWaitCancelled"): + wait_id = payload.get("condition_wait_id") + if isinstance(wait_id, str): + active_ordered_waits.pop(wait_id, None) if boundary_kind is None: continue @@ -6336,6 +6382,8 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: condition_wait_ids_by_sequence, ) if wait_id is not None: + if wait_id in ordered_condition_history.waits: + continue condition_wait_terminal_indexes.setdefault(wait_id, event_index) if not _append_selection_condition_resolution(ev, wait_id, False): wait_resolutions[wait_id] = "timed_out" @@ -6526,6 +6574,10 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: condition_wait_id = condition_wait_ids_by_sequence.get(workflow_sequence) else: condition_wait_id = None + receipt_sequence = _condition_input_order.positive_sequence(ev.get("sequence")) + if (condition_wait_id in ordered_condition_history.waits + and receipt_sequence not in ordered_condition_history.applied_signal_receipts): + continue pending_receivers.append(_PendingReceiver( history_index=event_index, result_index=len(resolved_results), @@ -6543,6 +6595,7 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: external_storage_cache=external_storage_cache, ), condition_wait_id=condition_wait_id, + receipt_sequence=receipt_sequence, after_cancellation_delivery=( cancellation.delivery_index is not None and event_index > cancellation.delivery_index ), @@ -6550,6 +6603,11 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: elif etype == "UpdateApplied": update_name = payload.get("update_name") if isinstance(update_name, str) and update_name: + applied_sequence = _condition_input_order.positive_sequence(ev.get("sequence")) + receipt_sequence = ( + ordered_condition_history.update_receipts.get(applied_sequence) + if applied_sequence is not None else None + ) workflow_sequence = _workflow_sequence(payload) if event_index in receiver_condition_wait_ids: condition_wait_id = receiver_condition_wait_ids[event_index] @@ -6574,6 +6632,7 @@ def _receiver_condition_wait_bindings() -> dict[int, str | None]: external_storage_cache=external_storage_cache, ), condition_wait_id=condition_wait_id, + receipt_sequence=receipt_sequence, after_cancellation_delivery=( cancellation.delivery_index is not None and event_index > cancellation.delivery_index ), @@ -6666,6 +6725,88 @@ def _apply_condition_wait_receivers(condition_wait_id: str | None) -> None: for _ in range(boundary): _apply_receiver(pending_receivers.pop(0)) + def _ordered_condition_result( + wait_id: str, wait: _condition_input_order.Wait, predicate: Callable[[], bool], + competing: _condition_input_order.CompetingSelection | None = None, + ) -> tuple[bool | None, int | None, str | None]: + receivers = sorted( + (receiver for receiver in pending_receivers + if receiver.condition_wait_id == wait_id and receiver.receipt_sequence is not None), + key=lambda receiver: cast(int, receiver.receipt_sequence), + ) + consumed: set[int] = set() + + def apply(receiver: _PendingReceiver) -> None: + _apply_receiver(receiver) + consumed.add(id(receiver)) + + try: + if wait.settled is not None: + cutoff = ( + (wait.satisfying_receipt or wait.opening_sequence) + if wait.settled else cast(int, wait.fired_sequence) - 1 + ) + for receiver in receivers: + if cast(int, receiver.receipt_sequence) > cutoff: + break + apply(receiver) + return wait.settled, wait.satisfying_receipt, None + + if reconstruction_only: + for receiver in receivers: + apply(receiver) + return None, None, None + + if not allow_ordered_condition_inputs or pending_condition_input is None: + raise LocalActivityExecutionAborted("ordered condition replay requires the Server input snapshot") + first_pending = pending_condition_input[0] + terminal_boundary = min( + wait.fired_sequence if wait.fired_sequence is not None else math.inf, + competing.sequence if competing is not None else math.inf, + ) + boundary = min(first_pending, terminal_boundary) if first_pending is not None else terminal_boundary + eligible = [receiver for receiver in receivers if cast(int, receiver.receipt_sequence) < boundary] + entry_count = 0 + receipt: int | None = None + for receiver in eligible: + if cast(int, receiver.receipt_sequence) > wait.opening_sequence: + break + apply(receiver) + receipt = receiver.receipt_sequence + entry_count += 1 + + def evaluate() -> tuple[bool, Exception | None]: + try: + return bool(predicate()), None + except Exception as error: + return False, error + + satisfied, predicate_error = evaluate() + if satisfied and (receipt is not None or wait.fired_sequence is None): + return True, receipt, None + for receiver in eligible[entry_count:]: + apply(receiver) + satisfied, predicate_error = evaluate() + if satisfied: + return True, receiver.receipt_sequence, None + settled_prefix = first_pending is None or first_pending >= terminal_boundary + if settled_prefix and predicate_error is not None: + raise predicate_error + if settled_prefix and terminal_boundary != math.inf: + winner = ( + competing.terminal_id + if competing is not None and competing.sequence == terminal_boundary else None + ) + return False, None, winner + return None, None, None + finally: + pending_receivers[:] = [receiver for receiver in pending_receivers if id(receiver) not in consumed] + + def _release_ordered_condition_receivers(wait_id: str) -> None: + for receiver in pending_receivers: + if receiver.condition_wait_id == wait_id: + receiver.condition_wait_id = None + def _condition_wait_mismatch( opened: Mapping[str, Any], cmd: WaitCondition, ) -> NonDeterministicReplayError | None: @@ -8301,8 +8442,37 @@ def _advance_selection_clock(base: int, size: int, failure: BaseException | None has_recorded_member_history = True if marker is None: if has_recorded_member_history: + group_id = next(iter(handles.values())).selection_group_id + for sequence, leaf in enumerate(annotated, start=group_base): + if not isinstance(leaf, WaitCondition) or not selection_steps.get(sequence): + continue + wait_id = _selection_leaf_identity("condition", sequence) + wait = ordered_condition_history.waits.get(wait_id or "") + if wait is None or wait.settled is not None: + continue + try: + competing = _condition_input_order.competing_selection( + events, group_id, + ) + decision, receipt, competing_id = _ordered_condition_result( + wait_id, wait, leaf.predicate, competing, + ) + except LocalActivityExecutionAborted: + raise + except Exception as exc: + return _state([ + _fail_workflow_from_exception(exc, prefix="wait_condition predicate raised"), + ]) + if decision is not None: + pending.append( + _ResolveConditionWait(wait_id, decision, receipt, competing_id), + ) return _state(pending) _set_replaying(False) + if allow_ordered_condition_inputs and author_ordered_condition_inputs: + for leaf in annotated: + if isinstance(leaf, WaitCondition) and leaf.timeout_seconds is not None: + leaf._ordered_inputs = True pending.extend(annotated) return _state(pending) @@ -8375,7 +8545,13 @@ def _advance_selection_clock(base: int, size: int, failure: BaseException | None ): leaf = annotated[sequence - group_base] if isinstance(leaf, WaitCondition): - _apply_condition_wait_receivers(_selection_leaf_identity("condition", sequence)) + wait_id = _selection_leaf_identity("condition", sequence) + ordered_wait = ordered_condition_history.waits.get(wait_id or "") + if ordered_wait is None: + _apply_condition_wait_receivers(wait_id) + else: + _ordered_condition_result(wait_id, ordered_wait, leaf.predicate) + _release_ordered_condition_receivers(wait_id) next_value = SelectionResult( key=winner.key, index=winner.index, @@ -8764,6 +8940,11 @@ def _advance_selection_clock(base: int, size: int, failure: BaseException | None if step is not None: _assert_step_matches(cmd, step) _set_replaying(False) + cmd._ordered_inputs = ( + allow_ordered_condition_inputs + and author_ordered_condition_inputs + and cmd.timeout_seconds is not None + ) pending.append(cmd) return _state(pending) # Terminal cleanup may only skip a later open after this @@ -8815,6 +8996,29 @@ def _advance_selection_clock(base: int, size: int, failure: BaseException | None raise mismatch opened_id = opened.get("condition_wait_id") if isinstance(opened_id, str): + ordered_wait = ordered_condition_history.waits.get(opened_id) + if ordered_wait is not None: + try: + resolution_value, receipt, _ = _ordered_condition_result( + opened_id, ordered_wait, cmd.predicate, + ) + except LocalActivityExecutionAborted: + raise + except Exception as exc: + return _state([ + _fail_workflow_from_exception(exc, prefix="wait_condition predicate raised"), + ]) + if resolution_value is None: + return _state(pending) + if ordered_wait.settled is None: + pending.append(_ResolveConditionWait(opened_id, resolution_value, receipt)) + else: + _advance_cancellation_clock([condition_wait_terminal_indexes.get(opened_id)]) + _release_ordered_condition_receivers(opened_id) + terminal_condition_reopen_cmd = None + next_value = resolution_value + wait_yield_count += 1 + break resolution = wait_resolutions.get(opened_id) _apply_condition_wait_receivers(opened_id) if resolution is not None: diff --git a/tests/fixtures/replay_regressions/ordered-condition-early-signal-after-timer.json b/tests/fixtures/replay_regressions/ordered-condition-early-signal-after-timer.json new file mode 100644 index 0000000..cf475c2 --- /dev/null +++ b/tests/fixtures/replay_regressions/ordered-condition-early-signal-after-timer.json @@ -0,0 +1,104 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "python-ordered-condition-early-signal-after-timer", + "protocol_version": "1.20", + "bindings": [ + "python" + ], + "workflow": { + "type": "tests.ordered-condition-input", + "input": [], + "payload_codec": "avro" + }, + "worker_task": { + "condition_wait_pending_input_sequence": null + }, + "history": [ + { + "sequence": 3, + "event_type": "ConditionWaitOpened", + "payload": { + "condition_key": "approval", + "condition_definition_fingerprint": "dwpy2:sha256:3c3fa63e37a2afd9a6d1d658d11dca846beb98ff4f11f3fe365f505b5ada2b1a", + "timeout_seconds": 2, + "condition_wait_input_order": "durable_receipt_order", + "deadline_policy": "occurrence", + "condition_wait_timeout_budget_seconds": 2, + "condition_wait_occurrence_id": "python:condition-wait:0", + "condition_wait_id": "approval-wait", + "sequence": 1 + } + }, + { + "sequence": 4, + "event_type": "TimerScheduled", + "payload": { + "condition_key": "approval", + "condition_definition_fingerprint": "dwpy2:sha256:3c3fa63e37a2afd9a6d1d658d11dca846beb98ff4f11f3fe365f505b5ada2b1a", + "timeout_seconds": 2, + "condition_wait_input_order": "durable_receipt_order", + "deadline_policy": "occurrence", + "condition_wait_timeout_budget_seconds": 2, + "condition_wait_occurrence_id": "python:condition-wait:0", + "condition_wait_id": "approval-wait", + "sequence": 1, + "timer_id": "approval-timer", + "timer_kind": "condition_timeout", + "delay_seconds": 2 + } + }, + { + "sequence": 5, + "event_type": "SignalReceived", + "payload": { + "workflow_command_id": "receipt-approve", + "signal_name": "approval", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCAgEA" + } + } + }, + { + "sequence": 6, + "event_type": "TimerFired", + "payload": { + "condition_key": "approval", + "condition_definition_fingerprint": "dwpy2:sha256:3c3fa63e37a2afd9a6d1d658d11dca846beb98ff4f11f3fe365f505b5ada2b1a", + "timeout_seconds": 2, + "condition_wait_input_order": "durable_receipt_order", + "deadline_policy": "occurrence", + "condition_wait_timeout_budget_seconds": 2, + "condition_wait_occurrence_id": "python:condition-wait:0", + "condition_wait_id": "approval-wait", + "sequence": 1, + "timer_id": "approval-timer", + "timer_kind": "condition_timeout", + "delay_seconds": 2 + } + }, + { + "sequence": 7, + "event_type": "SignalApplied", + "payload": { + "workflow_command_id": "receipt-approve", + "signal_name": "approval" + } + } + ], + "expected": { + "command_sequence": [ + { + "type": "resolve_condition_wait", + "condition_wait_id": "approval-wait", + "satisfied": true, + "input_receipt_sequence": 5 + }, + { + "type": "complete_workflow", + "result": true + } + ] + } +} diff --git a/tests/test_ordered_condition_input.py b/tests/test_ordered_condition_input.py new file mode 100644 index 0000000..db07de9 --- /dev/null +++ b/tests/test_ordered_condition_input.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from collections.abc import Generator +from typing import Any + +from durable_workflow import serializer, workflow +from durable_workflow.workflow import CompleteWorkflow, WorkflowContext, commands_to_server_commands, replay + + +@workflow.defn(name="tests.ordered-condition-input") +class Approval: + def __init__(self) -> None: + self.approved = False + + @workflow.signal("approval") + def approval(self, accepted: bool) -> None: + self.approved = accepted + + def run(self, ctx: WorkflowContext) -> Generator[Any, Any, bool]: + return (yield ctx.wait_condition(lambda: self.approved, key="approval", timeout=2)) + + +def test_a_replacement_worker_replays_the_first_applied_true_prefix() -> None: + legacy = replay(Approval, [], [], allow_ordered_condition_inputs=True) + legacy_open, = commands_to_server_commands(legacy.commands, "test") + assert "condition_wait_input_order" not in legacy_open + + opening = replay( + Approval, [], [], allow_ordered_condition_inputs=True, author_ordered_condition_inputs=True, + ) + opened, = commands_to_server_commands(opening.commands, "test") + assert opened.pop("type") == "open_condition_wait" + assert opened["condition_wait_input_order"] == "durable_receipt_order" + opened.update(sequence=1, condition_wait_id="approval-wait") + timer = {**opened, "timer_id": "original-timer", "timer_kind": "condition_timeout", "delay_seconds": 2} + + def event(sequence: int, name: str, payload: dict[str, Any]) -> dict[str, Any]: + return {"sequence": sequence, "event_type": name, "payload": payload} + + receipts = [ + event(5, "SignalReceived", {"workflow_command_id": "approve", "signal_name": "approval", + "arguments": serializer.envelope([True])}), + event(6, "SignalReceived", {"workflow_command_id": "withdraw", "signal_name": "approval", + "arguments": serializer.envelope([False])}), + ] + history = [event(3, "ConditionWaitOpened", opened), event(4, "TimerScheduled", timer), + *receipts, event(7, "TimerFired", timer)] + still_pending = replay(Approval, history, [], allow_ordered_condition_inputs=True, pending_condition_input=(5,)) + assert not still_pending.commands + + history.extend([ + event(8, "SignalApplied", {"workflow_command_id": "approve", "signal_name": "approval"}), + event(9, "SignalApplied", {"workflow_command_id": "withdraw", "signal_name": "approval"}), + ]) + outcome = replay(Approval, history, [], allow_ordered_condition_inputs=True, pending_condition_input=(None,)) + commands = commands_to_server_commands(outcome.commands, "test") + assert commands[0] == {"type": "resolve_condition_wait", "condition_wait_id": "approval-wait", + "satisfied": True, "input_receipt_sequence": 5} + assert isinstance(outcome.commands[-1], CompleteWorkflow) and outcome.commands[-1].result is True + + history.append(event(10, "ConditionWaitSatisfied", { + **opened, "input_receipt_sequence": 5, "timer_fired_sequence": 7, "timer_id": "original-timer", + })) + recorded = replay(Approval, history, []) + assert isinstance(recorded.commands[-1], CompleteWorkflow) and recorded.commands[-1].result is True + commands = commands_to_server_commands(recorded.commands, "test") + assert [command["type"] for command in commands] == ["complete_workflow"] diff --git a/tests/test_replay_regression_corpus.py b/tests/test_replay_regression_corpus.py index 6b7c901..e908687 100644 --- a/tests/test_replay_regression_corpus.py +++ b/tests/test_replay_regression_corpus.py @@ -29,6 +29,7 @@ WorkflowContext, commands_to_server_commands, query_state, + replay, ) from tests.business_clock_workflows import ( ChildBusinessClockWorkflow, @@ -52,6 +53,7 @@ GoldenTimeoutWaitWorkflow, GoldenVersionMarkerWorkflow, ) +from tests.test_ordered_condition_input import Approval as OrderedConditionApproval from tests.test_parallel_failure_order import ReviewPlain, ReviewSelectCancel, ReviewZeroCommandCatch from tests.test_parallel_group_boundaries import GroupAfterSelectionWithCancellation from tests.test_parallel_group_policy import ParallelFailurePolicyWorkflow @@ -520,6 +522,7 @@ def run(self, ctx: WorkflowContext, message: str) -> None: WORKFLOW_TYPES["tests.replay.condition-identity"] = ConditionIdentityWorkflow WORKFLOW_TYPES["tests.replay.entry-arguments-required"] = RequiredEntryArgumentWorkflow WORKFLOW_TYPES["tests.replay.parallel-failure-policy"] = ParallelFailurePolicyWorkflow +WORKFLOW_TYPES["tests.ordered-condition-input"] = OrderedConditionApproval # Immutable evidence whose recorded expectation was the sdk-python#338 defect: @@ -896,7 +899,17 @@ async def run_first_task() -> list[dict[str, Any]]: workflows=[WORKFLOW_TYPES[name] for name in worker_registrations], ) registered_workflows = list(worker.workflows.values()) - if query is None: + if workflow_type == "tests.ordered-condition-input": + task = fixture["worker_task"] + outcome = replay( + OrderedConditionApproval, history, [] if start_input is None else start_input, + allow_ordered_condition_inputs=True, + pending_condition_input=(task["condition_wait_pending_input_sequence"],), + ) + commands = _command_documents(outcome.commands) + message_stream_cursors = outcome.message_stream_cursors + message_stream_waits = outcome.message_stream_waits + elif query is None: outcome = Replayer(workflows=registered_workflows).replay( history, start_input,