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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions scripts/ci/run-replay-regression-fixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,7 @@ private static function workflow(string $workflowType): callable
}

return match ($workflowType) {
'golden.ordered-condition' => self::workflow('golden.signal'),
'golden.signal-occurrence-unavailable', 'golden.signal-occurrence-deferred' => self::workflow('golden.signal'),
'golden.telemetry-context' => static function (WorkflowContext $context): array {
$result = $context->activity('golden.greet', ['Ada']);
Expand Down Expand Up @@ -1493,6 +1494,7 @@ private static function workerTaskAttributes(array $fixture): array

return array_intersect_key($workerTask, array_flip([
'resume_source_kind', 'resume_source_id', 'workflow_signal_id', 'workflow_command_id', 'signal_name',
'condition_wait_pending_input_sequence',
]));
}

Expand Down
8 changes: 8 additions & 0 deletions src/Worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
use DurableWorkflow\Worker\QueryTaskAuthority;
use DurableWorkflow\Worker\Replayer;
use DurableWorkflow\Worker\ReplayResult;
use DurableWorkflow\Worker\ConditionInputOrder;
use DurableWorkflow\Worker\ScopedActivityCancellationObserved;
use DurableWorkflow\Worker\WorkflowClaimAborted;
use DurableWorkflow\Worker\WorkflowClaimDeferred;
Expand Down Expand Up @@ -956,6 +957,7 @@
'query_tasks',
'workflow_updates',
'durable_history_replay',
ConditionInputOrder::CAPABILITY,
'grouped_condition_wait_replay',
'workflow_entry_arguments_validation',
'graceful_shutdown',
Expand Down Expand Up @@ -2105,7 +2107,7 @@
}

/** @param array<string, mixed> $task */
private function executeWorkflowTask(array $task): void

Check warning on line 2110 in src/Worker.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

This method has 4 returns, which is more than the 3 allowed.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-php&issues=AaIKsUNKtJ-hThYyBLT3&open=AaIKsUNKtJ-hThYyBLT3&pullRequest=475
{
$traceScope = null;
$previousLocalActivity = $this->workflowExecutedLocalActivity;
Expand Down Expand Up @@ -2179,6 +2181,12 @@
}
$this->completionPipeline?->join();
$this->assertPipelineAuthority();
if ($commands === [] && array_key_exists(ConditionInputOrder::PENDING_INPUT, $task)) {
$this->client->failWorkflowTask($taskId, $leaseOwner, $attempt,
'Workflow task waiting for scheduled history.', 'WorkflowTaskWaitingForHistory');

return;
}
$this->assertWorkflowMemoUpdatesAvailable($commands);
$this->assertServiceOperationsAvailable($commands);
$this->assertChildStartTurnAvailable($commands);
Expand Down
208 changes: 208 additions & 0 deletions src/Worker/ConditionInputOrder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
<?php

declare(strict_types=1);

namespace DurableWorkflow\Worker;

use DurableWorkflow\Exception\NonDeterministicWorkflow;
use Throwable;

/** @internal */
final class ConditionInputOrder
{
public const CAPABILITY = 'condition_wait_input_order';

public const AUTHORING = 'condition_wait_input_order_authoring';

public const ORDER = 'durable_receipt_order';

public const PENDING_INPUT = 'condition_wait_pending_input_sequence';

/** @var array<string, array{open: int, schedule: ?int, timer: ?string, fire: ?int}> */
private array $waits = [];

/** @var list<int> */
private array $appliedPositions = [];

/** @var array<string, array{id: string, sequence: int}> */
private array $competingSelections = [];

/** @param list<array<string, mixed>> $history */
public function __construct(array $history)

Check failure on line 31 in src/Worker/ConditionInputOrder.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 67 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-php&issues=AaIKsULetJ-hThYyBLT1&open=AaIKsULetJ-hThYyBLT1&pullRequest=475
{
$receipts = [];
$terminals = [];
foreach ($history as $event) {
$type = $event['event_type'] ?? $event['type'] ?? null;
$payload = is_array($event['payload'] ?? null) ? $event['payload'] : [];
$sequence = $event['sequence'] ?? null;
if (is_int($sequence) && in_array($type, ['ChildRunCompleted', 'ChildRunFailed', 'ChildRunCancelled', 'ChildRunTerminated'], true)) {
$terminals[$sequence] = [$event['id'] ?? $event['event_id'] ?? null, $type];
}
if ($type === 'SelectionCandidateReady') {
$group = $payload['selection_group_id'] ?? null;
$position = $payload['resolution_event_sequence'] ?? null;
$terminalId = $payload['resolution_event_id'] ?? null;
if (!is_string($group) || $group === '' || isset($this->competingSelections[$group])
|| !is_int($position) || $position < 1 || !is_int($sequence) || $position >= $sequence
|| !is_string($terminalId) || $terminalId === ''
|| ($terminals[$position] ?? null) !== [$terminalId, $payload['resolution_event_type'] ?? null]) {
throw $this->mismatch();
}
$this->competingSelections[$group] = ['id' => $terminalId, 'sequence' => $position];
}
$commandId = $event['workflow_command_id'] ?? $payload['workflow_command_id'] ?? null;
if (is_int($sequence) && $sequence > 0 && is_string($commandId) && $commandId !== '') {
if ($type === 'SignalReceived' || $type === 'UpdateAccepted') {
$receipts[$type][$commandId] ??= $sequence;
} elseif ($type === 'SignalApplied' || $type === 'UpdateApplied') {
$receiptType = $type === 'SignalApplied' ? 'SignalReceived' : 'UpdateAccepted';
if (isset($receipts[$receiptType][$commandId])) {
$this->appliedPositions[] = $receipts[$receiptType][$commandId];
}
}
}
$wait = $payload['condition_wait_id'] ?? null;
if (!is_string($wait) || $wait === '') {
continue;
}
if ($type === 'ConditionWaitOpened' && self::marked($payload)) {
if (!is_int($sequence) || $sequence < 1 || isset($this->waits[$wait])) {
throw $this->mismatch();
}
$this->waits[$wait] = ['open' => $sequence, 'schedule' => null, 'timer' => null, 'fire' => null];
continue;
}
$opening = $this->waits[$wait] ?? null;
if ($opening === null) {
continue;
}
if ($type === 'TimerScheduled') {
$timer = $payload['timer_id'] ?? null;
if (!self::marked($payload) || ($payload['timer_kind'] ?? null) !== 'condition_timeout'
|| !is_int($sequence) || $sequence <= $opening['open'] || $opening['schedule'] !== null
|| !is_string($timer) || $timer === '') {
throw $this->mismatch();
}
$this->waits[$wait]['schedule'] = $sequence;
$this->waits[$wait]['timer'] = $timer;
} elseif ($type === 'TimerFired') {
if (!self::marked($payload) || ($payload['timer_kind'] ?? null) !== 'condition_timeout'
|| ($payload['timer_id'] ?? null) !== $opening['timer'] || $opening['schedule'] === null
|| !is_int($sequence) || $sequence <= $opening['schedule'] || $opening['fire'] !== null) {
throw $this->mismatch();
}
$this->waits[$wait]['fire'] = $sequence;
} elseif ($type === 'ConditionWaitSatisfied' || $type === 'ConditionWaitTimedOut') {
$fire = $opening['fire'];
$receipt = $payload['input_receipt_sequence'] ?? null;
if (!self::marked($payload) || ($payload['timer_fired_sequence'] ?? null) !== $fire
|| !is_int($sequence) || $sequence <= ($fire ?? $opening['open'])
|| ($receipt !== null && (!is_int($receipt) || $receipt < 1 || $receipt >= $sequence))
|| ($type === 'ConditionWaitTimedOut' && ($fire === null || $receipt !== null))
|| ($type === 'ConditionWaitSatisfied' && $fire !== null && ($receipt === null || $receipt >= $fire))) {
throw $this->mismatch();
}
}
}
foreach ($this->waits as $wait) {
if ($wait['schedule'] === null) {
throw $this->mismatch();
}
}
sort($this->appliedPositions, SORT_NUMERIC);
}

/** @param array<string, mixed> $payload */
public static function marked(array $payload): bool
{
return ($payload[self::CAPABILITY] ?? null) === self::ORDER;
}

public function has(?string $id): bool
{
return $id !== null && isset($this->waits[$id]);
}

/**
* @param array<string, mixed> $task
* @return array<string, mixed>|null
*/
public function decide(

Check warning on line 131 in src/Worker/ConditionInputOrder.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

This method has 5 returns, which is more than the 3 allowed.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-php&issues=AaIKsULetJ-hThYyBLT0&open=AaIKsULetJ-hThYyBLT0&pullRequest=475

Check failure on line 131 in src/Worker/ConditionInputOrder.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 32 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=durable-workflow_sdk-php&issues=AaIKsULetJ-hThYyBLT2&open=AaIKsULetJ-hThYyBLT2&pullRequest=475
string $id,
array $task,
WorkflowContext $context,
WorkflowCommand $command,
?string $selectionGroup = null,
): ?array
{
if (!array_key_exists(self::PENDING_INPUT, $task)) {
throw new WorkflowClaimDeferred('condition_input_snapshot_missing: ordered condition replay requires the original worker snapshot.');
}
$pending = $task[self::PENDING_INPUT];
if ($pending !== null && (!is_int($pending) || $pending < 1)) {
throw $this->mismatch();
}
$wait = $this->waits[$id];
$fire = $wait['fire'];
$candidate = $selectionGroup === null ? null : ($this->competingSelections[$selectionGroup] ?? null);
$terminal = min($fire ?? PHP_INT_MAX, $candidate['sequence'] ?? PHP_INT_MAX);
$limit = min($pending ?? PHP_INT_MAX, $terminal);
$prefix = [];
$entryReceipt = null;
foreach ($this->appliedPositions as $receipt) {
if ($receipt > $wait['open'] || $receipt >= $limit) {
break;
}
$prefix[$receipt] = true;
$entryReceipt = $receipt;
}
$result = ['type' => 'resolve_condition_wait', 'condition_wait_id' => $id];
$error = null;
$evaluate = static function (array $view) use ($context, $command, &$error): bool {
try {
$error = null;

return $context->withConditionInputReceipts($view, $command->conditionSatisfied(...));
} catch (Throwable $failure) {
$error = $failure;

return false;
}
};
if ($evaluate($prefix) && ($entryReceipt !== null || $fire === null)) {
return $result + ['satisfied' => true] + ($entryReceipt === null ? [] : ['input_receipt_sequence' => $entryReceipt]);
}
foreach ($this->appliedPositions as $receipt) {
if ($receipt >= $limit) {
break;
}
if (isset($prefix[$receipt])) {
continue;
}
$prefix[$receipt] = true;
if ($evaluate($prefix)) {
return $result + ['satisfied' => true, 'input_receipt_sequence' => $receipt];
}
}
if ($pending === null || $pending >= $terminal) {
if ($error !== null) {
throw $error;
}
if ($candidate !== null && $candidate['sequence'] === $terminal) {
return $result + ['satisfied' => false, 'competing_resolution_event_id' => $candidate['id']];
}
if ($fire !== null) {
return $result + ['satisfied' => false];
}
}

return null;
}

private function mismatch(): NonDeterministicWorkflow
{
return new NonDeterministicWorkflow('Ordered condition history does not match its original timer and receipt boundary.',
reason: 'condition_input_order_mismatch');
}
}
38 changes: 35 additions & 3 deletions src/Worker/Replayer.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ public function replay(
// 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);
$orderedConditions = new ConditionInputOrder($history);
$authorOrderedConditions = ($task[ConditionInputOrder::AUTHORING] ?? null) === true;
$signalMarkerSequences = [];
$steps = array_values(array_filter($steps, static function (array $step) use (&$signalMarkerSequences): bool {
if ($step['shape'] === 'version_marker' && $step['detail'] === AppliedSignals::CHANGE_ID) {
Expand Down Expand Up @@ -533,6 +535,10 @@ public function replay(
...$metadata,
'parallel_group_path' => $path,
]);
if ($suspended->mode === 'select' && $command->type === 'open_condition_wait'
&& $authorOrderedConditions) {
$command = $this->anchorNewConditionChain($command, true);
}
if (($encodingFailure = $this->appendWorkflowCommand(
$commands,
$command,
Expand Down Expand Up @@ -565,6 +571,18 @@ public function replay(
$history, $cancellation, $context, $cancellationConsumed);
}
if ($command->type === 'open_condition_wait') {
$waitId = $this->stringValue($step['condition_wait_id'] ?? null);
if ($waitId !== null && $orderedConditions->has($waitId)) {
$groupId = $path[0]['parallel_group_id'] ?? '';
if (!isset($selectionResolutions[$groupId])) {
$decision = $orderedConditions->decide($waitId, $task, $context, $command, $groupId);
if ($decision !== null) {
$commands[] = $decision;
}
}
$pending = true;
continue;
}
if ($command->conditionSatisfied()) {
$results[$offset] = true;
continue;
Expand Down Expand Up @@ -963,6 +981,16 @@ public function replay(
$suspended = $this->resumeExecution($execution, $businessReplayClock, $step['value'], $step);
continue;
}
$waitId = $this->stringValue($step['condition_wait_id'] ?? null);
if ($waitId !== null && $orderedConditions->has($waitId)) {
$decision = $orderedConditions->decide($waitId, $task, $context, $suspended);
if ($decision === null) {
return $this->result($commands, $context);
}
$commands[] = $decision;
$suspended = $this->resumeExecution($execution, $businessReplayClock, $decision['satisfied']);
continue;
}
$satisfied = $appliedSignals->live(static fn (): bool => $suspended->conditionSatisfied());
if (($encodingFailure = $this->recordAppliedSignalMarker($appliedSignals, $commands, $nextSequence, $taskQueue, $context)) !== null) {
return $encodingFailure;
Expand Down Expand Up @@ -1055,7 +1083,7 @@ public function replay(
continue;
}
if ($suspended->type === 'open_condition_wait') {
$suspended = $this->anchorNewConditionChain($suspended);
$suspended = $this->anchorNewConditionChain($suspended, $authorOrderedConditions);
}
if (($encodingFailure = $this->appendWorkflowCommand(
$commands,
Expand Down Expand Up @@ -1662,18 +1690,19 @@ private function recordedConditionDeadlinePolicy(array $payload, int $sequence):
* the authored timeout; timeout_seconds stays the replay input (#269).
* Grouped waits keep their authored per-open timeout.
*/
private function anchorNewConditionChain(WorkflowCommand $command): WorkflowCommand
private function anchorNewConditionChain(WorkflowCommand $command, bool $authorOrderedConditions): WorkflowCommand
{
$timeout = $command->attributes['timeout_seconds'] ?? null;
if (!$this->conditionOccurrenceDeadline || !is_int($timeout)
|| !is_string($command->attributes['condition_wait_occurrence_id'] ?? null)
|| array_key_exists('parallel_group_path', $command->attributes)) {
|| (!$authorOrderedConditions && array_key_exists('parallel_group_path', $command->attributes))) {
return $command;
}

return $command->withAttributes([
'deadline_policy' => self::CONDITION_DEADLINE_POLICY,
'condition_wait_timeout_budget_seconds' => $timeout,
...($authorOrderedConditions ? [ConditionInputOrder::CAPABILITY => ConditionInputOrder::ORDER] : []),
]);
}

Expand Down Expand Up @@ -2127,6 +2156,9 @@ private function recordedSteps(array $history, bool $preserveConditionReopens, C
}
} elseif ($type === 'TimerFired') {
if (($payload['timer_kind'] ?? null) === 'condition_timeout') {
if (ConditionInputOrder::marked($payload)) {
continue;
}
$conditionStepKey = $this->conditionStepKey($payload, $conditionStepsByWaitId);
if ($conditionStepKey !== null
&& isset($steps[$conditionStepKey])
Expand Down
Loading