diff --git a/CHANGELOG.md b/CHANGELOG.md index c3bc358d..0b09e17c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,27 @@ project follows [Semantic Versioning](https://semver.org/). (durable-workflow/.github#216). Nothing was written and no receipt was selected, so the refusal is never resent automatically. +### Fixed + +- `WorkflowContext::signals()` returns only signals the Server has applied to + the run (a `SignalApplied` event, or a `SignalReceived` carrying the + `workflow_sequence` of the wait that consumed it), plus the signal the current + workflow task delivers. It previously returned every received signal, so + workflow code could act on a signal the Server had not applied yet and later + rejected, for example closing the run before a queued update was applied. + Signals now reach workflow code in message order with updates, as in embedded + Workflow, Python and Rust. `SignalReceived` records that name neither a + signal ID nor a command ID are still returned. Replay compatibility: the + change is gated by the version marker + `durable-workflow.sdk-php.signals-applied-only`. The worker records it the + first time hiding an unapplied signal changes what `signals()` returns to a + live decision (a call at the end of the recorded history, or the predicate of + a condition wait whose outcome is not recorded). A history without the marker + replays with every received signal visible; with it, live decisions and calls + replayed at or after the marker's sequence use the applied-only view, and + calls replayed before it keep the earlier view. Runs that never meet an + unapplied signal record no marker (#434). + ## [3.20.0] - 2026-11-18 ### Added diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index dafd1a97..c65df3d7 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -713,6 +713,23 @@ invoked. The workflow reads their committed values with `$context->signals('set-language')` during replay. Query and update methods are executed with immutable `QueryContext` state. +`signals()` returns only signals the Server has applied to the run, plus the +signal the current workflow task delivers, in the order the Server received +them. The Server applies signals in message order with updates, so an update +sent before a signal is applied first. A signal that has been received but not +yet applied is not returned, and one the Server rejects (for example because +the run closed first) never is. + +Earlier SDK releases returned every received signal, so the applied-only view +is versioned with the marker `durable-workflow.sdk-php.signals-applied-only`. +The worker records it the first time hiding an unapplied signal changes what +`signals()` returns to a live decision: a call at the end of the recorded +history, or the predicate of a condition wait whose outcome is not recorded. +A history without the marker replays with every received signal visible. With +the marker, live decisions and calls replayed at or after the marker's sequence +use the applied-only view, and calls replayed before it keep the earlier view. +A run that never meets an unapplied signal records no marker. + The PHP SDK does not expose update-validator authoring. Worker registration therefore declares an empty `update_validators` list for every workflow type; capability discovery and Server admission must not infer validator parity from diff --git a/scripts/ci/run-replay-regression-fixture.php b/scripts/ci/run-replay-regression-fixture.php index fbbe0bf2..fffbf838 100644 --- a/scripts/ci/run-replay-regression-fixture.php +++ b/scripts/ci/run-replay-regression-fixture.php @@ -703,7 +703,7 @@ private static function executeLayout( 'arguments' => $codec->envelope($input), 'history_events' => $layout === 'inline' ? $history : [], 'next_history_page_token' => $layout === 'paginated' ? 'regression-page-1' : '', - ], self::taskAttributes($workflowType)); + ], self::taskAttributes($workflowType), self::workerTaskAttributes($fixture)); $pagedHistory[$taskId] = $layout === 'paginated' ? $history : []; } $transport = new ReplayRegressionTransport( @@ -959,6 +959,15 @@ private static function workflow(string $workflowType): callable return $result; }, + // sdk-php#434: only applied signals, and the one this task delivers. + 'golden.signal-applied' => static fn (WorkflowContext $context): array => ['signals' => $context->signals('approve')], + // sdk-php#434: a decision taken from the signals visible to this task. + 'golden.signal-decision' => static function (WorkflowContext $context): array { + $approved = $context->signals('approve') !== []; + $result = $context->activity($approved ? 'golden.approved' : 'golden.waiting'); + + return ['result' => $result, 'signals' => $context->signals('approve')]; + }, 'golden.immediate-condition' => static function (WorkflowContext $context): array { $first = $context->activity('golden.first'); $satisfied = $context->waitCondition(static fn (): bool => true, key: 'already-ready'); @@ -1419,6 +1428,21 @@ private static function selectionHandleIsolationWorkflow(): callable }; } + /** + * The resume context a signal-delivering workflow task carries (sdk-php#434). + * + * @param array $fixture + * @return array + */ + private static function workerTaskAttributes(array $fixture): array + { + $workerTask = is_array($fixture['worker_task'] ?? null) ? $fixture['worker_task'] : []; + + return array_intersect_key($workerTask, array_flip([ + 'resume_source_kind', 'resume_source_id', 'workflow_signal_id', 'workflow_command_id', 'signal_name', + ])); + } + /** @return array */ private static function taskAttributes(string $workflowType): array { diff --git a/src/Worker/AppliedSignals.php b/src/Worker/AppliedSignals.php new file mode 100644 index 00000000..0e05ded2 --- /dev/null +++ b/src/Worker/AppliedSignals.php @@ -0,0 +1,228 @@ + $signalIds + * @param array $commandIds + */ + private function __construct( + private readonly array $signalIds, + private readonly array $commandIds, + private readonly ?int $markerSequence, + ) { + } + + /** + * @param list> $history + * @param array $task + */ + public static function fromHistory(array $history, array $task): self + { + $signalIds = []; + $commandIds = []; + $markerSequence = null; + foreach ($history as $event) { + $type = $event['event_type'] ?? $event['type'] ?? null; + $payload = is_array($event['payload'] ?? null) ? $event['payload'] : []; + if ($type === 'SignalApplied' + || ($type === 'SignalReceived' && self::recordedSequence($payload['workflow_sequence'] ?? null))) { + self::remember($signalIds, $commandIds, $payload['signal_id'] ?? null, + $payload['workflow_command_id'] ?? $event['workflow_command_id'] ?? null); + } elseif ($markerSequence === null && self::isMarker($type, $payload)) { + $markerSequence = $payload['sequence']; + } + } + if (($task['resume_source_kind'] ?? null) === 'workflow_signal') { + self::remember($signalIds, $commandIds, $task['workflow_signal_id'] ?? $task['resume_source_id'] ?? null, + $task['workflow_command_id'] ?? null); + } + + return new self($signalIds, $commandIds, $markerSequence); + } + + /** @param array $payload */ + public static function isMarker(mixed $type, array $payload): bool + { + return $type === 'VersionMarkerRecorded' && ($payload['change_id'] ?? null) === self::CHANGE_ID + && is_int($payload['sequence'] ?? null) && $payload['sequence'] > 0; + } + + /** @internal The Replayer reports its position: the next authored sequence and whether it is the live end. */ + public function bind(Closure $position): void + { + $this->position = $position; + } + + /** + * @internal Evaluate a condition predicate whose outcome is not recorded. + * + * @template T + * @param Closure(): T $evaluation + * @return T + */ + public function live(Closure $evaluation): mixed + { + $previous = $this->liveEvaluation; + $this->liveEvaluation = true; + try { + return $evaluation(); + } finally { + $this->liveEvaluation = $previous; + } + } + + /** + * Keep the received signals workflow code observes, in history order. + * + * @param array> $received `SignalReceived` events of one name by history position + * @return array> + */ + public function select(array $received): array + { + $applied = array_filter($received, fn (array $event): bool => $this->observes($event)); + if (count($applied) === count($received)) { + return $received; + } + + return $this->appliedOnly() || $this->requestMarker() ? $applied : $received; + } + + /** @param array $event a `SignalReceived` event */ + public function observes(array $event): bool + { + $payload = is_array($event['payload'] ?? null) ? $event['payload'] : []; + $signalId = self::identity($payload['signal_id'] ?? null); + $commandId = self::identity($payload['workflow_command_id'] ?? $event['workflow_command_id'] ?? null); + + return self::recordedSequence($payload['workflow_sequence'] ?? null) + || ($signalId === null && $commandId === null) + || ($signalId !== null && isset($this->signalIds[$signalId])) + || ($commandId !== null && isset($this->commandIds[$commandId])); + } + + /** + * @internal Whether this replay must record the marker it has not sent yet. + * + * @phpstan-impure + */ + public function takeMarker(): bool + { + if (!$this->markerRequested || $this->markerFlushed) { + return false; + } + $this->markerFlushed = true; + + return true; + } + + private function appliedOnly(): bool + { + if ($this->markerRequested) { + return true; + } + if ($this->markerSequence === null) { + return false; + } + [$sequence, $live] = $this->position(); + + return $live || $sequence >= $this->markerSequence; + } + + /** Record the marker at a live decision of a history without one. */ + private function requestMarker(): bool + { + if ($this->markerSequence !== null || !$this->position()[1]) { + return false; + } + $this->markerRequested = true; + + return true; + } + + /** @return array{int, bool} */ + private function position(): array + { + [$sequence, $end] = $this->position === null ? [PHP_INT_MAX, false] : ($this->position)(); + + return [$sequence, $end || ($this->liveEvaluation && $this->position !== null)]; + } + + /** + * @param array $signalIds + * @param array $commandIds + */ + private static function remember(array &$signalIds, array &$commandIds, mixed $signalId, mixed $commandId): void + { + if (($signalId = self::identity($signalId)) !== null) { + $signalIds[$signalId] = true; + } + if (($commandId = self::identity($commandId)) !== null) { + $commandIds[$commandId] = true; + } + } + + private static function identity(mixed $value): ?string + { + return (is_string($value) && $value !== '') || is_int($value) ? (string) $value : null; + } + + private static function recordedSequence(mixed $value): bool + { + return (is_int($value) && $value > 0) || (is_string($value) && preg_match('/\A[1-9]\d*\z/', $value) === 1); + } +} diff --git a/src/Worker/Replayer.php b/src/Worker/Replayer.php index b3359f18..31316f5f 100644 --- a/src/Worker/Replayer.php +++ b/src/Worker/Replayer.php @@ -121,6 +121,30 @@ public function refuseNewGroupedConditionWaits(?Closure $refusal): void private ?BusinessReplayClock $lastBusinessReplayClock = null; + /** + * Send the applied-only signal marker once, the first time that view + * changed a live decision of this task (sdk-php#434). + * + * @param list> $commands + * @phpstan-impure + */ + private function recordAppliedSignalMarker( + AppliedSignals $appliedSignals, + array &$commands, + int &$nextSequence, + string $taskQueue, + ?WorkflowContext $context, + ): ?ReplayResult { + if (!$appliedSignals->takeMarker()) { + return null; + } + $failure = $this->appendWorkflowCommand($commands, + WorkflowCommand::versionMarker(AppliedSignals::CHANGE_ID, -1, 1, 'patched'), $taskQueue, $context); + ++$nextSequence; + + return $failure; + } + /** @internal Whether the most recent replay asked for business time it could not have. */ public function lastReplayReadUnavailableTime(): bool { @@ -198,6 +222,19 @@ public function replay( } $strictSequences = $cancellation->request !== null || $scopes->openings !== []; $steps = $this->recordedSteps($history, $strictSequences, $scopes); + // sdk-php#434: the applied-only signal marker is transparent to the + // authored command sequence; only its position selects the view. + $appliedSignals = AppliedSignals::fromHistory($history, $task); + $signalMarkerSequences = []; + $steps = array_values(array_filter($steps, static function (array $step) use (&$signalMarkerSequences): bool { + if ($step['shape'] === 'version_marker' && $step['detail'] === AppliedSignals::CHANGE_ID) { + $signalMarkerSequences[$step['sequence']] = true; + + return false; + } + + return true; + })); $stepsBySequence = []; foreach ($steps as $step) { $stepsBySequence[$step['sequence']] = $step; @@ -226,7 +263,7 @@ public function replay( $context = null; $businessReplayClock = new BusinessReplayClock($history, (string) ($task['workflow_id'] ?? ''), (string) ($task['run_id'] ?? '')); $this->lastBusinessReplayClock = $businessReplayClock; - $execution = new Fiber(ExecutionTelemetry::bind(function () use ($handler, $history, $input, $task, $businessReplayClock, $cancellation, $scopes, $localActivityExecutor, $prepareLocalActivities, $prepareLocalActivityGroups, $localActivityCancellationPolicies, $allowScopeAuthoring, $allowScopedPreparedLocalActivities, &$context): mixed { + $execution = new Fiber(ExecutionTelemetry::bind(function () use ($handler, $history, $input, $task, $businessReplayClock, $appliedSignals, $cancellation, $scopes, $localActivityExecutor, $prepareLocalActivities, $prepareLocalActivityGroups, $localActivityCancellationPolicies, $allowScopeAuthoring, $allowScopedPreparedLocalActivities, &$context): mixed { $current = Fiber::getCurrent(); if ($current === null) { throw new LogicException('Workflow execution did not start inside its Fiber.'); @@ -249,6 +286,7 @@ public function replay( $scopes->openings !== [], $allowScopedPreparedLocalActivities, $businessReplayClock, + $appliedSignals, ); try { @@ -261,15 +299,24 @@ public function replay( $stepCursor = 0; $commands = []; + $nextSequence = 1; + $appliedSignals->bind(static function () use (&$nextSequence, &$stepCursor, &$steps, $completedHistory): array { + return [$nextSequence, $stepCursor >= count($steps) && !$completedHistory]; + }); /** @var array $versionDecisions */ $versionDecisions = []; $suspended = $businessReplayClock->invoke($execution->start(...)); - $nextSequence = 1; $cancellationConsumed = false; $consumedScopeDeliveries = []; $consumedConditionTail = null; while (!$execution->isTerminated()) { + while (isset($signalMarkerSequences[$nextSequence])) { + ++$nextSequence; + } + if (($encodingFailure = $this->recordAppliedSignalMarker($appliedSignals, $commands, $nextSequence, $taskQueue, $context)) !== null) { + return $encodingFailure; + } if ($consumedConditionTail !== null) { $remaining = $this->restoreConsumedConditionTail($suspended, $consumedConditionTail); if ($remaining !== []) { @@ -277,8 +324,12 @@ public function replay( } $consumedConditionTail = null; } - if ($suspended instanceof WorkflowCommand && !isset($cancelledConditionSequences[$nextSequence]) - && ($conditionResult = $this->unrecordedConditionResult($suspended, $steps[$stepCursor] ?? null)) !== null) { + $conditionResult = $suspended instanceof WorkflowCommand && !isset($cancelledConditionSequences[$nextSequence]) + ? $this->unrecordedConditionResult($suspended, $steps[$stepCursor] ?? null) : null; + if (($encodingFailure = $this->recordAppliedSignalMarker($appliedSignals, $commands, $nextSequence, $taskQueue, $context)) !== null) { + return $encodingFailure; + } + if ($conditionResult !== null) { $suspended = $this->resumeExecution($execution, $businessReplayClock, $conditionResult); continue; } @@ -865,7 +916,11 @@ public function replay( $suspended = $this->resumeExecution($execution, $businessReplayClock, $step['value'], $step); continue; } - if ($suspended->conditionSatisfied()) { + $satisfied = $appliedSignals->live(static fn (): bool => $suspended->conditionSatisfied()); + if (($encodingFailure = $this->recordAppliedSignalMarker($appliedSignals, $commands, $nextSequence, $taskQueue, $context)) !== null) { + return $encodingFailure; + } + if ($satisfied) { $consumedConditionTail = $this->conditionTailAfterConsumption($step, $suspended, true); $suspended = $this->resumeExecution($execution, $businessReplayClock, true); continue; @@ -988,6 +1043,9 @@ public function replay( } } $this->assertNoRemainingSteps($steps, $stepCursor, 'complete_workflow'); + if (($encodingFailure = $this->recordAppliedSignalMarker($appliedSignals, $commands, $nextSequence, $taskQueue, $context)) !== null) { + return $encodingFailure; + } $result = $execution->getReturn(); if ($result instanceof \Generator) { throw new LogicException( diff --git a/src/Worker/WorkflowContext.php b/src/Worker/WorkflowContext.php index efc0abac..f6ca93cc 100644 --- a/src/Worker/WorkflowContext.php +++ b/src/Worker/WorkflowContext.php @@ -174,6 +174,7 @@ public function __construct( private bool $hasAuthoredCancellationScopes = false, private readonly bool $allowScopedPreparedLocalActivities = false, private readonly ?BusinessReplayClock $businessReplayClock = null, + private readonly ?AppliedSignals $appliedSignals = null, ) { $this->execution = $execution; $this->loadMessageStreamMessages(); @@ -883,18 +884,43 @@ public function observeCancellationReplayTime(?array $event): void ($this->cancellationReplayClock ??= new CancellationReplayClock())->observe($event); } - /** @return list> */ + /** + * The arguments of each signal with this name applied to the run, in the + * order the Server received them. + * + * A signal the Server has received but not yet applied is not included: + * the Server applies signals in message order with updates, when the + * workflow task that delivers the signal completes, and can still reject + * one it has not applied (sdk-php#434). The signal the current workflow + * task delivers is included. Runs recorded before this rule keep their + * earlier view: the first live call that hides a received signal records + * the version marker `durable-workflow.sdk-php.signals-applied-only` + * (see {@see AppliedSignals}). + * + * @return list> + */ public function signals(string $signalName): array { - $signals = []; - foreach ($this->history as $event) { - if (($event['event_type'] ?? $event['type'] ?? null) !== 'SignalReceived') { - continue; - } + return $this->receivedSignals($signalName, $this->appliedSignals); + } + + /** @return list> */ + private function receivedSignals(string $signalName, ?AppliedSignals $applied): array + { + $received = []; + foreach ($this->history as $order => $event) { $payload = isset($event['payload']) && is_array($event['payload']) ? $event['payload'] : []; - if (($payload['signal_name'] ?? null) !== $signalName) { - continue; + if (($event['event_type'] ?? $event['type'] ?? null) === 'SignalReceived' + && ($payload['signal_name'] ?? null) === $signalName) { + $received[$order] = $payload; } + } + if ($applied !== null) { + $received = array_intersect_key($received, $applied->select(array_map( + static fn (array $payload): array => ['event_type' => 'SignalReceived', 'payload' => $payload], $received))); + } + $signals = []; + foreach ($received as $payload) { $raw = $payload['value'] ?? $payload['input'] ?? $payload['arguments'] ?? null; $decoded = (is_array($raw) || is_string($raw)) ? $this->codec->decodeEnvelope($raw) : null; $signals[] = is_array($decoded) && array_is_list($decoded) ? $decoded : [$decoded]; @@ -935,7 +961,8 @@ private function loadMessageStreamMessages(): void { $seenPositions = []; $seenMessageIds = []; - foreach ($this->signals(self::MESSAGE_STREAM_SIGNAL) as $arguments) { + // Message streams keep their own cursor over every received message. + foreach ($this->receivedSignals(self::MESSAGE_STREAM_SIGNAL, null) as $arguments) { if (count($arguments) !== 1 || !is_array($arguments[0])) { continue; } diff --git a/tests/AppliedSignalsTest.php b/tests/AppliedSignalsTest.php new file mode 100644 index 00000000..8b13c6bb --- /dev/null +++ b/tests/AppliedSignalsTest.php @@ -0,0 +1,249 @@ +codec = new AvroPayloadCodec(); + } + + public function testAQueuedUpdateIsAppliedBeforeAReceivedSignalClosesTheRun(): void + { + // The update was queued before the release signal. The update's task + // must not see the release signal, so the run stays open for it. + $history = [ + $this->conditionOpened(), + ['event_type' => 'UpdateAccepted', 'payload' => ['update_id' => 'update-1', 'update_name' => 'change', + 'arguments' => $this->codec->envelope([1])]], + $this->received('signal-release', 'command-release', 'release'), + ]; + + $updateTask = $this->replayCondition($history, ['workflow_update_id' => 'update-1', 'update_name' => 'change']); + self::assertSame('record_version_marker', $updateTask->commands[0]['type']); + self::assertSame(AppliedSignals::CHANGE_ID, $updateTask->commands[0]['change_id']); + self::assertSame(1, $updateTask->commands[0]['version']); + self::assertNotContains('complete_workflow', array_column($updateTask->commands, 'type')); + + // The update task recorded the marker; the signal's own task delivers it. + $history[] = $this->marker(2); + $signalTask = $this->replayCondition($history, ['resume_source_kind' => 'workflow_signal', + 'workflow_signal_id' => 'signal-release', 'workflow_command_id' => 'command-release', 'signal_name' => 'release']); + self::assertSame(['complete_workflow'], array_column($signalTask->commands, 'type')); + self::assertSame(['released' => [['go']]], $this->codec->decodeEnvelope($signalTask->commands[0]['result'])); + } + + public function testARejectedSignalIsNeverObservedByANewDecision(): void + { + $history = [ + $this->conditionOpened(), + $this->marker(2), + $this->received('signal-release', 'command-release', 'release'), + ['event_type' => 'SignalRejected', 'payload' => ['signal_id' => 'signal-release', + 'workflow_command_id' => 'command-release', 'signal_name' => 'release', + 'rejection_reason' => 'run_closed_before_signal_applied']], + ]; + + self::assertNotContains('complete_workflow', array_column($this->replayCondition($history)->commands, 'type')); + } + + public function testAppliedSignalsAreObservedInReceiptOrder(): void + { + $history = [ + $this->received('signal-1', 'command-1', 'release', 'first'), + $this->received('signal-2', 'command-2', 'release', 'second'), + $this->received('signal-3', 'command-3', 'release', 'third', workflowSequence: 4), + $this->received('signal-4', 'command-4', 'release', 'fourth'), + ['event_type' => 'SignalApplied', 'payload' => ['signal_id' => 'signal-2', 'workflow_command_id' => 'command-2', + 'signal_name' => 'release', 'value' => $this->codec->envelope(['second'])]], + ['event_type' => 'SignalApplied', 'payload' => ['workflow_command_id' => 'command-1', 'signal_name' => 'release', + 'value' => $this->codec->envelope(['first'])]], + ['event_type' => 'SignalReceived', 'payload' => ['signal_name' => 'release', + 'arguments' => $this->codec->envelope(['imported'])]], + ]; + $workflow = static fn (WorkflowContext $context): array => $context->signals('release'); + + $result = (new Replayer($this->codec))->replay($workflow, $history, [], 'php-workers'); + + // Applied by event (by signal or command identity), consumed with a + // sequence, and an identity-less imported record; never the unapplied one. + self::assertSame(['record_version_marker', 'complete_workflow'], array_column($result->commands, 'type')); + self::assertSame([['first'], ['second'], ['third'], ['imported']], + $this->codec->decodeEnvelope($result->commands[1]['result'])); + } + + public function testAHistoryThatNeverReadsSignalsReplaysUnchanged(): void + { + $history = [ + $this->received('signal-pending', 'command-pending', 'approve'), + ['event_type' => 'ActivityScheduled', 'payload' => ['sequence' => 1, 'activity_type' => 'work']], + ['event_type' => 'ActivityCompleted', 'payload' => ['sequence' => 1, 'activity_type' => 'work', + 'result' => $this->codec->envelope('done')]], + $this->received('signal-later', 'command-later', 'approve'), + ]; + $workflow = static fn (WorkflowContext $context): mixed => $context->activity('work'); + + $result = (new Replayer($this->codec))->replay($workflow, $history, [], 'php-workers'); + + self::assertCount(1, $result->commands); + self::assertSame('complete_workflow', $result->commands[0]['type']); + self::assertSame('done', $this->codec->decodeEnvelope($result->commands[0]['result'])); + } + + public function testReadingSignalsThatAreAllAppliedRecordsNoMarker(): void + { + $history = [ + $this->received('signal-1', 'command-1', 'approve', 'first', workflowSequence: 1), + ['event_type' => 'SignalReceived', 'payload' => ['signal_name' => 'approve', + 'arguments' => $this->codec->envelope(['imported'])]], + ]; + $workflow = static fn (WorkflowContext $context): array => $context->signals('approve'); + + $result = (new Replayer($this->codec))->replay($workflow, $history, [], 'php-workers'); + + self::assertSame(['complete_workflow'], array_column($result->commands, 'type')); + self::assertSame([['first'], ['imported']], $this->codec->decodeEnvelope($result->commands[0]['result'])); + } + + public function testAHistoryWithoutTheMarkerKeepsTheEarlierViewForRecordedDecisions(): void + { + // Recorded by an earlier release: the activity was chosen while + // signal-observed was received but not yet applied. + $history = [ + $this->received('signal-observed', 'command-observed', 'approve', 'first'), + ['event_type' => 'ActivityScheduled', 'payload' => ['sequence' => 1, 'activity_type' => 'approved']], + ['event_type' => 'ActivityCompleted', 'payload' => ['sequence' => 1, 'activity_type' => 'approved', + 'result' => $this->codec->envelope('ok')]], + ]; + + $result = (new Replayer($this->codec))->replay(self::decision(), $history, [], 'php-workers'); + + // The recorded decision replays unchanged; the first live decision the + // applied-only view changes records the marker before it. + self::assertSame(['record_version_marker', 'schedule_activity'], array_column($result->commands, 'type')); + self::assertSame('second-waiting', $result->commands[1]['activity_type']); + } + + public function testTheMarkerSelectsTheAppliedViewFromItsPositionOn(): void + { + $history = [ + $this->received('signal-observed', 'command-observed', 'approve', 'first'), + ['event_type' => 'ActivityScheduled', 'payload' => ['sequence' => 1, 'activity_type' => 'approved']], + ['event_type' => 'ActivityCompleted', 'payload' => ['sequence' => 1, 'activity_type' => 'approved', + 'result' => $this->codec->envelope('ok')]], + $this->marker(2), + ['event_type' => 'ActivityScheduled', 'payload' => ['sequence' => 3, 'activity_type' => 'second-waiting']], + ['event_type' => 'ActivityCompleted', 'payload' => ['sequence' => 3, 'activity_type' => 'second-waiting', + 'result' => $this->codec->envelope('later')]], + ]; + + $result = (new Replayer($this->codec))->replay(self::decision(), $history, [], 'php-workers'); + + self::assertSame(['complete_workflow'], array_column($result->commands, 'type')); + self::assertSame(['ok', 'later', []], $this->codec->decodeEnvelope($result->commands[0]['result'])); + } + + public function testAChangedWorkflowIsReportedWithoutTryingTheEarlierView(): void + { + // The marker selects the applied view, so the recorded "approved" choice + // cannot be explained by the unapplied signal: it is nondeterministic. + $history = [ + $this->marker(1), + $this->received('signal-observed', 'command-observed', 'approve'), + ['event_type' => 'ActivityScheduled', 'payload' => ['sequence' => 2, 'activity_type' => 'approved']], + ]; + + try { + (new Replayer($this->codec))->replay(self::decision(), $history, [], 'php-workers'); + self::fail('A changed workflow must remain nondeterministic.'); + } catch (NonDeterministicWorkflow $error) { + self::assertSame(2, $error->sequence); + self::assertStringContainsString('waiting', $error->getMessage()); + } + } + + public function testACompletedHistoryRecordsNoMarker(): void + { + $history = [ + $this->received('signal-observed', 'command-observed', 'approve', 'first'), + ['event_type' => 'WorkflowCompleted', 'payload' => []], + ]; + $workflow = static fn (WorkflowContext $context): array => $context->signals('approve'); + + $result = (new Replayer($this->codec))->replay($workflow, $history, [], 'php-workers'); + + self::assertSame(['complete_workflow'], array_column($result->commands, 'type')); + self::assertSame([['first']], $this->codec->decodeEnvelope($result->commands[0]['result'])); + } + + private static function decision(): \Closure + { + return static function (WorkflowContext $context): array { + $first = $context->activity($context->signals('approve') !== [] ? 'approved' : 'waiting'); + $second = $context->activity($context->signals('approve') !== [] ? 'second-approved' : 'second-waiting'); + + return [$first, $second, $context->signals('approve')]; + }; + } + + /** @return array */ + private function conditionOpened(): array + { + return ['event_type' => 'ConditionWaitOpened', 'payload' => ['sequence' => 1, + 'condition_wait_id' => 'wait-release', 'condition_key' => 'release', 'timeout_seconds' => 300]]; + } + + /** @return array */ + private function marker(int $sequence): array + { + return ['event_type' => 'VersionMarkerRecorded', 'payload' => ['sequence' => $sequence, + 'change_id' => AppliedSignals::CHANGE_ID, 'version' => 1, 'min_supported' => -1, 'max_supported' => 1]]; + } + + /** @return array */ + private function received(string $signalId, string $commandId, string $name, string $value = 'go', ?int $workflowSequence = null): array + { + $payload = ['signal_id' => $signalId, 'workflow_command_id' => $commandId, 'signal_name' => $name, + 'arguments' => $this->codec->envelope([$value])]; + if ($workflowSequence !== null) { + $payload['workflow_sequence'] = $workflowSequence; + } + + return ['event_type' => 'SignalReceived', 'payload' => $payload]; + } + + /** + * @param list> $history + * @param array $task + */ + private function replayCondition(array $history, array $task = []): ReplayResult + { + $workflow = static function (WorkflowContext $context): array { + $context->waitCondition(static fn (): bool => $context->signals('release') !== [], key: 'release', timeout: 300); + + return ['released' => $context->signals('release')]; + }; + + return (new Replayer($this->codec))->replay($workflow, $history, [], 'php-workers', + ['workflow_id' => 'workflow-434', 'run_id' => 'run-434'] + $task); + } +} diff --git a/tests/Support/ReplayRegressionFixture.php b/tests/Support/ReplayRegressionFixture.php index bffade69..bab06e68 100644 --- a/tests/Support/ReplayRegressionFixture.php +++ b/tests/Support/ReplayRegressionFixture.php @@ -199,6 +199,16 @@ public static function execute(array $fixture): array $codec = new AvroPayloadCodec(); $scopedCleanup = $workflowType === 'golden.prepared-local-scoped-cleanup'; $task = self::taskAttributes($workflowType); + $workerTask = $fixture['worker_task'] ?? []; + if (!is_array($workerTask)) { + throw new RuntimeException("{$identity}.worker_task must be an object."); + } + // The resume context a signal-delivering task carries (sdk-php#434). + foreach (['resume_source_kind', 'resume_source_id', 'workflow_signal_id', 'workflow_command_id', 'signal_name'] as $field) { + if (array_key_exists($field, $workerTask)) { + $task[$field] = $workerTask[$field]; + } + } if ($scopedCleanup) { foreach ($history as $event) { if (($event['event_type'] ?? $event['type'] ?? null) === 'WorkflowStarted') { @@ -525,6 +535,15 @@ private static function workflow(string $workflowType): callable return $result; }, + // sdk-php#434: only applied signals, and the one this task delivers. + 'golden.signal-applied' => static fn (WorkflowContext $context): array => ['signals' => $context->signals('approve')], + // sdk-php#434: a decision taken from the signals visible to this task. + 'golden.signal-decision' => static function (WorkflowContext $context): array { + $approved = $context->signals('approve') !== []; + $result = $context->activity($approved ? 'golden.approved' : 'golden.waiting'); + + return ['result' => $result, 'signals' => $context->signals('approve')]; + }, 'golden.immediate-condition' => static function (WorkflowContext $context): array { $first = $context->activity('golden.first'); $satisfied = $context->waitCondition(static fn (): bool => true, key: 'already-ready'); diff --git a/tests/fixtures/replay-regressions/signals-applied-only-marker-recorded.json b/tests/fixtures/replay-regressions/signals-applied-only-marker-recorded.json new file mode 100644 index 00000000..161bba27 --- /dev/null +++ b/tests/fixtures/replay-regressions/signals-applied-only-marker-recorded.json @@ -0,0 +1,87 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "php-signals-applied-only-marker-recorded", + "protocol_version": "1.20", + "bindings": [ + "php" + ], + "workflow": { + "type": "golden.signal-decision", + "input": [] + }, + "history": [ + { + "event_type": "SignalReceived", + "payload": { + "signal_id": "signal-pending", + "workflow_command_id": "command-pending", + "signal_name": "approve", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCgpmaXJzdAA=" + } + } + }, + { + "event_type": "VersionMarkerRecorded", + "payload": { + "sequence": 1, + "change_id": "durable-workflow.sdk-php.signals-applied-only", + "version": 1, + "min_supported": -1, + "max_supported": 1 + } + }, + { + "event_type": "ActivityScheduled", + "payload": { + "sequence": 2, + "activity_type": "golden.waiting" + } + }, + { + "event_type": "ActivityCompleted", + "payload": { + "sequence": 2, + "activity_type": "golden.waiting", + "result": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwocd2FpdGluZy1yZXN1bHQ=" + } + } + }, + { + "event_type": "SignalReceived", + "payload": { + "signal_id": "signal-later", + "workflow_command_id": "command-later", + "signal_name": "approve", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCgxzZWNvbmQA" + } + } + } + ], + "command_sequence": [ + { + "type": "complete_workflow", + "result": { + "result": "waiting-result", + "signals": [] + } + } + ], + "expected": { + "command_sequence": [ + { + "type": "complete_workflow", + "result": { + "result": "waiting-result", + "signals": [] + } + } + ] + } +} diff --git a/tests/fixtures/replay-regressions/signals-observe-only-applied.json b/tests/fixtures/replay-regressions/signals-observe-only-applied.json new file mode 100644 index 00000000..193c2f03 --- /dev/null +++ b/tests/fixtures/replay-regressions/signals-observe-only-applied.json @@ -0,0 +1,116 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "php-signals-observe-only-applied", + "protocol_version": "1.20", + "bindings": [ + "php" + ], + "workflow": { + "type": "golden.signal-applied", + "input": [] + }, + "worker_task": { + "resume_source_kind": "workflow_signal", + "resume_source_id": "signal-current", + "workflow_signal_id": "signal-current", + "workflow_command_id": "command-current", + "signal_name": "approve" + }, + "history": [ + { + "event_type": "SignalReceived", + "payload": { + "signal_id": "signal-first", + "workflow_command_id": "command-first", + "signal_name": "approve", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCgpmaXJzdAA=" + } + } + }, + { + "event_type": "SignalApplied", + "payload": { + "signal_id": "signal-first", + "workflow_command_id": "command-first", + "signal_name": "approve", + "value": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCgpmaXJzdAA=" + } + } + }, + { + "event_type": "SignalReceived", + "payload": { + "signal_id": "signal-current", + "workflow_command_id": "command-current", + "signal_name": "approve", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCg5jdXJyZW50AA==" + } + } + }, + { + "event_type": "SignalReceived", + "payload": { + "signal_id": "signal-unapplied", + "workflow_command_id": "command-unapplied", + "signal_name": "approve", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCgxzZWNvbmQA" + } + } + } + ], + "command_sequence": [ + { + "type": "record_version_marker", + "change_id": "durable-workflow.sdk-php.signals-applied-only", + "version": 1, + "min_supported": -1, + "max_supported": 1 + }, + { + "type": "complete_workflow", + "result": { + "signals": [ + [ + "first" + ], + [ + "current" + ] + ] + } + } + ], + "expected": { + "command_sequence": [ + { + "type": "record_version_marker", + "change_id": "durable-workflow.sdk-php.signals-applied-only", + "version": 1, + "min_supported": -1, + "max_supported": 1 + }, + { + "type": "complete_workflow", + "result": { + "signals": [ + [ + "first" + ], + [ + "current" + ] + ] + } + } + ] + } +} diff --git a/tests/fixtures/replay-regressions/signals-unapplied-legacy-history.json b/tests/fixtures/replay-regressions/signals-unapplied-legacy-history.json new file mode 100644 index 00000000..ddb85a88 --- /dev/null +++ b/tests/fixtures/replay-regressions/signals-unapplied-legacy-history.json @@ -0,0 +1,91 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "php-signals-unapplied-legacy-history", + "protocol_version": "1.20", + "bindings": [ + "php" + ], + "workflow": { + "type": "golden.signal-decision", + "input": [] + }, + "history": [ + { + "event_type": "SignalReceived", + "payload": { + "signal_id": "signal-observed", + "workflow_command_id": "command-observed", + "signal_name": "approve", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCgpmaXJzdAA=" + } + } + }, + { + "event_type": "ActivityScheduled", + "payload": { + "sequence": 1, + "activity_type": "golden.approved" + } + }, + { + "event_type": "ActivityCompleted", + "payload": { + "sequence": 1, + "activity_type": "golden.approved", + "result": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwoeYXBwcm92ZWQtcmVzdWx0" + } + } + }, + { + "event_type": "SignalReceived", + "payload": { + "signal_id": "signal-later", + "workflow_command_id": "command-later", + "signal_name": "approve", + "arguments": { + "codec": "avro", + "blob": "wwHioz3/VYAiNwwCCgxzZWNvbmQA" + } + } + } + ], + "command_sequence": [ + { + "type": "record_version_marker", + "change_id": "durable-workflow.sdk-php.signals-applied-only", + "version": 1, + "min_supported": -1, + "max_supported": 1 + }, + { + "type": "complete_workflow", + "result": { + "result": "approved-result", + "signals": [] + } + } + ], + "expected": { + "command_sequence": [ + { + "type": "record_version_marker", + "change_id": "durable-workflow.sdk-php.signals-applied-only", + "version": 1, + "min_supported": -1, + "max_supported": 1 + }, + { + "type": "complete_workflow", + "result": { + "result": "approved-result", + "signals": [] + } + } + ] + } +}