diff --git a/CHANGELOG.md b/CHANGELOG.md index ce8c22b5..f1cd96ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- `enableActivityContinuation` consumes activity workflow continuation v2 + (#500, server#1181) when a native Server advertises it. Version 2 is + preferred over version 1, and version 1 stays the fallback. The worker seeds + its sticky cache from the `continuation_tail` a workflow task completion + returns. It then speculates the next workflow task from the cache plus its + own activity result, with no history request. Each accepted answer's tail + keeps the cache exact. The answer can carry the next activity, which runs in + the same tick. A tail that does not continue the cache evicts the entry. An + omitted tail keeps the old boundary, and the leased activity completes the + ordinary way. Declines process the carried workflow poll, and refusals send + the ordinary completion with the same poll. An unknown outcome resends the + identical v2 request. A malformed `v2` member disables version 2 only. The + option stays off by default. Continuations are unqualified and may cost + throughput until the server#1181 benchmark passes. See the + [worker guide](docs/portal/build/workers.md#activity-continuation-version-2). + ## [3.32.0] - 2026-11-26 ### Fixed diff --git a/docs/portal/build/workers.md b/docs/portal/build/workers.md index 1aac75df..4a08adb5 100644 --- a/docs/portal/build/workers.md +++ b/docs/portal/build/workers.md @@ -144,6 +144,75 @@ completion outcomes follow completion error/recovery rules. They do not become eligibility declines. Drain or disable opted-in workers before downgrading a producer or introducing older serving nodes. No speedup is promised. +**Continuations are unqualified.** Enabling them may cost throughput. The +[server#1078](https://github.com/durable-workflow/server/issues/1078) A/B +measured version 1 as slower than the ordinary path under load. Version 2 must +pass the [server#1181](https://github.com/durable-workflow/server/issues/1181) +benchmark before the option can become a default. Until then it stays off. + +### Activity continuation version 2 + +A native Server that implements version 2 advertises it inside the same +capability, as `supported_versions` containing `2` and a `v2` member. The +worker uses version 2 when all of these hold: + +- `enableActivityContinuation` is on; +- the `v2` member is well formed, with `version` exactly `2` and the expected + `complete_endpoint`; +- the registration negotiated sticky history suffixes; +- no worker interceptors are configured. + +A malformed `v2` member turns off version 2 only. Version 1 stays the fallback +when version 2 is not advertised, or after a Server refuses it with +`unsupported_continuation_version`. That refusal holds until the worker +registers again. + +Version 2 speculates from the worker's sticky cache and never asks the Server +for history: + +1. A workflow task completion with a cached boundary asks for + `continuation_tail`. The Server answers with the events it wrote after that + boundary. With a tail requested, the carried activity poll leases only an + activity this completion created. +2. The worker appends the tail only when it continues the cache exactly. A tail + that does not continue the cache evicts the run's entry. An omitted tail + (over a Server budget, or `tail_unavailable` on a retry) keeps the old + boundary. +3. After an activity succeeds, the worker sends version 2 only when the cache + starts with `WorkflowStarted`, is contiguous, and ends in this attempt's + `ActivityStarted`. It also needs a reserved workflow poll slot, and the + replay with the result must pass the version 1 checks. Otherwise it sends + the ordinary completion, which costs nothing extra. +4. An accepted answer returns the next tail and may carry the next activity, + which the worker runs in the same tick. After 16 such activities in one + tick, the request carries no activity poll, so the tick ends and query and + workflow polls get a turn. + +Answers follow the +[contract](https://github.com/durable-workflow/server/blob/main/docs/contracts/activity-workflow-continuation-v2.md): + +- **Decline.** The result is recorded. The worker processes the carried + workflow poll answer. It evicts the cache entry for + `cache_identity_mismatch` and `run_not_open`, and keeps it for every other + reason. +- **Refusal** (a 4xx, or 500 `invalid_continuation_receipt` or + `history_invariant_violated`). Nothing was written, so the worker sends the + ordinary activity completion with the same carried workflow poll. The two + 500 reasons also evict the cache entry and log an error. 409 `stale_attempt` + and `conflicting_completion` keep the ordinary stale-attempt and duplicate + handling and are not retried. +- **Unknown outcome** (another 5xx, or a transport failure). The worker resends + the identical request on the completion retry schedule, never an ordinary + completion. A retry that outlasts its attempts is logged as + `worker.outcome_unpublished`, and the Server re-delivers the attempt when + its lease ends. + +Diagnostics: `worker.activity_continuation` (with `version`, `outcome`, +`reason` and `tail`), `worker.activity_continuation_skipped`, +`worker.activity_continuation_refused`, +`worker.activity_continuation_tail_rejected` and +`worker.activity_continuation_tail_refused`. + ### Poll timeouts and early disconnects When the Server advertises `task_delivery`, the managed worker negotiates diff --git a/scripts/ci/run-replay-regression-fixture.php b/scripts/ci/run-replay-regression-fixture.php index a04edf42..d5bde703 100644 --- a/scripts/ci/run-replay-regression-fixture.php +++ b/scripts/ci/run-replay-regression-fixture.php @@ -661,6 +661,18 @@ private static function execute(array $fixture): void return; } + if ($workflowType === 'golden.activity-continuation-v2') { + require_once __DIR__.'/../../tests/Support/FakeTransport.php'; + require_once __DIR__.'/../../tests/Support/ActivityContinuationV2Scenario.php'; + $observed = \DurableWorkflow\Tests\Support\ActivityContinuationV2Scenario::run(); + self::assertMatches($fixture['command_sequence'], $observed['commands'], $identity.self::COMMAND_SEQUENCE_CONTEXT); + $commands = $observed['commands']; + unset($observed['commands']); + self::assertMatches($fixture['expected'], ($commands[0] ?? []) + $observed, $identity.self::EXPECTED_CONTEXT); + + return; + } + if ($workflowType === 'golden.worker-interceptor') { require_once __DIR__.'/../../tests/Support/FakeTransport.php'; require_once __DIR__.'/../../tests/Support/WorkerInterceptorScenario.php'; diff --git a/src/Client.php b/src/Client.php index 839aa12c..89b28a98 100644 --- a/src/Client.php +++ b/src/Client.php @@ -2841,11 +2841,14 @@ public function deliverWorkflowCancellation( * run_id: string, * build_id: string, * ttl_seconds: int, - * metrics: array{hit: int, miss: int, eviction: int, forced_cold_replay: int} + * metrics: array{hit: int, miss: int, eviction: int, forced_cold_replay: int}, + * history_last_sequence?: int * }|null $stickyCache * @param array{worker_id: string, task_queue: string, poll_request_id: string, timeout_seconds: int}|null $activityPoll * @param array{worker_id: string, task_queue: string, poll_request_id: string, timeout_seconds: int, history_page_size: int, task_kinds: list}|null $workflowPoll * @param array|null $selectionChildAwait + * @param array{version: int}|null $continuationTail Server #1181: ask for the history after the + * sticky_cache boundary, read after this completion's writes. Requires history_last_sequence. * @return array */ public function completeWorkflowTask( @@ -2859,6 +2862,7 @@ public function completeWorkflowTask( ?array $activityPoll = null, ?array $workflowPoll = null, ?array $selectionChildAwait = null, + ?array $continuationTail = null, ): array { if (($messageStreamCursors !== [] || $messageStreamWaits !== []) && !Version::supportsMessageStreams()) { throw new InvalidArgumentException('Message stream completion metadata requires worker protocol 1.15 or newer.'); @@ -2916,6 +2920,7 @@ public function completeWorkflowTask( 'activity_poll' => $activityPoll, 'workflow_poll' => $workflowPoll, 'selection_handle' => $selectionChildAwait, + 'continuation_tail' => $continuationTail, ], static fn (mixed $value): bool => $value !== [] && $value !== null)); } @@ -3029,9 +3034,12 @@ public function activityContinuationHistory(string $taskId, string $activityAtte /** * Server #1078: complete an activity and propose the run's next workflow task commands. + * A version 2 continuation (Server #1181) also names the sticky cache it was speculated + * from and may carry an activity poll for the activity its commands schedule. * * @param array{worker_id: string, task_queue: string, poll_request_id: string, timeout_seconds: int, history_page_size: int, task_kinds: list} $workflowPoll - * @param array{version: int, history_through_sequence: int, history_last_event_id: string, commands: list>} $continuation + * @param array{version: int, history_through_sequence: int, history_last_event_id: string, commands: list>, sticky_cache?: array} $continuation + * @param array{worker_id: string, task_queue: string, poll_request_id: string, timeout_seconds: int}|null $activityPoll * @return array */ public function completeActivityTaskWithContinuation( @@ -3041,6 +3049,7 @@ public function completeActivityTaskWithContinuation( mixed $result, array $workflowPoll, array $continuation, + ?array $activityPoll = null, ): array { foreach ($continuation['commands'] as $command) { if (array_key_exists('target_build', $command)) { @@ -3049,14 +3058,20 @@ public function completeActivityTaskWithContinuation( } $this->taskDelivery->carried('/worker/workflow-tasks/poll', $workflowPoll); + $this->taskDelivery->carried('/worker/activity-tasks/poll', $activityPoll); - return $this->worker('POST', self::ACTIVITY_TASK_PATH.$this->segment($taskId).'/continuation/complete', [ + $body = [ 'activity_attempt_id' => $activityAttemptId, 'lease_owner' => $leaseOwner, 'result' => $this->codec->envelope($result), 'workflow_poll' => $workflowPoll, - 'continuation' => $continuation, - ]); + ]; + if ($activityPoll !== null) { + $body['activity_poll'] = $activityPoll; + } + $body['continuation'] = $continuation; + + return $this->worker('POST', self::ACTIVITY_TASK_PATH.$this->segment($taskId).'/continuation/complete', $body); } /** diff --git a/src/Worker.php b/src/Worker.php index ab29bc0c..e284b509 100644 --- a/src/Worker.php +++ b/src/Worker.php @@ -117,6 +117,17 @@ final class Worker private const TRANSIENT_RETRY_SLEEP_SLICE_SECONDS = 0.1; private const MAX_STALE_REGISTRATION_BACKOFF_SECONDS = 60.0; private const REREGISTRATION_METRIC = 'durable_workflow_worker_reregistrations'; + /** Server #1181: the registration capabilities a v2 continuation may require; this Worker always registers both. */ + private const CONTINUATION_V2_WORKER_CAPABILITIES = ['sticky_execution', 'sticky_history_suffix']; + /** The v2 refusals that report corrupt stored state: complete the activity the ordinary way and report it. */ + private const CONTINUATION_V2_CORRUPT_STATE = ['invalid_continuation_receipt', 'history_invariant_violated']; + /** v2 declines after which the cache no longer names this run's history (contract "Declines and fallback"). */ + private const CONTINUATION_V2_EVICTING_DECLINES = ['cache_identity_mismatch', 'run_not_open']; + /** + * Activities an accepted v2 answer may hand straight to the next one within a tick. Past it the + * request carries no activity poll, so the tick ends and query and workflow polls get a turn. + */ + private const CONTINUATION_V2_MAX_CHAINED_ACTIVITIES = 16; /** @var array */ private array $workflows = []; @@ -201,6 +212,16 @@ final class Worker private bool $queryPollDeferredForCarriedWorkflow = false; /** @var array|null The server's advertised activity_workflow_continuation v1 contract. */ private ?array $activityContinuation = null; + /** @var array{supported_commands: list, max_commands: int}|null The advertised v2 member (Server #1181). */ + private ?array $activityContinuationV2 = null; + /** A Server answered 422 unsupported_continuation_version; v2 stays off until the Worker registers again. */ + private bool $activityContinuationV2Refused = false; + /** The activity poll an accepted v2 continuation carried, observed after its activity task ends. */ + private ?CarriedPoll $continuationActivityPoll = null; + /** The current activity's v2 continuation met an unknown outcome: it is resent, never replaced. */ + private bool $continuationV2OutcomeUnknown = false; + /** Activities this tick ran from leases accepted v2 continuations carried. */ + private int $continuationChainLength = 0; private int $workflowTasksInFlight = 0; private ?CarriedPoll $carriedActivityPoll = null; private int $activityTasksInFlight = 0; @@ -252,9 +273,10 @@ public function __construct( /** Opt-in. Changes when completion failures become visible; never applies to public tick(). */ private readonly bool $enableCompletionPipelining = false, /** - * Opt-in (Server #1078). After an activity succeeds, replay its run with the result and send the - * next workflow commands with the completion. Used only when the server advertises - * activity_workflow_continuation; anything unsupported falls back to the ordinary path. + * Opt-in (Server #1078, #1181). After an activity succeeds, replay its run with the result and send + * the next workflow commands with the completion. Used only when the server advertises + * activity_workflow_continuation; v2 is preferred when advertised and v1 is the fallback. + * Anything unsupported falls back to the ordinary path. Unqualified: it may cost throughput. */ private readonly bool $enableActivityContinuation = false, /** @@ -672,6 +694,7 @@ private function establishRegistration(array $registration): void { $this->applyHeartbeatInterval($registration); $this->captureRegistrationFence($registration); + $this->activityContinuationV2Refused = false; $this->discoverGroupedConditionWaitSupport($registration); $this->queryTaskAuthoritySupported = $this->client->workerProtocolVersion === '1.20' && ($registration['server_capabilities']['query_task_authority'] ?? null) === true @@ -779,6 +802,7 @@ private function recoverStaleRegistration(): bool $this->carriedWorkflowPoll = null; $this->queryPollDeferredForCarriedWorkflow = false; $this->carriedActivityPoll = null; + $this->continuationActivityPoll = null; $this->workflowPollGrant = null; $this->claimCancellation = null; $this->claimDeliveredCancellationId = null; @@ -1316,44 +1340,59 @@ private function performTick(int $pollTimeoutSeconds): bool // Finish only a lease already delivered by the completion; create no new carrier. $this->shutdownRequested = false; } + $this->continuationChainLength = 0; try { - $activityPoll = $this->pollWithRetry( - 'activity', - fn (string $requestId, int $timeoutSeconds): array => $this->client->pollActivityTaskResponse( - $this->workerId, - $this->taskQueue, - $timeoutSeconds, - $requestId, - ), - $handled ? 0 : $pollTimeoutSeconds, - $this->carriedActivityPoll, - ); - if ($activityPoll === null) { - return $handled; - } - if ($this->stopForTerminalPoll($activityPoll)) { - return $handled; - } - $this->rememberCarriedPollCapabilities($activityPoll); - $this->heartbeatIfDue(); - if ($this->crossKindPollWakeReceived($activityPoll)) { - $pollTimeoutSeconds = 0; - } - $activityTask = $this->taskFromPoll($activityPoll); - if ($activityTask !== null) { - // Only the poll response carries server_capabilities; the claim alone cannot - // distinguish an older Server from a supported claim without a checkpoint. - $this->polledActivityHeartbeatResume = ActivityHeartbeatResume::fromPoll( - $activityPoll, $this->client->namespace, $this->workerId, $this->taskQueue); - try { - $this->executePolledTask('activity', $activityTask); - } finally { - $this->polledActivityHeartbeatResume = null; + do { + $activityPoll = $this->pollWithRetry( + 'activity', + fn (string $requestId, int $timeoutSeconds): array => $this->client->pollActivityTaskResponse( + $this->workerId, + $this->taskQueue, + $timeoutSeconds, + $requestId, + ), + $handled ? 0 : $pollTimeoutSeconds, + $this->carriedActivityPoll, + ); + if ($activityPoll === null) { + return $handled; } - $handled = true; - } + if ($this->stopForTerminalPoll($activityPoll)) { + return $handled; + } + $this->rememberCarriedPollCapabilities($activityPoll); + $this->heartbeatIfDue(); + if ($this->crossKindPollWakeReceived($activityPoll)) { + $pollTimeoutSeconds = 0; + } + $activityTask = $this->taskFromPoll($activityPoll); + if ($activityTask !== null) { + // Only the poll response carries server_capabilities; the claim alone cannot + // distinguish an older Server from a supported claim without a checkpoint. + $this->polledActivityHeartbeatResume = ActivityHeartbeatResume::fromPoll( + $activityPoll, $this->client->namespace, $this->workerId, $this->taskQueue); + try { + $this->executePolledTask('activity', $activityTask); + } finally { + $this->polledActivityHeartbeatResume = null; + } + $handled = true; + } + // Server #1181: an accepted v2 continuation leased the run's next activity. + $this->carriedActivityPoll = $this->takeContinuationActivityLease(); + if ($this->carriedActivityPoll !== null) { + ++$this->continuationChainLength; + } + if ($this->carriedActivityPoll !== null && $this->shutdownRequested) { + // Finish only the lease the completion already delivered; create no new carrier. + $stopAfterCarriedLease = true; + $this->drainingCarriedLease = true; + $this->shutdownRequested = false; + } + } while ($this->carriedActivityPoll !== null); } finally { $this->carriedActivityPoll = null; + $this->continuationActivityPoll = null; $this->shutdownRequested = $stopAfterCarriedLease || $this->shutdownRequested; $this->drainingCarriedLease = false; } @@ -1510,6 +1549,54 @@ private function rememberCarriedPollCapabilities(array $response): void && is_array($continuation['supported_commands'] ?? null) && is_int($continuation['max_commands'] ?? null) && ($continuation['complete_endpoint'] ?? null) === '/worker/activity-tasks/{taskId}/continuation/complete' ? $continuation : null; + $this->activityContinuationV2 = self::activityContinuationV2Contract($continuation); + } + + /** + * Server #1181: the v2 member of activity_workflow_continuation, or null. It is read on its + * own, so a malformed member disables v2 and never v1. + * + * @return array{supported_commands: list, max_commands: int}|null + */ + private static function activityContinuationV2Contract(mixed $continuation): ?array + { + if (!is_array($continuation)) { + return null; + } + $versions = $continuation['supported_versions'] ?? null; + $v2 = $continuation['v2'] ?? null; + if (!is_array($versions) || !in_array(2, $versions, true) || !is_array($v2) || array_is_list($v2) + || ($v2['version'] ?? null) !== 2 + || ($v2['complete_endpoint'] ?? null) !== '/worker/activity-tasks/{taskId}/continuation/complete') { + return null; + } + $commands = $v2['supported_commands'] ?? null; + $maxCommands = $v2['max_commands'] ?? null; + $required = $v2['requires_worker_capabilities'] ?? null; + if (!is_array($commands) || !array_is_list($commands) || $commands === [] + || array_filter($commands, static fn (mixed $command): bool => !is_string($command)) !== [] + || !is_int($maxCommands) || $maxCommands < 1 + || !is_array($required) || !array_is_list($required) + // Every Worker registers both; a requirement it does not know is never met. + || array_diff($required, self::CONTINUATION_V2_WORKER_CAPABILITIES) !== [] + || !is_int($v2['tail_max_events'] ?? null) || $v2['tail_max_events'] < 1 + || !is_int($v2['tail_max_bytes'] ?? null) || $v2['tail_max_bytes'] < 1) { + return null; + } + + return ['supported_commands' => $commands, 'max_commands' => $maxCommands]; + } + + /** + * Server #1181: v2 is used only when the option is on, the Server advertises a well-formed v2 + * member and has not refused its version, and this registration takes sticky history suffixes. + * Worker interceptors wrap every workflow task, so they keep the ordinary path, as in v1. + */ + private function activityContinuationV2Selected(): bool + { + return $this->enableActivityContinuation && $this->activityContinuationV2 !== null + && !$this->activityContinuationV2Refused && $this->stickyHistorySuffixSupported + && $this->interceptors->isEmpty(); } private function observeCarriedWorkflowCompletion(): void @@ -1695,6 +1782,8 @@ private function pollFailurePolicy(string $kind, string $requestId, ServerExcept * @param array{task_id: string, activity_attempt_id: string, lease_owner: string}|null $activityTaskLease * @param string|null $fencedTaskId A failure report or query answer repeated under its original task, * attempt and lease through an outage (see settledByServer()). + * @param (\Closure(): bool)|null $uncertainOutcome True when the failed request's outcome is unknown + * and the identical request must be resent (an activity workflow continuation v2, Server #1181). * @return T */ private function retryStorageAdmission( @@ -1703,6 +1792,7 @@ private function retryStorageAdmission( ?array $workflowTaskLease = null, ?array $activityTaskLease = null, ?string $fencedTaskId = null, + ?\Closure $uncertainOutcome = null, ): mixed { $attempt = 0; @@ -1783,7 +1873,8 @@ private function retryStorageAdmission( $untypedOutage = !$exception->isStorageAdmissionFailure() && !$backendUnavailable && !$activityDiscoveryUnavailable && !$exception->isTransientConnectionFailure() && !$exception->isTransientUpstreamFailure() - && TransientFailure::is($exception, acknowledgement: true); + && (TransientFailure::is($exception, acknowledgement: true) + || ($uncertainOutcome !== null && $uncertainOutcome() === true)); // Cluster info failed before this request was sent (see // RuntimePayloadUploads); repeating it is safe. $discoveryOutage = $untypedOutage && $exception->isPayloadDiscoveryUnavailable(); @@ -2053,6 +2144,7 @@ private function stopForTerminalPoll(array $response): bool $this->staleRegistrationObserved = true; $this->carriedWorkflowPoll = null; $this->carriedActivityPoll = null; + $this->continuationActivityPoll = null; $this->completionPipeline?->requestStop(); $this->shutdownRequested = true; @@ -2397,6 +2489,13 @@ function () use ($task, $history, $workflowType, $updateId, &$messageStreamCurso $this->assertSignalExternalWorkflowAvailable($commands); $this->assertCancellationPoliciesAvailable($commands); $stickyClaim = $this->stickyCacheClaim($task); + // Server #1181: seed the cache for a v2 continuation of the activity this completion schedules. + $continuationTail = $this->activityContinuationV2Selected() && isset($stickyClaim['history_last_sequence']); + if ($continuationTail && ($updateId === null || $updateId === '')) { + $this->stickyCache->rememberContext((string) $task['workflow_id'], (string) $task['run_id'], + $this->effectiveBuildId(), ['workflow_type' => $workflowType, + 'arguments' => $task['arguments'] ?? $task['input'] ?? null]); + } $this->prepareCompletionPipeline($task, $commands); $this->assertPipelineAuthority(); $promotedContinuation = false; @@ -2413,11 +2512,28 @@ function () use ($task, $history, $workflowType, $updateId, &$messageStreamCurso $this->notifyDeliveredWorkflowHistory('completion', $taskId, $attempt, $commands); $complete = fn (array $commands, array $messageStreamCursors, array $messageStreamWaits, ?array $selectionChildAwait = null): array => $this->retryStorageAdmission('workflow_complete', function () use ( - $taskId, $leaseOwner, $attempt, $commands, $messageStreamCursors, $messageStreamWaits, $stickyClaim, $carried, $workflowCarried, $promotedContinuation, $selectionChildAwait, + $task, $taskId, $leaseOwner, $attempt, $commands, $messageStreamCursors, $messageStreamWaits, $stickyClaim, $carried, $workflowCarried, $promotedContinuation, $selectionChildAwait, &$continuationTail, ): array { try { - return $this->client->completeWorkflowTask($taskId, $leaseOwner, $attempt, $commands, - $messageStreamCursors, $messageStreamWaits, $stickyClaim, $carried?->request, $workflowCarried?->request, $selectionChildAwait); + try { + return $this->client->completeWorkflowTask($taskId, $leaseOwner, $attempt, $commands, + $messageStreamCursors, $messageStreamWaits, $stickyClaim, $carried?->request, $workflowCarried?->request, $selectionChildAwait, + $continuationTail ? ['version' => 2] : null); + } catch (ServerException $error) { + if (!$continuationTail || $error->status !== 422 || $error->reason !== 'invalid_continuation_tail') { + throw $error; + } + // Refused before any write: the Server holds no history after the cached + // boundary. The cache cannot be trusted, so complete without a tail. + $continuationTail = false; + $this->forgetCachedRun($task); + $this->diagnostic('worker.activity_continuation_tail_refused', [ + 'task_id' => $taskId, 'workflow_task_attempt' => $attempt, 'reason' => $error->reason, + ], 'warning'); + + return $this->client->completeWorkflowTask($taskId, $leaseOwner, $attempt, $commands, + $messageStreamCursors, $messageStreamWaits, $stickyClaim, $carried?->request, $workflowCarried?->request, $selectionChildAwait); + } } catch (ServerException $error) { $carried?->uncertainCompletion(); $workflowCarried?->uncertainCompletion(); @@ -2464,6 +2580,9 @@ function () use ($task, $history, $workflowType, $updateId, &$messageStreamCurso $completion = $complete($commands, [], []); } $this->notifyDeliveredWorkflowHistory('accepted', $taskId, $attempt, $commands); + if ($continuationTail) { + $this->applyWorkflowCompletionTail($task, $stickyClaim['history_last_sequence'], $completion); + } $this->writeWorkflowLogs($workflowLogs); if ($carried !== null) { // Payload hydration belongs to the next task, never this completed parent's catch path. @@ -2743,6 +2862,307 @@ private function speculateActivityContinuation(array $task, mixed $result): ?arr 'commands' => $commands]; } + /** + * Server #1181: speculate the run's next workflow task from the sticky cache plus this + * activity's own result, with no history request. Returns the v2 continuation member, or + * null for the ordinary completion. The worker preconditions of the v2 contract: + * - the cache entry exists, starts with WorkflowStarted and is contiguous; + * - its tail ends in this attempt's ActivityStarted, so a lease this Worker did not seed + * (for example one a replayed carried poll handed back) is completed the ordinary way; + * - the replay of the cache plus one synthetic ActivityCompleted at through + 1 produced + * 1 to max_commands supported commands and passes the v1 speculation checks. + * The caller has reserved the workflow poll slot. + * + * @param array $task + * @return array{version: int, history_through_sequence: int, history_last_event_id: string, sticky_cache: array, commands: list>}|null + */ + private function speculateActivityContinuationV2(array $task, mixed $result): ?array + { + $contract = $this->activityContinuationV2; + $taskId = (string) ($task['task_id'] ?? ''); + $attemptId = (string) ($task['activity_attempt_id'] ?? $task['attempt_id'] ?? ''); + $executionId = $task['activity_execution_id'] ?? null; + $workflowId = $task['workflow_id'] ?? null; + $runId = $task['run_id'] ?? null; + $skip = function (string $reason) use ($taskId, $attemptId): ?array { + $this->diagnostic('worker.activity_continuation_skipped', [ + 'task_id' => $taskId, 'activity_attempt_id' => $attemptId, 'version' => 2, 'reason' => $reason, + ]); + + return null; + }; + if ($contract === null || $attemptId === '' || !is_string($executionId) || $executionId === '' + || !is_string($workflowId) || $workflowId === '' || !is_string($runId) || $runId === '' + || ($task['lease_owner'] ?? $this->workerId) !== $this->workerId) { + return $skip('task_identity'); + } + $buildId = $this->effectiveBuildId(); + $history = $this->stickyCache->cachedHistory($workflowId, $runId, $buildId); + if ($history === null) { + return $skip('cache_miss'); + } + if (!StickyWorkflowCache::startsWithWorkflowStart($history)) { + return $skip('cache_incomplete'); + } + $expected = 1; + foreach ($history as $event) { + if (($event['sequence'] ?? null) !== $expected) { + return $skip('cache_not_contiguous'); + } + ++$expected; + } + $last = $history[array_key_last($history)]; + $through = $last['sequence']; + $lastEventId = $last['id'] ?? null; + if (($last['event_type'] ?? $last['type'] ?? null) !== 'ActivityStarted' + || !is_array($last['payload'] ?? null) || ($last['payload']['activity_attempt_id'] ?? null) !== $attemptId) { + return $skip('cache_tail_not_this_activity'); + } + if (!is_string($lastEventId) || $lastEventId === '' || strlen($lastEventId) > 64) { + return $skip('cache_event_id'); + } + $claim = $this->stickyCacheClaim($task); + $context = $this->stickyCache->context($workflowId, $runId, $buildId); + $workflowType = $context['workflow_type'] ?? null; + $handler = is_string($workflowType) ? ($this->workflows[$workflowType] ?? null) : null; + if ($claim === null || ($claim['history_last_sequence'] ?? null) !== $through || $handler === null) { + return $skip('cache_context'); + } + // The worker's own result, in the shape the server records: this activity's last + // scheduling event with its result. The event has no ID or time: the Server assigns them. + $scheduled = null; + foreach ($history as $event) { + if (in_array($event['event_type'] ?? null, ['ActivityScheduled', 'ActivityStarted'], true) + && ($event['payload']['activity_execution_id'] ?? null) === $executionId) { + $scheduled = $event; + } + } + if (!is_array($scheduled) || !is_array($scheduled['payload'] ?? null)) { + return $skip('activity_not_scheduled'); + } + try { + $payload = $scheduled['payload']; + $payload['result'] = $this->client->payloadCodec()->envelope($result); + $payload['payload_codec'] = 'avro'; + $payload['activity_attempt_id'] = $attemptId; + $payload['attempt_number'] = (int) ($task['attempt_number'] ?? 1); + $history[] = ['id' => null, 'sequence' => $through + 1, 'event_type' => 'ActivityCompleted', 'payload' => $payload, + 'recorded_at' => null, 'workflow_task_id' => $taskId, 'workflow_command_id' => null]; + $input = $this->decodeArguments($context['arguments'] ?? null); + WorkflowEntryArguments::validate($handler, $input, $workflowType); + $replay = $this->replayer->replay($handler, $history, $input, $this->taskQueue, [ + 'workflow_type' => $workflowType, 'workflow_id' => $workflowId, 'run_id' => $runId, 'cancel_requested' => false, + ]); + } catch (Throwable $error) { + $this->diagnostic('worker.activity_continuation_skipped', [ + 'task_id' => $taskId, 'activity_attempt_id' => $attemptId, 'version' => 2, 'error' => $error::class, + ]); + + return null; + } + $commands = $replay->commands; + if ($this->replayer->lastReplayReadUnavailableTime() || $replay->terminalFailure !== null + || $replay->messageStreamCursors !== [] || $replay->messageStreamWaits !== [] + || $replay->cancellationDelivery !== null || $replay->preparedLocalActivity !== null + || $replay->preparedLocalActivityGroup !== null || $replay->cancellationScopeOpening !== null + || $replay->cancellationScopeDelivery !== null + || $commands === [] || count($commands) > $contract['max_commands']) { + return null; + } + foreach ($commands as $command) { + if (!in_array($command['type'] ?? null, $contract['supported_commands'], true) + || array_key_exists('cancellation_scope_id', $command) || array_key_exists('parallel_group_path', $command)) { + return null; + } + } + + $this->speculativeWorkflowLogs = $this->replayer->takeWorkflowLogs(); + + return ['version' => 2, 'history_through_sequence' => $through, 'history_last_event_id' => $lastEventId, + 'sticky_cache' => $claim, 'commands' => $commands]; + } + + /** Server #1181: an activity poll for the activity an accepted v2 continuation's commands schedule. */ + private function reserveContinuationActivityPoll(string $leaseOwner): ?CarriedPoll + { + if (!$this->workflowCompletionActivityPollSupported || $this->activities === [] + || $leaseOwner !== $this->workerId || $this->shutdownRequested || $this->drainingCarriedLease + || $this->continuationActivityPoll !== null + || $this->continuationChainLength >= self::CONTINUATION_V2_MAX_CHAINED_ACTIVITIES) { + return null; + } + + return new CarriedPoll([ + 'worker_id' => $this->workerId, 'task_queue' => $this->taskQueue, + 'poll_request_id' => 'php-activity-poll-'.bin2hex(random_bytes(16)), 'timeout_seconds' => 0, + ], hrtime(true) / 1e9); + } + + /** The activity lease an accepted v2 continuation carried, observed after its own activity task ended. */ + private function takeContinuationActivityLease(): ?CarriedPoll + { + $poll = $this->continuationActivityPoll; + $this->continuationActivityPoll = null; + if ($poll === null || !$poll->observeCompletion('activity_poll') || !$poll->hasLease()) { + return null; + } + + return $poll; + } + + /** + * The contract's "Refusals" table: a 5xx other than the corrupt-state refusals, or a + * transport failure, leaves the outcome unknown. + */ + private static function continuationV2OutcomeUnknown(ServerException $error): bool + { + return $error->status === 0 || $error->isTransientUpstreamFailure() + || ($error->status >= 500 && $error->status <= 599 + && !in_array($error->reason, self::CONTINUATION_V2_CORRUPT_STATE, true)); + } + + /** + * A refused v2 continuation wrote nothing; the caller sends the ordinary completion. + * + * @param array $task + */ + private function refuseActivityContinuationV2(array $task, ServerException $error): void + { + $corrupt = $error->status >= 500 && in_array($error->reason, self::CONTINUATION_V2_CORRUPT_STATE, true); + if ($error->status === 422 && $error->reason === 'unsupported_continuation_version') { + // A Server without v2: use v1 or the ordinary path until the Worker registers again. + $this->activityContinuationV2Refused = true; + } + if ($corrupt) { + $this->forgetCachedRun($task); + } + $this->diagnostic('worker.activity_continuation_refused', [ + 'task_id' => $task['task_id'] ?? null, + 'activity_attempt_id' => $task['activity_attempt_id'] ?? $task['attempt_id'] ?? null, + 'version' => 2, 'status' => $error->status, 'reason' => $error->reason, + ], $corrupt ? 'error' : 'warning'); + } + + /** + * Server #1181: apply a v2 answer (contract "Answer", "Declines and fallback"). The carried + * workflow poll answer is processed by its own carrier; this handles the cache, the carried + * activity lease and the speculative workflow logs. + * + * @param array $task + * @param array{history_through_sequence: int} $continuation + * @param array $completion + */ + private function observeActivityContinuationV2(array $task, array $continuation, array $completion, + ?CarriedPoll $workflowCarrier, ?CarriedPoll $activityCarrier): void + { + $decision = $completion['continuation'] ?? null; + $outcome = is_array($decision) && ($decision['version'] ?? null) === 2 ? ($decision['outcome'] ?? null) : null; + $reason = is_array($decision) ? ($decision['reason'] ?? null) : null; + $tail = null; + if ($outcome === 'accepted') { + // The accepted speculation is this run's workflow task. + $this->writeWorkflowLogs($this->speculativeWorkflowLogs); + $tail = $this->applyContinuationTail($task, $continuation['history_through_sequence'], + $completion['continuation_tail'] ?? null, missingIsOmitted: false); + $runStatus = is_array($decision['completion'] ?? null) ? ($decision['completion']['run_status'] ?? null) : null; + if (!in_array($runStatus, ['running', 'waiting'], true)) { + $this->forgetCachedRun($task); + } + // The resumed workflow task was completed by this request, so its carried poll + // leased nothing to drain, even after an uncertain first attempt. + if ($workflowCarrier !== null && $this->carriedWorkflowPoll === $workflowCarrier) { + $this->carriedWorkflowPoll = null; + } + if ($activityCarrier !== null) { + $activityCarrier->completion = $completion; + $this->continuationActivityPoll = $activityCarrier; + } + $this->pollSweepRequested = true; + } elseif ($outcome === 'declined') { + if (in_array($reason, self::CONTINUATION_V2_EVICTING_DECLINES, true)) { + $this->forgetCachedRun($task); + } + } else { + // The result is recorded, but the decision is unreadable: trust nothing speculative. + $this->forgetCachedRun($task); + } + $this->diagnostic('worker.activity_continuation', [ + 'task_id' => $task['task_id'] ?? null, + 'activity_attempt_id' => $task['activity_attempt_id'] ?? $task['attempt_id'] ?? null, + 'version' => 2, 'outcome' => $outcome, 'reason' => $reason, 'tail' => $tail, + 'workflow_task_id' => is_array($decision) ? ($decision['workflow_task_id'] ?? null) : null, + ], $outcome === null ? 'warning' : 'info'); + } + + /** + * Server #1181: the tail a workflow task completion returned for its continuation_tail request. + * + * @param array $task + */ + private function applyWorkflowCompletionTail(array $task, int $afterSequence, mixed $completion): void + { + if (!is_array($completion)) { + return; + } + // An older Server ignores the request and records the old boundary, as for an omitted tail. + $this->applyContinuationTail($task, $afterSequence, $completion['continuation_tail'] ?? null, missingIsOmitted: true); + if (array_key_exists('run_status', $completion) && !in_array($completion['run_status'], ['running', 'waiting'], true)) { + $this->forgetCachedRun($task); + } + } + + /** + * The contract's "Tail rules": append a tail only when it continues the cache exactly, keep + * the old boundary for an omitted tail, and evict otherwise. Returns what happened. + * + * @param array $task + */ + private function applyContinuationTail(array $task, int $afterSequence, mixed $tail, bool $missingIsOmitted): string + { + $workflowId = (string) ($task['workflow_id'] ?? ''); + $runId = (string) ($task['run_id'] ?? ''); + if ($workflowId === '' || $runId === '') { + return 'evicted'; + } + if ($tail === null && $missingIsOmitted) { + return 'omitted'; + } + if (is_array($tail) && ($tail['version'] ?? null) === 2 && ($tail['after_sequence'] ?? null) === $afterSequence) { + if (array_key_exists('omitted', $tail)) { + if (is_string($tail['omitted']) && $tail['omitted'] !== '' && !array_key_exists('history_events', $tail)) { + // The next sticky poll delivers the suffix after the old boundary. The leased + // activity is not speculated on: the cache does not end in its ActivityStarted. + return 'omitted'; + } + } else { + $events = $tail['history_events'] ?? null; + $last = $tail['last_sequence'] ?? null; + if (is_int($last) && is_array($events) && array_is_list($events) + && array_filter($events, static fn (mixed $event): bool => !is_array($event) || ($event !== [] && array_is_list($event))) === [] + && $this->stickyCache->appendTail($workflowId, $runId, $this->effectiveBuildId(), $afterSequence, $last, $events)) { + return 'appended'; + } + } + } + $this->forgetCachedRun($task); + $this->diagnostic('worker.activity_continuation_tail_rejected', [ + 'task_id' => $task['task_id'] ?? null, 'workflow_id' => $workflowId, 'run_id' => $runId, + 'after_sequence' => $afterSequence, + ], 'warning'); + + return 'evicted'; + } + + /** @param array $task */ + private function forgetCachedRun(array $task): void + { + $workflowId = (string) ($task['workflow_id'] ?? ''); + $runId = (string) ($task['run_id'] ?? ''); + if ($workflowId !== '' && $runId !== '') { + $this->stickyCache->forget($workflowId, $runId, $this->effectiveBuildId()); + } + } + /** @param list}> $records */ private function writeWorkflowLogs(array $records): void { @@ -3840,6 +4260,7 @@ private function executeActivityTask(array $task): void $callbackStopped = false; $callbackStarted = false; $resultComputed = false; + $this->continuationV2OutcomeUnknown = false; $heartbeatResume = $this->polledActivityHeartbeatResume ?? ActivityHeartbeatResume::unavailable(); $this->polledActivityHeartbeatResume = null; try { @@ -3927,13 +4348,48 @@ static function () use (&$callbackStopped): void { $callbackStopped = true; }, $resultComputed = true; $carried = $this->reserveWorkflowPoll($leaseOwner); $this->speculativeWorkflowLogs = []; - $continuation = $carried === null ? null : $this->speculateActivityContinuation($task, $result); + $continuation = null; + $continuationV2 = null; + if ($carried !== null) { + // Server #1181: v2 is preferred when negotiated. Its preconditions failing means the + // ordinary completion, which costs nothing extra; v1 is the fallback only without v2. + if ($this->activityContinuationV2Selected()) { + $continuationV2 = $this->speculateActivityContinuationV2($task, $result); + } else { + $continuation = $this->speculateActivityContinuation($task, $result); + } + } // Only an accepted speculation writes its lines; nothing stays behind for another task. $this->replayer->takeWorkflowLogs(); + $activityCarrier = $continuationV2 === null ? null : $this->reserveContinuationActivityPoll($leaseOwner); + /** @var array|null $completion A committed completion found by a retry answers null. */ $completion = $this->retryStorageAdmission( 'activity_complete', - function () use ($taskId, $attemptId, $leaseOwner, $result, $carried, &$continuation): array { + function () use ($task, $taskId, $attemptId, $leaseOwner, $result, $carried, $activityCarrier, &$continuation, &$continuationV2): array { try { + if ($carried !== null && $continuationV2 !== null) { + try { + $answer = $this->client->completeActivityTaskWithContinuation( + $taskId, $attemptId, $leaseOwner, $result, $carried->request, $continuationV2, $activityCarrier?->request); + $this->continuationV2OutcomeUnknown = false; + + return $answer; + } catch (ServerException $error) { + $this->continuationV2OutcomeUnknown = self::continuationV2OutcomeUnknown($error); + if ($this->continuationV2OutcomeUnknown) { + // The Server may have committed it: resend the identical request. + $activityCarrier?->uncertainCompletion(); + throw $error; + } + if ($error->status === 409 && in_array($error->reason, ['stale_attempt', 'conflicting_completion'], true)) { + // Ordinary stale-attempt or duplicate handling; never retried. + throw $error; + } + // A refusal wrote nothing, so the same carried workflow poll is safe. + $this->refuseActivityContinuationV2($task, $error); + $continuationV2 = null; + } + } if ($carried !== null && $continuation !== null) { try { return $this->client->completeActivityTaskWithContinuation( @@ -3970,10 +4426,14 @@ function () use ($taskId, $attemptId, $leaseOwner, $result, $carried, &$continua 'activity_attempt_id' => $attemptId, 'lease_owner' => $leaseOwner, ], + uncertainOutcome: fn (): bool => $this->continuationV2OutcomeUnknown, ); if ($carried !== null) { $carried->completion = $completion; } + if ($continuationV2 !== null && $completion !== null) { + $this->observeActivityContinuationV2($task, $continuationV2, $completion, $carried, $activityCarrier); + } if ($continuation !== null) { $outcome = is_array($completion['continuation'] ?? null) ? $completion['continuation'] : []; if (($outcome['outcome'] ?? null) === 'accepted') { @@ -3995,7 +4455,7 @@ function () use ($taskId, $attemptId, $leaseOwner, $result, $carried, &$continua if ($exception instanceof ServerException && $this->discardClosedActivityAttempt($task, $exception)) { return; } - if ($resultComputed && TransientFailure::is($exception, acknowledgement: true)) { + if ($resultComputed && ($this->continuationV2OutcomeUnknown || TransientFailure::is($exception, acknowledgement: true))) { // An outage outlasted publishing a computed result. It is not // an activity failure: leave the attempt to the Server, which // re-delivers it when the lease ends (a committed completion @@ -5226,7 +5686,8 @@ private function localActivityAttemptId( * run_id: string, * build_id: string, * ttl_seconds: int, - * metrics: array{hit: int, miss: int, eviction: int, forced_cold_replay: int} + * metrics: array{hit: int, miss: int, eviction: int, forced_cold_replay: int}, + * history_last_sequence?: int * }|null */ private function stickyCacheClaim(array $task): ?array diff --git a/src/Worker/StickyWorkflowCache.php b/src/Worker/StickyWorkflowCache.php index d7a5683f..b11aed09 100644 --- a/src/Worker/StickyWorkflowCache.php +++ b/src/Worker/StickyWorkflowCache.php @@ -15,7 +15,7 @@ final class StickyWorkflowCache { public const MAX_TTL_SECONDS = 3600; - /** @var array>, expires_at: float, touched_at: float}> */ + /** @var array>, expires_at: float, touched_at: float, context?: array}> */ private array $entries = []; /** @var array{hit: int, miss: int, eviction: int, forced_cold_replay: int} */ @@ -44,11 +44,15 @@ public function remember(string $workflowId, string $runId, string $buildId, arr { $now = ($this->clock)(); $key = self::key($workflowId, $runId, $buildId); + $context = $this->entries[$key]['context'] ?? null; $this->entries[$key] = [ 'history' => $durableHistory, 'expires_at' => $now + $this->ttlSeconds, 'touched_at' => $now, ]; + if ($context !== null) { + $this->entries[$key]['context'] = $context; + } $this->evictExpired($now); while (count($this->entries) > $this->capacity) { uasort($this->entries, static fn (array $left, array $right): int => $left['touched_at'] <=> $right['touched_at']); @@ -120,6 +124,83 @@ public function history( return array_merge($entry['history'], $runtimeHistory); } + /** + * @internal Activity workflow continuation v2 (Server #1181): append a history tail the + * Server returned after exactly $afterSequence. The tail must continue the cached history + * with the rule a sticky_history_suffix v1 suffix follows. Anything else evicts the entry, + * because the Server has already moved its sticky boundary past the cached one. + * + * @param list> $events + */ + public function appendTail(string $workflowId, string $runId, string $buildId, int $afterSequence, int $lastSequence, array $events): bool + { + $now = ($this->clock)(); + $this->evictExpired($now); + $key = self::key($workflowId, $runId, $buildId); + $entry = $this->entries[$key] ?? null; + if ($entry === null) { + return false; + } + $history = $entry['history']; + $cachedLast = $history === [] ? null : self::sequenceOf($history[array_key_last($history)]); + if ($cachedLast !== $afterSequence || !self::startsWithWorkflowStart($history) + || !self::continues($events, $afterSequence, $lastSequence)) { + unset($this->entries[$key]); + ++$this->metrics['eviction']; + + return false; + } + $this->entries[$key]['history'] = array_merge($history, $events); + $this->entries[$key]['touched_at'] = $now; + + return true; + } + + /** + * @internal The cached history for this run, without counting a hit or a miss. + * + * @return list>|null + */ + public function cachedHistory(string $workflowId, string $runId, string $buildId): ?array + { + $this->evictExpired(($this->clock)()); + + return $this->entries[self::key($workflowId, $runId, $buildId)]['history'] ?? null; + } + + /** + * @internal What a replay of this run needs besides its history (its workflow type and + * input), kept with the entry and evicted with it. + * + * @param array $context + */ + public function rememberContext(string $workflowId, string $runId, string $buildId, array $context): void + { + $key = self::key($workflowId, $runId, $buildId); + if (isset($this->entries[$key])) { + $this->entries[$key]['context'] = $context; + } + } + + /** + * @internal + * @return array|null + */ + public function context(string $workflowId, string $runId, string $buildId): ?array + { + return $this->entries[self::key($workflowId, $runId, $buildId)]['context'] ?? null; + } + + /** @internal Drop this run's entry, for example when the Server says the cache no longer matches. */ + public function forget(string $workflowId, string $runId, string $buildId): void + { + $key = self::key($workflowId, $runId, $buildId); + if (isset($this->entries[$key])) { + unset($this->entries[$key]); + ++$this->metrics['eviction']; + } + } + /** @param list> $suffix */ private static function continues(array $suffix, int $after, ?int $last): bool { diff --git a/tests/Integration/ActivityContinuationV2Test.php b/tests/Integration/ActivityContinuationV2Test.php new file mode 100644 index 00000000..1658cb39 --- /dev/null +++ b/tests/Integration/ActivityContinuationV2Test.php @@ -0,0 +1,298 @@ +}> */ + private array $diagnostics = []; + + protected function setUp(): void + { + if (getenv('DURABLE_WORKFLOW_CONTINUATION_V2_QUALIFICATION') !== '1') { + self::markTestSkipped('Activity workflow continuation v2 qualification is opt-in.'); + } + $url = getenv('DURABLE_WORKFLOW_RUNTIME_URL'); + if (!is_string($url) || trim($url) === '') { + self::markTestSkipped('DURABLE_WORKFLOW_RUNTIME_URL is not set.'); + } + $token = getenv('DURABLE_WORKFLOW_AUTH_TOKEN'); + $this->url = $url; + $this->token = is_string($token) && $token !== '' ? $token : 'test-token'; + $capability = (new Client($this->url, token: $this->token))->clusterInfo() + ->raw['worker_protocol']['server_capabilities']['activity_workflow_continuation'] ?? null; + if (!is_array($capability) || !in_array(2, $capability['supported_versions'] ?? [], true) + || ($capability['v2']['version'] ?? null) !== 2) { + self::markTestSkipped('The Server does not advertise activity_workflow_continuation v2.'); + } + $this->bootstrap = (string) tempnam(sys_get_temp_dir(), 'php-continuation-v2-lease-'); + file_put_contents($this->bootstrap, 'url, true) + .', token: '.var_export($this->token, true).');'); + chmod($this->bootstrap, 0600); + } + + protected function tearDown(): void + { + if ($this->bootstrap !== '' && is_file($this->bootstrap)) { + unlink($this->bootstrap); + } + } + + public function testAcceptedContinuationsCarryTheRunFromTailToTail(): void + { + $run = $this->driveRun('accept', static fn (array $request): ?array => null); + self::assertSame(21, $run['result']); + self::assertSame(3, $run['activity_completed'], 'Each activity is recorded once.'); + self::assertSame([], $run['requests']['history'], 'v2 never asks for history.'); + $decisions = $this->decisions(); + self::assertSame(['accepted', 'accepted', 'accepted'], array_column($decisions, 'outcome')); + self::assertSame(['appended', 'appended', 'appended'], array_column($decisions, 'tail')); + self::assertSame([], $run['requests']['ordinary'], 'No activity needed the ordinary completion.'); + } + + public function testAnUnknownOutcomeIsResentIdenticallyAndAnsweredFromTheReceipt(): void + { + $dropped = false; + $run = $this->driveRun('unknown', static function (array $request) use (&$dropped): ?array { + if (!$dropped && str_ends_with($request['uri'], '/continuation/complete')) { + $dropped = true; + + // The Server commits the request; its answer is lost on the way back. + return ['drop_answer' => true]; + } + + return null; + }); + self::assertTrue($dropped); + self::assertSame(21, $run['result']); + self::assertSame(3, $run['activity_completed']); + $first = array_values(array_filter($run['requests']['continuation'], + static fn (array $row): bool => $row['uri'] === $run['requests']['continuation'][0]['uri'])); + self::assertCount(2, $first); + self::assertSame($first[0]['body'], $first[1]['body'], 'The resent request is identical.'); + self::assertSame('already_completed', $first[1]['answer']['reason'] ?? null); + self::assertSame('accepted', $first[1]['answer']['continuation']['outcome'] ?? null, 'The receipt keeps the decision.'); + self::assertSame([], $run['requests']['ordinary']); + } + + public function testARefusalFallsBackToTheOrdinaryCompletion(): void + { + $refused = false; + $run = $this->driveRun('refusal', static function (array $request) use (&$refused): ?array { + if (!$refused && str_ends_with($request['uri'], '/continuation/complete')) { + $refused = true; + $request['body']['continuation']['unknown_member'] = true; + + return ['body' => $request['body']]; + } + + return null; + }); + self::assertTrue($refused); + self::assertSame(21, $run['result']); + self::assertSame(3, $run['activity_completed']); + // The refused activity completed the ordinary way with the same carried workflow poll. + $refusedRequest = $run['requests']['continuation'][0]; + $ordinary = $run['requests']['ordinary'][0] ?? null; + self::assertSame(422, $refusedRequest['status'] ?? null); + self::assertIsArray($ordinary); + self::assertSame(str_replace('/continuation/complete', '/complete', $refusedRequest['uri']), $ordinary['uri']); + self::assertSame($refusedRequest['body']['workflow_poll'], $ordinary['body']['workflow_poll']); + self::assertSame($refusedRequest['body']['result'], $ordinary['body']['result']); + self::assertTrue($ordinary['answer']['recorded'] ?? false); + $refusals = array_values(array_filter($this->diagnostics, static fn (array $row): bool => $row[0] === 'worker.activity_continuation_refused')); + self::assertSame([[422, 'invalid_continuation']], array_map(static fn (array $row): array => [$row[1]['status'], $row[1]['reason']], $refusals)); + } + + public function testASignalDeclinesTheContinuationAndTheRunStillCompletes(): void + { + $run = $this->driveRun('signal', static fn (array $request): ?array => null, signalFirstActivity: true); + self::assertSame(21, $run['result']); + self::assertSame(3, $run['activity_completed']); + $first = $this->decisions()[0]; + self::assertSame('declined', $first['outcome']); + self::assertContains($first['reason'], ['history_changed', 'pending_workflow_task']); + } + + public function testAnOverBudgetTailIsOmittedAndTheLeasedActivityCompletesTheOrdinaryWay(): void + { + $run = $this->driveRun('budget', static fn (array $request): ?array => null, bigFirstResult: true); + self::assertSame(300_014, $run['result']); + $first = $this->decisions()[0]; + self::assertSame(['accepted', 'omitted'], [$first['outcome'], $first['tail']]); + self::assertCount(1, array_filter($this->diagnostics, static fn (array $row): bool + => $row[0] === 'worker.activity_continuation_skipped' && ($row[1]['reason'] ?? null) === 'cache_tail_not_this_activity')); + self::assertNotSame([], $run['requests']['ordinary']); + } + + /** + * Start one run of three sequential activities and drive a managed Worker until it is closed. + * + * @param \Closure(array{uri: string, body: array|null}): (array|null) $intercept + * @return array{result: mixed, activity_completed: int, requests: array>>} + */ + private function driveRun(string $case, \Closure $intercept, bool $signalFirstActivity = false, bool $bigFirstResult = false): array + { + $suffix = $case.'-'.bin2hex(random_bytes(4)); + $queue = 'php-continuation-v2-'.$suffix; + $workflowId = 'php-continuation-v2-'.$suffix; + $type = 'tests.php-continuation-v2'; + $client = new Client($this->url, token: $this->token); + $worker = null; + $deadline = microtime(true) + 60; + $transport = new class($intercept, $client, $workflowId, $deadline, static function () use (&$worker): void { + $worker?->requestShutdown(); + }) implements BoundedTransport { + /** @var array>> */ + public array $requests = ['continuation' => [], 'ordinary' => [], 'history' => []]; + private readonly Psr18Transport $inner; + private float $checkedAt = 0.0; + + public function __construct(private readonly \Closure $intercept, private readonly Client $client, private readonly string $workflowId, private readonly float $deadline, + private readonly \Closure $stop) + { + $this->inner = new Psr18Transport(); + } + + public function supportsBoundedRequests(): bool + { + return $this->inner->supportsBoundedRequests(); + } + + public function send(string $method, string $uri, array $headers, ?array $body = null): ?array + { + return $this->exchange($uri, $body, fn (?array $body): ?array => $this->inner->send($method, $uri, $headers, $body)); + } + + public function sendBounded(string $method, string $uri, array $headers, ?array $body, int $timeoutSeconds): ?array + { + return $this->exchange($uri, $body, + fn (?array $body): ?array => $this->inner->sendBounded($method, $uri, $headers, $body, $timeoutSeconds)); + } + + /** @param \Closure(?array): ?array $send */ + private function exchange(string $uri, ?array $body, \Closure $send): ?array + { + if (str_ends_with($uri, '/workflow-tasks/poll')) { + $this->stopWhenClosed(); + } + $change = ($this->intercept)(['uri' => $uri, 'body' => $body]) ?? []; + $body = $change['body'] ?? $body; + $row = ['uri' => $uri, 'body' => $body]; + try { + $answer = $send($body); + } catch (TransportException $error) { + $this->record($uri, $row + ['status' => $error->status, 'answer' => $error->response]); + throw $error; + } + $this->record($uri, $row + ['answer' => $answer]); + if (($change['drop_answer'] ?? false) === true) { + throw new TransportException('The answer was lost.', transientConnectionFailure: true); + } + + return $answer; + } + + /** @param array $row */ + private function record(string $uri, array $row): void + { + if (str_ends_with($uri, '/continuation/complete')) { + $this->requests['continuation'][] = $row; + } elseif (str_ends_with($uri, '/continuation/history')) { + $this->requests['history'][] = $row; + } elseif (preg_match('~/activity-tasks/[^/]+/complete$~', $uri) === 1) { + $this->requests['ordinary'][] = $row; + } + } + + private function stopWhenClosed(): void + { + if (microtime(true) >= $this->deadline) { + ($this->stop)(); + + return; + } + if (microtime(true) - $this->checkedAt < 0.2) { + return; + } + $this->checkedAt = microtime(true); + try { + $status = strtolower((string) $this->client->describeWorkflow($this->workflowId)->status); + } catch (\Throwable) { + return; + } + if (!in_array($status, ['running', 'waiting', 'pending'], true)) { + ($this->stop)(); + } + } + }; + $worker = new Worker((new Client($this->url, token: $this->token, transport: $transport)) + ->withActivityLeaseBootstrap($this->bootstrap), $queue, + workerId: 'php-v2-'.$suffix, buildId: 'php-v2-build', + diagnosticListener: function (string $event, array $context): void { + $this->diagnostics[] = [$event, $context]; + }, + enableActivityContinuation: true); + $worker->declareSignal($type, 'note'); + $worker->registerWorkflow($type, static fn (WorkflowContext $context): mixed + => self::lengthOf($context->activity('tests.php-continuation-v2.first')) + + $context->activity('tests.php-continuation-v2.step', [7]) + + $context->activity('tests.php-continuation-v2.step', [7])); + $worker->registerActivity('tests.php-continuation-v2.first', function (ActivityContext $context) use ( + $client, $workflowId, $signalFirstActivity, $bigFirstResult, + ): int|string { + if ($signalFirstActivity) { + $client->signalWorkflow($workflowId, 'note', [1]); + } + + return $bigFirstResult ? str_repeat('x', 300_000) : 7; + }); + $worker->registerActivity('tests.php-continuation-v2.step', static fn (ActivityContext $context, int $value): int => $value); + + $client->startWorkflow($type, $workflowId, $queue); + $worker->run(0); + self::assertLessThan($deadline, microtime(true), 'The run closed before the deadline.'); + $result = $client->workflowResult($workflowId, timeoutSeconds: 5); + $runId = $client->describeWorkflow($workflowId)->runId; + $completed = 0; + foreach ($client->iterateWorkflowHistory($workflowId, (string) $runId) as $event) { + $completed += ($event['event_type'] ?? null) === 'ActivityCompleted' ? 1 : 0; + } + + return ['result' => $result, 'activity_completed' => $completed, 'requests' => $transport->requests]; + } + + private static function lengthOf(int|string $value): int + { + return is_string($value) ? strlen($value) : $value; + } + + /** @return list> */ + private function decisions(): array + { + return array_values(array_map(static fn (array $row): array => $row[1], array_filter($this->diagnostics, + static fn (array $row): bool => $row[0] === 'worker.activity_continuation' && ($row[1]['version'] ?? null) === 2))); + } +} diff --git a/tests/Integration/README.md b/tests/Integration/README.md index 16e60237..b44764bc 100644 --- a/tests/Integration/README.md +++ b/tests/Integration/README.md @@ -257,3 +257,31 @@ fixture requirement does not add an SDK runtime platform requirement. Also resol the consumer with Composer platform PHP8.1, ext-curl=false and ext-openssl=false to verify installation compatibility. Keep source component evidence separate from normally installed published-package acceptance. + +# Activity workflow continuation v2 + +`ActivityContinuationV2Test.php` drives a managed Worker with +`enableActivityContinuation` against a real native Server +(server#1181, sdk-php#500). It covers an accepted chain of continuations with +no history reads, an unknown outcome resent identically and answered from the +receipt, a refusal that falls back to the ordinary completion, a decline caused +by a signal, and an over-budget tail that is omitted. + +The cases are opt-in, and they skip unless the Server's cluster info advertises +the `v2` member of `activity_workflow_continuation`. A Server release without +v2 therefore never fails them. Use a disposable Server and its token. Do not +point the test at a shared runtime. + +```sh +export DURABLE_WORKFLOW_CONTINUATION_V2_QUALIFICATION=1 +export DURABLE_WORKFLOW_RUNTIME_URL=http://localhost:8080 +export DURABLE_WORKFLOW_AUTH_TOKEN=test-token +vendor/bin/phpunit tests/Integration/ActivityContinuationV2Test.php +``` + +Before a Server release includes v2, build the native image from an exact +Server commit with `Dockerfile.native`. Start it with `DW_RUST_EXPERIMENTAL=1`, +because a development build without a release version refuses to start +otherwise. These cases check correctness only. They are not the server#1181 +throughput benchmark. + diff --git a/tests/Support/ActivityContinuationV2Scenario.php b/tests/Support/ActivityContinuationV2Scenario.php new file mode 100644 index 00000000..a6ddb627 --- /dev/null +++ b/tests/Support/ActivityContinuationV2Scenario.php @@ -0,0 +1,152 @@ +>, continuation_versions: list, history_reads: int, ordinary_completions: int, activity_callback_count: int} */ + public static function run(): array + { + $codec = new AvroPayloadCodec(); + $caps = ['workflow_task_completion_activity_poll' => true, 'activity_completion_workflow_poll' => true, + 'activity_workflow_continuation' => ['version' => 1, + 'history_endpoint' => '/worker/activity-tasks/{taskId}/continuation/history', + 'complete_endpoint' => '/worker/activity-tasks/{taskId}/continuation/complete', + 'supported_commands' => self::COMMANDS, 'max_history_events' => 256, 'max_commands' => 16, + 'supported_versions' => [1, 2], + 'v2' => ['version' => 2, 'complete_endpoint' => '/worker/activity-tasks/{taskId}/continuation/complete', + 'supported_commands' => self::COMMANDS, 'max_commands' => 16, + 'requires_worker_capabilities' => ['sticky_execution', 'sticky_history_suffix'], + 'tail_max_events' => 64, 'tail_max_bytes' => 262144]]]; + $time = gmdate('Y-m-d\TH:i:s.000000\Z'); + $event = static fn (int $sequence, string $type, array $payload): array => ['id' => "event-{$sequence}", + 'sequence' => $sequence, 'event_type' => $type, 'payload' => $payload, 'recorded_at' => $time]; + $activity = static fn (string $execution, int $sequence, array $extra = []): array => ['sequence' => $sequence, + 'activity_execution_id' => $execution, 'activity_type' => 'golden.continuation-step', + 'activity' => ['type' => 'golden.continuation-step']] + $extra; + $started = static fn (int $sequence, string $execution, int $activitySequence, string $attempt): array + => $event($sequence, 'ActivityStarted', $activity($execution, $activitySequence, ['activity_attempt_id' => $attempt])); + $completed = static fn (int $sequence, string $execution, int $activitySequence, string $attempt): array + => $event($sequence, 'ActivityCompleted', $activity($execution, $activitySequence, + ['activity_attempt_id' => $attempt, 'result' => $codec->envelope(7), 'payload_codec' => 'avro'])); + $lease = static fn (string $taskId, string $execution, string $attempt): array => ['leased' => true, 'answer' => [ + 'task' => ['task_id' => $taskId, 'activity_attempt_id' => $attempt, 'activity_execution_id' => $execution, + 'attempt_number' => 1, 'lease_owner' => 'corpus-worker', 'activity_type' => 'golden.continuation-step', + 'payload_codec' => 'avro', 'workflow_id' => 'workflow', 'run_id' => 'run'], + 'poll_status' => 'leased', 'protocol_version' => '1.20', 'server_capabilities' => $caps, 'server_time' => $time]]; + $accepted = static fn (string $taskId, string $attempt, string $runStatus, array $tail, array $poll): array => [ + 'task_id' => $taskId, 'activity_attempt_id' => $attempt, 'outcome' => 'completed', 'recorded' => true, + 'reason' => null, 'next_task_id' => 'next', + 'continuation' => ['version' => 2, 'outcome' => 'accepted', 'workflow_task_id' => 'next', 'workflow_task_attempt' => 1, + 'completion' => ['task_id' => 'next', 'run_id' => 'run', 'run_status' => $runStatus, 'workflow_task_attempt' => 1, + 'outcome' => 'completed', 'recorded' => true, 'reason' => null, 'created_task_ids' => []]], + 'continuation_tail' => $tail, 'activity_poll' => $poll]; + + $polls = 0; + $continuations = []; + $historyReads = $ordinary = 0; + $transport = new FakeTransport(handler: static function (string $method, string $uri, array $headers, ?array $body) use ( + $caps, $time, $event, $started, $completed, $lease, $accepted, $codec, &$polls, &$continuations, &$historyReads, &$ordinary, + ): array { + if (str_ends_with($uri, '/workflow-tasks/poll')) { + return ++$polls > 1 ? ['task' => null, 'poll_status' => 'empty'] : ['task' => ['task_id' => 'first', + 'workflow_task_attempt' => 1, 'lease_owner' => 'corpus-worker', 'workflow_id' => 'workflow', 'run_id' => 'run', + 'workflow_type' => 'golden.activity-continuation-v2', 'payload_codec' => 'avro', + 'arguments' => $codec->envelope([]), 'sticky_replay_mode' => 'cold_replay', 'history_after_sequence' => 0, + 'history_last_sequence' => 1, 'history_events' => [$event(1, 'WorkflowStarted', [])], + 'lease_expires_at' => gmdate('Y-m-d\TH:i:s.000000\Z', time() + 30)], + 'poll_status' => 'leased', 'protocol_version' => '1.20', 'server_capabilities' => $caps, 'server_time' => $time]; + } + if (str_ends_with($uri, '/workflow-tasks/first/complete')) { + if (($body['continuation_tail'] ?? null) !== ['version' => 2]) { + throw new RuntimeException('The workflow task completion must ask for the v2 tail.'); + } + + return ['task_id' => 'first', 'run_id' => 'run', 'run_status' => 'waiting', 'workflow_task_attempt' => 1, + 'outcome' => 'completed', 'recorded' => true, 'reason' => null, 'created_task_ids' => ['step-1'], + 'continuation_tail' => ['version' => 2, 'after_sequence' => 1, 'last_sequence' => 3, 'history_events' => [ + $event(2, 'ActivityScheduled', ['sequence' => 1, 'activity_execution_id' => 'a1', + 'activity_type' => 'golden.continuation-step', 'activity' => ['type' => 'golden.continuation-step']]), + $started(3, 'a1', 1, 'attempt-1')]], + 'activity_poll' => $lease('step-1', 'a1', 'attempt-1')]; + } + if (preg_match('~/activity-tasks/(step-\d)/continuation/complete$~', $uri, $match) === 1) { + $continuations[] = $body['continuation'] ?? null; + + return $match[1] === 'step-1' + ? $accepted('step-1', 'attempt-1', 'waiting', ['version' => 2, 'after_sequence' => 3, 'last_sequence' => 6, + 'history_events' => [$completed(4, 'a1', 1, 'attempt-1'), $event(5, 'ActivityScheduled', + ['sequence' => 2, 'activity_execution_id' => 'a2', 'activity_type' => 'golden.continuation-step', + 'activity' => ['type' => 'golden.continuation-step']]), $started(6, 'a2', 2, 'attempt-2')]], + $lease('step-2', 'a2', 'attempt-2')) + : $accepted('step-2', 'attempt-2', 'completed', ['version' => 2, 'after_sequence' => 6, 'last_sequence' => 8, + 'history_events' => [$completed(7, 'a2', 2, 'attempt-2'), $event(8, 'WorkflowCompleted', [])]], + ['leased' => false]); + } + if (str_ends_with($uri, '/continuation/history')) { + ++$historyReads; + + return ['continuation' => ['version' => 1, 'eligible' => false, 'reason' => 'pending_workflow_task']]; + } + if (preg_match('~/activity-tasks/(step-\d)/complete$~', $uri, $match) === 1) { + ++$ordinary; + + return ['task_id' => $match[1], 'outcome' => 'completed', 'recorded' => true, 'reason' => null]; + } + if (str_ends_with($uri, '/heartbeat')) { + return ['task_id' => 'first', 'workflow_task_attempt' => 1, 'lease_owner' => 'corpus-worker', 'renewed' => true]; + } + if (str_ends_with($uri, '/poll')) { + return ['task' => null, 'poll_status' => 'empty']; + } + throw new RuntimeException("Unexpected continuation scenario request {$method} {$uri}"); + }); + $calls = 0; + $worker = new Worker(new Client('https://replay.invalid', transport: $transport, codec: $codec), 'corpus-queue', + workerId: 'corpus-worker', buildId: 'corpus-build', enableActivityContinuation: true); + $worker->registerWorkflow('golden.activity-continuation-v2', static fn (WorkflowContext $context): int + => $context->activity('golden.continuation-step') + $context->activity('golden.continuation-step')); + $worker->registerActivity('golden.continuation-step', static function (ActivityContext $context) use (&$calls): int { + ++$calls; + + return 7; + }); + // Registration is what learns the Server's sticky_history_suffix capability. + (new \ReflectionProperty($worker, 'stickyHistorySuffixSupported'))->setValue($worker, true); + $worker->tick(0); + $last = $continuations[array_key_last($continuations)] ?? null; + $commands = is_array($last) && is_array($last['commands'] ?? null) ? $last['commands'] : []; + + return [ + 'commands' => array_map(static function (array $command) use ($codec): array { + if (isset($command['result']) && is_array($command['result'])) { + $command['result'] = $codec->decodeEnvelope($command['result']); + } + + return $command; + }, $commands), + 'continuation_versions' => array_map(static fn (mixed $continuation): mixed + => is_array($continuation) ? ($continuation['version'] ?? null) : null, $continuations), + 'history_reads' => $historyReads, + 'ordinary_completions' => $ordinary, + 'activity_callback_count' => $calls, + ]; + } +} diff --git a/tests/Support/ReplayRegressionFixture.php b/tests/Support/ReplayRegressionFixture.php index a9f40b6f..6fc054fb 100644 --- a/tests/Support/ReplayRegressionFixture.php +++ b/tests/Support/ReplayRegressionFixture.php @@ -110,6 +110,16 @@ public static function execute(array $fixture): array return $observed['commands']; } + if ($workflowType === 'golden.activity-continuation-v2') { + $observed = ActivityContinuationV2Scenario::run(); + self::assertMatches($fixture['command_sequence'], $observed['commands'], $identity.'.command_sequence'); + $commands = $observed['commands']; + unset($observed['commands']); + self::assertMatches($fixture['expected'], ($commands[0] ?? []) + $observed, $identity.'.expected'); + + return $commands; + } + if ($workflowType === 'golden.local-activity-backoff-repeat') { return self::executeLocalBackoffRepeat($identity, $history, $fixture); } diff --git a/tests/WorkerActivityContinuationV2Test.php b/tests/WorkerActivityContinuationV2Test.php new file mode 100644 index 00000000..937c6f73 --- /dev/null +++ b/tests/WorkerActivityContinuationV2Test.php @@ -0,0 +1,772 @@ +}> */ + private array $diagnostics = []; + + public function testAWorkflowTaskTailSeedsTheCacheAndAcceptedContinuationsChainWithoutHistoryReads(): void + { + $transport = $this->transport(); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + + // The workflow task completion asks for the tail and carries an activity poll. + $completed = self::requests($transport, '/workflow-tasks/wf-1/complete'); + self::assertCount(1, $completed); + self::assertSame(['version' => 2], $completed[0]['body']['continuation_tail']); + self::assertSame(1, $completed[0]['body']['sticky_cache']['history_last_sequence']); + self::assertArrayHasKey('activity_poll', $completed[0]['body']); + + // Both activities ran in the same tick, each completed by one v2 request. + self::assertSame(['activity', 'activity'], $calls); + self::assertSame([], self::requests($transport, '/continuation/history'), 'v2 never asks for history.'); + self::assertSame([], self::requests($transport, '/act-1/complete')); + self::assertSame([], self::requests($transport, '/act-2/complete')); + + $first = self::requests($transport, '/act-1/continuation/complete'); + self::assertCount(1, $first); + $body = $first[0]['body']; + self::assertSame(['version', 'history_through_sequence', 'history_last_event_id', 'sticky_cache', 'commands'], + array_keys($body['continuation'])); + self::assertSame(2, $body['continuation']['version']); + self::assertSame(3, $body['continuation']['history_through_sequence']); + self::assertSame('event-3', $body['continuation']['history_last_event_id']); + self::assertSame(['worker_id' => 'worker', 'workflow_id' => self::WORKFLOW_ID, 'run_id' => self::RUN_ID, + 'build_id' => self::BUILD_ID, 'history_last_sequence' => 3], + array_intersect_key($body['continuation']['sticky_cache'], + array_flip(['worker_id', 'workflow_id', 'run_id', 'build_id', 'history_last_sequence']))); + self::assertSame(['schedule_activity'], array_column($body['continuation']['commands'], 'type')); + self::assertSame(7, (new AvroPayloadCodec())->decodeEnvelope($body['result'])); + self::assertSame('worker', $body['workflow_poll']['worker_id']); + self::assertSame('worker', $body['activity_poll']['worker_id']); + + $second = self::requests($transport, '/act-2/continuation/complete'); + self::assertCount(1, $second); + $body = $second[0]['body']; + self::assertSame(6, $body['continuation']['history_through_sequence'], 'Speculated from the first answer\'s tail.'); + self::assertSame('event-6', $body['continuation']['history_last_event_id']); + self::assertSame(['complete_workflow'], array_column($body['continuation']['commands'], 'type')); + self::assertSame(14, (new AvroPayloadCodec())->decodeEnvelope($body['continuation']['commands'][0]['result'])); + + // The run completed, so its cache entry is gone. + self::assertNull($this->cachedHistory($worker)); + self::assertSame(['accepted', 'accepted'], array_column($this->events('worker.activity_continuation'), 'outcome')); + self::assertSame(['appended', 'appended'], array_column($this->events('worker.activity_continuation'), 'tail')); + } + + public function testAChainThatReachedItsBoundCarriesNoActivityPollSoTheTickEnds(): void + { + $transport = $this->transport(); + $calls = []; + $worker = $this->worker($transport, $calls); + // Each lease an accepted answer carried counts toward the per-tick bound. At the bound the + // next v2 request carries no activity poll, so ordinary polling takes that activity. + $bound = (new \ReflectionClassConstant(Worker::class, 'CONTINUATION_V2_MAX_CHAINED_ACTIVITIES'))->getValue(); + self::assertSame(16, $bound); + $reserve = new \ReflectionMethod($worker, 'reserveContinuationActivityPoll'); + (new \ReflectionProperty($worker, 'workflowCompletionActivityPollSupported'))->setValue($worker, true); + self::assertNotNull($reserve->invoke($worker, 'worker')); + (new \ReflectionProperty($worker, 'continuationChainLength'))->setValue($worker, $bound); + self::assertNull($reserve->invoke($worker, 'worker'), 'At the bound the v2 request carries no activity poll.'); + self::assertNull($reserve->invoke($worker, 'someone-else')); + } + + #[DataProvider('v2Unavailable')] + public function testWithoutAUsableV2MemberTheWorkerKeepsV1AndAsksForNoTail(mixed $continuation): void + { + $transport = $this->transport(capability: $continuation); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertArrayNotHasKey('continuation_tail', self::requests($transport, '/workflow-tasks/wf-1/complete')[0]['body']); + // A malformed v2 member disables v2 only: v1 still asks for history. + self::assertCount(1, self::requests($transport, '/act-1/continuation/history')); + foreach (self::requests($transport, '/continuation/complete') as $request) { + self::assertSame(1, $request['body']['continuation']['version']); + } + } + + public static function v2Unavailable(): iterable + { + $contract = self::capability(); + $without = static function (string $field) use ($contract): array { + unset($contract['v2'][$field]); + + return $contract; + }; + $with = static function (string $field, mixed $value) use ($contract): array { + $contract['v2'][$field] = $value; + + return $contract; + }; + yield 'v1 only' => [array_diff_key($contract, ['supported_versions' => true, 'v2' => true])]; + yield 'versions without 2' => [['supported_versions' => [1]] + $contract]; + yield 'v2 without supported_versions' => [array_diff_key($contract, ['supported_versions' => true])]; + yield 'v2 member is a list' => [['v2' => [2]] + $contract]; + yield 'string version' => [$with('version', '2')]; + yield 'float version' => [$with('version', 2.0)]; + yield 'other endpoint' => [$with('complete_endpoint', '/worker/activity-tasks/{taskId}/continuation/v2')]; + yield 'unknown worker requirement' => [$with('requires_worker_capabilities', ['sticky_execution', 'sticky_history_suffix', 'future'])]; + yield 'missing requirements' => [$without('requires_worker_capabilities')]; + yield 'no commands' => [$with('supported_commands', [])]; + yield 'bad max commands' => [$with('max_commands', 0)]; + yield 'missing tail budget' => [$without('tail_max_events')]; + yield 'bad byte budget' => [$with('tail_max_bytes', '262144')]; + } + + #[DataProvider('workerConditions')] + public function testV2NeedsEveryWorkerCondition(bool $enabled, bool $suffixes, bool $interceptors, bool $v1): void + { + $transport = $this->transport(); + $calls = []; + $worker = $this->worker($transport, $calls, enabled: $enabled, suffixes: $suffixes, interceptors: $interceptors); + self::assertTrue($worker->tick(0)); + self::assertArrayNotHasKey('continuation_tail', self::requests($transport, '/workflow-tasks/wf-1/complete')[0]['body']); + self::assertCount($v1 ? 1 : 0, self::requests($transport, '/continuation/history')); + foreach (self::requests($transport, '/continuation/complete') as $request) { + self::assertSame(1, $request['body']['continuation']['version']); + } + } + + public static function workerConditions(): iterable + { + yield 'option off (the default)' => [false, true, false, false]; + yield 'no sticky history suffixes' => [true, false, false, true]; + yield 'worker interceptors' => [true, true, true, false]; + } + + #[DataProvider('unusableTails')] + public function testAWorkflowTaskTailThatCannotSeedTheCacheKeepsTheOrdinaryCompletion(\Closure $tail, bool $kept): void + { + $transport = $this->transport(workflowCompletion: static fn (array $answer): array => $tail($answer)); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertSame(['activity'], $calls); + self::assertSame([], self::requests($transport, '/continuation/complete')); + self::assertSame([], self::requests($transport, '/continuation/history'), 'v2 is negotiated, so v1 is not tried.'); + $ordinary = self::requests($transport, '/act-1/complete'); + self::assertCount(1, $ordinary); + self::assertArrayHasKey('workflow_poll', $ordinary[0]['body']); + $history = $this->cachedHistory($worker); + if ($kept) { + self::assertNotNull($history); + self::assertSame(1, $history[array_key_last($history)]['sequence'], 'The cache keeps its old boundary.'); + } else { + self::assertNull($history, 'A tail that does not continue the cache evicts it.'); + } + } + + public static function unusableTails(): iterable + { + $omit = static fn (string $reason): \Closure => static function (array $answer) use ($reason): array { + $answer['continuation_tail'] = ['version' => 2, 'after_sequence' => 1, 'omitted' => $reason]; + + return $answer; + }; + yield 'event budget' => [$omit('tail_event_budget_exceeded'), true]; + yield 'byte budget' => [$omit('tail_byte_budget_exceeded'), true]; + yield 'retried completion' => [$omit('tail_unavailable'), true]; + yield 'older Server (no tail)' => [static function (array $answer): array { + unset($answer['continuation_tail']); + + return $answer; + }, true]; + yield 'other boundary' => [static function (array $answer): array { + $answer['continuation_tail']['after_sequence'] = 2; + + return $answer; + }, false]; + yield 'gap' => [static function (array $answer): array { + array_shift($answer['continuation_tail']['history_events']); + + return $answer; + }, false]; + yield 'last sequence mismatch' => [static function (array $answer): array { + $answer['continuation_tail']['last_sequence'] = 4; + + return $answer; + }, false]; + yield 'other version' => [static function (array $answer): array { + $answer['continuation_tail']['version'] = 3; + + return $answer; + }, false]; + yield 'malformed events' => [static function (array $answer): array { + $answer['continuation_tail']['history_events'] = 'events'; + + return $answer; + }, false]; + } + + public function testATailEndingInAnotherAttemptsActivityStartedIsCompletedTheOrdinaryWay(): void + { + // A replayed carried poll can hand back a lease this completion did not create. + $transport = $this->transport(workflowCompletion: static function (array $answer): array { + $answer['continuation_tail']['history_events'][1]['payload']['activity_attempt_id'] = 'attempt-other'; + + return $answer; + }); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertSame([], self::requests($transport, '/continuation/complete')); + self::assertCount(1, self::requests($transport, '/act-1/complete')); + self::assertSame(3, self::lastSequence($this->cachedHistory($worker)), 'The tail itself continued the cache.'); + self::assertContains('cache_tail_not_this_activity', array_column($this->events('worker.activity_continuation_skipped'), 'reason')); + } + + public function testARefusedTailRequestIsSentAgainWithoutTheTailAndEvictsTheCache(): void + { + $refused = false; + $transport = $this->transport(workflowCompletion: static function (array $answer, array $body) use (&$refused): array|TransportException { + if (isset($body['continuation_tail'])) { + $refused = true; + + return new TransportException('Boundary past history.', 422, + ['reason' => 'invalid_continuation_tail', 'message' => 'invalid_continuation_tail']); + } + unset($answer['continuation_tail']); + + return $answer; + }); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertTrue($refused); + $completed = self::requests($transport, '/workflow-tasks/wf-1/complete'); + self::assertCount(2, $completed); + self::assertArrayNotHasKey('continuation_tail', $completed[1]['body']); + self::assertSame($completed[0]['body']['commands'], $completed[1]['body']['commands']); + self::assertNull($this->cachedHistory($worker)); + self::assertSame([], self::requests($transport, '/continuation/complete')); + } + + #[DataProvider('declines')] + public function testEachDeclineKeepsTheOrdinaryCompletionAndEvictsOnlyWhenTheContractSays(string $reason, bool $evicts): void + { + $transport = $this->transport(continuation: static fn (array $body): array => self::declined($reason, + $reason === 'workflow_slot_unavailable' ? null : ['leased' => false])); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertSame(['activity'], $calls, 'A decline never leases an activity.'); + self::assertCount(1, self::requests($transport, '/act-1/continuation/complete')); + self::assertSame([], self::requests($transport, '/act-1/complete'), 'The result is recorded; it is never sent again.'); + self::assertSame($evicts ? null : 3, self::lastSequence($this->cachedHistory($worker))); + $observed = $this->events('worker.activity_continuation'); + self::assertSame([['declined', $reason]], array_map(static fn (array $event): array => [$event['outcome'], $event['reason']], $observed)); + } + + public static function declines(): iterable + { + foreach (['external_payload', 'standalone_activity', 'cancellation_requested', 'parallel_group', 'pending_workflow_task', + 'pending_update', 'history_changed', 'workflow_slot_unavailable', 'no_workflow_task', 'dispatch_selected_other_task'] as $reason) { + yield $reason => [$reason, false]; + } + yield 'cache_identity_mismatch' => ['cache_identity_mismatch', true]; + yield 'run_not_open' => ['run_not_open', true]; + } + + public function testADeclinedContinuationsCarriedWorkflowTaskReplaysFromTheKeptCachePlusItsSuffix(): void + { + $transport = $this->transport(continuation: static fn (array $body): array + => self::declined('history_changed', ['leased' => true, 'answer' => self::resumedWorkflowAnswer()])); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertTrue($worker->tick(0)); + $resumed = self::requests($transport, '/workflow-tasks/wf-2/complete'); + self::assertCount(1, $resumed, 'The carried workflow task is finished the ordinary way.'); + self::assertSame(['schedule_activity'], array_column($resumed[0]['body']['commands'], 'type')); + self::assertSame([], self::requests($transport, '/workflow-tasks/wf-2/history'), 'The kept cache plus the suffix is a sticky hit.'); + } + + #[DataProvider('refusals')] + public function testEachRefusalSendsTheOrdinaryCompletionWithTheSameWorkflowPoll(int $status, string $reason, bool $disables, bool $evicts): void + { + $transport = $this->transport(continuation: static fn (array $body): TransportException + => new TransportException($reason, $status, ['reason' => $reason, 'message' => $reason])); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + $sent = self::requests($transport, '/act-1/continuation/complete'); + self::assertCount(1, $sent, 'A refusal is not retried.'); + $ordinary = self::requests($transport, '/act-1/complete'); + self::assertCount(1, $ordinary); + self::assertSame($sent[0]['body']['workflow_poll'], $ordinary[0]['body']['workflow_poll']); + self::assertSame($sent[0]['body']['result'], $ordinary[0]['body']['result']); + self::assertArrayNotHasKey('continuation', $ordinary[0]['body']); + self::assertSame($disables, self::property($worker, 'activityContinuationV2Refused')); + self::assertSame($evicts ? null : 3, self::lastSequence($this->cachedHistory($worker))); + $refusal = $this->events('worker.activity_continuation_refused'); + self::assertCount(1, $refusal); + self::assertSame([$status, $reason], [$refusal[0]['status'], $refusal[0]['reason']]); + } + + public static function refusals(): iterable + { + yield 'invalid_continuation' => [422, 'invalid_continuation', false, false]; + yield 'unsupported_continuation_version' => [422, 'unsupported_continuation_version', true, false]; + yield 'unsupported_continuation_command' => [422, 'unsupported_continuation_command', false, false]; + yield 'continuation_requires_workflow_poll' => [422, 'continuation_requires_workflow_poll', false, false]; + yield 'continuation_result_exceeds_budget' => [413, 'continuation_result_exceeds_budget', false, false]; + yield 'continuation_receipt_exceeds_budget' => [413, 'continuation_receipt_exceeds_budget', false, false]; + yield 'completion_budget_exceeded' => [409, 'completion_budget_exceeded', false, false]; + yield 'continuation_run_deadline_expired' => [409, 'continuation_run_deadline_expired', false, false]; + yield 'invalid_continuation_receipt' => [500, 'invalid_continuation_receipt', false, true]; + yield 'history_invariant_violated' => [500, 'history_invariant_violated', false, true]; + } + + public function testAServerWithoutV2KeepsV1AfterRefusingTheVersion(): void + { + $transport = $this->transport(continuation: static fn (array $body): TransportException => new TransportException( + 'unsupported_continuation_version', 422, ['reason' => 'unsupported_continuation_version'])); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertTrue(self::property($worker, 'activityContinuationV2Refused')); + $method = new \ReflectionMethod($worker, 'activityContinuationV2Selected'); + self::assertFalse($method->invoke($worker), 'The next workflow task asks for no tail and v1 is the fallback.'); + } + + public function testAStaleAttemptIsHandledAsAnOrdinaryStaleCompletion(): void + { + $transport = $this->transport(continuation: static fn (array $body): TransportException => new TransportException( + 'stale', 409, ['reason' => 'stale_attempt', 'recorded' => false, 'task_id' => 'act-1', + 'activity_attempt_id' => 'attempt-1', 'lease_owner' => 'worker', 'outcome' => 'completed', + 'attempt_status' => 'expired', 'activity_status' => 'pending', 'task_status' => 'completed', + 'can_continue' => false])); + $calls = []; + $worker = $this->worker($transport, $calls); + $worker->tick(0); + self::assertCount(1, self::requests($transport, '/act-1/continuation/complete')); + self::assertSame([], self::requests($transport, '/act-1/complete')); + self::assertSame([], self::requests($transport, '/act-1/fail')); + } + + public function testAConflictingCompletionIsNeverRetriedOrReplaced(): void + { + $transport = $this->transport(continuation: static fn (array $body): TransportException => new TransportException( + 'conflict', 409, ['reason' => 'conflicting_completion', 'recorded' => false, 'task_id' => 'act-1'])); + $calls = []; + $worker = $this->worker($transport, $calls); + try { + $worker->tick(0); + } catch (ServerException $error) { + self::assertSame('conflicting_completion', $error->reason); + } + self::assertCount(1, self::requests($transport, '/act-1/continuation/complete')); + self::assertSame([], self::requests($transport, '/act-1/complete')); + } + + #[DataProvider('unknownOutcomes')] + public function testAnUnknownOutcomeResendsTheIdenticalV2Request(\Closure $failure): void + { + $attempts = 0; + $transport = $this->transport(continuation: function (array $body, string $taskId) use ($failure, &$attempts): array|\Throwable { + if ($taskId === 'act-1' && ++$attempts === 1) { + return $failure(); + } + + return $taskId === 'act-1' ? self::acceptedFirst() : self::acceptedLast(); + }); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + $sent = self::requests($transport, '/act-1/continuation/complete'); + self::assertCount(2, $sent); + self::assertSame($sent[0]['body'], $sent[1]['body'], 'The resent request is identical.'); + self::assertSame([], self::requests($transport, '/act-1/complete'), 'An unknown outcome is never replaced by an ordinary completion.'); + self::assertSame(['activity', 'activity'], $calls, 'The activity callback is not repeated.'); + } + + public static function unknownOutcomes(): iterable + { + yield 'transport failure' => [static fn (): TransportException => new TransportException('reset', transientConnectionFailure: true)]; + yield 'bodiless 502' => [static fn (): TransportException => new TransportException('Bad gateway', 502)]; + yield 'generic 500' => [static fn (): TransportException => new TransportException('error', 500, ['reason' => 'server_error'])]; + yield 'typed 500' => [static fn (): TransportException => new TransportException('db', 500, ['reason' => 'database_error'])]; + yield 'typed 503' => [static fn (): TransportException => new TransportException('fault', 503, ['reason' => 'transition_fault'])]; + } + + public function testAnUnknownOutcomeThatOutlastsItsRetriesIsLeftToTheServer(): void + { + $transport = $this->transport(continuation: static fn (array $body): TransportException + => new TransportException('db', 500, ['reason' => 'database_error'])); + $calls = []; + $worker = $this->worker($transport, $calls); + $worker->tick(0); + self::assertGreaterThan(2, count(self::requests($transport, '/act-1/continuation/complete'))); + self::assertSame([], self::requests($transport, '/act-1/complete')); + self::assertSame([], self::requests($transport, '/act-1/fail'), 'The computed result is not an activity failure.'); + self::assertCount(1, $this->events('worker.outcome_unpublished')); + } + + public function testARetryAnsweredWithAnUnavailableTailCompletesTheLeasedActivityTheOrdinaryWay(): void + { + $attempts = 0; + $transport = $this->transport(continuation: static function (array $body, string $taskId) use (&$attempts): array|\Throwable { + if (++$attempts === 1) { + return new TransportException('reset', transientConnectionFailure: true); + } + $answer = self::acceptedFirst(); + $answer['recorded'] = false; + $answer['reason'] = 'already_completed'; + $answer['continuation_tail'] = ['version' => 2, 'after_sequence' => 3, 'omitted' => 'tail_unavailable']; + + return $answer; + }); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertSame(['activity', 'activity'], $calls, 'The carried activity still runs.'); + self::assertCount(2, self::requests($transport, '/act-1/continuation/complete')); + self::assertSame([], self::requests($transport, '/act-2/continuation/complete'), 'Nothing is speculated on it.'); + self::assertCount(1, self::requests($transport, '/act-2/complete')); + self::assertSame(3, self::lastSequence($this->cachedHistory($worker)), 'The cache keeps its old boundary.'); + } + + #[DataProvider('acceptedTails')] + public function testAnAcceptedAnswersTailMustContinueTheCacheBeforeTheLeasedActivityIsSpeculated(\Closure $edit, ?int $cached): void + { + $transport = $this->transport(continuation: static fn (array $body, string $taskId): array + => $taskId === 'act-1' ? $edit(self::acceptedFirst()) : self::acceptedLast()); + $calls = []; + $worker = $this->worker($transport, $calls); + self::assertTrue($worker->tick(0)); + self::assertSame(['activity', 'activity'], $calls); + self::assertSame([], self::requests($transport, '/act-2/continuation/complete')); + self::assertCount(1, self::requests($transport, '/act-2/complete')); + self::assertSame($cached, self::lastSequence($this->cachedHistory($worker))); + } + + public static function acceptedTails(): iterable + { + yield 'omitted' => [static function (array $answer): array { + $answer['continuation_tail'] = ['version' => 2, 'after_sequence' => 3, 'omitted' => 'tail_byte_budget_exceeded']; + + return $answer; + }, 3]; + yield 'missing' => [static function (array $answer): array { + unset($answer['continuation_tail']); + + return $answer; + }, null]; + yield 'not continuing' => [static function (array $answer): array { + $answer['continuation_tail']['after_sequence'] = 4; + + return $answer; + }, null]; + yield 'another attempt started' => [static function (array $answer): array { + $answer['continuation_tail']['history_events'][2]['payload']['activity_attempt_id'] = 'attempt-replayed'; + + return $answer; + }, 6]; + } + + public function testTheStickyCacheAppendsOnlyAnExactContinuation(): void + { + $cache = new StickyWorkflowCache(10, 60, static fn (): float => 0.0); + $history = [self::event(1, 'WorkflowStarted', ['workflow_type' => 'test.workflow'])]; + self::assertFalse($cache->appendTail('w', 'r', 'b', 1, 2, [self::event(2, 'TimerScheduled', [])]), 'No entry, nothing to continue.'); + $cache->remember('w', 'r', 'b', $history); + $cache->rememberContext('w', 'r', 'b', ['workflow_type' => 'test.workflow']); + self::assertTrue($cache->appendTail('w', 'r', 'b', 1, 2, [self::event(2, 'TimerScheduled', [])])); + self::assertSame([1, 2], array_column($cache->cachedHistory('w', 'r', 'b') ?? [], 'sequence')); + $cache->remember('w', 'r', 'b', $cache->cachedHistory('w', 'r', 'b') ?? []); + self::assertSame(['workflow_type' => 'test.workflow'], $cache->context('w', 'r', 'b'), 'Remembering history keeps the context.'); + self::assertFalse($cache->appendTail('w', 'r', 'b', 2, 4, [self::event(4, 'TimerFired', [])]), 'A gap evicts.'); + self::assertNull($cache->cachedHistory('w', 'r', 'b')); + self::assertNull($cache->context('w', 'r', 'b')); + self::assertSame(1, $cache->metrics()['eviction']); + } + + /** @param list $calls */ + private function worker(FakeTransport $transport, array &$calls, bool $enabled = true, bool $suffixes = true, + bool $interceptors = false): Worker + { + // Retry backoff advances a test clock instead of sleeping. + $now = microtime(true); + $worker = new Worker(new Client('https://continuation.invalid', transport: $transport), 'queue', workerId: 'worker', + buildId: self::BUILD_ID, clock: static function () use (&$now): float { + return $now; + }, sleeper: static function (int $microseconds) use (&$now): void { + $now += $microseconds / 1_000_000; + }, + diagnosticListener: function (string $event, array $context): void { + $this->diagnostics[] = [$event, $context]; + }, + enableActivityContinuation: $enabled, + interceptors: $interceptors ? [new \DurableWorkflow\Worker\Interceptor\PassthroughWorkerInterceptor()] : []); + // Registration is what learns the Server's sticky_history_suffix capability. + (new \ReflectionProperty($worker, 'stickyHistorySuffixSupported'))->setValue($worker, $suffixes); + $worker->registerWorkflow('test.workflow', static fn (WorkflowContext $context): int + => $context->activity('test.activity') + $context->activity('test.activity')); + $worker->registerActivity('test.activity', static function (ActivityContext $context) use (&$calls): int { + $calls[] = 'activity'; + + return 7; + }); + + return $worker; + } + + /** + * A native Server for one run: the first workflow task schedules the first activity and, when + * asked, answers its tail with the activity's ActivityStarted and carries that activity. + * + * @param (\Closure(array, array): (array|\Throwable))|null $workflowCompletion + * @param (\Closure(array, string): (array|\Throwable))|null $continuation + */ + private function transport(mixed $capability = 'default', ?\Closure $workflowCompletion = null, ?\Closure $continuation = null): FakeTransport + { + $caps = self::caps($capability === 'default' ? self::capability() : $capability); + $workflowPolls = 0; + + return new FakeTransport(handler: static function (string $method, string $uri, array $headers, ?array $body) use ( + $caps, $workflowCompletion, $continuation, &$workflowPolls, + ): ?array { + $respond = static function (array|\Throwable $answer): array { + if ($answer instanceof \Throwable) { + throw $answer; + } + + return $answer; + }; + if (str_ends_with($uri, '/workflow-tasks/poll')) { + return ++$workflowPolls === 1 ? self::firstWorkflowAnswer($caps) : ['task' => null, 'poll_status' => 'empty']; + } + if (str_ends_with($uri, '/workflow-tasks/wf-1/complete')) { + $answer = ['task_id' => 'wf-1', 'run_id' => self::RUN_ID, 'run_status' => 'waiting', 'workflow_task_attempt' => 1, + 'outcome' => 'completed', 'recorded' => true, 'reason' => null, 'created_task_ids' => ['act-1']]; + if (isset($body['continuation_tail'])) { + $answer['continuation_tail'] = ['version' => 2, 'after_sequence' => 1, 'last_sequence' => 3, + 'history_events' => [self::scheduled(2, 'execution-1', 1), self::activityStarted(3, 'execution-1', 1, 'attempt-1')]]; + } + if (isset($body['activity_poll'])) { + $answer['activity_poll'] = ['leased' => true, 'answer' => self::activityAnswer('act-1', 'execution-1', 'attempt-1', $caps)]; + } + + return $respond($workflowCompletion === null ? $answer : $workflowCompletion($answer, $body)); + } + if (preg_match('~/activity-tasks/(act-\d)/continuation/complete$~', $uri, $match) === 1) { + $answer = $continuation === null ? ($match[1] === 'act-1' ? self::acceptedFirst() : self::acceptedLast()) + : $continuation($body, $match[1]); + if (is_array($answer) && isset($answer['activity_poll']['answer'])) { + $answer['activity_poll']['answer']['server_capabilities'] = $caps; + } + + return $respond($answer); + } + if (str_ends_with($uri, '/continuation/history')) { + return ['task_id' => 'act-1', 'activity_attempt_id' => 'attempt-1', + 'continuation' => ['version' => 1, 'eligible' => false, 'reason' => 'pending_workflow_task']]; + } + if (preg_match('~/activity-tasks/(act-\d)/complete$~', $uri, $match) === 1) { + return ['task_id' => $match[1], 'outcome' => 'completed', 'recorded' => true, 'reason' => null]; + } + if (preg_match('~/workflow-tasks/(wf-\d)/complete$~', $uri, $match) === 1) { + return ['task_id' => $match[1], 'outcome' => 'completed', 'recorded' => true, 'reason' => null, + 'run_status' => 'waiting', 'created_task_ids' => []]; + } + if (preg_match('~/workflow-tasks/(wf-\d)/heartbeat$~', $uri, $match) === 1) { + return ['task_id' => $match[1], 'workflow_task_attempt' => 1, 'lease_owner' => 'worker', 'renewed' => true]; + } + if (str_ends_with($uri, '/poll')) { + return ['task' => null, 'poll_status' => 'empty']; + } + self::fail("Unexpected request {$method} {$uri}"); + }); + } + + /** @return array */ + private static function capability(): array + { + return ['version' => 1, + 'history_endpoint' => '/worker/activity-tasks/{taskId}/continuation/history', + 'complete_endpoint' => '/worker/activity-tasks/{taskId}/continuation/complete', + 'supported_commands' => self::COMMANDS, 'max_history_events' => 256, 'max_commands' => 16, + 'supported_versions' => [1, 2], + 'v2' => ['version' => 2, 'complete_endpoint' => '/worker/activity-tasks/{taskId}/continuation/complete', + 'supported_commands' => self::COMMANDS, 'max_commands' => 16, + 'requires_worker_capabilities' => ['sticky_execution', 'sticky_history_suffix'], + 'tail_max_events' => 64, 'tail_max_bytes' => 262144]]; + } + + /** @return array */ + private static function caps(mixed $capability): array + { + return ['workflow_task_completion_activity_poll' => true, 'activity_completion_workflow_poll' => true] + + ($capability === null ? [] : ['activity_workflow_continuation' => $capability]); + } + + /** @return array */ + private static function event(int $sequence, string $type, array $payload): array + { + return ['id' => 'event-'.$sequence, 'sequence' => $sequence, 'event_type' => $type, 'payload' => $payload, + 'recorded_at' => '2026-11-26T12:00:0'.min($sequence, 9).'.000000Z', 'workflow_task_id' => null, 'workflow_command_id' => null]; + } + + /** @return array */ + private static function scheduled(int $sequence, string $executionId, int $activitySequence): array + { + return self::event($sequence, 'ActivityScheduled', ['sequence' => $activitySequence, 'activity_execution_id' => $executionId, + 'activity_type' => 'test.activity', 'activity' => ['type' => 'test.activity']]); + } + + /** @return array */ + private static function activityStarted(int $sequence, string $executionId, int $activitySequence, string $attemptId): array + { + return self::event($sequence, 'ActivityStarted', ['sequence' => $activitySequence, 'activity_execution_id' => $executionId, + 'activity_type' => 'test.activity', 'activity' => ['type' => 'test.activity'], 'activity_attempt_id' => $attemptId, + 'attempt_number' => 1]); + } + + /** @return array */ + private static function activityCompleted(int $sequence, string $executionId, int $activitySequence, string $attemptId): array + { + return self::event($sequence, 'ActivityCompleted', ['sequence' => $activitySequence, 'activity_execution_id' => $executionId, + 'activity_type' => 'test.activity', 'activity' => ['type' => 'test.activity'], 'activity_attempt_id' => $attemptId, + 'attempt_number' => 1, 'result' => (new AvroPayloadCodec())->envelope(7), 'payload_codec' => 'avro']); + } + + private static function now(): DateTimeImmutable + { + return new DateTimeImmutable('now', new DateTimeZone('UTC')); + } + + /** @return array */ + private static function firstWorkflowAnswer(array $caps): array + { + return ['task' => ['task_id' => 'wf-1', 'workflow_task_attempt' => 1, 'lease_owner' => 'worker', + 'workflow_id' => self::WORKFLOW_ID, 'run_id' => self::RUN_ID, 'workflow_type' => 'test.workflow', + 'payload_codec' => 'avro', 'arguments' => (new AvroPayloadCodec())->envelope([]), + 'sticky_replay_mode' => 'cold_replay', 'history_after_sequence' => 0, 'history_last_sequence' => 1, + 'history_events' => [self::event(1, 'WorkflowStarted', ['workflow_type' => 'test.workflow'])], + 'lease_expires_at' => self::now()->modify('+30 seconds')->format('Y-m-d\TH:i:s.u\Z')], + 'poll_status' => 'leased', 'protocol_version' => '1.20', 'server_capabilities' => $caps, + 'server_time' => self::now()->format('Y-m-d\TH:i:s.u\Z')]; + } + + /** The workflow task a declined continuation's carried poll leased: a sticky suffix after the cache. */ + private static function resumedWorkflowAnswer(): array + { + return ['task' => ['task_id' => 'wf-2', 'workflow_task_attempt' => 1, 'lease_owner' => 'worker', + 'workflow_id' => self::WORKFLOW_ID, 'run_id' => self::RUN_ID, 'workflow_type' => 'test.workflow', + 'payload_codec' => 'avro', 'arguments' => (new AvroPayloadCodec())->envelope([]), + 'sticky_replay_mode' => 'sticky_hit_expected', 'history_after_sequence' => 3, 'history_last_sequence' => 4, + 'history_events' => [self::activityCompleted(4, 'execution-1', 1, 'attempt-1')], + 'lease_expires_at' => self::now()->modify('+30 seconds')->format('Y-m-d\TH:i:s.u\Z')], + 'poll_status' => 'leased', 'protocol_version' => '1.20', 'server_capabilities' => [], + 'server_time' => self::now()->format('Y-m-d\TH:i:s.u\Z')]; + } + + /** @return array */ + private static function activityAnswer(string $taskId, string $executionId, string $attemptId, array $caps = []): array + { + return ['task' => ['task_id' => $taskId, 'activity_attempt_id' => $attemptId, 'activity_execution_id' => $executionId, + 'attempt_number' => 1, 'lease_owner' => 'worker', 'activity_type' => 'test.activity', 'payload_codec' => 'avro', + 'workflow_id' => self::WORKFLOW_ID, 'run_id' => self::RUN_ID], + 'poll_status' => 'leased', 'protocol_version' => '1.20', 'server_capabilities' => $caps, + 'server_time' => self::now()->format('Y-m-d\TH:i:s.u\Z')]; + } + + /** The first activity's accepted answer: the second activity is scheduled, leased and in the tail. */ + private static function acceptedFirst(): array + { + return ['task_id' => 'act-1', 'activity_attempt_id' => 'attempt-1', 'outcome' => 'completed', 'recorded' => true, + 'reason' => null, 'next_task_id' => 'wf-2', + 'continuation' => ['version' => 2, 'outcome' => 'accepted', 'workflow_task_id' => 'wf-2', 'workflow_task_attempt' => 1, + 'completion' => ['task_id' => 'wf-2', 'run_id' => self::RUN_ID, 'run_status' => 'waiting', 'workflow_task_attempt' => 1, + 'outcome' => 'completed', 'recorded' => true, 'reason' => null, 'created_task_ids' => ['act-2']]], + 'continuation_tail' => ['version' => 2, 'after_sequence' => 3, 'last_sequence' => 6, 'history_events' => [ + self::activityCompleted(4, 'execution-1', 1, 'attempt-1'), self::scheduled(5, 'execution-2', 2), + self::activityStarted(6, 'execution-2', 2, 'attempt-2')]], + 'activity_poll' => ['leased' => true, 'answer' => self::activityAnswer('act-2', 'execution-2', 'attempt-2')]]; + } + + /** The second activity's accepted answer: the run completed. */ + private static function acceptedLast(): array + { + return ['task_id' => 'act-2', 'activity_attempt_id' => 'attempt-2', 'outcome' => 'completed', 'recorded' => true, + 'reason' => null, 'next_task_id' => 'wf-3', + 'continuation' => ['version' => 2, 'outcome' => 'accepted', 'workflow_task_id' => 'wf-3', 'workflow_task_attempt' => 1, + 'completion' => ['task_id' => 'wf-3', 'run_id' => self::RUN_ID, 'run_status' => 'completed', 'workflow_task_attempt' => 1, + 'outcome' => 'completed', 'recorded' => true, 'reason' => null, 'created_task_ids' => []]], + 'continuation_tail' => ['version' => 2, 'after_sequence' => 6, 'last_sequence' => 8, 'history_events' => [ + self::activityCompleted(7, 'execution-2', 2, 'attempt-2'), self::event(8, 'WorkflowCompleted', [])]], + 'activity_poll' => ['leased' => false]]; + } + + /** @param array|null $workflowPoll */ + private static function declined(string $reason, ?array $workflowPoll): array + { + return ['task_id' => 'act-1', 'activity_attempt_id' => 'attempt-1', 'outcome' => 'completed', 'recorded' => true, + 'reason' => null, 'next_task_id' => 'wf-2', 'continuation' => ['version' => 2, 'outcome' => 'declined', 'reason' => $reason]] + + ($workflowPoll === null ? [] : ['workflow_poll' => $workflowPoll]); + } + + /** @return list>|null */ + private function cachedHistory(Worker $worker): ?array + { + /** @var StickyWorkflowCache $cache */ + $cache = self::property($worker, 'stickyCache'); + + return $cache->cachedHistory(self::WORKFLOW_ID, self::RUN_ID, self::BUILD_ID); + } + + /** @param list>|null $history */ + private static function lastSequence(?array $history): ?int + { + return $history === null || $history === [] ? null : $history[array_key_last($history)]['sequence']; + } + + private static function property(Worker $worker, string $name): mixed + { + return (new \ReflectionProperty($worker, $name))->getValue($worker); + } + + /** @return list> */ + private function events(string $name): array + { + return array_values(array_map(static fn (array $row): array => $row[1], + array_filter($this->diagnostics, static fn (array $row): bool => $row[0] === $name))); + } + + /** @return list> */ + private static function requests(FakeTransport $transport, string $suffix): array + { + return array_values(array_filter($transport->requests, static fn (array $row): bool => str_ends_with($row['uri'], $suffix))); + } +} diff --git a/tests/fixtures/replay-regressions/activity-continuation-v2-tail-chain.json b/tests/fixtures/replay-regressions/activity-continuation-v2-tail-chain.json new file mode 100644 index 00000000..a5e2d3b0 --- /dev/null +++ b/tests/fixtures/replay-regressions/activity-continuation-v2-tail-chain.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "php-activity-continuation-v2-tail-chain", + "protocol_version": "1.20", + "bindings": [ + "php" + ], + "workflow": { + "type": "golden.activity-continuation-v2", + "input": [] + }, + "command_sequence": [ + { + "type": "complete_workflow", + "result": 14 + } + ], + "expected": { + "type": "complete_workflow", + "result": 14, + "continuation_versions": [2, 2], + "history_reads": 0, + "ordinary_completions": 0, + "activity_callback_count": 2 + } +}