diff --git a/CHANGELOG.md b/CHANGELOG.md index 071350c15..be01d0d1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,22 @@ column outside the migrator transaction under the schema lock budget, with no backfill. To fill it for opted-in runs that closed before the upgrade, rebuild them with `workflow:v2:rebuild-projections --run-id=...`. +- A signal wait interrupted by a delivered cooperative cancellation, including + timeout cleanup, is no longer reported as received by a later signal + (#1315). `SignalWaits`, run detail and the projected waits show it as + `cancelled` with source status `cancellation_delivered`, also for the member + waits of a delivered group. A signal accepted after delivery is buffered + under its own command identity, as any signal without an open wait is: its + `SignalReceived` and `SignalRejected` no longer carry the interrupted wait's + `signal_wait_id`, and it no longer schedules a workflow task that could not + apply it. A `WorkflowTimedOut` run now closes its open signal waits like the + other terminal events. History is unchanged and replay keeps its earlier + view of these waits; runs recorded before the upgrade show the corrected + wait state on their next projection. + One upgrade edge case: on an external (bridge) worker, an in-flight run + whose late signal an earlier engine attributed to the interrupted wait, and + which then opens a new wait for that signal, may not schedule a task for it + until another task runs. Embedded runs are unaffected. ## 2.42.0 - 2026-11-26 diff --git a/src/V2/Support/DefaultWorkflowTaskBridge.php b/src/V2/Support/DefaultWorkflowTaskBridge.php index d8a9662b7..f97359a98 100644 --- a/src/V2/Support/DefaultWorkflowTaskBridge.php +++ b/src/V2/Support/DefaultWorkflowTaskBridge.php @@ -3102,7 +3102,7 @@ private function cancelSelectionLeaf(WorkflowRun $run, WorkflowTask $task, int $ } $run->unsetRelation('historyEvents'); - foreach (SignalWaits::forRun($run) as $wait) { + foreach (SignalWaits::forRun($run, replayCompatible: true) as $wait) { if (($wait['sequence'] ?? null) === $sequence && ($wait['status'] ?? null) === 'open') { return true; } diff --git a/src/V2/Support/RunWaitView.php b/src/V2/Support/RunWaitView.php index b2eba2ecf..32a2de0d8 100644 --- a/src/V2/Support/RunWaitView.php +++ b/src/V2/Support/RunWaitView.php @@ -293,6 +293,10 @@ private static function signalWaits(WorkflowRun $run, array $taskByTimerId): arr ), 'cancelled' => match ($wait['source_status']) { 'timeout_cancelled' => sprintf('Signal %s timeout was cancelled.', $wait['signal_name']), + 'cancellation_delivered' => sprintf( + 'Signal %s wait ended when cancellation was delivered to it.', + $wait['signal_name'], + ), 'cancelled' => 'Signal wait ended when the run was cancelled.', 'terminated' => 'Signal wait ended when the run was terminated.', 'continued' => 'Signal wait ended when the run continued as new.', diff --git a/src/V2/Support/SignalWaits.php b/src/V2/Support/SignalWaits.php index d1e3e9d19..4c8ca52e6 100644 --- a/src/V2/Support/SignalWaits.php +++ b/src/V2/Support/SignalWaits.php @@ -36,8 +36,20 @@ public static function bufferedWaitIdForCommandId(string $commandId): string * command_status: string|null, * command_outcome: string|null * }> + * + * A cooperative cancellation delivered at a signal wait, or at a group + * containing one, ends that wait: workflow code was interrupted there and + * can never resume it with a signal. A workflow timeout closes open waits + * like every other terminal event. Signals accepted afterwards therefore + * do not resolve, and are not attributed to, the interrupted wait. + * + * Pass $replayCompatible to read the states replay decisions have always + * read, in which neither a delivered cancellation nor a workflow timeout + * closes a wait. Execution paths that derive replay cursors or + * history-writing decisions from these states use it, so that a history + * recorded before these closures existed replays unchanged. */ - public static function forRun(WorkflowRun $run): array + public static function forRun(WorkflowRun $run, bool $replayCompatible = false): array { $run->loadMissing('historyEvents'); @@ -45,182 +57,21 @@ public static function forRun(WorkflowRun $run): array $openWaitIdsByName = []; foreach ($run->historyEvents->sortBy('sequence') as $event) { - if (! $event instanceof WorkflowHistoryEvent) { - continue; - } - - $signalName = self::stringValue($event->payload['signal_name'] ?? null); - - if ($event->event_type === HistoryEventType::SignalWaitOpened) { - if ($signalName === null) { - continue; - } - - $waitId = self::waitIdForOpenedEvent($event); - - if ($waitId === null) { - continue; - } - - $waits[$waitId] = [ - 'id' => $waitId, - 'signal_wait_id' => $waitId, - 'signal_id' => null, - 'signal_name' => $signalName, - 'sequence' => self::intValue($event->payload['sequence'] ?? null), - 'status' => 'open', - 'source_status' => 'waiting', - 'opened_at' => $event->recorded_at ?? $event->created_at, - 'deadline_at' => null, - 'resolved_at' => null, - 'timeout_fired_at' => null, - 'timeout_seconds' => self::intValue($event->payload['timeout_seconds'] ?? null), - 'timer_id' => null, - 'command_id' => null, - 'command_sequence' => null, - 'command_status' => null, - 'command_outcome' => null, - ]; - - $openWaitIdsByName[$signalName] ??= []; - $openWaitIdsByName[$signalName][] = $waitId; - - continue; - } - - if ( - in_array($event->event_type, [ - HistoryEventType::TimerScheduled, - HistoryEventType::TimerFired, - HistoryEventType::TimerCancelled, - ], true) - && self::stringValue($event->payload['timer_kind'] ?? null) === 'signal_timeout' - ) { - if ($signalName === null) { - continue; - } - - $explicitWaitId = self::stringValue($event->payload['signal_wait_id'] ?? null); - $waitId = $event->event_type === HistoryEventType::TimerScheduled - ? $explicitWaitId - : self::consumeOpenWaitId($openWaitIdsByName, $signalName, $explicitWaitId); - - if ($waitId === null || ! isset($waits[$waitId])) { - continue; - } - - $waits[$waitId]['timer_id'] = self::stringValue($event->payload['timer_id'] ?? null) - ?? $waits[$waitId]['timer_id']; - $waits[$waitId]['timeout_seconds'] = self::intValue($event->payload['delay_seconds'] ?? null) - ?? self::intValue($event->payload['timeout_seconds'] ?? null) - ?? $waits[$waitId]['timeout_seconds']; - $waits[$waitId]['deadline_at'] = self::timestamp($event->payload['fire_at'] ?? null) - ?? $waits[$waitId]['deadline_at']; - - if ($event->event_type === HistoryEventType::TimerScheduled) { - continue; - } - - if (($waits[$waitId]['status'] ?? null) !== 'open') { - continue; - } - - $waits[$waitId]['status'] = $event->event_type === HistoryEventType::TimerFired - ? 'resolved' - : 'cancelled'; - $waits[$waitId]['source_status'] = $event->event_type === HistoryEventType::TimerFired - ? 'timed_out' - : 'timeout_cancelled'; - $waits[$waitId]['resolved_at'] = $event->recorded_at ?? $event->created_at; - $waits[$waitId]['timeout_fired_at'] = $event->event_type === HistoryEventType::TimerFired - ? self::timestamp( - $event->payload['fired_at'] ?? null - ) ?? ($event->recorded_at ?? $event->created_at) - : $waits[$waitId]['timeout_fired_at']; - - continue; - } - - if ($event->event_type === HistoryEventType::SignalWaitCancelled) { - $waitId = self::stringValue($event->payload['signal_wait_id'] ?? null); - if ($waitId !== null && isset($waits[$waitId]) && $waits[$waitId]['status'] === 'open') { - $waits[$waitId]['status'] = 'cancelled'; - $waits[$waitId]['source_status'] = 'scope_cancelled'; - $waits[$waitId]['resolved_at'] = $event->recorded_at ?? $event->created_at; - self::consumeOpenWaitId($openWaitIdsByName, $waits[$waitId]['signal_name'], $waitId); - } - continue; - } - - if ($event->event_type === HistoryEventType::SelectionOperationCancelled) { - self::closeCancelledSelectionWaits($waits, $openWaitIdsByName, $event); - - continue; - } - - if (in_array($event->event_type, [ - HistoryEventType::SignalReceived, - HistoryEventType::SignalApplied, - ], true)) { - if ($signalName === null) { - continue; - } - - $waitId = self::consumeOpenWaitId( - $openWaitIdsByName, - $signalName, - self::stringValue($event->payload['signal_wait_id'] ?? null), - ); - - if ($waitId === null || ! isset($waits[$waitId])) { - continue; - } - - $currentStatus = $waits[$waitId]['status'] ?? null; - $currentSourceStatus = $waits[$waitId]['source_status'] ?? null; - $canApplyReceivedSignal = $event->event_type === HistoryEventType::SignalApplied - && $currentStatus === 'resolved' - && $currentSourceStatus === 'received'; - - if ($currentStatus !== 'open' && ! $canApplyReceivedSignal) { - continue; - } - - $waits[$waitId]['status'] = 'resolved'; - $waits[$waitId]['source_status'] = $event->event_type === HistoryEventType::SignalApplied - ? 'applied' - : 'received'; - $waits[$waitId]['signal_id'] = self::stringValue($event->payload['signal_id'] ?? null) - ?? $waits[$waitId]['signal_id']; - $waits[$waitId]['resolved_at'] = $event->recorded_at ?? $event->created_at; - $waits[$waitId]['command_id'] = self::stringValue($event->workflow_command_id) - ?? self::stringValue($event->payload['workflow_command_id'] ?? null) - ?? self::stringValue(self::commandSnapshot($event)['id'] ?? null); - $waits[$waitId]['command_sequence'] = self::commandSequence($event); - $waits[$waitId]['command_status'] = self::commandStatus($event); - $waits[$waitId]['command_outcome'] = self::commandOutcome($event); - - continue; - } - - if (in_array($event->event_type, [ - HistoryEventType::WorkflowCompleted, - HistoryEventType::WorkflowFailed, - HistoryEventType::WorkflowCancelled, - HistoryEventType::WorkflowTerminated, - HistoryEventType::WorkflowContinuedAsNew, - ], true)) { - self::closeOpenWaits($waits, $openWaitIdsByName, $event); + if ($event instanceof WorkflowHistoryEvent) { + self::applyEvent($waits, $openWaitIdsByName, $event, $replayCompatible); } } return array_values($waits); } - public static function openWaitIdForName(WorkflowRun $run, string $signalName): ?string - { + public static function openWaitIdForName( + WorkflowRun $run, + string $signalName, + bool $replayCompatible = false, + ): ?string { $openWaits = array_values(array_filter( - self::forRun($run), + self::forRun($run, $replayCompatible), static fn (array $wait): bool => $wait['signal_name'] === $signalName && $wait['status'] === 'open', )); @@ -291,6 +142,251 @@ private static function closeCancelledSelectionWaits( unset($wait); } + /** + * @param array> $waits + * @param array> $openWaitIdsByName + */ + private static function applyEvent( + array &$waits, + array &$openWaitIdsByName, + WorkflowHistoryEvent $event, + bool $replayCompatible, + ): void { + switch ($event->event_type) { + case HistoryEventType::SignalWaitOpened: + self::openWait($waits, $openWaitIdsByName, $event); + break; + case HistoryEventType::TimerScheduled: + case HistoryEventType::TimerFired: + case HistoryEventType::TimerCancelled: + self::applySignalTimeoutEvent($waits, $openWaitIdsByName, $event); + break; + case HistoryEventType::SignalWaitCancelled: + self::closeScopeCancelledWait($waits, $openWaitIdsByName, $event); + break; + case HistoryEventType::SelectionOperationCancelled: + self::closeCancelledSelectionWaits($waits, $openWaitIdsByName, $event); + break; + case HistoryEventType::SignalReceived: + case HistoryEventType::SignalApplied: + self::applySignalEvent($waits, $openWaitIdsByName, $event); + break; + case HistoryEventType::WorkflowCompleted: + case HistoryEventType::WorkflowFailed: + case HistoryEventType::WorkflowCancelled: + case HistoryEventType::WorkflowTerminated: + case HistoryEventType::WorkflowContinuedAsNew: + self::closeOpenWaits($waits, $openWaitIdsByName, $event); + break; + case HistoryEventType::CooperativeCancellationDelivered: + if (! $replayCompatible) { + self::closeInterruptedWaits($waits, $openWaitIdsByName, $event); + } + break; + case HistoryEventType::WorkflowTimedOut: + if (! $replayCompatible) { + self::closeOpenWaits($waits, $openWaitIdsByName, $event); + } + break; + default: + // Other events don't change a signal wait. + break; + } + } + + /** + * @param array> $waits + * @param array> $openWaitIdsByName + */ + private static function openWait(array &$waits, array &$openWaitIdsByName, WorkflowHistoryEvent $event): void + { + $signalName = self::stringValue($event->payload['signal_name'] ?? null); + $waitId = $signalName === null ? null : self::waitIdForOpenedEvent($event); + + if ($signalName === null || $waitId === null) { + return; + } + + $waits[$waitId] = [ + 'id' => $waitId, + 'signal_wait_id' => $waitId, + 'signal_id' => null, + 'signal_name' => $signalName, + 'sequence' => self::intValue($event->payload['sequence'] ?? null), + 'status' => 'open', + 'source_status' => 'waiting', + 'opened_at' => $event->recorded_at ?? $event->created_at, + 'deadline_at' => null, + 'resolved_at' => null, + 'timeout_fired_at' => null, + 'timeout_seconds' => self::intValue($event->payload['timeout_seconds'] ?? null), + 'timer_id' => null, + 'command_id' => null, + 'command_sequence' => null, + 'command_status' => null, + 'command_outcome' => null, + ]; + + $openWaitIdsByName[$signalName] ??= []; + $openWaitIdsByName[$signalName][] = $waitId; + } + + /** + * @param array> $waits + * @param array> $openWaitIdsByName + */ + private static function applySignalTimeoutEvent( + array &$waits, + array &$openWaitIdsByName, + WorkflowHistoryEvent $event, + ): void { + $signalName = self::stringValue($event->payload['signal_name'] ?? null); + + if (self::stringValue($event->payload['timer_kind'] ?? null) !== 'signal_timeout' || $signalName === null) { + return; + } + + $explicitWaitId = self::stringValue($event->payload['signal_wait_id'] ?? null); + $waitId = $event->event_type === HistoryEventType::TimerScheduled + ? $explicitWaitId + : self::consumeOpenWaitId($openWaitIdsByName, $signalName, $explicitWaitId); + + if ($waitId === null || ! isset($waits[$waitId])) { + return; + } + + $waits[$waitId]['timer_id'] = self::stringValue($event->payload['timer_id'] ?? null) + ?? $waits[$waitId]['timer_id']; + $waits[$waitId]['timeout_seconds'] = self::intValue($event->payload['delay_seconds'] ?? null) + ?? self::intValue($event->payload['timeout_seconds'] ?? null) + ?? $waits[$waitId]['timeout_seconds']; + $waits[$waitId]['deadline_at'] = self::timestamp($event->payload['fire_at'] ?? null) + ?? $waits[$waitId]['deadline_at']; + + if ($event->event_type === HistoryEventType::TimerScheduled + || ($waits[$waitId]['status'] ?? null) !== 'open') { + return; + } + + $fired = $event->event_type === HistoryEventType::TimerFired; + $waits[$waitId]['status'] = $fired ? 'resolved' : 'cancelled'; + $waits[$waitId]['source_status'] = $fired ? 'timed_out' : 'timeout_cancelled'; + $waits[$waitId]['resolved_at'] = $event->recorded_at ?? $event->created_at; + $waits[$waitId]['timeout_fired_at'] = $fired + ? self::timestamp($event->payload['fired_at'] ?? null) ?? ($event->recorded_at ?? $event->created_at) + : $waits[$waitId]['timeout_fired_at']; + } + + /** + * @param array> $waits + * @param array> $openWaitIdsByName + */ + private static function closeScopeCancelledWait( + array &$waits, + array &$openWaitIdsByName, + WorkflowHistoryEvent $event, + ): void { + $waitId = self::stringValue($event->payload['signal_wait_id'] ?? null); + + if ($waitId !== null && isset($waits[$waitId]) && $waits[$waitId]['status'] === 'open') { + $waits[$waitId]['status'] = 'cancelled'; + $waits[$waitId]['source_status'] = 'scope_cancelled'; + $waits[$waitId]['resolved_at'] = $event->recorded_at ?? $event->created_at; + self::consumeOpenWaitId($openWaitIdsByName, $waits[$waitId]['signal_name'], $waitId); + } + } + + /** + * @param array> $waits + * @param array> $openWaitIdsByName + */ + private static function applySignalEvent( + array &$waits, + array &$openWaitIdsByName, + WorkflowHistoryEvent $event, + ): void { + $signalName = self::stringValue($event->payload['signal_name'] ?? null); + + if ($signalName === null) { + return; + } + + $waitId = self::consumeOpenWaitId( + $openWaitIdsByName, + $signalName, + self::stringValue($event->payload['signal_wait_id'] ?? null), + ); + + if ($waitId === null || ! isset($waits[$waitId])) { + return; + } + + $applied = $event->event_type === HistoryEventType::SignalApplied; + $currentStatus = $waits[$waitId]['status'] ?? null; + $canApplyReceivedSignal = $applied + && $currentStatus === 'resolved' + && ($waits[$waitId]['source_status'] ?? null) === 'received'; + + if ($currentStatus !== 'open' && ! $canApplyReceivedSignal) { + return; + } + + $waits[$waitId]['status'] = 'resolved'; + $waits[$waitId]['source_status'] = $applied ? 'applied' : 'received'; + $waits[$waitId]['signal_id'] = self::stringValue($event->payload['signal_id'] ?? null) + ?? $waits[$waitId]['signal_id']; + $waits[$waitId]['resolved_at'] = $event->recorded_at ?? $event->created_at; + $waits[$waitId]['command_id'] = self::stringValue($event->workflow_command_id) + ?? self::stringValue($event->payload['workflow_command_id'] ?? null) + ?? self::stringValue(self::commandSnapshot($event)['id'] ?? null); + $waits[$waitId]['command_sequence'] = self::commandSequence($event); + $waits[$waitId]['command_status'] = self::commandStatus($event); + $waits[$waitId]['command_outcome'] = self::commandOutcome($event); + } + + /** + * Close the open signal waits a delivered cooperative cancellation + * interrupted: the wait at a signal delivery, or the member waits of a + * delivered parallel or selection group. A delivery at a durable handle + * await or a started child await leaves the operation itself awaitable, + * so it closes nothing here. + * + * @param array> $waits + * @param array> $openWaitIdsByName + */ + private static function closeInterruptedWaits( + array &$waits, + array &$openWaitIdsByName, + WorkflowHistoryEvent $event, + ): void { + $callKind = self::stringValue($event->payload['call_kind'] ?? null); + $baseSequence = self::intValue($event->payload['sequence'] ?? null); + $span = match ($callKind) { + 'signal' => 1, + 'parallel' => self::intValue($event->payload['sequence_span'] ?? null) ?? 1, + default => null, + }; + + if ($baseSequence === null || $span === null || $span < 1) { + return; + } + + foreach ($waits as $waitId => $wait) { + $sequence = self::intValue($wait['sequence'] ?? null); + if ($sequence === null + || $sequence < $baseSequence + || $sequence - $baseSequence >= $span + || ($wait['status'] ?? null) !== 'open') { + continue; + } + + $waits[$waitId]['status'] = 'cancelled'; + $waits[$waitId]['source_status'] = 'cancellation_delivered'; + $waits[$waitId]['resolved_at'] = $event->recorded_at ?? $event->created_at; + self::consumeOpenWaitId($openWaitIdsByName, $wait['signal_name'], (string) $waitId); + } + } + /** * @param array> $waits * @param array> $openWaitIdsByName diff --git a/src/V2/Support/WorkflowExecutor.php b/src/V2/Support/WorkflowExecutor.php index afbba8aaa..9770a8373 100644 --- a/src/V2/Support/WorkflowExecutor.php +++ b/src/V2/Support/WorkflowExecutor.php @@ -8112,7 +8112,7 @@ private function cancelDurableLeaf( if ($call instanceof SignalCall) { $run->unsetRelation('historyEvents'); - $open = collect(SignalWaits::forRun($run)) + $open = collect(SignalWaits::forRun($run, replayCompatible: true)) ->contains(static fn (array $wait): bool => ($wait['sequence'] ?? null) === $sequence && ($wait['status'] ?? null) === 'open'); @@ -8215,7 +8215,7 @@ private function visibleSequenceForCurrent(WorkflowRun $run, mixed $current, int $current instanceof SignalCall => ( $this->appliedSignalEvent($run, $sequence, $current) !== null || $this->pendingSignalCommand($run, $current) !== null - || SignalWaits::openWaitIdForName($run, $current->name) !== null + || SignalWaits::openWaitIdForName($run, $current->name, replayCompatible: true) !== null ) ? $sequence + 1 : $sequence, $current instanceof ChildWorkflowCall => ( ChildRunHistory::scheduledEventForSequence($run, $sequence) !== null diff --git a/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php b/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php index 379d3562a..7ee51601d 100644 --- a/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php +++ b/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php @@ -117,6 +117,7 @@ use Workflow\V2\Support\ScheduleManager; use Workflow\V2\Support\ServiceCallPrincipal; use Workflow\V2\Support\ServiceCallScheduler; +use Workflow\V2\Support\SignalWaits; use Workflow\V2\Support\TaskRepairPolicy; use Workflow\V2\Support\VersionUsageQuery; use Workflow\V2\Support\WorkflowCommandNormalizer; @@ -3328,6 +3329,10 @@ public function testFixturesExecuteThroughDeclaredReplayConsumers(): void $this->assertLaterSignalBelongsToItsCurrentSelection($fixture); continue; } + if ($fixture['id'] === 'cooperative-delivery-ends-signal-wait-attribution') { + $this->assertDeliveredCancellationEndsTheSignalWait($fixture); + continue; + } if ($fixture['id'] === 'selection-child-await-history') { // The live park and resume records are covered by the dedicated test. @@ -7223,6 +7228,80 @@ private function assertLaterSignalBelongsToItsCurrentSelection(array $fixture): $this->assertSame(0, $run->tasks()->where('status', TaskStatus::Failed)->count()); } + /** + * A cooperative cancellation delivered at a signal wait ends that wait. + * The retained history attributed a later signal to the interrupted wait, + * as engines before #1315 did; it still replays, but the derived views + * report the wait as ended at delivery. A live run then attributes a + * signal accepted after delivery to no wait. + * + * @param array $fixture + */ + private function assertDeliveredCancellationEndsTheSignalWait(array $fixture): void + { + $expected = $fixture['interrupted_wait']; + $assertInterrupted = function (WorkflowRun $run, string $waitId) use ($expected): void { + $run = $run->fresh(['historyEvents']); + $wait = collect(SignalWaits::forRun($run))->firstWhere('signal_wait_id', $waitId); + $this->assertIsArray($wait); + $this->assertSame('cancelled', $wait['status']); + $this->assertSame($expected['source_status'], $wait['source_status']); + $this->assertNull($wait['signal_id']); + $this->assertNull(SignalWaits::openWaitIdForName($run, $expected['signal_name'])); + $detail = collect(RunDetailView::forRun($run)['waits']) + ->first(static fn (array $row): bool => ($row['kind'] ?? null) === 'signal' + && ($row['id'] ?? null) === $waitId); + $this->assertIsArray($detail); + $this->assertSame('cancelled', $detail['status']); + $this->assertSame($expected['source_status'], $detail['source_status']); + }; + + $retained = $this->createRunFromFixture($fixture); + $assertInterrupted($retained, $expected['signal_wait_id']); + + $stub = WorkflowStub::make( + $fixture['workflow']['type'], + sprintf('regression-corpus-embedded-%d', ++$this->workflowNumber), + ); + $stub->start(...$fixture['workflow']['arguments']); + $run = WorkflowRun::query()->findOrFail($stub->runId()); + $this->runReadyWorkflowTask($run); + $opened = $run->historyEvents() + ->where('event_type', HistoryEventType::SignalWaitOpened)->sole(); + $request = WorkflowStub::loadRun($run->id)->requestCancellation('interrupt the signal wait', 30); + $this->runReadyWorkflowTask($run); + $delivery = $run->historyEvents() + ->where('event_type', HistoryEventType::CooperativeCancellationDelivered)->sole(); + $this->assertSame($request->commandId(), $delivery->workflow_command_id); + $this->assertSame('signal', $delivery->payload['call_kind']); + $this->assertSame($opened->payload['sequence'], $delivery->payload['sequence']); + $assertInterrupted($run, $opened->payload['signal_wait_id']); + + $late = $stub->refresh() + ->attemptSignal($expected['signal_name']); + $this->assertTrue($late->accepted()); + $bufferedWaitId = SignalWaits::bufferedWaitIdForCommandId($late->commandId()); + $received = $run->historyEvents() + ->where('event_type', HistoryEventType::SignalReceived)->sole(); + $this->assertSame($bufferedWaitId, $received->payload['signal_wait_id']); + $this->assertSame( + $bufferedWaitId, + WorkflowSignal::query()->where('workflow_command_id', $late->commandId())->sole()->signal_wait_id, + ); + $assertInterrupted($run, $opened->payload['signal_wait_id']); + $this->assertSame(0, $run->historyEvents()->where('event_type', HistoryEventType::SignalApplied)->count()); + + // The retained history still replays to its cleanup unchanged. + $before = $retained->historyEvents() + ->orderBy('sequence') + ->get() + ->toArray(); + $state = (new QueryStateReplayer())->replayState($retained->fresh(['historyEvents'])); + $this->assertSame(2, $state->sequence); + $this->assertInstanceOf(ActivityCall::class, $state->current); + $this->assertSame($before, $retained->historyEvents()->orderBy('sequence')->get()->toArray()); + } + /** * @param array $fixture */ diff --git a/tests/Feature/V2/V2FinallyCleanupTest.php b/tests/Feature/V2/V2FinallyCleanupTest.php index 167d87f42..e87ad86e2 100644 --- a/tests/Feature/V2/V2FinallyCleanupTest.php +++ b/tests/Feature/V2/V2FinallyCleanupTest.php @@ -8,6 +8,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Queue; use Symfony\Component\Process\Process; +use Tests\Fixtures\V2\TestCancelledSignalReawaitWorkflow; use Tests\Fixtures\V2\TestCooperativeActivityCleanupWorkflow; use Tests\Fixtures\V2\TestCooperativeChildCleanupWorkflow; use Tests\Fixtures\V2\TestCooperativeNormalCleanupWorkflow; @@ -287,6 +288,105 @@ public function testCooperativeCancellationInterruptsSignalAndConditionWaits(): } } + /** + * #1315: the derived signal-wait view treats a wait interrupted by + * cancellation delivery as ended, but the executor's step cursor keeps + * reading it as it always has. Workflow code here catches the delivery + * at a signal wait and waits for the same signal again. An update applied + * while the first wait was open records its handler's step cursor; every + * later replay re-applies it at that wait, and must see the same cursor. + */ + public function testReplayKeepsTheStepCursorAtASignalWaitInterruptedByDelivery(): void + { + Queue::fake(); + + $workflow = WorkflowStub::make(TestCancelledSignalReawaitWorkflow::class); + $workflow->start(); + $runId = $workflow->runId(); + $this->assertIsString($runId); + $this->runReadyTask($runId, TaskType::Workflow); + + $mark = $workflow->submitUpdate('mark'); + $this->assertTrue($mark->accepted()); + $this->runReadyTask($runId, TaskType::Workflow); + $this->assertSame(2, $workflow->inspectUpdate($mark->updateId())->result()); + + $this->assertTrue($workflow->requestCancellation('stop', 60)->accepted()); + $this->runReadyTask($runId, TaskType::Workflow); + $opened = WorkflowHistoryEvent::query() + ->where('workflow_run_id', $runId) + ->where('event_type', HistoryEventType::SignalWaitOpened->value) + ->orderBy('sequence') + ->get(); + $this->assertSame( + [1, 2], + $opened->map(static fn (WorkflowHistoryEvent $event): int => $event->payload['sequence']) + ->all() + ); + $delivered = WorkflowHistoryEvent::query() + ->where('workflow_run_id', $runId) + ->where('event_type', HistoryEventType::CooperativeCancellationDelivered->value) + ->sole(); + $this->assertSame('signal', $delivered->payload['call_kind']); + $this->assertSame(1, $delivered->payload['sequence']); + + // The second wait is a new occurrence, so a signal now resolves it + // and not the interrupted wait. + $this->assertNotSame($opened[0]->payload['signal_wait_id'], $opened[1]->payload['signal_wait_id']); + $signal = $workflow->refresh() + ->attemptSignal('approve', 'yes'); + $this->assertTrue($signal->accepted()); + $this->assertSame( + $opened[1]->payload['signal_wait_id'], + WorkflowHistoryEvent::query() + ->where('workflow_run_id', $runId) + ->where('event_type', HistoryEventType::SignalReceived->value) + ->sole() + ->payload['signal_wait_id'], + ); + $this->runReadyTask($runId, TaskType::Workflow); + $this->runReadyTask($runId, TaskType::Activity); + + // Neither wait is open or has a pending signal when this task + // replays the interrupted one, so only the replay view keeps the + // cursor the update saw when it was applied. + $this->runReadyTask($runId, TaskType::Workflow); + + $memo = $workflow->refresh() + ->memo(); + $this->assertSame([ + 'marked_at' => 2, + ], $memo); + $this->assertSame([ + 'StartAccepted', + 'WorkflowStarted', + 'SignalWaitOpened', + 'UpdateAccepted', + 'UpdateApplied', + 'UpdateCompleted', + 'MessageCursorAdvanced', + 'CooperativeCancellationRequested', + 'CooperativeCancellationDelivered', + 'SignalWaitOpened', + 'SignalReceived', + 'MessageCursorAdvanced', + 'SignalApplied', + 'ActivityScheduled', + 'ActivityStarted', + 'ActivityCompleted', + 'MemoUpserted', + ], array_slice(WorkflowHistoryEvent::query() + ->where('workflow_run_id', $runId) + ->orderBy('sequence') + ->pluck('event_type') + ->map(static fn (mixed $type): string => $type instanceof HistoryEventType ? $type->value : (string) $type) + ->all(), 0, 17)); + $this->assertSame(0, WorkflowTask::query() + ->where('workflow_run_id', $runId) + ->where('status', TaskStatus::Failed->value) + ->count()); + } + public function testCooperativeCancellationInterruptsChildWaitAndAppliesParentClosePolicy(): void { Queue::fake(); diff --git a/tests/Feature/V2/V2TimeoutCleanupTest.php b/tests/Feature/V2/V2TimeoutCleanupTest.php index 72208675e..59e7c2733 100644 --- a/tests/Feature/V2/V2TimeoutCleanupTest.php +++ b/tests/Feature/V2/V2TimeoutCleanupTest.php @@ -34,7 +34,9 @@ use Workflow\V2\Models\WorkflowRunSummary; use Workflow\V2\Models\WorkflowTask; use Workflow\V2\StartOptions; +use Workflow\V2\Support\RunDetailView; use Workflow\V2\Support\RunSummaryProjector; +use Workflow\V2\Support\SignalWaits; use Workflow\V2\Support\WorkflowTaskLeaseLoss; use Workflow\V2\TaskWatchdog; use Workflow\V2\WorkflowStub; @@ -566,16 +568,33 @@ public function testExpiryWhileWaitingOnASignalInterruptsTheWaitAndALateSignalNe $run = WorkflowRun::query()->findOrFail($runId); $started = $this->assertTimeoutInterruptionDelivered($workflow, $run, 'signal', $opened->payload['sequence']); + // Delivery ended the wait: it is reported as interrupted, not open. + $waitId = $opened->payload['signal_wait_id']; + $this->assertInterruptedSignalWait($runId, $waitId); + // A signal that arrives during cleanup is recorded but never satisfies - // the interrupted wait, even when its own workflow task runs first. + // the interrupted wait. No wait is open, so it is buffered under its + // own command identity, as any signal without an open wait is, and + // it schedules no workflow task of its own. $late = $workflow->refresh() ->attemptSignal('approve', 'late'); $this->assertTrue($late->accepted()); - $this->runReadyWorkflowTask($runId); + $bufferedWaitId = SignalWaits::bufferedWaitIdForCommandId($late->commandId()); + $received = $this->soleEvent($runId, HistoryEventType::SignalReceived); + $this->assertSame($late->commandId(), $received->payload['workflow_command_id']); + $this->assertSame($bufferedWaitId, $received->payload['signal_wait_id']); + $this->assertSame(0, WorkflowTask::query() + ->where('workflow_run_id', $runId) + ->where('task_type', TaskType::Workflow->value) + ->where('status', TaskStatus::Ready->value) + ->count()); + $this->assertInterruptedSignalWait($runId, $waitId); $this->assertSame(0, $this->eventCount($runId, HistoryEventType::SignalApplied)); $this->assertArrayNotHasKey('business', $workflow->refresh()->memo()); $this->assertFalse(WorkflowRun::query()->findOrFail($runId)->status->isTerminal()); + // The cleanup's workflow task runs with the signal pending and still + // does not apply it. $this->runReadyActivityTask($runId); $this->runReadyWorkflowTask($runId); @@ -583,6 +602,8 @@ public function testExpiryWhileWaitingOnASignalInterruptsTheWaitAndALateSignalNe $rejected = $this->soleEvent($runId, HistoryEventType::SignalRejected); $this->assertSame($late->commandId(), $rejected->payload['workflow_command_id']); $this->assertSame('run_closed_before_signal_applied', $rejected->payload['rejection_reason']); + $this->assertSame($bufferedWaitId, $rejected->payload['signal_wait_id']); + $this->assertInterruptedSignalWait($runId, $waitId); $this->assertSame(0, $this->eventCount($runId, HistoryEventType::SignalApplied)); $this->assertArrayNotHasKey('business', $workflow->refresh()->memo()); $this->assertSame('Hello, cleanup!', $workflow->memo()['cleanup']); @@ -639,11 +660,19 @@ public function testExpiryWhileWaitingOnASelectionCancelsEveryBranchAndNoBranchC $outcome = $activities->complete($claim['activity_attempt_id'], Serializer::serialize('late-work')); $this->assertFalse($outcome['recorded']); - // The signal branch can't win the selection after cleanup started. + // The signal branch can't win the selection after cleanup started: + // its wait ended at delivery, and a late signal is buffered. + $waitId = $opened->payload['signal_wait_id']; + $this->assertInterruptedSignalWait($runId, $waitId); $late = $workflow->refresh() ->attemptSignal('approve', 'late'); $this->assertTrue($late->accepted()); - $this->runReadyWorkflowTask($runId); + $this->assertSame( + SignalWaits::bufferedWaitIdForCommandId($late->commandId()), + $this->soleEvent($runId, HistoryEventType::SignalReceived)->payload['signal_wait_id'], + ); + $this->runReadyWorkflowTaskIfAny($runId); + $this->assertInterruptedSignalWait($runId, $waitId); $this->assertSame(0, $this->eventCount($runId, HistoryEventType::SignalApplied)); $this->assertSame(0, $this->eventCount($runId, HistoryEventType::SelectionResolved)); @@ -970,6 +999,30 @@ private function sorted(mixed $values): ?array return $values; } + /** + * The derived wait views report a wait interrupted by cancellation + * delivery as ended there, never as received or resolved. + */ + private function assertInterruptedSignalWait(string $runId, string $waitId): void + { + $run = WorkflowRun::query()->findOrFail($runId); + $wait = collect(SignalWaits::forRun($run))->firstWhere('signal_wait_id', $waitId); + $this->assertIsArray($wait); + $this->assertSame('cancelled', $wait['status']); + $this->assertSame('cancellation_delivered', $wait['source_status']); + $this->assertNull($wait['signal_id']); + $this->assertNull($wait['command_id']); + $this->assertNotSame($waitId, SignalWaits::openWaitIdForName($run, 'approve')); + + $detail = collect(RunDetailView::forRun($run->fresh())['waits']) + ->first(static fn (array $wait): bool => ($wait['kind'] ?? null) === 'signal' + && ($wait['id'] ?? null) === $waitId); + $this->assertIsArray($detail); + $this->assertSame('cancelled', $detail['status']); + $this->assertSame('cancellation_delivered', $detail['source_status']); + $this->assertNull($detail['command_id']); + } + private function soleEvent(string $runId, HistoryEventType $type): WorkflowHistoryEvent { return WorkflowHistoryEvent::query() diff --git a/tests/Fixtures/V2/ReplayRegression/cooperative-delivery-ends-signal-wait-attribution.json b/tests/Fixtures/V2/ReplayRegression/cooperative-delivery-ends-signal-wait-attribution.json new file mode 100644 index 000000000..a44d7fc1b --- /dev/null +++ b/tests/Fixtures/V2/ReplayRegression/cooperative-delivery-ends-signal-wait-attribution.json @@ -0,0 +1,59 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "cooperative-delivery-ends-signal-wait-attribution", + "protocol_version": "1.0", + "bindings": ["php"], + "workflow": { + "type": "Tests\\Fixtures\\V2\\TestSignalCancellationCleanupWorkflow", + "arguments": [], + "payload_codec": "avro" + }, + "history": [ + { + "sequence": 1, + "event_type": "WorkflowStarted", + "payload": {}, + "recorded_at": "2026-11-26T00:00:00+00:00" + }, + { + "sequence": 2, + "event_type": "SignalWaitOpened", + "payload": {"signal_name": "finish", "signal_wait_id": "finish-interrupted", "sequence": 1}, + "recorded_at": "2026-11-26T00:00:01+00:00" + }, + { + "sequence": 3, + "event_type": "CooperativeCancellationRequested", + "payload": {"workflow_command_id": "cancel-at-signal-wait-1", "command_type": "request_cancellation"}, + "recorded_at": "2026-11-26T00:00:02+00:00" + }, + { + "sequence": 4, + "event_type": "CooperativeCancellationDelivered", + "payload": {"workflow_command_id": "cancel-at-signal-wait-1", "sequence": 1, "call_kind": "signal"}, + "recorded_at": "2026-11-26T00:00:03+00:00" + }, + { + "sequence": 5, + "event_type": "SignalReceived", + "payload": { + "workflow_command_id": "late-signal-command-1", + "signal_id": "late-signal-1", + "signal_name": "finish", + "signal_wait_id": "finish-interrupted" + }, + "recorded_at": "2026-11-26T00:00:04+00:00" + } + ], + "expected": { + "completed": false, + "result": null, + "commands": [{"type": "schedule_activity", "activity_type": "Tests\\Fixtures\\V2\\TestRetryActivity"}] + }, + "interrupted_wait": { + "signal_name": "finish", + "signal_wait_id": "finish-interrupted", + "source_status": "cancellation_delivered" + } +} diff --git a/tests/Fixtures/V2/TestCancelledSignalReawaitWorkflow.php b/tests/Fixtures/V2/TestCancelledSignalReawaitWorkflow.php new file mode 100644 index 000000000..f540b1d58 --- /dev/null +++ b/tests/Fixtures/V2/TestCancelledSignalReawaitWorkflow.php @@ -0,0 +1,53 @@ + false, + ]; + } catch (WorkflowCancellationRequestedException) { + $approval = await('approve'); + activity(TestGreetingActivity::class, 'cleanup'); + upsertMemo([ + 'marked_at' => $this->markedAt, + ]); + + return [ + 'interrupted' => true, + 'approval' => $approval, + 'marked_at' => $this->markedAt, + ]; + } + } + + #[UpdateMethod] + public function mark(): int + { + return $this->markedAt = $this->executionCursor(); + } +} diff --git a/tests/Unit/V2/DurableWaitProjectionTest.php b/tests/Unit/V2/DurableWaitProjectionTest.php index b13c5d7a7..d730fba26 100644 --- a/tests/Unit/V2/DurableWaitProjectionTest.php +++ b/tests/Unit/V2/DurableWaitProjectionTest.php @@ -445,7 +445,87 @@ public function testOpenSignalWaitLookupUsesSequenceTimeAndIdentityOrdering(): v $this->assertNull(SignalWaits::openWaitIdForName($run, 'missing')); } - #[DataProvider('terminalEventProvider')] + public function testDeliveredCancellationEndsTheInterruptedSignalWait(): void + { + $run = $this->runWithHistoryEvents([ + $this->historyEvent(HistoryEventType::SignalWaitOpened, 1, [ + 'signal_wait_id' => 'interrupted', + 'signal_name' => 'approval', + 'sequence' => 1, + ]), + $this->historyEvent(HistoryEventType::CooperativeCancellationDelivered, 2, [ + 'workflow_command_id' => 'cancel-1', + 'sequence' => 1, + 'call_kind' => 'signal', + ], '2026-08-27T15:00:00Z'), + // A history recorded before this closure attributed a later + // signal to the interrupted wait. It must not resolve that wait. + $this->historyEvent(HistoryEventType::SignalReceived, 3, [ + 'signal_name' => 'approval', + 'signal_wait_id' => 'interrupted', + 'signal_id' => 'late-signal', + ], null, 'late-command'), + $this->historyEvent(HistoryEventType::SignalWaitOpened, 4, [ + 'signal_wait_id' => 'cleanup-wait', + 'signal_name' => 'approval', + 'sequence' => 3, + ]), + ]); + + $waits = $this->indexBy(SignalWaits::forRun($run), 'signal_wait_id'); + $this->assertSame('cancelled', $waits['interrupted']['status']); + $this->assertSame('cancellation_delivered', $waits['interrupted']['source_status']); + $this->assertSame('2026-08-27T15:00:00+00:00', $this->timestamp($waits['interrupted']['resolved_at'])); + $this->assertNull($waits['interrupted']['signal_id']); + $this->assertNull($waits['interrupted']['command_id']); + $this->assertSame('open', $waits['cleanup-wait']['status']); + $this->assertSame('cleanup-wait', SignalWaits::openWaitIdForName($run, 'approval')); + + // Replay decisions keep reading the states they always read. + $legacy = $this->indexBy(SignalWaits::forRun($run, replayCompatible: true), 'signal_wait_id'); + $this->assertSame('resolved', $legacy['interrupted']['status']); + $this->assertSame('received', $legacy['interrupted']['source_status']); + } + + public function testDeliveredGroupCancellationEndsOnlyItsMemberSignalWaits(): void + { + $opened = static fn (string $id, int $sequence): array => [ + 'signal_wait_id' => $id, + 'signal_name' => 'approval', + 'sequence' => $sequence, + ]; + $groupRun = $this->runWithHistoryEvents([ + $this->historyEvent(HistoryEventType::SignalWaitOpened, 1, $opened('before', 1)), + $this->historyEvent(HistoryEventType::SignalWaitOpened, 2, $opened('first-member', 2)), + $this->historyEvent(HistoryEventType::SignalWaitOpened, 3, $opened('second-member', 3)), + $this->historyEvent(HistoryEventType::SignalWaitOpened, 4, $opened('after', 4)), + $this->historyEvent(HistoryEventType::CooperativeCancellationDelivered, 5, [ + 'sequence' => 2, + 'call_kind' => 'parallel', + 'sequence_span' => 2, + ]), + ]); + + $waits = $this->indexBy(SignalWaits::forRun($groupRun), 'signal_wait_id'); + $this->assertSame('open', $waits['before']['status']); + $this->assertSame('cancellation_delivered', $waits['first-member']['source_status']); + $this->assertSame('cancellation_delivered', $waits['second-member']['source_status']); + $this->assertSame('open', $waits['after']['status']); + + // A durable handle await leaves the awaited operation itself open. + $handleRun = $this->runWithHistoryEvents([ + $this->historyEvent(HistoryEventType::SignalWaitOpened, 1, $opened('handle-operation', 1)), + $this->historyEvent(HistoryEventType::CooperativeCancellationDelivered, 2, [ + 'sequence' => 2, + 'call_kind' => 'selection_handle', + 'operation_sequence' => 1, + ]), + ]); + + $this->assertSame('open', SignalWaits::forRun($handleRun)[0]['status']); + } + + #[DataProvider('signalTerminalEventProvider')] public function testSignalWaitProjectionClosesOpenWaitsWithTerminalSourceStatus( HistoryEventType $eventType, string $sourceStatus, @@ -463,6 +543,10 @@ public function testSignalWaitProjectionClosesOpenWaitsWithTerminalSourceStatus( $this->assertSame('cancelled', $wait['status']); $this->assertSame($sourceStatus, $wait['source_status']); + + if ($eventType === HistoryEventType::WorkflowTimedOut) { + $this->assertSame('open', SignalWaits::forRun($run, replayCompatible: true)[0]['status']); + } } /** @@ -477,6 +561,15 @@ public static function terminalEventProvider(): iterable yield 'continued as new' => [HistoryEventType::WorkflowContinuedAsNew, 'continued']; } + /** + * @return iterable + */ + public static function signalTerminalEventProvider(): iterable + { + yield from self::terminalEventProvider(); + yield 'timed out' => [HistoryEventType::WorkflowTimedOut, 'closed']; + } + /** * @param list $events */