From c832276d98afcb9297252e70dd4ed61bc1344076 Mon Sep 17 00:00:00 2001 From: Richard McDaniel <1130888+rmcdaniel@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:40:56 +0000 Subject: [PATCH] Keep the sticky cache on empty tails and renew its TTL on appends (#500) Two follow-ups from the independent review of #501, both in StickyWorkflowCache::appendTail, both affecting only the opt-in continuation v2 path: - An empty tail at the cached boundary (last_sequence == after_sequence, no events), as a completion that records no events answers, now keeps the entry instead of evicting it. The run's next workflow task stays a sticky hit instead of a cold replay. - An appended tail now renews expires_at, as remember() does. A chain of accepted continuations longer than the TTL no longer loses its cache. Unit tests fail without each fix. A new replay corpus scenario shows an empty tail keeping the cache, so the next workflow task replays the cache plus its suffix with no authoritative history read; the base revision evicts and refetches. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- docs/portal/build/workers.md | 3 +- scripts/ci/run-replay-regression-fixture.php | 11 ++ src/Worker/StickyWorkflowCache.php | 6 +- .../Support/ContinuationEmptyTailScenario.php | 113 ++++++++++++++++++ tests/Support/ReplayRegressionFixture.php | 9 ++ tests/WorkerActivityContinuationV2Test.php | 38 ++++++ .../continuation-empty-tail-keeps-cache.json | 25 ++++ 8 files changed, 205 insertions(+), 3 deletions(-) create mode 100644 tests/Support/ContinuationEmptyTailScenario.php create mode 100644 tests/fixtures/replay-regressions/continuation-empty-tail-keeps-cache.json diff --git a/CHANGELOG.md b/CHANGELOG.md index f1cd96ae..686d6554 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,8 @@ project follows [Semantic Versioning](https://semver.org/). 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 + ordinary way. An empty tail at the boundary keeps the entry, and each + appended tail renews the entry's TTL. 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 diff --git a/docs/portal/build/workers.md b/docs/portal/build/workers.md index 4a08adb5..37c0bb4b 100644 --- a/docs/portal/build/workers.md +++ b/docs/portal/build/workers.md @@ -177,7 +177,8 @@ for history: 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. + boundary, and so does an empty tail at that boundary. Each appended tail + renews the entry's TTL, so a long chain of accepted steps keeps its cache. 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 diff --git a/scripts/ci/run-replay-regression-fixture.php b/scripts/ci/run-replay-regression-fixture.php index d5bde703..c6ee7691 100644 --- a/scripts/ci/run-replay-regression-fixture.php +++ b/scripts/ci/run-replay-regression-fixture.php @@ -661,6 +661,17 @@ private static function execute(array $fixture): void return; } + if ($workflowType === 'golden.continuation-empty-tail') { + require_once __DIR__.'/../../tests/Support/FakeTransport.php'; + require_once __DIR__.'/../../tests/Support/ContinuationEmptyTailScenario.php'; + $observed = \DurableWorkflow\Tests\Support\ContinuationEmptyTailScenario::run(); + self::assertMatches($fixture['command_sequence'], $observed['commands'], $identity.self::COMMAND_SEQUENCE_CONTEXT); + self::assertMatches($fixture['expected'], $observed['commands'][0] + ['authoritative_fetches' => $observed['authoritative_fetches'], + 'tail_requests' => $observed['tail_requests']], $identity.self::EXPECTED_CONTEXT); + + return; + } + if ($workflowType === 'golden.activity-continuation-v2') { require_once __DIR__.'/../../tests/Support/FakeTransport.php'; require_once __DIR__.'/../../tests/Support/ActivityContinuationV2Scenario.php'; diff --git a/src/Worker/StickyWorkflowCache.php b/src/Worker/StickyWorkflowCache.php index b11aed09..432705d9 100644 --- a/src/Worker/StickyWorkflowCache.php +++ b/src/Worker/StickyWorkflowCache.php @@ -143,14 +143,18 @@ public function appendTail(string $workflowId, string $runId, string $buildId, i } $history = $entry['history']; $cachedLast = $history === [] ? null : self::sequenceOf($history[array_key_last($history)]); + // An empty tail at the cached boundary (a completion that recorded no events) continues it. + $empty = $events === [] && $lastSequence === $afterSequence; if ($cachedLast !== $afterSequence || !self::startsWithWorkflowStart($history) - || !self::continues($events, $afterSequence, $lastSequence)) { + || (!$empty && !self::continues($events, $afterSequence, $lastSequence))) { unset($this->entries[$key]); ++$this->metrics['eviction']; return false; } $this->entries[$key]['history'] = array_merge($history, $events); + // The tail is the run's latest workflow task, so the entry lives as long as remember() keeps it. + $this->entries[$key]['expires_at'] = $now + $this->ttlSeconds; $this->entries[$key]['touched_at'] = $now; return true; diff --git a/tests/Support/ContinuationEmptyTailScenario.php b/tests/Support/ContinuationEmptyTailScenario.php new file mode 100644 index 00000000..61cbc6b0 --- /dev/null +++ b/tests/Support/ContinuationEmptyTailScenario.php @@ -0,0 +1,113 @@ +>, authoritative_fetches: int, tail_requests: int} */ + public static function run(): array + { + $codec = new AvroPayloadCodec(); + $caps = ['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]]]; + $event = static fn (int $sequence, string $type, array $payload): array + => ['id' => "event-{$sequence}", 'sequence' => $sequence, 'event_type' => $type, 'payload' => $payload]; + $full = [ + $event(1, 'WorkflowStarted', ['workflow_type' => 'golden.continuation-empty-tail']), + $event(2, 'ActivityScheduled', ['sequence' => 1, 'activity_type' => 'golden.first', 'activity_execution_id' => 'a1']), + $event(3, 'ActivityCompleted', ['sequence' => 1, 'activity_type' => 'golden.first', 'activity_execution_id' => 'a1', + 'result' => $codec->envelope('one')]), + ]; + $tasks = [ + ['task_id' => 'first', 'sticky_replay_mode' => 'cold_replay', 'history_after_sequence' => 0, + 'history_last_sequence' => 1, 'history_events' => array_slice($full, 0, 1)], + ['task_id' => 'second', 'sticky_replay_mode' => 'sticky_hit_expected', 'history_after_sequence' => 1, + 'history_last_sequence' => 3, 'history_events' => array_slice($full, 1)], + ]; + $polls = $fetches = $tailRequests = 0; + $completions = []; + $transport = new FakeTransport(handler: static function (string $method, string $uri, array $headers, ?array $body) use ( + $tasks, $full, $caps, &$polls, &$fetches, &$tailRequests, &$completions, + ): array { + if (str_ends_with($uri, '/workflow-tasks/poll')) { + $task = $tasks[$polls++] ?? null; + + return $task === null ? ['task' => null, 'poll_status' => 'stopped', 'reason' => 'worker_stopped'] + : ['poll_status' => 'leased', 'server_capabilities' => $caps, + 'task' => $task + ['workflow_task_attempt' => 1, 'workflow_id' => 'workflow', 'run_id' => 'run', + 'workflow_type' => 'golden.continuation-empty-tail', 'lease_owner' => 'corpus-worker', + 'payload_codec' => 'avro']]; + } + if (preg_match('#/workflow-tasks/(first|second)/history$#', $uri) === 1) { + ++$fetches; + + return ['history_events' => $full, 'next_history_page_token' => '']; + } + if (preg_match('#/workflow-tasks/(first|second)/complete$#', $uri, $match) === 1) { + $completions[$match[1]] = $body['commands'] ?? []; + $answer = ['task_id' => $match[1], 'run_id' => 'run', 'run_status' => 'waiting', 'workflow_task_attempt' => 1, + 'outcome' => 'completed', 'recorded' => true, 'reason' => null, 'created_task_ids' => []]; + if ($match[1] === 'first') { + if (($body['continuation_tail'] ?? null) !== ['version' => 2]) { + throw new RuntimeException('The first completion must ask for the v2 tail.'); + } + ++$tailRequests; + $answer['continuation_tail'] = ['version' => 2, 'after_sequence' => 1, 'last_sequence' => 1, + 'history_events' => []]; + } + + return $answer; + } + if (preg_match('#/workflow-tasks/(first|second)/heartbeat$#', $uri, $match) === 1) { + return ['task_id' => $match[1], '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 empty-tail scenario request {$method} {$uri}"); + }); + $worker = new Worker(new Client('https://replay.invalid', transport: $transport, codec: $codec), 'corpus-queue', + workerId: 'corpus-worker', buildId: 'corpus-build', clock: static fn (): float => 0.0, + enableActivityContinuation: true); + $worker->registerWorkflow('golden.continuation-empty-tail', static fn (WorkflowContext $context): mixed + => $context->activity('golden.first')); + // Registration is what learns the Server's sticky_history_suffix capability. + (new \ReflectionProperty($worker, 'stickyHistorySuffixSupported'))->setValue($worker, true); + $worker->tick(0); + $worker->tick(0); + if (!isset($completions['second'])) { + throw new RuntimeException('The empty-tail scenario did not complete its second workflow task.'); + } + + 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; + }, $completions['second']), 'authoritative_fetches' => $fetches, 'tail_requests' => $tailRequests]; + } +} diff --git a/tests/Support/ReplayRegressionFixture.php b/tests/Support/ReplayRegressionFixture.php index 6fc054fb..0b06e747 100644 --- a/tests/Support/ReplayRegressionFixture.php +++ b/tests/Support/ReplayRegressionFixture.php @@ -110,6 +110,15 @@ public static function execute(array $fixture): array return $observed['commands']; } + if ($workflowType === 'golden.continuation-empty-tail') { + $observed = ContinuationEmptyTailScenario::run(); + self::assertMatches($fixture['command_sequence'], $observed['commands'], $identity.'.command_sequence'); + self::assertMatches($fixture['expected'], $observed['commands'][0] + ['authoritative_fetches' => $observed['authoritative_fetches'], + 'tail_requests' => $observed['tail_requests']], $identity.'.expected'); + + return $observed['commands']; + } + if ($workflowType === 'golden.activity-continuation-v2') { $observed = ActivityContinuationV2Scenario::run(); self::assertMatches($fixture['command_sequence'], $observed['commands'], $identity.'.command_sequence'); diff --git a/tests/WorkerActivityContinuationV2Test.php b/tests/WorkerActivityContinuationV2Test.php index 937c6f73..47f4f636 100644 --- a/tests/WorkerActivityContinuationV2Test.php +++ b/tests/WorkerActivityContinuationV2Test.php @@ -197,6 +197,11 @@ public static function unusableTails(): iterable 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 'empty tail at the boundary' => [static function (array $answer): array { + $answer['continuation_tail'] = ['version' => 2, 'after_sequence' => 1, 'last_sequence' => 1, 'history_events' => []]; + + return $answer; + }, true]; yield 'older Server (no tail)' => [static function (array $answer): array { unset($answer['continuation_tail']); @@ -512,6 +517,39 @@ public function testTheStickyCacheAppendsOnlyAnExactContinuation(): void self::assertSame(1, $cache->metrics()['eviction']); } + public function testAnEmptyTailAtTheCachedBoundaryKeepsTheEntry(): void + { + // A completion that recorded no events answers last_sequence == after_sequence with no events. + $cache = new StickyWorkflowCache(10, 60, static fn (): float => 0.0); + $cache->remember('w', 'r', 'b', [self::event(1, 'WorkflowStarted', [])]); + self::assertTrue($cache->appendTail('w', 'r', 'b', 1, 1, [])); + self::assertSame([1], array_column($cache->cachedHistory('w', 'r', 'b') ?? [], 'sequence')); + self::assertSame(0, $cache->metrics()['eviction']); + self::assertFalse($cache->appendTail('w', 'r', 'b', 1, 2, []), 'An empty tail that claims events evicts.'); + self::assertNull($cache->cachedHistory('w', 'r', 'b')); + $cache->remember('w', 'r', 'b', [self::event(1, 'WorkflowStarted', [])]); + self::assertFalse($cache->appendTail('w', 'r', 'b', 2, 2, []), 'An empty tail at another boundary evicts.'); + self::assertNull($cache->cachedHistory('w', 'r', 'b')); + } + + public function testAnAppendedTailRenewsTheEntrysTtl(): void + { + $now = 0.0; + $cache = new StickyWorkflowCache(10, 60, static function () use (&$now): float { + return $now; + }); + $cache->remember('w', 'r', 'b', [self::event(1, 'WorkflowStarted', [])]); + $now = 50.0; + self::assertTrue($cache->appendTail('w', 'r', 'b', 1, 2, [self::event(2, 'TimerScheduled', [])])); + $now = 100.0; + self::assertSame([1, 2], array_column($cache->cachedHistory('w', 'r', 'b') ?? [], 'sequence'), + 'A chain of accepted steps keeps the entry past the TTL of its last remember().'); + $now = 50.0; + self::assertTrue($cache->appendTail('w', 'r', 'b', 2, 2, []), 'An empty tail renews it too.'); + $now = 111.0; + self::assertNull($cache->cachedHistory('w', 'r', 'b'), 'The entry still expires a TTL after its last append.'); + } + /** @param list $calls */ private function worker(FakeTransport $transport, array &$calls, bool $enabled = true, bool $suffixes = true, bool $interceptors = false): Worker diff --git a/tests/fixtures/replay-regressions/continuation-empty-tail-keeps-cache.json b/tests/fixtures/replay-regressions/continuation-empty-tail-keeps-cache.json new file mode 100644 index 00000000..88b66a1c --- /dev/null +++ b/tests/fixtures/replay-regressions/continuation-empty-tail-keeps-cache.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "php-continuation-empty-tail-keeps-cache", + "protocol_version": "1.20", + "bindings": [ + "php" + ], + "workflow": { + "type": "golden.continuation-empty-tail", + "input": [] + }, + "command_sequence": [ + { + "type": "complete_workflow", + "result": "one" + } + ], + "expected": { + "type": "complete_workflow", + "result": "one", + "authoritative_fetches": 0, + "tail_requests": 1 + } +}