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
13 changes: 10 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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()`,
rebuild the workflow with their own carrier. A query task or pre-accept
update validation rebuilds with its own task's `replay_clock`. When that
task has no `replay_clock` key (Servers without durable-workflow/server#1338),
a rebuild in which the workflow reads the clock at entry
fails the query or validation, even if the workflow catches
`ReplayClockUnavailable`, rather than answering with state the workflow task
never computed. An explicit `null`, or an object this SDK rejects, means
the workflow task had no carrier either, so the rebuild proceeds. Upgrade note: an in-flight run whose code
branches on entry unavailability takes the other branch after this upgrade,
so version such code or drain those runs first. `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)
Expand Down
9 changes: 7 additions & 2 deletions docs/sdk-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1214,8 +1214,13 @@ 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;
update validation whose task has no `replay_clock` key, which Servers before
durable-workflow/server#1338 never send. The query or validation then fails,
even when the workflow catches the error, so it never answers with state the
workflow task did not compute. A `replay_clock` of `null` on those tasks
means the run has no provable start, so the workflow task had no carrier
either and the rebuild proceeds. So does an object this SDK rejects, which
it rejected on the workflow task too;
- 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;
Expand Down
30 changes: 26 additions & 4 deletions src/durable_workflow/replay_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,16 @@ class _Frame:
time: datetime | None
thread: int
task: object | None
entry: bool = False


_ACTIVE: ContextVar[_Frame | None] = ContextVar("business_replay_clock", default=None)
_DISCARD = threading.local()


@contextlib.contextmanager
def execution_scope(owner: object | None, time: datetime | None) -> Iterator[None]:
token = _ACTIVE.set(_Frame(owner, time, threading.get_ident(), _task()))
def execution_scope(owner: object | None, time: datetime | None, *, entry: bool = False) -> Iterator[None]:
token = _ACTIVE.set(_Frame(owner, time, threading.get_ident(), _task(), entry))
try:
yield
finally:
Expand Down Expand Up @@ -139,9 +140,14 @@ def _collection(phase: str, info: Mapping[str, int]) -> None:
def read(owner: object) -> datetime:
frame = _ACTIVE.get()
if (getattr(_DISCARD, "active", False) or getattr(_DISCARD, "collecting", False)
or frame is None or frame.owner is not owner or frame.time is None
or frame is None or frame.owner is not owner
or frame.thread != threading.get_ident() or frame.task is not _task()):
raise ReplayClockUnavailable()
if frame.time is None:
clock = getattr(owner, "_business_clock", None)
if frame.entry and isinstance(clock, BusinessReplayClock):
clock.entry_read_unavailable()
raise ReplayClockUnavailable()
return frame.time


Expand Down Expand Up @@ -295,6 +301,14 @@ def __init__(
self.initial = (None, entry.started_at)
self._pending: tuple[int | None, datetime | None] = self.initial
self._current: tuple[int | None, datetime | None] = self.initial
# Whether the pending/current time is still the entry value. An empty
# group carries it into the next resume without consuming history.
self._pending_entry = True
self._current_entry = False
# A query or validation rebuild whose task does not attest the entry
# carrier cannot know what the workflow task's entry read returned.
self.entry_unattested = False
self.unattested_entry_read = False
for index, event in enumerate(events):
self._index_event(index, event, sequence_claim)

Expand Down Expand Up @@ -367,9 +381,16 @@ def _redrive_start(self, index: int, payload: Mapping[str, Any], workflow_id: st

def resume(self, owner: object, function: Callable[..., _T], *args: Any) -> _T:
self._current, self._pending = self._pending, (None, None)
with execution_scope(owner, self._current[1]):
entry, self._pending_entry = self._pending_entry, False
self._current_entry = entry
with execution_scope(owner, self._current[1], entry=entry):
return function(*args)

def entry_read_unavailable(self) -> None:
"""Record an entry read that only an unattested rebuild found unavailable."""
if self.entry_unattested:
self.unattested_entry_read = True

def snapshot(self) -> datetime | None:
# Only this final inspected prefix is proved for a query callback.
index, time = self._current
Expand All @@ -381,6 +402,7 @@ def unavailable(self) -> None:
def preserve_boundary(self) -> None:
"""An empty group consumes no new event and retains the proved prefix."""
self._pending = self._current
self._pending_entry = self._current_entry

def observe_activity_group(
self, members: Sequence[_GroupMember], failed_member: int | None, *, reconstruction: bool,
Expand Down
2 changes: 2 additions & 0 deletions src/durable_workflow/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -4317,6 +4317,7 @@ async def _run_query_task_core(self, task: dict[str, Any], *, client: Client | N
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"),
replay_clock_attested="replay_clock" in task,
)
await authority.confirm()
async def execute() -> Any:
Expand Down Expand Up @@ -4864,6 +4865,7 @@ async def _run_update_validation_task(self, task: dict[str, Any]) -> str:
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"),
replay_clock_attested="replay_clock" in task,
),
)
result = invoke()
Expand Down
32 changes: 29 additions & 3 deletions src/durable_workflow/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3241,8 +3241,10 @@ def replay_now(self) -> datetime:
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). Entry is
unavailable without that carrier, including query and update-
validation rebuilds and offline replay that omit it. Other groups,
unavailable without that carrier, including offline replay that
omits it. A query or update-validation rebuild whose task has no
``replay_clock`` key fails when the workflow reads entry time, even
if it catches the error. Other groups,
inline/local operations, unproved times and group-only query time
remain unavailable. Reads are stable,
and proved boundaries may move backwards. Adopt
Expand Down Expand Up @@ -3904,6 +3906,12 @@ def replay(
).outcome


_UNATTESTED_ENTRY = (
"the workflow read replay_now() at entry, and this task does not carry the replay_clock "
"entry instant its workflow task used"
)


def _prepare_query_state(
workflow_cls: type,
history_events: Iterable[dict[str, Any]],
Expand All @@ -3920,6 +3928,7 @@ def _prepare_query_state(
prepare_local_activity_groups: bool = False,
local_activity_cancellation_policies: tuple[str, ...] = (),
replay_clock_entry: Mapping[str, Any] | None = None,
replay_clock_attested: bool = True,
) -> Callable[[], Any]:
"""Prepare the query so a worker can recheck authority after replay."""
try:
Expand All @@ -3938,9 +3947,13 @@ def _prepare_query_state(
prepare_local_activity_groups=prepare_local_activity_groups,
local_activity_cancellation_policies=local_activity_cancellation_policies,
replay_clock_entry=replay_clock_entry,
replay_clock_attested=replay_clock_attested,
)
except Exception as exc:
raise QueryFailed(f"workflow replay failed before query: {exc}") from exc
if state.context._business_clock.unattested_entry_read:
state.outcome.close()
raise QueryFailed(f"workflow replay failed before query: {_UNATTESTED_ENTRY}")
if state.outcome.commands and isinstance(state.outcome.commands[0], FailWorkflow):
failure = state.outcome.commands[0]
state.outcome.close()
Expand Down Expand Up @@ -4141,6 +4154,7 @@ class _UpdateValidationReplayOptions:
prepare_local_activity_groups: bool = False
local_activity_cancellation_policies: tuple[str, ...] = ()
replay_clock_entry: Mapping[str, Any] | None = None
replay_clock_attested: bool = True


def validate_update(
Expand Down Expand Up @@ -4212,12 +4226,17 @@ def _prepare_update_validation(
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,
replay_clock_attested=replay_options.replay_clock_attested,
)
except Exception as exc:
raise UpdateValidationFailed(
f"workflow replay failed before update validation: {str(exc) or type(exc).__name__}"
) from exc

if state.context._business_clock.unattested_entry_read:
state.outcome.close()
raise UpdateValidationFailed(f"workflow replay failed before update validation: {_UNATTESTED_ENTRY}")

if state.outcome.commands and isinstance(state.outcome.commands[0], FailWorkflow):
failure = state.outcome.commands[0]
state.outcome.close()
Expand Down Expand Up @@ -5452,6 +5471,7 @@ def _replay_state(
author_ordered_condition_inputs: bool = False,
pending_condition_input: tuple[int | None] | None = None,
replay_clock_entry: Mapping[str, Any] | None = None,
replay_clock_attested: bool = True,
) -> _ReplayState:
_validate_workflow_entrypoint(workflow_cls)
_workflow_handler_registries(workflow_cls)
Expand Down Expand Up @@ -5795,6 +5815,12 @@ def _replay_state(
events, workflow_id or "", run_id, sequence_claim=_workflow_sequence,
entry=replay_clock.entry_instant(replay_clock_entry, run_id),
)
# Server sends a query or validation task's replay_clock key whenever it
# can (server#1338): an object, or null when no start is provable. A
# missing key leaves the workflow task's entry value unknown, so an entry
# read must fail the rebuild, not diverge. An object this SDK rejects was
# rejected on the workflow task too, so it attests no carrier, like null.
ctx._business_clock.entry_unattested = reconstruction_only and not replay_clock_attested
lifetime = _ReplayLifetime(ctx.logger)

def _set_replaying(replaying: bool) -> None:
Expand Down Expand Up @@ -7002,7 +7028,7 @@ def _assert_continuation_replayed() -> None:
# by a successfully bound body is still an actual workflow failure.
try:
_refresh_replay_logging()
with replay_clock.execution_scope(ctx, ctx._business_clock.initial[1]):
with replay_clock.execution_scope(ctx, ctx._business_clock.initial[1], entry=True):
gen = entry(ctx, *start_input)
except NonDeterministicReplayError:
raise
Expand Down
45 changes: 45 additions & 0 deletions tests/business_clock_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,48 @@ def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def]
return {"activity_type": error.activity_type, "message": str(error), "clock": clock_text(ctx),
"legacy": ctx.now().isoformat(timespec="microseconds")}
raise AssertionError("expected the recorded group failure")


@workflow.defn(name="tests.replay.tolerant-entry-clock")
class TolerantEntryWorkflow:
"""Catches unavailability at entry, so a carrier-less rebuild would build other state."""

def __init__(self) -> None:
self.entry: str | None = None

def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def]
self.entry = clock_text(ctx)
yield ctx.schedule_activity("clock.first", [])
yield ctx.start_timer(2)
return self.entry

@workflow.query("entry")
def entry_query(self) -> str | None:
return self.entry

@workflow.update("touch")
def touch(self) -> str | None:
return self.entry

@workflow.update_validator("touch")
def validate_touch(self) -> None:
return None


@workflow.defn(name="tests.replay.empty-group-entry-clock")
class EmptyGroupEntryWorkflow:
"""An empty group carries the entry value into the next resume."""

def __init__(self) -> None:
self.entry: str | None = None

def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def]
yield []
self.entry = clock_text(ctx)
yield ctx.schedule_activity("clock.first", [])
yield ctx.start_timer(2)
return self.entry

@workflow.query("entry")
def entry_query(self) -> str | None:
return self.entry
Loading