From 403652a76bce06cc3a1bf913994156eeb418ad2d Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:19:48 +0000 Subject: [PATCH 1/3] Read the WorkerReplayClock entry carrier in replay_now() ctx.replay_now() now returns the run's canonical start at ordinary workflow entry when the workflow task carries a valid replay_clock object (WorkerReplayClock v1, server#1156). The carrier must name the task's run, use strict six-digit UTC and agree with the history's start kind; a redrive anchor that history already proves is never replaced. Tasks without a carrier keep entry unavailable and ctx.now() keeps its fixed start. Refs durable-workflow/.github#215 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++ docs/sdk-reference.md | 19 +++ src/durable_workflow/replay_clock.py | 42 +++++ src/durable_workflow/worker.py | 1 + src/durable_workflow/workflow.py | 16 +- ...business-clock-ordinary-entry-carrier.json | 107 ++++++++++++ tests/test_business_replay_clock_entry.py | 157 ++++++++++++++++++ tests/test_replay_regression_corpus.py | 25 +++ 8 files changed, 376 insertions(+), 2 deletions(-) create mode 100644 tests/fixtures/replay_regressions/business-clock-ordinary-entry-carrier.json create mode 100644 tests/test_business_replay_clock_entry.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e205279..adffc3b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,17 @@ 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. `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 7dd67b49..fa0e2e45 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -1192,6 +1192,25 @@ 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, and every replay of the +same history returns the same values. + +Where the SDK cannot prove the time, `ctx.replay_now()` raises +`ReplayClockUnavailable` instead of using any other time: a task without the +carrier (older Servers), group, inline and local operations it does not yet +support, query callbacks, 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 2b608381..494b061c 100644 --- a/src/durable_workflow/replay_clock.py +++ b/src/durable_workflow/replay_clock.py @@ -34,6 +34,40 @@ _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"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}Z") + + +@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. + """ + if not isinstance(carrier, Mapping) or not {"schema", "workflow_run_id", "started_at", "source"} <= set(carrier): + return None + if carrier["schema"] != ENTRY_SCHEMA or carrier["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, carrier["source"]) def _task() -> object | None: @@ -232,6 +266,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,6 +284,13 @@ 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: + 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): diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index 6844ea55..bd4b53d6 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: diff --git a/src/durable_workflow/workflow.py b/src/durable_workflow/workflow.py index 0924c922..5f82243d 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -3214,8 +3214,11 @@ 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); a task + without that carrier leaves entry unavailable. 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. @@ -3830,6 +3833,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 +3842,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 +3871,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 @@ -5406,6 +5416,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 +5758,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 00000000..672f3381 --- /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 00000000..ebce1fd6 --- /dev/null +++ b/tests/test_business_replay_clock_entry.py @@ -0,0 +1,157 @@ +"""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, timezone +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from durable_workflow import Worker, serializer +from durable_workflow.client import Client +from durable_workflow.replay_clock import EntryInstant, entry_instant +from durable_workflow.workflow import CompleteWorkflow, 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(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), +]) +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] + + +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 diff --git a/tests/test_replay_regression_corpus.py b/tests/test_replay_regression_corpus.py index b781c266..20766f38 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]] From af1fe9bf5faed32985862caba0196129697dd2ff Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:51:09 +0000 Subject: [PATCH 2/3] Rebuild update, query and validation bodies with the task carrier Review of #380: a body that reads replay_now() at entry must rebuild with the same entry value for updates. apply_update, query_state and validate_update (and the worker paths that call them), replay_history and Replayer.replay now accept the task's replay_clock object. Query tasks and pre-accept validation don't receive one from Server yet, so those rebuilds fail visibly; the docs now say so. The carrier key set must be exact, a non-string source counts as absent, and an unproved redrive start's own replayed_started_at must agree with the carrier. Refs durable-workflow/.github#215 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +- docs/sdk-reference.md | 26 +++-- src/durable_workflow/replay_clock.py | 19 +++- src/durable_workflow/testing.py | 8 ++ src/durable_workflow/worker.py | 3 + src/durable_workflow/workflow.py | 18 ++- tests/test_business_replay_clock_entry.py | 128 +++++++++++++++++++++- 7 files changed, 193 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index adffc3b4..f12096ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,8 +14,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. `ctx.now()` - still returns the fixed start time. (durable-workflow/.github#215) + 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()`, `query_state()`, `apply_update()` and + `validate_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 diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index fa0e2e45..414fe51f 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -1201,15 +1201,27 @@ run's canonical start from the workflow task's `replay_clock` carrier 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, and every replay of the -same history returns the same values. +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: a task without the -carrier (older Servers), group, inline and local operations it does not yet -support, query callbacks, 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. +`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); +- 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`; +- 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`. diff --git a/src/durable_workflow/replay_clock.py b/src/durable_workflow/replay_clock.py index 494b061c..a2c02514 100644 --- a/src/durable_workflow/replay_clock.py +++ b/src/durable_workflow/replay_clock.py @@ -54,9 +54,11 @@ def entry_instant(carrier: Any, run_id: str) -> EntryInstant | None: task's run and its instant is strict UTC with six fractional digits. No other time (lease, dispatch, history insertion or wall time) substitutes. """ - if not isinstance(carrier, Mapping) or not {"schema", "workflow_run_id", "started_at", "source"} <= set(carrier): + # 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 - if carrier["schema"] != ENTRY_SCHEMA or carrier["source"] not in _ENTRY_SOURCES: + 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 @@ -67,7 +69,7 @@ def entry_instant(carrier: Any, run_id: str) -> EntryInstant | None: started_at = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc) except ValueError: return None - return EntryInstant(started_at, carrier["source"]) + return EntryInstant(started_at, source) def _task() -> object | None: @@ -289,13 +291,22 @@ def __init__( # 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: + 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") + recorded = _time(payload.get("replayed_started_at")) if isinstance(payload, Mapping) else None + if recorded is not None and recorded != 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 7ef9018f..9e89adc2 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 bd4b53d6..cf8c1118 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -3108,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) @@ -4300,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: @@ -4846,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 5f82243d..b5279ff3 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -3215,8 +3215,9 @@ def replay_now(self) -> datetime: activities. Group success retains the selected event's full precision; matching caught failure uses canonical-v1 integer milliseconds. Ordinary entry reads the run's canonical start from the workflow - task's ``replay_clock`` carrier (``WorkerReplayClock`` v1); a task - without that carrier leaves entry unavailable. Other groups, + 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 @@ -3417,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) @@ -3442,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: @@ -3890,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: @@ -3907,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 @@ -3961,6 +3967,7 @@ def 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, ) -> Any: """Replay workflow state and invoke a query, normalizing handler failures. @@ -3974,6 +3981,7 @@ def 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, )() try: registry: dict[str, str] = getattr(workflow_cls, "__workflow_queries__", {}) or {} @@ -3997,6 +4005,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. @@ -4021,6 +4030,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 @@ -4107,6 +4117,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( @@ -4124,6 +4135,7 @@ def validate_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, ) -> Any: """Replay and invoke a validator synchronously, refusing asynchronous results.""" from .errors import UpdateRejected @@ -4136,6 +4148,7 @@ def validate_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, ), )() try: @@ -4177,6 +4190,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( diff --git a/tests/test_business_replay_clock_entry.py b/tests/test_business_replay_clock_entry.py index ebce1fd6..b58da6b8 100644 --- a/tests/test_business_replay_clock_entry.py +++ b/tests/test_business_replay_clock_entry.py @@ -4,16 +4,28 @@ import asyncio from copy import deepcopy -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Any from unittest.mock import AsyncMock import pytest -from durable_workflow import Worker, serializer +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 EntryInstant, entry_instant -from durable_workflow.workflow import CompleteWorkflow, replay +from durable_workflow.testing import replay_history +from durable_workflow.workflow import ( + CompleteUpdate, + CompleteWorkflow, + FailUpdate, + Replayer, + WorkflowContext, + apply_update, + query_state, + replay, + validate_update, +) from tests.business_clock_workflows import NativeRedriveBusinessClockWorkflow, ScalarBusinessClockWorkflow from tests.test_business_replay_clock import history @@ -77,6 +89,9 @@ def test_microseconds_are_kept_exactly_in_utc() -> None: 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"), @@ -131,6 +146,10 @@ def test_unproved_redrive_history_accepts_only_a_redrive_anchor_for_entry() -> N 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] def test_worker_reads_the_task_carrier_identically_on_every_lease() -> None: @@ -155,3 +174,106 @@ async def lease(attempt: int, entry: Any) -> Any: 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} + assert query_state(EntryDeadlineWorkflow, events, [], "deadline", replay_clock_entry=carrier(), **options) == ( + DEADLINE + ) + assert validate_update(EntryDeadlineWorkflow, events, [], "extend", [], replay_clock_entry=carrier(), + **options) 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_state(EntryDeadlineWorkflow, events, [], "deadline", **options) + with pytest.raises(UpdateValidationFailed): + validate_update(EntryDeadlineWorkflow, events, [], "extend", [], **options) + 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"] From f3716bfd73150269aa7232286d645779c9a53f1e Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:56:55 +0000 Subject: [PATCH 3/3] Keep public query and validation signatures within the Sonar limit The worker calls _prepare_query_state and _prepare_update_validation, so the public query_state and validate_update don't need the carrier. A present but unreadable replayed_started_at now refuses the carrier, the entry pattern is ASCII-only, and the docs name proof-less starts and the in-memory environment among the unavailable cases. Refs durable-workflow/.github#215 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +-- docs/sdk-reference.md | 6 ++-- src/durable_workflow/replay_clock.py | 8 +++-- src/durable_workflow/workflow.py | 4 --- tests/test_business_replay_clock_entry.py | 37 +++++++++++++++++------ 5 files changed, 38 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f12096ae..392a3699 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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()`, `query_state()`, `apply_update()` and - `validate_update()` accept the task's object as `replay_clock_entry`. + `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 diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index 414fe51f..e937cbd9 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -1211,12 +1211,14 @@ Where the SDK cannot prove the time, `ctx.replay_now()` raises `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); +- 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`; + 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. diff --git a/src/durable_workflow/replay_clock.py b/src/durable_workflow/replay_clock.py index a2c02514..dc274c8c 100644 --- a/src/durable_workflow/replay_clock.py +++ b/src/durable_workflow/replay_clock.py @@ -36,7 +36,7 @@ _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"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}Z") +_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) @@ -302,8 +302,10 @@ 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") - recorded = _time(payload.get("replayed_started_at")) if isinstance(payload, Mapping) else None - if recorded is not None and recorded != started_at: + 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 diff --git a/src/durable_workflow/workflow.py b/src/durable_workflow/workflow.py index b5279ff3..83913744 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -3967,7 +3967,6 @@ def 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, ) -> Any: """Replay workflow state and invoke a query, normalizing handler failures. @@ -3981,7 +3980,6 @@ def 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, )() try: registry: dict[str, str] = getattr(workflow_cls, "__workflow_queries__", {}) or {} @@ -4135,7 +4133,6 @@ def validate_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, ) -> Any: """Replay and invoke a validator synchronously, refusing asynchronous results.""" from .errors import UpdateRejected @@ -4148,7 +4145,6 @@ def validate_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, ), )() try: diff --git a/tests/test_business_replay_clock_entry.py b/tests/test_business_replay_clock_entry.py index b58da6b8..ff0dac11 100644 --- a/tests/test_business_replay_clock_entry.py +++ b/tests/test_business_replay_clock_entry.py @@ -13,7 +13,7 @@ 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 EntryInstant, entry_instant +from durable_workflow.replay_clock import BusinessReplayClock, EntryInstant, entry_instant from durable_workflow.testing import replay_history from durable_workflow.workflow import ( CompleteUpdate, @@ -21,10 +21,12 @@ FailUpdate, Replayer, WorkflowContext, + _prepare_query_state, + _prepare_update_validation, + _UpdateValidationReplayOptions, + _workflow_sequence, apply_update, - query_state, replay, - validate_update, ) from tests.business_clock_workflows import NativeRedriveBusinessClockWorkflow, ScalarBusinessClockWorkflow from tests.test_business_replay_clock import history @@ -101,6 +103,7 @@ def test_microseconds_are_kept_exactly_in_utc() -> None: 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 @@ -150,6 +153,13 @@ def test_unproved_redrive_history_accepts_only_a_redrive_anchor_for_entry() -> N 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: @@ -210,11 +220,18 @@ def validate_extend(self) -> None: 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} - assert query_state(EntryDeadlineWorkflow, events, [], "deadline", replay_clock_entry=carrier(), **options) == ( - DEADLINE - ) - assert validate_update(EntryDeadlineWorkflow, events, [], "extend", [], replay_clock_entry=carrier(), - **options) is None + 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", @@ -226,9 +243,9 @@ def test_query_update_and_validation_rebuild_the_body_with_the_task_carrier() -> # Without a carrier the entry read is unavailable, so the rebuild fails visibly. with pytest.raises(QueryFailed, match="unavailable"): - query_state(EntryDeadlineWorkflow, events, [], "deadline", **options) + query(None) with pytest.raises(UpdateValidationFailed): - validate_update(EntryDeadlineWorkflow, events, [], "extend", [], **options) + validate(None) assert isinstance(apply_update(EntryDeadlineWorkflow, [*events, accepted], [], "update-1", **options), FailUpdate)