Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 33 additions & 0 deletions docs/sdk-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
55 changes: 55 additions & 0 deletions src/durable_workflow/replay_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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]] = {}
Expand All @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions src/durable_workflow/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -681,13 +682,18 @@ 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,
history_events,
list(start_input or []),
run_id=run_id,
payload_codec=payload_codec,
replay_clock_entry=replay_clock_entry,
)


Expand All @@ -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.

Expand All @@ -712,6 +719,7 @@ def replay_history_file(
start_input,
run_id=run_id,
payload_codec=payload_codec,
replay_clock_entry=replay_clock_entry,
)


Expand Down
4 changes: 4 additions & 0 deletions src/durable_workflow/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand Down
26 changes: 24 additions & 2 deletions src/durable_workflow/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3214,8 +3214,12 @@
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.
Expand Down Expand Up @@ -3414,7 +3418,9 @@
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)
Expand All @@ -3439,6 +3445,7 @@
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:
Expand Down Expand Up @@ -3830,6 +3837,7 @@
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.

Expand All @@ -3838,6 +3846,11 @@
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,
Expand All @@ -3862,6 +3875,7 @@
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


Expand All @@ -3880,6 +3894,7 @@
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:
Expand All @@ -3897,6 +3912,7 @@
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
Expand Down Expand Up @@ -3987,6 +4003,7 @@
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.

Expand All @@ -4011,6 +4028,7 @@
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
Expand Down Expand Up @@ -4097,6 +4115,7 @@
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(
Expand Down Expand Up @@ -4167,6 +4186,7 @@
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(
Expand Down Expand Up @@ -5380,32 +5400,33 @@

@replay_clock.isolated
def _replay_state(
workflow_cls: type,
history_events: Iterable[dict[str, Any]],
start_input: list[Any],
*,
workflow_id: str | None = None,
run_id: str = "",
workflow_command_id: str | None = None,
payload_codec: str | None = None,
external_storage: ExternalStorageDriver | None = None,
external_storage_cache: ExternalPayloadCache | None = None,
cancel_requested: bool = False,
cancellation_request: Mapping[str, Any] | None = None,
local_activity_executor: Callable[[RecordLocalActivity], Any] | None = None,
prepare_local_activities: bool = False,
prepare_local_activity_groups: bool = False,
local_activity_cancellation_policies: tuple[str, ...] = (),
stop_at_uncommitted_cancellation: bool = False,
reconstruction_only: bool = False,
allow_cancellation_scope_authoring: bool = False,
allow_cancellation_scope_delivery: bool = False,
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,
replay_clock_entry: Mapping[str, Any] | None = None,

Check warning on line 5429 in src/durable_workflow/workflow.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Function "_replay_state" has 26 parameters, which is greater than the 13 authorized.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-python&issues=AaIURJ04wtJ3wGsrqZf8&open=AaIURJ04wtJ3wGsrqZf8&pullRequest=380
) -> _ReplayState:
_validate_workflow_entrypoint(workflow_cls)
_workflow_handler_registries(workflow_cls)
Expand Down Expand Up @@ -5747,6 +5768,7 @@
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)

Expand Down
Loading