diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e20527..392a369 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `ctx.replay_now()` is available at ordinary workflow entry, before any + durable step. It returns the run's canonical start from the workflow task's + `replay_clock` carrier (`WorkerReplayClock` v1, sent by Server 3.6.0 and + later, durable-workflow/server#1156). Every lease of the same run carries the + same value, so replay is unchanged. A task without a valid carrier, or whose + carrier disagrees with the history's start kind, keeps entry unavailable, and + a redrive anchor that history already proves is never replaced. Update tasks + rebuild the workflow with their own carrier. Query tasks and pre-accept + update validation don't receive a carrier from Server yet, so rebuilding a + workflow that reads the clock at entry fails them visibly. `replay()`, + `Replayer.replay()`, `replay_history()` and `apply_update()` accept the + task's object as `replay_clock_entry`. + `ctx.now()` still returns the fixed start time. (durable-workflow/.github#215) + ## [2.23.1] - 2026-11-24 2.23.1 is the first published release containing the 2.23.0 changes. The diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index 7dd67b4..e937cbd 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -1192,6 +1192,39 @@ decision. Never compare UTC and monotonic values or subtract monotonic readings from different processes or hosts. Subtracting Python `ctx.now()` values does not measure elapsed time. +### Advancing replay clock + +`ctx.replay_now()` is an additive UTC clock that advances with consumed +history. At ordinary workflow entry, before any durable step, it returns the +run's canonical start from the workflow task's `replay_clock` carrier +(`WorkerReplayClock` v1, sent by Server 3.6.0 and later). After a supported +activity, timer or child step it returns that step's recorded time, so a +deadline loop around a durable timer terminates and the difference between two +reads after two durable steps measures their recorded elapsed time. Repeated +reads between durable steps return the same value. Step times come from +history, so every replay returns them again. The entry value comes from the +task's carrier, which Server sends unchanged on every workflow task of the run, +including update tasks. + +Where the SDK cannot prove the time, `ctx.replay_now()` raises +`ReplayClockUnavailable` instead of using any other time, and an unhandled +`ReplayClockUnavailable` fails the workflow like any other exception. It is +unavailable for: + +- an entry read on a task without the carrier: Servers older than 3.6.0, or a + run whose start Server cannot prove; +- an entry read while rebuilding the workflow for a query task or a pre-accept + update validation, because Server does not yet send the carrier on those + tasks. Such queries and validations fail visibly; +- offline replay (`replay_history`, `Replayer.replay`) unless you pass the + task's object as `replay_clock_entry`, and the in-memory + `WorkflowEnvironment`, which supplies no carrier; +- group, inline and local operations it does not yet support, query handler + reads, and cancellation scopes. + +Adopt business-time decisions through normal workflow versioning. `ctx.now()` +keeps its fixed start time, so runs that already read it replay unchanged. + For event ordering, use Workflow Stream offsets, the relevant message/outbox sequence, or a deterministic workflow-local counter paired with `run_id`. Carry application sequence state explicitly through continue-as-new when diff --git a/src/durable_workflow/replay_clock.py b/src/durable_workflow/replay_clock.py index 2b60838..dc274c8 100644 --- a/src/durable_workflow/replay_clock.py +++ b/src/durable_workflow/replay_clock.py @@ -34,6 +34,42 @@ _SELECTION_FIELDS = ("selection_member_key", "selection_member_index", "selection_member_base_sequence", "selection_member_size", "selection_member_kind") _GroupMember = tuple[int | None, int, str, Sequence[Mapping[str, Any]] | None] +ENTRY_SCHEMA = "durable-workflow.worker-replay-clock/v1" +_ENTRY_SOURCES = frozenset({"run_started_at", "redrive_replayed_started_at"}) +_ENTRY_INSTANT = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z", re.ASCII) + + +@dataclass(frozen=True) +class EntryInstant: + """A validated ``WorkerReplayClock`` v1 carrier from a workflow task (server#1156).""" + + started_at: datetime + source: str + + +def entry_instant(carrier: Any, run_id: str) -> EntryInstant | None: + """Validate a task's ``replay_clock`` object; anything unproved is absent. + + The object is the Server's only availability signal. Its run must be the + task's run and its instant is strict UTC with six fractional digits. No + other time (lease, dispatch, history insertion or wall time) substitutes. + """ + # The v1 schema forbids additional properties, so the key set is exact. + if not isinstance(carrier, Mapping) or set(carrier) != {"schema", "workflow_run_id", "started_at", "source"}: + return None + source = carrier["source"] + if carrier["schema"] != ENTRY_SCHEMA or not isinstance(source, str) or source not in _ENTRY_SOURCES: + return None + if not _identity(run_id) or carrier["workflow_run_id"] != run_id: + return None + value = carrier["started_at"] + if not isinstance(value, str) or _ENTRY_INSTANT.fullmatch(value) is None: + return None + try: + started_at = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc) + except ValueError: + return None + return EntryInstant(started_at, source) def _task() -> object | None: @@ -232,6 +268,7 @@ class BusinessReplayClock: def __init__( self, events: Sequence[Mapping[str, Any]], workflow_id: str, run_id: str, *, sequence_claim: Callable[[Mapping[str, Any]], int | None], + entry: EntryInstant | None = None, ) -> None: self.events = events self._by_sequence: dict[int, list[int]] = {} @@ -249,11 +286,29 @@ def __init__( if (isinstance(payload, Mapping) and self._start_prefix(index, payload) and self._redrive_start(index, payload, workflow_id, run_id)): self.initial = (index, _time(payload.get("replayed_started_at"))) + if entry is not None and self.initial[1] is None: + # The Server's carrier gives ordinary entry its canonical start. Its + # source must agree with the history's own start kind, and a + # redrive anchor this history already proves is never replaced. + expected = "redrive_replayed_started_at" if self._redrive_declared else "run_started_at" + if entry.source == expected and self._entry_agrees(starts, entry.started_at): + self.initial = (None, entry.started_at) self._pending: tuple[int | None, datetime | None] = self.initial self._current: tuple[int | None, datetime | None] = self.initial for index, event in enumerate(events): self._index_event(index, event, sequence_claim) + def _entry_agrees(self, starts: Sequence[int], started_at: datetime) -> bool: + """An anchor the start event records itself must equal the carrier's.""" + for index in starts: + payload = self.events[index].get("payload") + if not isinstance(payload, Mapping) or "replayed_started_at" not in payload: + continue + # A present but unreadable anchor is a conflict, not an absence. + if _time(payload["replayed_started_at"]) != started_at: + return False + return True + def _index_event( self, index: int, event: Mapping[str, Any], sequence_claim: Callable[[Mapping[str, Any]], int | None], ) -> None: diff --git a/src/durable_workflow/testing.py b/src/durable_workflow/testing.py index 7ef9018..9e89adc 100644 --- a/src/durable_workflow/testing.py +++ b/src/durable_workflow/testing.py @@ -670,6 +670,7 @@ def replay_history( *, run_id: str = "", payload_codec: str | None = None, + replay_clock_entry: Mapping[str, Any] | None = None, ) -> ReplayOutcome: """Replay a production history against current workflow code. @@ -681,6 +682,10 @@ def replay_history( This is the supported way to regression-test a workflow change against real production traffic: dump the history from ``Client.get_history``, save the JSON, and replay it on every PR. + + A workflow that reads ``ctx.replay_now()`` at entry needs the workflow + task's ``replay_clock`` object as ``replay_clock_entry``; history alone + does not carry that instant. """ return replay( workflow_cls, @@ -688,6 +693,7 @@ def replay_history( list(start_input or []), run_id=run_id, payload_codec=payload_codec, + replay_clock_entry=replay_clock_entry, ) @@ -698,6 +704,7 @@ def replay_history_file( *, run_id: str = "", payload_codec: str | None = None, + replay_clock_entry: Mapping[str, Any] | None = None, ) -> ReplayOutcome: """Convenience wrapper: load a JSON history file and replay it. @@ -712,6 +719,7 @@ def replay_history_file( start_input, run_id=run_id, payload_codec=payload_codec, + replay_clock_entry=replay_clock_entry, ) diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index 6844ea5..cf8c111 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -2174,6 +2174,7 @@ async def _replay_workflow_claim( 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, + replay_clock_entry=task.get("replay_clock"), ) if outcome.cancellation_scope_delivery is not None: if outcome.commands: @@ -3107,6 +3108,7 @@ async def _run_workflow_task_with_history( prepare_local_activities=self._prepared_local_activities_supported, prepare_local_activity_groups=self._prepared_local_activity_groups_supported, local_activity_cancellation_policies=self._local_activity_cancellation_policies, + replay_clock_entry=task.get("replay_clock"), ) except NonDeterministicReplayError as exc: log.exception("workflow update task %s replay failed for run %s", task_id, run_id) @@ -4299,6 +4301,7 @@ async def _run_query_task_core(self, task: dict[str, Any], *, client: Client | N prepare_local_activities=self._prepared_local_activities_supported, prepare_local_activity_groups=self._prepared_local_activity_groups_supported, local_activity_cancellation_policies=self._local_activity_cancellation_policies, + replay_clock_entry=task.get("replay_clock"), ) await authority.confirm() async def execute() -> Any: @@ -4845,6 +4848,7 @@ async def _run_update_validation_task(self, task: dict[str, Any]) -> str: prepare_local_activities=self._prepared_local_activities_supported, prepare_local_activity_groups=self._prepared_local_activity_groups_supported, local_activity_cancellation_policies=self._local_activity_cancellation_policies, + replay_clock_entry=task.get("replay_clock"), ), ) result = invoke() diff --git a/src/durable_workflow/workflow.py b/src/durable_workflow/workflow.py index 0924c92..8391374 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -3214,8 +3214,12 @@ def replay_now(self) -> datetime: children, explicit redrive start, and validated lists of remote activities. Group success retains the selected event's full precision; matching caught failure uses canonical-v1 integer milliseconds. - Ordinary entry, other groups, inline/local operations, unproved times - and group-only query time remain unavailable. Reads are stable, + Ordinary entry reads the run's canonical start from the workflow + task's ``replay_clock`` carrier (``WorkerReplayClock`` v1). Entry is + unavailable without that carrier, including query and update- + validation rebuilds and offline replay that omit it. Other groups, + inline/local operations, unproved times and group-only query time + remain unavailable. Reads are stable, and proved boundaries may move backwards. Adopt business-time decisions through normal workflow versioning. ``now()`` remains the legacy fixed-start accessor, and timestamps are not order IDs. @@ -3414,7 +3418,9 @@ def replay( external_storage_cache: ExternalPayloadCache | None = None, cancel_requested: bool = False, record_parallel_failure_order: bool = False, + replay_clock_entry: Mapping[str, Any] | None = None, ) -> ReplayOutcome: + """Replay ``history``; pass the task's ``replay_clock`` to reproduce entry reads.""" events = _history_events_from_export(history) selected_workflow_type = workflow_type or _workflow_type_from_history(events) workflow_cls = self._workflow_cls(selected_workflow_type) @@ -3439,6 +3445,7 @@ def replay( external_storage_cache=external_storage_cache, cancel_requested=cancel_requested, record_parallel_failure_order=record_parallel_failure_order, + replay_clock_entry=replay_clock_entry, ) def _workflow_cls(self, workflow_type: str | None) -> type: @@ -3830,6 +3837,7 @@ def replay( allow_ordered_condition_inputs: bool = False, author_ordered_condition_inputs: bool = False, pending_condition_input: tuple[int | None] | None = None, + replay_clock_entry: Mapping[str, Any] | None = None, ) -> ReplayOutcome: """Replay ``history_events`` and return the next commands. @@ -3838,6 +3846,11 @@ def replay( recorded member failure (sdk-python#307). Direct calls to this helper default to recording off. Workers pass their configured setting. Replay always follows a marker already present in history. + + ``replay_clock_entry`` is the workflow task's ``replay_clock`` object + (``WorkerReplayClock`` v1, server#1156). When it validates for ``run_id``, + ``WorkflowContext.replay_now()`` reads its ``started_at`` at ordinary + entry; otherwise entry stays unavailable. Workers pass the task's object. """ return _replay_state( workflow_cls, @@ -3862,6 +3875,7 @@ def replay( allow_ordered_condition_inputs=allow_ordered_condition_inputs, author_ordered_condition_inputs=author_ordered_condition_inputs, pending_condition_input=pending_condition_input, + replay_clock_entry=replay_clock_entry, ).outcome @@ -3880,6 +3894,7 @@ def _prepare_query_state( prepare_local_activities: bool = False, prepare_local_activity_groups: bool = False, local_activity_cancellation_policies: tuple[str, ...] = (), + replay_clock_entry: Mapping[str, Any] | None = None, ) -> Callable[[], Any]: """Prepare the query so a worker can recheck authority after replay.""" try: @@ -3897,6 +3912,7 @@ def _prepare_query_state( prepare_local_activities=prepare_local_activities, prepare_local_activity_groups=prepare_local_activity_groups, local_activity_cancellation_policies=local_activity_cancellation_policies, + replay_clock_entry=replay_clock_entry, ) except Exception as exc: raise QueryFailed(f"workflow replay failed before query: {exc}") from exc @@ -3987,6 +4003,7 @@ def apply_update( prepare_local_activities: bool = False, prepare_local_activity_groups: bool = False, local_activity_cancellation_policies: tuple[str, ...] = (), + replay_clock_entry: Mapping[str, Any] | None = None, ) -> CompleteUpdate | FailUpdate: """Replay current workflow state and run one accepted update handler. @@ -4011,6 +4028,7 @@ def apply_update( prepare_local_activities=prepare_local_activities, prepare_local_activity_groups=prepare_local_activity_groups, local_activity_cancellation_policies=local_activity_cancellation_policies, + replay_clock_entry=replay_clock_entry, ) except NonDeterministicReplayError: raise @@ -4097,6 +4115,7 @@ class _UpdateValidationReplayOptions: prepare_local_activities: bool = False prepare_local_activity_groups: bool = False local_activity_cancellation_policies: tuple[str, ...] = () + replay_clock_entry: Mapping[str, Any] | None = None def validate_update( @@ -4167,6 +4186,7 @@ def _prepare_update_validation( prepare_local_activities=replay_options.prepare_local_activities, prepare_local_activity_groups=replay_options.prepare_local_activity_groups, local_activity_cancellation_policies=replay_options.local_activity_cancellation_policies, + replay_clock_entry=replay_options.replay_clock_entry, ) except Exception as exc: raise UpdateValidationFailed( @@ -5406,6 +5426,7 @@ def _replay_state( allow_ordered_condition_inputs: bool = False, author_ordered_condition_inputs: bool = False, pending_condition_input: tuple[int | None] | None = None, + replay_clock_entry: Mapping[str, Any] | None = None, ) -> _ReplayState: _validate_workflow_entrypoint(workflow_cls) _workflow_handler_registries(workflow_cls) @@ -5747,6 +5768,7 @@ def _replay_state( ctx._schedule_origin = _schedule_origin(events) ctx._business_clock = replay_clock.BusinessReplayClock( events, workflow_id or "", run_id, sequence_claim=_workflow_sequence, + entry=replay_clock.entry_instant(replay_clock_entry, run_id), ) lifetime = _ReplayLifetime(ctx.logger) diff --git a/tests/fixtures/replay_regressions/business-clock-ordinary-entry-carrier.json b/tests/fixtures/replay_regressions/business-clock-ordinary-entry-carrier.json new file mode 100644 index 0000000..672f338 --- /dev/null +++ b/tests/fixtures/replay_regressions/business-clock-ordinary-entry-carrier.json @@ -0,0 +1,107 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "business-clock-ordinary-entry-carrier", + "protocol_version": "1.20", + "bindings": [ + "python" + ], + "description": "A workflow task's WorkerReplayClock v1 carrier (server#1156) gives replay_now() the run's canonical start at ordinary entry. History insertion time is not substituted, the legacy fixed-start now() is unchanged, and a second lease of the same run decides identically.", + "workflow": { + "type": "tests.replay.business-clock", + "input": [], + "payload_codec": "avro", + "workflow_id": "business-clock-instance", + "run_id": "business-clock-run" + }, + "worker_task": { + "replay_clock": { + "schema": "durable-workflow.worker-replay-clock/v1", + "workflow_run_id": "business-clock-run", + "started_at": "2026-11-01T00:00:00.000000Z", + "source": "run_started_at" + } + }, + "history": [ + { + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "tests.replay.business-clock", + "workflow_instance_id": "business-clock-instance", + "workflow_run_id": "business-clock-run" + }, + "sequence": 1 + }, + { + "event_type": "ActivityScheduled", + "payload": { + "sequence": 1, + "activity_execution_id": "clock-activity", + "activity_type": "clock.first" + }, + "sequence": 2 + }, + { + "event_type": "ActivityCompleted", + "recorded_at": "2026-11-01T00:00:03.123456Z", + "payload": { + "sequence": 1, + "activity_execution_id": "clock-activity", + "activity_type": "clock.first", + "result": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwoKZmlyc3Q=" + } + }, + "sequence": 3 + }, + { + "event_type": "TimerScheduled", + "payload": { + "sequence": 2, + "timer_id": "clock-timer", + "timer_kind": "durable_timer", + "delay_seconds": 2 + }, + "sequence": 4 + }, + { + "event_type": "TimerFired", + "recorded_at": "2026-11-01T00:00:05.654321Z", + "payload": { + "sequence": 2, + "timer_id": "clock-timer", + "timer_kind": "durable_timer", + "delay_seconds": 2 + }, + "sequence": 5 + }, + { + "event_type": "WorkflowTaskCompleted", + "recorded_at": "2026-12-01T00:00:00Z", + "payload": {}, + "sequence": 6 + } + ], + "expected": { + "command_sequence": [ + { + "type": "complete_workflow", + "result": { + "clock": [ + "2026-11-01T00:00:00.000000+00:00", + "2026-11-01T00:00:03.123456+00:00", + "2026-11-01T00:00:05.654321+00:00" + ], + "legacy": [ + "2026-11-01T00:00:00.123456+00:00", + "2026-11-01T00:00:00.123456+00:00", + "2026-11-01T00:00:00.123456+00:00" + ], + "elapsed_seconds": 2.530865 + } + } + ] + } +} diff --git a/tests/test_business_replay_clock_entry.py b/tests/test_business_replay_clock_entry.py new file mode 100644 index 0000000..ff0dac1 --- /dev/null +++ b/tests/test_business_replay_clock_entry.py @@ -0,0 +1,296 @@ +"""The WorkerReplayClock v1 entry carrier (server#1156, durable-workflow/.github#215).""" + +from __future__ import annotations + +import asyncio +from copy import deepcopy +from datetime import datetime, timedelta, timezone +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from durable_workflow import Worker, serializer, workflow +from durable_workflow.client import Client +from durable_workflow.errors import QueryFailed, UpdateValidationFailed +from durable_workflow.replay_clock import BusinessReplayClock, EntryInstant, entry_instant +from durable_workflow.testing import replay_history +from durable_workflow.workflow import ( + CompleteUpdate, + CompleteWorkflow, + FailUpdate, + Replayer, + WorkflowContext, + _prepare_query_state, + _prepare_update_validation, + _UpdateValidationReplayOptions, + _workflow_sequence, + apply_update, + replay, +) +from tests.business_clock_workflows import NativeRedriveBusinessClockWorkflow, ScalarBusinessClockWorkflow +from tests.test_business_replay_clock import history + +RUN = "business-clock-run" +START = "2026-11-01T00:00:00.000000+00:00" + + +def carrier(**changes: Any) -> dict[str, Any]: + return { + "schema": "durable-workflow.worker-replay-clock/v1", "workflow_run_id": RUN, + "started_at": "2026-11-01T00:00:00.000000Z", "source": "run_started_at", **changes, + } + + +def result(events: list[dict[str, Any]], entry: Any, workflow: type = ScalarBusinessClockWorkflow, + run_id: str = RUN) -> Any: + outcome = replay(workflow, events, [], payload_codec="avro", run_id=run_id, replay_clock_entry=entry) + try: + assert len(outcome.commands) == 1 + command = outcome.commands[0] + assert isinstance(command, CompleteWorkflow), command + return command.result + finally: + outcome.close() + + +def test_entry_read_returns_the_carried_start_and_replays_identically() -> None: + events = history() + original = deepcopy(events) + first = result(events, carrier()) + assert first == result(events, carrier()) + assert first == { + "clock": [START, "2026-11-01T00:00:03.123456+00:00", "2026-11-01T00:00:05.654321+00:00"], + # History insertion time is not the entry instant, and now() stays fixed-start. + "legacy": ["2026-11-01T00:00:00.123456+00:00"] * 3, + "elapsed_seconds": 2.530865, + } + assert events == original + + +def test_absent_carrier_keeps_entry_unavailable() -> None: + assert result(history(), None)["clock"][0] is None + + +def test_microseconds_are_kept_exactly_in_utc() -> None: + value = entry_instant(carrier(started_at="2026-11-12T10:00:00.123456Z"), RUN) + assert value == EntryInstant(datetime(2026, 11, 12, 10, 0, 0, 123456, tzinfo=timezone.utc), "run_started_at") + assert result(history(), carrier(started_at="2026-10-31T23:59:59.999999Z"))["clock"][0] == ( + "2026-10-31T23:59:59.999999+00:00" + ) + + +@pytest.mark.parametrize("entry", [ + "not an object", + [carrier()], + {key: value for key, value in carrier().items() if key != "source"}, + {key: value for key, value in carrier().items() if key != "started_at"}, + carrier(schema="durable-workflow.worker-replay-clock/v2"), + carrier(workflow_run_id="another-run"), + carrier(workflow_run_id=""), + carrier(workflow_run_id=None), + carrier(source="history_inserted_at"), + carrier(source=None), + carrier(source=["run_started_at"]), + carrier(source={"run_started_at": True}), + carrier(extra="field"), + carrier(started_at="2026-11-01T00:00:00Z"), + carrier(started_at="2026-11-01T00:00:00.000Z"), + carrier(started_at="2026-11-01T00:00:00.000000+00:00"), + carrier(started_at="2026-11-01T00:00:00.000000z"), + carrier(started_at="2026-11-01 00:00:00.000000Z"), + carrier(started_at="2026-02-30T00:00:00.000000Z"), + carrier(started_at="2026-11-01T24:00:00.000000Z"), + carrier(started_at=1761955200), + carrier(started_at=None), + carrier(started_at="2026-11-01T00:00:00.000000Z"), +]) +def test_unproved_carriers_are_absent(entry: Any) -> None: + assert entry_instant(entry, RUN) is None + assert result(history(), entry)["clock"][0] is None + + +def test_carrier_needs_the_task_run() -> None: + assert entry_instant(carrier(workflow_run_id=""), "") is None + assert result(history(), carrier(), run_id="")["clock"][0] is None + + +def test_redrive_anchor_on_ordinary_history_is_refused() -> None: + assert result(history(), carrier(source="redrive_replayed_started_at"))["clock"][0] is None + + +def redrive_fixture() -> tuple[list[dict[str, Any]], str, str]: + from tests.test_replay_clock import redrive_fixture as load + + fixture = load("business-clock-native-redrive-entry") + events = fixture["history"] + return events, fixture["workflow"]["run_id"], events[1]["payload"]["replayed_started_at"] + + +def test_history_proved_redrive_anchor_is_never_replaced() -> None: + events, run, _ = redrive_fixture() + expected = result(events, None, NativeRedriveBusinessClockWorkflow, run_id=run) + assert expected["clock"][0] == "2026-11-03T00:00:00.000000+00:00" + for entry in ( + carrier(workflow_run_id=run, source="redrive_replayed_started_at", started_at="2026-10-01T00:00:00.000000Z"), + carrier(workflow_run_id=run), + ): + assert result(events, entry, NativeRedriveBusinessClockWorkflow, run_id=run) == expected + + +def test_unproved_redrive_history_accepts_only_a_redrive_anchor_for_entry() -> None: + events, run, _ = redrive_fixture() + del events[1]["payload"]["workflow_link_id"] # The SDK can no longer prove the anchor itself. + assert result(events, None, NativeRedriveBusinessClockWorkflow, run_id=run)["clock"] == [None, None] + assert result(events, carrier(workflow_run_id=run), NativeRedriveBusinessClockWorkflow, + run_id=run)["clock"] == [None, None] + anchored = result(events, carrier(workflow_run_id=run, source="redrive_replayed_started_at", + started_at="2026-11-03T00:00:00.000000Z"), + NativeRedriveBusinessClockWorkflow, run_id=run) + # Only entry gains the Server's anchor; the unproved reused boundary stays unavailable. + assert anchored["clock"] == ["2026-11-03T00:00:00.000000+00:00", None] + # The start event's own recorded anchor must agree with the carrier. + assert result(events, carrier(workflow_run_id=run, source="redrive_replayed_started_at", + started_at="2026-11-02T00:00:00.000000Z"), + NativeRedriveBusinessClockWorkflow, run_id=run)["clock"] == [None, None] + # A present but unreadable recorded anchor conflicts rather than reading as absent. + events[1]["payload"]["replayed_started_at"] = "not a time" + entry = entry_instant(carrier(workflow_run_id=run, source="redrive_replayed_started_at", + started_at="2026-11-03T00:00:00.000000Z"), run) + clock = BusinessReplayClock(events, events[1]["payload"]["workflow_instance_id"], run, + sequence_claim=_workflow_sequence, entry=entry) + assert clock.initial == (None, None) + + +def test_worker_reads_the_task_carrier_identically_on_every_lease() -> None: + async def lease(attempt: int, entry: Any) -> Any: + client = AsyncMock(spec=Client) + worker = Worker(client, task_queue="clock", workflows=[ScalarBusinessClockWorkflow]) + task = { + "task_id": f"task-{attempt}", "workflow_type": "tests.replay.business-clock", + "workflow_task_attempt": attempt, "workflow_id": "business-clock-instance", "run_id": RUN, + "history_events": history(), "arguments": serializer.envelope([], codec="avro"), + "payload_codec": "avro", + } + if entry is not None: + task["replay_clock"] = entry + await worker._run_workflow_task(task) + client.complete_workflow_task.assert_awaited_once() + commands = client.complete_workflow_task.call_args.kwargs["commands"] + assert [command["type"] for command in commands] == ["complete_workflow"] + return serializer.decode_envelope(commands[0]["result"]) + + first = asyncio.run(lease(1, carrier())) + assert first["clock"][0] == START + assert asyncio.run(lease(2, carrier())) == first + assert asyncio.run(lease(3, None))["clock"][0] is None + + +@workflow.defn(name="tests.replay.business-clock-entry-deadline") +class EntryDeadlineWorkflow: + def __init__(self) -> None: + self.deadline: datetime | None = None + self.extensions = 0 + + def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def] + self.deadline = ctx.replay_now() + timedelta(hours=1) + yield ctx.schedule_activity("clock.first", []) + yield ctx.start_timer(2) + return self.deadline.isoformat() + + @workflow.query("deadline") + def deadline_query(self) -> str: + assert self.deadline is not None + return self.deadline.isoformat() + + @workflow.update("extend") + def extend(self) -> str: + assert self.deadline is not None + self.extensions += 1 + return (self.deadline + timedelta(minutes=self.extensions)).isoformat() + + @workflow.update_validator("extend") + def validate_extend(self) -> None: + assert self.deadline is not None + + +DEADLINE = "2026-11-01T01:00:00+00:00" + + +def test_query_update_and_validation_rebuild_the_body_with_the_task_carrier() -> None: + events = history()[:3] + options: dict[str, Any] = {"payload_codec": "avro", "run_id": RUN} + def query(entry: Any) -> Any: + return _prepare_query_state(EntryDeadlineWorkflow, events, [], "deadline", replay_clock_entry=entry, + **options)() + + def validate(entry: Any) -> Any: + return _prepare_update_validation( + EntryDeadlineWorkflow, events, [], "extend", [], + replay_options=_UpdateValidationReplayOptions(run_id=RUN, payload_codec="avro", replay_clock_entry=entry), + )() + + assert query(carrier()) == DEADLINE + assert validate(carrier()) is None + accepted = {"event_type": "UpdateAccepted", "payload": { + "update_id": "update-1", "update_name": "extend", + "arguments": serializer.encode([], codec="avro"), "payload_codec": "avro", + }} + applied = apply_update(EntryDeadlineWorkflow, [*events, accepted], [], "update-1", + replay_clock_entry=carrier(), **options) + assert isinstance(applied, CompleteUpdate), applied + assert applied.result == "2026-11-01T01:01:00+00:00" + + # Without a carrier the entry read is unavailable, so the rebuild fails visibly. + with pytest.raises(QueryFailed, match="unavailable"): + query(None) + with pytest.raises(UpdateValidationFailed): + validate(None) + assert isinstance(apply_update(EntryDeadlineWorkflow, [*events, accepted], [], "update-1", **options), FailUpdate) + + +def test_offline_replay_tools_accept_the_task_carrier() -> None: + events = history() + outcome = replay_history(EntryDeadlineWorkflow, events, [], run_id=RUN, payload_codec="avro", + replay_clock_entry=carrier()) + try: + assert [type(command) for command in outcome.commands] == [CompleteWorkflow] + assert outcome.commands[0].result == DEADLINE + finally: + outcome.close() + outcome = Replayer(workflows=[EntryDeadlineWorkflow]).replay( + events, [], workflow_type="tests.replay.business-clock-entry-deadline", run_id=RUN, + payload_codec="avro", replay_clock_entry=carrier(), + ) + try: + assert outcome.commands[0].result == DEADLINE + finally: + outcome.close() + + +def test_worker_update_task_rebuilds_the_body_with_its_carrier() -> None: + accepted = {"event_type": "UpdateAccepted", "payload": { + "update_id": "update-1", "update_name": "extend", + "arguments": serializer.encode([], codec="avro"), "payload_codec": "avro", + }} + + async def lease(entry: Any) -> list[dict[str, Any]]: + client = AsyncMock(spec=Client) + worker = Worker(client, task_queue="clock", workflows=[EntryDeadlineWorkflow]) + task = { + "task_id": "update-task", "workflow_type": "tests.replay.business-clock-entry-deadline", + "workflow_task_attempt": 1, "workflow_id": "business-clock-instance", "run_id": RUN, + "workflow_update_id": "update-1", "history_events": [*history()[:3], accepted], + "arguments": serializer.envelope([], codec="avro"), "payload_codec": "avro", + } + if entry is not None: + task["replay_clock"] = entry + await worker._run_workflow_task(task) + client.complete_workflow_task.assert_awaited_once() + commands: list[dict[str, Any]] = client.complete_workflow_task.call_args.kwargs["commands"] + return commands + + commands = asyncio.run(lease(carrier())) + assert [command["type"] for command in commands] == ["complete_update"], commands + assert serializer.decode_envelope(commands[0]["result"]) == "2026-11-01T01:01:00+00:00" + assert [command["type"] for command in asyncio.run(lease(None))] == ["fail_update"] diff --git a/tests/test_replay_regression_corpus.py b/tests/test_replay_regression_corpus.py index b781c26..20766f3 100644 --- a/tests/test_replay_regression_corpus.py +++ b/tests/test_replay_regression_corpus.py @@ -4,6 +4,7 @@ import json import os from collections.abc import Mapping, Sequence +from copy import deepcopy from importlib import metadata from pathlib import Path from typing import Any @@ -889,6 +890,30 @@ async def run_first_task() -> list[dict[str, Any]]: _assert_matches(fixture["expected"], {"command_sequence": commands}, f"{fixture['id']}.expected") return commands + worker_task = fixture.get("worker_task") + if isinstance(worker_task, dict) and "replay_clock" in worker_task: + # The entry carrier exists only on a real workflow task (server#1156). + # Two leases of the same run carry the same object and must decide the same. + async def run_lease(attempt: int) -> list[dict[str, Any]]: + client = AsyncMock(spec=Client) + worker = Worker(client, task_queue="regression-corpus", workflows=[WORKFLOW_TYPES[workflow_type]]) + await worker._run_workflow_task({ + "task_id": f"workflow-task-{attempt}", "workflow_type": workflow_type, + "workflow_task_attempt": attempt, "workflow_id": workflow["workflow_id"], + "run_id": workflow["run_id"], "history_events": deepcopy(history), + "arguments": serializer.envelope(start_input, codec=payload_codec), "payload_codec": payload_codec, + "replay_clock": deepcopy(worker_task["replay_clock"]), + }) + client.complete_workflow_task.assert_awaited_once() + commands = _decode_envelopes(client.complete_workflow_task.call_args.kwargs["commands"]) + assert isinstance(commands, list) + return commands + + commands = asyncio.run(run_lease(1)) + assert asyncio.run(run_lease(2)) == commands + _assert_matches(fixture["expected"], {"command_sequence": commands}, f"{fixture['id']}.expected") + return commands + query = workflow.get("query") query_result: Any = None registered_workflows = [WORKFLOW_TYPES[workflow_type]]