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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/portal/build/workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions scripts/ci/run-replay-regression-fixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
6 changes: 5 additions & 1 deletion src/Worker/StickyWorkflowCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
113 changes: 113 additions & 0 deletions tests/Support/ContinuationEmptyTailScenario.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

declare(strict_types=1);

namespace DurableWorkflow\Tests\Support;

use DurableWorkflow\Client;
use DurableWorkflow\Codec\AvroPayloadCodec;
use DurableWorkflow\Worker;
use DurableWorkflow\Worker\WorkflowContext;
use RuntimeException;

/**
* Activity workflow continuation v2 (server#1181, sdk-php#500): a workflow task completion asks
* for the tail and the Server answers an empty one at the cached boundary, as for a completion
* that recorded no events. The cache must keep its entry, so the run's next workflow task is a
* sticky hit that replays the cache plus its suffix without an authoritative history read.
*/
final class ContinuationEmptyTailScenario
{
private const COMMANDS = ['schedule_activity', 'start_timer', 'complete_workflow', 'record_version_marker'];

/** @return array{commands: list<array<string, mixed>>, 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];
}
}
9 changes: 9 additions & 0 deletions tests/Support/ReplayRegressionFixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
38 changes: 38 additions & 0 deletions tests/WorkerActivityContinuationV2Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);

Expand Down Expand Up @@ -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<string> $calls */
private function worker(FakeTransport $transport, array &$calls, bool $enabled = true, bool $suffixes = true,
bool $interceptors = false): Worker
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
}