diff --git a/CHANGELOG.md b/CHANGELOG.md index f00b927..bb66d36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index e937cbd..32adea8 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -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; diff --git a/src/durable_workflow/replay_clock.py b/src/durable_workflow/replay_clock.py index dc274c8..ba55a2b 100644 --- a/src/durable_workflow/replay_clock.py +++ b/src/durable_workflow/replay_clock.py @@ -85,6 +85,7 @@ class _Frame: time: datetime | None thread: int task: object | None + entry: bool = False _ACTIVE: ContextVar[_Frame | None] = ContextVar("business_replay_clock", default=None) @@ -92,8 +93,8 @@ class _Frame: @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: @@ -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 @@ -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) @@ -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 @@ -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, diff --git a/src/durable_workflow/worker.py b/src/durable_workflow/worker.py index dcfe2bf..859ed01 100644 --- a/src/durable_workflow/worker.py +++ b/src/durable_workflow/worker.py @@ -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: @@ -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() diff --git a/src/durable_workflow/workflow.py b/src/durable_workflow/workflow.py index 1c21cbc..e7f0b02 100644 --- a/src/durable_workflow/workflow.py +++ b/src/durable_workflow/workflow.py @@ -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 @@ -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]], @@ -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: @@ -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() @@ -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( @@ -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() @@ -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) @@ -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: @@ -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 diff --git a/tests/business_clock_workflows.py b/tests/business_clock_workflows.py index 0fe4143..2176ba3 100644 --- a/tests/business_clock_workflows.py +++ b/tests/business_clock_workflows.py @@ -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 diff --git a/tests/fixtures/replay_regressions/business-clock-query-entry-attestation-empty-group.json b/tests/fixtures/replay_regressions/business-clock-query-entry-attestation-empty-group.json new file mode 100644 index 0000000..d8d0281 --- /dev/null +++ b/tests/fixtures/replay_regressions/business-clock-query-entry-attestation-empty-group.json @@ -0,0 +1,235 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "business-clock-query-entry-attestation-empty-group", + "protocol_version": "1.20", + "bindings": [ + "python" + ], + "workflow": { + "type": "tests.replay.empty-group-entry-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" + }, + "query_name": "entry", + "query_tasks": [ + { + "label": "key-absent", + "history_events": [ + { + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "tests.replay.empty-group-entry-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 + } + ] + }, + { + "label": "explicit-null", + "history_events": [ + { + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "tests.replay.empty-group-entry-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 + } + ], + "replay_clock": null + }, + { + "label": "carrier", + "history_events": [ + { + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "tests.replay.empty-group-entry-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 + } + ], + "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.empty-group-entry-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": "2026-11-01T00:00:00.000000+00:00" + }, + { + "type": "query_task", + "label": "key-absent", + "outcome": "failed" + }, + { + "type": "query_task", + "label": "explicit-null", + "outcome": "completed", + "result": null + }, + { + "type": "query_task", + "label": "carrier", + "outcome": "completed", + "result": "2026-11-01T00:00:00.000000+00:00" + } + ] + } +} diff --git a/tests/fixtures/replay_regressions/business-clock-query-entry-attestation.json b/tests/fixtures/replay_regressions/business-clock-query-entry-attestation.json new file mode 100644 index 0000000..525e15f --- /dev/null +++ b/tests/fixtures/replay_regressions/business-clock-query-entry-attestation.json @@ -0,0 +1,235 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "business-clock-query-entry-attestation", + "protocol_version": "1.20", + "bindings": [ + "python" + ], + "workflow": { + "type": "tests.replay.tolerant-entry-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" + }, + "query_name": "entry", + "query_tasks": [ + { + "label": "key-absent", + "history_events": [ + { + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "tests.replay.tolerant-entry-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 + } + ] + }, + { + "label": "explicit-null", + "history_events": [ + { + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "tests.replay.tolerant-entry-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 + } + ], + "replay_clock": null + }, + { + "label": "carrier", + "history_events": [ + { + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "tests.replay.tolerant-entry-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 + } + ], + "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.tolerant-entry-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": "2026-11-01T00:00:00.000000+00:00" + }, + { + "type": "query_task", + "label": "key-absent", + "outcome": "failed" + }, + { + "type": "query_task", + "label": "explicit-null", + "outcome": "completed", + "result": null + }, + { + "type": "query_task", + "label": "carrier", + "outcome": "completed", + "result": "2026-11-01T00:00:00.000000+00:00" + } + ] + } +} diff --git a/tests/test_business_replay_clock_query_attestation.py b/tests/test_business_replay_clock_query_attestation.py new file mode 100644 index 0000000..adf6b26 --- /dev/null +++ b/tests/test_business_replay_clock_query_attestation.py @@ -0,0 +1,153 @@ +"""Query and validation rebuilds never diverge from the workflow task's entry read (.github#215).""" + +from __future__ import annotations + +import asyncio +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.workflow import ( + CompleteWorkflow, + WorkflowContext, + _prepare_query_state, + _prepare_update_validation, + _UpdateValidationReplayOptions, + replay, +) +from tests.business_clock_workflows import EmptyGroupEntryWorkflow, TolerantEntryWorkflow, clock_text +from tests.query_task_helpers import leased_query_task +from tests.test_business_replay_clock import history +from tests.test_replay_clock import redrive_fixture + +RUN = "business-clock-run" +CARRIER = { + "schema": "durable-workflow.worker-replay-clock/v1", "workflow_run_id": RUN, + "started_at": "2026-11-01T00:00:00.000000Z", "source": "run_started_at", +} +ENTRY = "2026-11-01T00:00:00.000000+00:00" +ABSENT = object() + + +@workflow.defn(name="tests.replay.no-entry-clock") +class NoEntryReadWorkflow: + def run(self, ctx: WorkflowContext): # type: ignore[no-untyped-def] + yield ctx.schedule_activity("clock.first", []) + self.after = clock_text(ctx) + yield ctx.start_timer(2) + return self.after + + @workflow.query("after") + def after_query(self) -> str | None: + return self.after + + +def workflow_task_entry(entry: Any) -> Any: + outcome = replay(TolerantEntryWorkflow, history(), [], payload_codec="avro", run_id=RUN, + replay_clock_entry=entry) + try: + command = outcome.commands[0] + assert isinstance(command, CompleteWorkflow) + return command.result + finally: + outcome.close() + + +def query(entry: Any, *, attested: bool, workflow_cls: type = TolerantEntryWorkflow, name: str = "entry") -> Any: + return _prepare_query_state(workflow_cls, history()[:3], [], name, payload_codec="avro", run_id=RUN, + replay_clock_entry=entry, replay_clock_attested=attested)() + + +def validate(entry: Any, *, attested: bool) -> Any: + return _prepare_update_validation( + TolerantEntryWorkflow, history()[:3], [], "touch", [], + replay_options=_UpdateValidationReplayOptions( + run_id=RUN, payload_codec="avro", replay_clock_entry=entry, replay_clock_attested=attested, + ), + )() + + +def test_a_carrier_attested_query_matches_the_workflow_task() -> None: + assert workflow_task_entry(CARRIER) == ENTRY + assert query(CARRIER, attested=True) == ENTRY + assert validate(CARRIER, attested=True) is None + + +def test_an_explicit_null_attests_that_the_workflow_task_had_no_carrier() -> None: + assert workflow_task_entry(None) is None + assert query(None, attested=True) is None + assert validate(None, attested=True) is None + + +def test_an_unattested_rebuild_fails_instead_of_answering_with_other_state() -> None: + with pytest.raises(QueryFailed, match="replay_clock"): + query(None, attested=False) + with pytest.raises(UpdateValidationFailed, match="replay_clock"): + validate(None, attested=False) + + +def test_a_rejected_object_attests_no_carrier_like_null() -> None: + invalid = {**CARRIER, "workflow_run_id": "another-run"} + assert workflow_task_entry(invalid) is None + assert query(invalid, attested=True) is None + assert validate(invalid, attested=True) is None + + +def test_entry_time_carried_through_an_empty_group_still_needs_attestation() -> None: + outcome = replay(EmptyGroupEntryWorkflow, history(), [], payload_codec="avro", run_id=RUN, + replay_clock_entry=CARRIER) + try: + assert outcome.commands[0].result == ENTRY + finally: + outcome.close() + assert query(CARRIER, attested=True, workflow_cls=EmptyGroupEntryWorkflow) == ENTRY + assert query(None, attested=True, workflow_cls=EmptyGroupEntryWorkflow) is None + with pytest.raises(QueryFailed, match="replay_clock"): + query(None, attested=False, workflow_cls=EmptyGroupEntryWorkflow) + + +def test_only_entry_reads_need_attestation() -> None: + # A read after the first durable step has history authority on both sides. + assert query(None, attested=False, workflow_cls=NoEntryReadWorkflow, name="after") == ( + "2026-11-01T00:00:03.123456+00:00" + ) + + +def test_a_history_proved_redrive_entry_needs_no_carrier() -> None: + from tests.business_clock_workflows import NativeRedriveBusinessClockWorkflow + + fixture = redrive_fixture("business-clock-native-redrive-entry") + # The rebuild itself succeeds; only the unknown query name refuses afterwards. + with pytest.raises(QueryFailed, match="unknown query"): + _prepare_query_state( + NativeRedriveBusinessClockWorkflow, fixture["history"], [], "missing", payload_codec="avro", + run_id=fixture["workflow"]["run_id"], replay_clock_attested=False, + ) + + +@pytest.mark.parametrize("carrier,expected", [(ABSENT, "failed"), (None, "completed"), (CARRIER, "completed")]) +def test_worker_query_task_attestation(carrier: Any, expected: str) -> None: + async def run() -> tuple[str, AsyncMock]: + client = AsyncMock(spec=Client) + worker = Worker(client, task_queue="clock", workflows=[TolerantEntryWorkflow]) + task = { + "query_task_id": "query-1", "workflow_id": "business-clock-instance", "run_id": RUN, + "workflow_type": "tests.replay.tolerant-entry-clock", "query_name": "entry", + "history_events": history()[:3], "workflow_arguments": serializer.envelope([], codec="avro"), + "query_arguments": serializer.envelope([], codec="avro"), "payload_codec": "avro", + } + if carrier is not ABSENT: + task["replay_clock"] = carrier + return await worker._run_query_task(leased_query_task(worker, task)), client + + outcome, client = asyncio.run(run()) + assert outcome == expected + if expected == "failed": + client.complete_query_task.assert_not_awaited() + assert "replay_clock" in client.fail_query_task.await_args.kwargs["message"] + else: + assert client.complete_query_task.await_args.kwargs["result"] == (ENTRY if carrier else None) diff --git a/tests/test_replay_regression_corpus.py b/tests/test_replay_regression_corpus.py index 06844f2..0c2ec2e 100644 --- a/tests/test_replay_regression_corpus.py +++ b/tests/test_replay_regression_corpus.py @@ -35,15 +35,18 @@ from tests.business_clock_workflows import ( ChildBusinessClockWorkflow, CyclicFinalizerBusinessClockWorkflow, + EmptyGroupEntryWorkflow, NativeRedriveBusinessClockWorkflow, ParallelActivityBusinessClockWorkflow, ParallelFailureBusinessClockWorkflow, PrefixedCoreTimerBusinessClockWorkflow, ScalarBusinessClockWorkflow, + TolerantEntryWorkflow, ) from tests.condition_fingerprint_workflows import FingerprintApproval, FingerprintGenexpr, FingerprintTerminalDuplicate from tests.deregistration_recovery import RecoveredWorkflow as FencedRecoveryWorkflow from tests.integration.test_signal_external_workflow import IntegrationSenderWorkflow +from tests.query_task_helpers import query_task_delivery from tests.test_coalescing_signal_timer_replay import CoalescingRefresh from tests.test_condition_occurrence_id import OccurrenceApproval, SelectionOccurrences from tests.test_condition_replay_drift import ConditionIdentityWorkflow @@ -462,6 +465,8 @@ def run(self, ctx: WorkflowContext, message: str) -> None: NativeRedriveBusinessClockWorkflow, PrefixedCoreTimerBusinessClockWorkflow, ScalarBusinessClockWorkflow, + TolerantEntryWorkflow, + EmptyGroupEntryWorkflow, PendingFinally, BlankFailureWorkflow, IdentityAcrossReplay, @@ -926,6 +931,28 @@ async def run_lease(attempt: int) -> list[dict[str, Any]]: commands = asyncio.run(run_lease(1)) assert asyncio.run(run_lease(2)) == commands + + # A query task rebuilds the body. Only an attested carrier, or an + # explicit null, may answer; a missing key fails instead (server#1338). + async def run_query(variant: dict[str, Any]) -> dict[str, Any]: + client = AsyncMock(spec=Client) + worker = Worker(client, task_queue="regression-corpus", workflows=[WORKFLOW_TYPES[workflow_type]]) + task = query_task_delivery({ + "query_task_id": f"query-{variant['label']}", "workflow_id": workflow["workflow_id"], + "run_id": workflow["run_id"], "workflow_type": workflow_type, + "query_name": worker_task["query_name"], "history_events": deepcopy(variant["history_events"]), + "workflow_arguments": serializer.envelope(start_input, codec=payload_codec), + "query_arguments": serializer.envelope([], codec=payload_codec), "payload_codec": payload_codec, + **({"replay_clock": deepcopy(variant["replay_clock"])} if "replay_clock" in variant else {}), + }, worker_id=worker.worker_id, task_queue=worker.task_queue) + outcome = await worker._run_query_task(task) + document: dict[str, Any] = {"type": "query_task", "label": variant["label"], "outcome": outcome} + if client.complete_query_task.await_args is not None: + document["result"] = client.complete_query_task.await_args.kwargs["result"] + return document + + for variant in worker_task.get("query_tasks", []): + commands.append(asyncio.run(run_query(variant))) _assert_matches(fixture["expected"], {"command_sequence": commands}, f"{fixture['id']}.expected") return commands