diff --git a/docs/rust-server-port.md b/docs/rust-server-port.md index a7c17a3c1..00e2d9e4e 100644 --- a/docs/rust-server-port.md +++ b/docs/rust-server-port.md @@ -598,8 +598,10 @@ contract fixture before its correction. and closes `WorkflowTimedOut`, `WorkflowTerminated` or `WorkflowCancelled` with the embedded 2.29.0 `timeout_cleanup` outcome. Children opt in on their own, and describe reports the cleanup state; both are registered - native divergences. The server capability stays unadvertised until - installed cross-SDK acceptance + native divergences. Cluster info and worker responses advertise + `timeout_cleanup: {supported: true, version: 1}`, after the contract + vectors 1 to 12 passed against published native with the published PHP + SDK 3.31.0 worker (`scripts/conformance/timeout-cleanup/run.sh`) ([#1201](https://github.com/durable-workflow/server/issues/1201)). - **Signal and update names PHP cannot store.** PHP validates signal, update and query names at 1 to 256 bytes with no control characters, but diff --git a/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml b/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml index d8e5f0864..643e0fcb9 100644 --- a/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml +++ b/resources/platform-protocol-specs/worker-protocol-api.openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: durable-workflow.v2.worker-protocol-api - version: "68" + version: "69" summary: Durable Workflow worker-plane HTTP+JSON API description: > Normative OpenAPI specification for the worker-plane HTTP+JSON API: @@ -1881,6 +1881,22 @@ components: This Server can replay history marked for durable input ordering. Workers that understand the marker register condition_wait_input_order. A separate field on the workflow lease permits opening a new marked wait. + timeout_cleanup: + type: object + required: [supported, version] + properties: + supported: { type: boolean, const: true } + version: { type: integer, const: 1 } + description: > + Present when the server implements opt-in deadline-triggered timeout + cleanup version 1 (server#1201). A start with timeout_cleanup_seconds + is admitted only on a queue with a live worker that lists + timeout_cleanup and sends capability_manifest.timeout_cleanup + {supported: true, version: 1}. Cleanup is delivered through the + cooperative cancellation path with a root context cause "timeout". + A worker reports an uncaught timeout-cleanup interruption with + fail_workflow failure.interruption "timeout_cleanup"; any other + failure records failed cleanup. The run always closes timed out. condition_wait_occurrence_deadline: type: boolean description: > diff --git a/rust/src/runtime/cluster_info.rs b/rust/src/runtime/cluster_info.rs index 786e54528..72098185c 100644 --- a/rust/src/runtime/cluster_info.rs +++ b/rust/src/runtime/cluster_info.rs @@ -126,7 +126,7 @@ pub(super) fn capabilities() -> Value { for name in unpublished { map.insert(name.into(), Value::Bool(false)); } - // Server #1201: published only once native passes installed acceptance. + // Server #1201: deadline-triggered timeout cleanup, version 1. if let Some(advertised) = super::timeout_cleanup::advertisement() { map.insert(super::timeout_cleanup::CAPABILITY.into(), advertised); } @@ -233,8 +233,10 @@ mod tests { // occurrence deadline, update outcome reads, task queue pauses and // command request keys, open-run version usage, guarded build // retirement, the Prometheus text scrape, signal-with-start, - // signal-external and the task-attention workflow list filter. - assert_eq!(caps.as_object().unwrap().len(), 69); + // signal-external, the task-attention workflow list filter and + // timeout cleanup. + assert_eq!(caps.as_object().unwrap().len(), 70); + assert_eq!(caps[super::super::timeout_cleanup::CAPABILITY], json!({"supported": true, "version": 1})); assert_eq!(caps[super::super::task_attention::VISIBILITY_FILTER_CAPABILITY], json!(true)); assert_eq!(caps[super::super::external_signals::CAPABILITY], json!(true)); assert_eq!(caps[super::super::version_usage::CAPABILITY], json!(true)); diff --git a/rust/src/runtime/store.rs b/rust/src/runtime/store.rs index 3ba43a4e1..e137d53d3 100644 --- a/rust/src/runtime/store.rs +++ b/rust/src/runtime/store.rs @@ -6852,7 +6852,7 @@ fn capabilities_template() -> Value { .expect("commands") .push(json!(super::wait_timeouts::RESOLVE_CONDITION_WAIT)); value[super::continuation::CAPABILITY] = super::continuation::capability(); - // Gated off until installed acceptance (Server #1201). + // Deadline-triggered timeout cleanup, version 1 (Server #1201). if let Some(advertised) = super::timeout_cleanup::advertisement() { value[super::timeout_cleanup::CAPABILITY] = advertised; } diff --git a/rust/src/runtime/timeout_cleanup.rs b/rust/src/runtime/timeout_cleanup.rs index 52e99f67e..e8062b6ad 100644 --- a/rust/src/runtime/timeout_cleanup.rs +++ b/rust/src/runtime/timeout_cleanup.rs @@ -32,13 +32,13 @@ pub(super) const INTERRUPTION: &str = "timeout_cleanup"; /// The largest admitted allowance. pub(super) const MAX_ALLOWANCE_SECONDS: i64 = 86_400; /// Whether `/api/cluster/info` and worker responses advertise -/// `timeout_cleanup: {supported: true, version: 1}`. Off until installed -/// cross-language acceptance against native passes every #1201 item: an SDK -/// worker that advertises the capability and delivers the typed timeout -/// interruption, the shared vectors 1-12 on every backend, and a published -/// SDK/Server tuple. Admission does not depend on it: a start is refused -/// unless an eligible worker on its queue advertises support. -pub(super) const ADVERTISED: bool = false; +/// `timeout_cleanup: {supported: true, version: 1}`. On since installed +/// acceptance of the contract vectors 1-12 passed against published native +/// with the published PHP SDK 3.31.0 worker, the first SDK that advertises +/// the capability and sends the interruption marker. Admission does not +/// depend on it: a start is refused unless an eligible worker on its queue +/// advertises support. +pub(super) const ADVERTISED: bool = true; const REASON: &str = "Workflow work deadline passed; timeout cleanup requested."; @@ -113,7 +113,7 @@ pub(super) fn worker_supports(capabilities: &Value, manifest: &Value) -> bool { listed && entry["supported"] == Value::Bool(true) && entry.get("version").is_none_or(|version| version == 1) } -/// The server's advertisement, when enabled. +/// The server's advertisement. pub(super) fn advertisement() -> Option { ADVERTISED.then(|| json!({"supported": true, "version": 1})) } @@ -379,13 +379,15 @@ store_methods! { Ok(()) } - /// Describe's `timeout_cleanup` (a native addition, registered as the - /// `describe-timeout-cleanup-state` divergence: embedded describe shows - /// neither the state nor the outcome). Only an opted-in run has it: + /// Describe's `timeout_cleanup`, registered as the + /// `describe-timeout-cleanup-state` divergence: embedded Workflow 2.40.0 + /// reports only entered or finished cleanup, with the same `outcome` + /// values. Only an opted-in run has it: /// `armed` before the work deadline is noticed, - /// `cancellation_cleanup_running` with `cause: timeout` while the - /// engine's request is open, then `finished` with the recorded outcome, - /// or `not_entered` when the run closed without entering cleanup. + /// `cancellation_cleanup_running` with `cause: timeout` and the portable + /// `outcome: running` while the engine's request is open, then + /// `finished` with the recorded outcome, or `not_entered` when the run + /// closed without entering cleanup. pub(super) async fn timeout_cleanup_view(executor: &mut DB::Connection, run: &DB::Row) -> Result> { let execution = DB::optional_instant(run, "execution_deadline_at")?; let run_deadline = DB::optional_instant(run, "run_deadline_at")?; @@ -422,7 +424,7 @@ store_methods! { "work_deadline_at": entered.get("work_deadline_at").cloned().unwrap_or_else(|| json!(iso(hard - chrono::Duration::seconds(allowance)))), "cleanup_deadline_at": entered.get("cleanup_deadline_at").cloned().unwrap_or_else(|| json!(iso(hard))), "started_at": entered.get("detected_at").cloned().unwrap_or(Value::Null), - "outcome": outcome.get("outcome").cloned().unwrap_or(Value::Null), + "outcome": if state == "cancellation_cleanup_running" { json!("running") } else { outcome.get("outcome").cloned().unwrap_or(Value::Null) }, "failure_id": outcome.get("failure_id").cloned().unwrap_or(Value::Null)}))) } @@ -515,7 +517,7 @@ mod tests { assert!(!worker_supports(&json!([]), &manifest)); assert!(!worker_supports(&json!(["timeout_cleanup"]), &json!({"timeout_cleanup": {"supported": false}}))); assert!(!worker_supports(&json!(["timeout_cleanup"]), &json!({"timeout_cleanup": {"supported": true, "version": 2}}))); - assert!(advertisement().is_none(), "advertisement stays off until installed cross-language acceptance"); + assert_eq!(advertisement(), Some(json!({"supported": true, "version": 1}))); } #[test] diff --git a/rust/tests/execution/timeout_cleanup.rs b/rust/tests/execution/timeout_cleanup.rs index 9269d16db..598d88cbe 100644 --- a/rust/tests/execution/timeout_cleanup.rs +++ b/rust/tests/execution/timeout_cleanup.rs @@ -147,10 +147,11 @@ async fn admission_refuses_invalid_allowances_and_queues_without_a_capable_worke let hard = chrono::DateTime::parse_from_rfc3339(payload["execution_deadline_at"].as_str().unwrap()).unwrap(); let work = (hard - chrono::Duration::seconds(ALLOWANCE)).format("%Y-%m-%dT%H:%M:%S+00:00").to_string(); assert_eq!(payload["timeout_cleanup"], json!({"allowance_seconds": ALLOWANCE, "work_deadlines": {"execution": work}})); - // Neither surface advertises end-to-end support yet. + // Both discovery surfaces advertise version 1. + let advertised = json!({"supported": true, "version": 1}); let (_, cluster) = request(&app, "GET", "/api/cluster/info", Value::Null).await; - assert!(cluster["capabilities"].get("timeout_cleanup").is_none(), "{}", cluster["capabilities"]); - assert!(cluster["worker_protocol"]["server_capabilities"].get("timeout_cleanup").is_none()); + assert_eq!(cluster["capabilities"]["timeout_cleanup"], advertised, "{}", cluster["capabilities"]); + assert_eq!(cluster["worker_protocol"]["server_capabilities"]["timeout_cleanup"], advertised); } // Vector 11: without the option nothing changes. @@ -533,6 +534,7 @@ async fn the_earliest_hard_deadline_names_the_kind_and_describe_follows_the_stat let (_, described) = request(&app, "GET", "/api/workflows/tc-run-kind", Value::Null).await; assert_eq!(described["timeout_cleanup"]["state"], "armed", "{described}"); assert_eq!(described["timeout_cleanup"]["cause"], Value::Null); + assert_eq!(described["timeout_cleanup"]["outcome"], Value::Null); assert_eq!(described["timeout_cleanup"]["allowance_seconds"], ALLOWANCE); assert_eq!(described["timeout_cleanup"]["timeout_kind"], "run"); let first = cleanup_poll(&app, "cleanup-worker").await; @@ -548,6 +550,7 @@ async fn the_earliest_hard_deadline_names_the_kind_and_describe_follows_the_stat let (_, described) = request(&app, "GET", "/api/workflows/tc-run-kind", Value::Null).await; let view = &described["timeout_cleanup"]; assert_eq!((view["state"].as_str(), view["cause"].as_str()), (Some("cancellation_cleanup_running"), Some("timeout")), "{view}"); + assert_eq!(view["outcome"], "running", "the portable open-cleanup outcome"); assert_eq!(view["started_at"], entered["detected_at"]); assert_eq!(view["cleanup_deadline_at"], json!(iso)); let task = cleanup_poll(&app, "cleanup-worker").await; diff --git a/scripts/conformance/server-parity/native-divergences.json b/scripts/conformance/server-parity/native-divergences.json index 46d21d174..e2cd5778d 100644 --- a/scripts/conformance/server-parity/native-divergences.json +++ b/scripts/conformance/server-parity/native-divergences.json @@ -73,7 +73,7 @@ "since": "native source PR #1235 (unreleased)", "applies_to": ["timeout-cleanup"], "published_php": "Published PHP does not admit timeout cleanup on service starts, and embedded Workflow 2.29.0 run detail and describe show neither the cleanup state nor its outcome; the outcome is visible only on the terminal history event and in the timeout failure message.", - "native": "Describe and run detail of an opted-in run carry timeout_cleanup {state: armed | cancellation_cleanup_running | finished | not_entered, cause (timeout once entered), allowance_seconds, timeout_kind, work_deadline_at, cleanup_deadline_at, started_at, outcome, failure_id}. A run without the opt-in has no timeout_cleanup key.", + "native": "Describe and run detail of an opted-in run carry timeout_cleanup {state: armed | cancellation_cleanup_running | finished | not_entered, cause (timeout once entered), allowance_seconds, timeout_kind, work_deadline_at, cleanup_deadline_at, started_at, outcome (running while cleanup is open, as embedded Workflow 2.40.0 reports it, then the recorded outcome), failure_id}. A run without the opt-in has no timeout_cleanup key; an opted-in run that has not entered cleanup reports it armed or not_entered where embedded 2.40.0 omits the field.", "harness": "No recorded corpus run opts in, so no comparator changes. The all-backend execution tests cover every state and outcome." }, { diff --git a/scripts/conformance/timeout-cleanup/run.sh b/scripts/conformance/timeout-cleanup/run.sh new file mode 100755 index 000000000..38471f773 --- /dev/null +++ b/scripts/conformance/timeout-cleanup/run.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# Installed timeout-cleanup acceptance (Server #1201): the contract vectors +# 1-12 from Workflow's docs/architecture/timeout-cleanup.md against a published +# native Server image (SQLite), with workers that run a published PHP SDK +# installed from Packagist. Nothing here builds product source. +# +# SERVER_IMAGE=durableworkflow/server@sha256:... PHP_SDK_VERSION=3.31.0 \ +# scripts/conformance/timeout-cleanup/run.sh [evidence-dir] +# +# EXPECT_ADVERTISED=true|false also checks the Server's timeout_cleanup +# advertisement in /api/cluster/info. Containers, the network (unless NETWORK +# names an existing one) and the PHP image this creates are removed on exit. +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +evidence=$(mkdir -p "${1:-$PWD/timeout-cleanup-evidence}" && cd "${1:-$PWD/timeout-cleanup-evidence}" && pwd) +: "${SERVER_IMAGE:?Set SERVER_IMAGE to a published native Server image}" +: "${PHP_SDK_VERSION:?Set PHP_SDK_VERSION to a published PHP SDK version}" +php_base=${PHP_IMAGE:-php:8.3-cli-bookworm} +composer_image=${COMPOSER_IMAGE:-composer:2} +prefix=${NAME_PREFIX:-dw-timeout-cleanup-$$} +limits=(--init --cpus "${CONTAINER_CPUS:-2}" --memory "${CONTAINER_MEMORY:-2g}" --pids-limit 1024) +token=timeout-cleanup-token +user="$(id -u):$(id -g)" +work=$(mktemp -d) +php_image="$prefix-php:local" +created_network= +if [[ -n "${NETWORK:-}" ]]; then + network=$NETWORK +else + network="$prefix-net" + docker network create "$network" >/dev/null + created_network=1 +fi + +containers=() +cleanup() { + status=$? + for container in "${containers[@]}"; do + docker logs "$container" > "$evidence/$container.log" 2>&1 || true + docker rm -f "$container" >/dev/null 2>&1 || true + done + docker image rm "$php_image" >/dev/null 2>&1 || true + [[ -n "$created_network" ]] && docker network rm "$network" >/dev/null 2>&1 || true + rm -rf "$work" + exit "$status" +} +trap cleanup EXIT + +# The harness and the exact published SDK, installed without dev packages. +cp "$here/worker.php" "$here/vectors.php" "$work/" +printf '{"require":{"durable-workflow/sdk":"%s"},"config":{"platform-check":false}}\n' "$PHP_SDK_VERSION" > "$work/composer.json" +docker run --rm --name "$prefix-composer" "${limits[@]}" --user "$user" -e COMPOSER_HOME=/tmp/composer -v "$work:/app" -w /app "$composer_image" \ + install --no-dev --no-interaction --no-progress --ignore-platform-req=ext-pcntl >/dev/null +docker run --rm --name "$prefix-composer" "${limits[@]}" --user "$user" -v "$work:/app" -w /app "$composer_image" \ + show --format=json durable-workflow/sdk > "$evidence/php-sdk.json" +# Cooperative PHP workers need pcntl and posix. +printf 'FROM %s\nRUN docker-php-ext-install pcntl >/dev/null\n' "$php_base" | docker build -q -t "$php_image" - >/dev/null + +mkdir -p "$work/state" "$evidence" +: > "$evidence/results.jsonl" +: > "$evidence/observations.jsonl" +docker run -d --name "$prefix-server" "${limits[@]}" --user "$user" --network "$network" --network-alias server \ + -e DW_RUST_EXPERIMENTAL=1 -e DW_AUTH_TOKEN="$token" -e DB_DATABASE=/state/server.sqlite \ + -e DW_BIND_ADDRESS=0.0.0.0:8080 -e DW_WORKFLOW_TASK_TIMEOUT=8 \ + -v "$work/state:/state" "$SERVER_IMAGE" >/dev/null +containers+=("$prefix-server") + +php() { + docker run --rm "${limits[@]}" --user "$user" --network "$network" -e TC_TOKEN="$token" \ + -e TC_RUN_SUFFIX="$suffix" -v "$work:/harness:ro" -v "$evidence:/evidence" "$php_image" php "/harness/$1" "${@:2}" +} + +worker() { + local name=$1; shift + docker run -d --name "$prefix-$name" "${limits[@]}" --user "$user" --network "$network" -e TC_TOKEN="$token" \ + -e TC_WORKER_ID="$name" "$@" -v "$work:/harness:ro" -v "$evidence:/evidence" "$php_image" php /harness/worker.php >/dev/null + containers+=("$prefix-$name") +} + +for _ in $(seq 60); do + if docker exec "$prefix-server" bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /api/ready HTTP/1.0\r\n\r\n" >&3 && head -n1 <&3 | grep -q " 200 "' 2>/dev/null; then + break + fi + sleep 1 +done +suffix=$(date +%s) + +worker main -e TC_QUEUE=timeout-cleanup +worker plain -e TC_QUEUE=tc-plain-queue -e TC_COOPERATIVE=0 +worker doomed -e TC_QUEUE=tc-replace -e TC_DIE_ON_CLEANUP=1 +sleep 5 + +docker run --rm --name "$prefix-discovery" "${limits[@]}" --network "$network" "$php_image" php -r ' + $context = stream_context_create(["http" => ["header" => "Authorization: Bearer '"$token"'\r\nX-Namespace: default\r\nX-Durable-Workflow-Control-Plane-Version: 2\r\n"]]); + echo file_get_contents("http://server:8080/api/cluster/info", false, $context);' > "$evidence/cluster-info.json" +advertised=$(jq -c '.capabilities.timeout_cleanup // null' "$evidence/cluster-info.json") +echo "Server timeout_cleanup advertisement: $advertised" +failed=0 +if [[ -n "${EXPECT_ADVERTISED:-}" ]]; then + expected=null + [[ "$EXPECT_ADVERTISED" == true ]] && expected='{"supported":true,"version":1}' + if [[ "$advertised" == "$expected" ]] \ + && [[ "$(jq -c '.worker_protocol.server_capabilities.timeout_cleanup // null' "$evidence/cluster-info.json")" == "$expected" ]]; then + echo '{"vector":"discovery","check":"advertisement matches EXPECT_ADVERTISED","passed":true}' >> "$evidence/results.jsonl" + else + echo "{\"vector\":\"discovery\",\"check\":\"advertisement matches EXPECT_ADVERTISED\",\"passed\":false,\"detail\":$advertised}" >> "$evidence/results.jsonl" + failed=1 + fi +fi + +php vectors.php main || failed=1 + +# Vector 5: the Server is paused from before the work deadline until after +# it, so the engine first notices it late. +resume_at=$(php vectors.php late-start | tail -n1) +docker pause "$prefix-server" >/dev/null +date +%s.%N > "$evidence/paused-at" +while (( $(date +%s) < resume_at )); do sleep 1; done +docker unpause "$prefix-server" >/dev/null +date +%s.%N > "$evidence/unpaused-at" +php vectors.php late-check || failed=1 + +# Vector 6: the worker holding the cleanup turn dies; a fresh process with +# the same code finishes it once the task lease expires. +php vectors.php replace-start || failed=1 +timeout 60 docker wait "$prefix-doomed" > "$evidence/doomed-exit-code" || failed=1 +worker replacement -e TC_QUEUE=tc-replace +php vectors.php replace-check || failed=1 + +passed=$(jq -s '[.[] | select(.passed)] | length' "$evidence/results.jsonl") +total=$(jq -s 'length' "$evidence/results.jsonl") +{ + echo "### Installed timeout cleanup vectors" + echo + echo "- Server image: \`$SERVER_IMAGE\` ($(docker image inspect "$SERVER_IMAGE" --format '{{index .RepoDigests 0}}' 2>/dev/null || echo unresolved))" + echo "- PHP SDK: \`$(jq -r '.name + " " + (.versions[0] // "")' "$evidence/php-sdk.json")\` from Packagist, source \`$(jq -r '.source.reference // "unknown"' "$evidence/php-sdk.json")\`" + echo "- Server advertisement: \`$advertised\`" + echo "- Checks passed: $passed of $total" + echo + echo "| Vector | Check | Result |" + echo "| --- | --- | --- |" + jq -r '"| \(.vector) | \(.check) | \(if .passed then "pass" else "FAIL" end) |"' "$evidence/results.jsonl" +} > "$evidence/summary.md" +[[ -n "${GITHUB_STEP_SUMMARY:-}" ]] && cat "$evidence/summary.md" >> "$GITHUB_STEP_SUMMARY" +cat "$evidence/summary.md" +[[ "$failed" == 0 && "$passed" == "$total" ]] diff --git a/scripts/conformance/timeout-cleanup/vectors.php b/scripts/conformance/timeout-cleanup/vectors.php new file mode 100644 index 000000000..c39ee8864 --- /dev/null +++ b/scripts/conformance/timeout-cleanup/vectors.php @@ -0,0 +1,370 @@ + getenv('TC_SERVER_URL') ?: 'http://server:8080', 'http_errors' => false, 'timeout' => 30, + 'headers' => ['Authorization' => 'Bearer '.(getenv('TC_TOKEN') ?: 'timeout-cleanup-token'), 'X-Namespace' => 'default', + 'X-Durable-Workflow-Control-Plane-Version' => '2', 'Accept' => 'application/json']]); +$codec = new AvroPayloadCodec(); +$failures = 0; + +/** @return array{int, array} */ +function call(Http $http, string $method, string $path, ?array $body = null): array +{ + for ($attempt = 1; ; $attempt++) { + try { + $response = $http->request($method, $path, $body === null ? [] : ['json' => $body]); + break; + } catch (GuzzleHttp\Exception\ConnectException $error) { + if ($attempt >= 30) { + throw $error; + } + usleep(500_000); + } + } + $decoded = json_decode((string) $response->getBody(), true); + + return [$response->getStatusCode(), is_array($decoded) ? $decoded : []]; +} + +function start(Http $http, AvroPayloadCodec $codec, string $id, string $type, string $queue, array $options): array +{ + return call($http, 'POST', '/api/workflows', ['workflow_id' => $id, 'workflow_type' => $type, 'task_queue' => $queue, + 'input' => $codec->envelope([$id])] + $options); +} + +function history(Http $http, string $id, string $run): array +{ + [$status, $body] = call($http, 'GET', "/api/workflows/$id/runs/$run/history"); + if ($status !== 200) { + throw new RuntimeException("history $id/$run: $status ".json_encode($body)); + } + @mkdir(EVIDENCE.'/histories'); + file_put_contents(EVIDENCE."/histories/$id-$run.json", json_encode($body['events'] ?? [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + + return $body['events'] ?? []; +} + +function events(array $history, string $type): array +{ + return array_values(array_filter($history, static fn (array $event): bool => $event['event_type'] === $type)); +} + +function payload(array $history, string $type): array +{ + $found = events($history, $type); + + return count($found) === 1 ? ($found[0]['payload'] ?? []) : ['missing' => $type, 'count' => count($found)]; +} + +function describe(Http $http, string $id): array +{ + return call($http, 'GET', "/api/workflows/$id")[1]; +} + +/** Waits until the workflow's current run is closed; returns its final run id. */ +function closed(Http $http, string $id, int $seconds = 90): string +{ + $until = time() + $seconds; + do { + $described = describe($http, $id); + if (($described['status'] ?? null) !== null && !in_array($described['status'], ['pending', 'running', 'waiting'], true) + && ($described['is_terminal'] ?? true) !== false) { + return (string) $described['run_id']; + } + sleep(1); + } while (time() < $until); + throw new RuntimeException("$id did not close: ".json_encode(describe($http, $id))); +} + +function waitFor(Http $http, string $id, string $run, string $type, int $seconds = 60): array +{ + $until = time() + $seconds; + do { + $history = history($http, $id, $run); + if (events($history, $type) !== []) { + return $history; + } + sleep(1); + } while (time() < $until); + throw new RuntimeException("$id: no $type within {$seconds}s"); +} + +function at(string $value): float +{ + return (float) (new DateTimeImmutable($value))->format('U.u'); +} + +/** Deadlines in events are whole seconds; WorkflowStarted keeps milliseconds. */ +function same(string $left, string $right, float $offset = 0.0): bool +{ + return abs(at($left) + $offset - at($right)) < 1; +} + +function observations(string $id): array +{ + $file = EVIDENCE.'/observations.jsonl'; + $lines = is_file($file) ? file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : []; + + return array_values(array_filter(array_map(static fn (string $line): array => json_decode($line, true), $lines), + static fn (array $seen): bool => $seen['vector'] === $id)); +} + +function check(int|string $vector, string $what, bool $passed, mixed $detail = null): void +{ + global $failures; + $vector = (string) $vector; + if (!$passed) { + $failures++; + } + $line = ['vector' => $vector, 'check' => $what, 'passed' => $passed] + ($passed ? [] : ['detail' => $detail]); + file_put_contents(EVIDENCE.'/results.jsonl', json_encode($line, JSON_UNESCAPED_SLASHES)."\n", FILE_APPEND); + fwrite(STDOUT, ($passed ? 'PASS ' : 'FAIL ')."$vector: $what".($passed ? '' : ' '.json_encode($detail, JSON_UNESCAPED_SLASHES))."\n"); +} + +/** One WorkflowTimeoutCleanupStarted, a typed timeout delivery, and a timed-out close. */ +function timedOut(Http $http, int|string $vector, string $id, string $run, string $outcome, string $kind): array +{ + $history = history($http, $id, $run); + $entered = events($history, 'WorkflowTimeoutCleanupStarted'); + check($vector, 'cleanup entered exactly once', count($entered) === 1, count($entered)); + $started = $entered[0]['payload'] ?? []; + $closed = payload($history, 'WorkflowTimedOut'); + check($vector, "WorkflowTimedOut with outcome $outcome", ($closed['timeout_cleanup']['outcome'] ?? null) === $outcome, $closed); + check($vector, "timeout kind $kind", ($started['timeout_kind'] ?? null) === $kind && ($closed['timeout_cleanup']['timeout_kind'] ?? null) === $kind, + [$started, $closed['timeout_cleanup'] ?? null]); + check($vector, 'cleanup deadline is the hard deadline', isset($started['cleanup_deadline_at'], $started['hard_deadline_at']) + && at($started['cleanup_deadline_at']) === at($started['hard_deadline_at']) + && ($closed['timeout_cleanup']['cleanup_deadline_at'] ?? null) === $started['cleanup_deadline_at'], $started); + $described = describe($http, $id); + check($vector, 'describe failed / timed_out', ($described['status'] ?? null) === 'failed' + && ($described['closed_reason'] ?? null) === 'timed_out', array_intersect_key($described, ['status' => 1, 'closed_reason' => 1])); + $seen = observations($id); + check($vector, 'workflow code received WorkflowTimeoutCleanupRequested with cause timeout', $seen !== [] + && array_filter($seen, static fn (array $one): bool => $one['timeout_subtype'] !== true || $one['cause'] !== 'timeout') === [], $seen); + + return [$history, $started, $closed]; +} + +$main = static function () use ($http, $codec, $suffix): void { + $q = 'timeout-cleanup'; + $id = static fn (string $name): string => "tc-$name-$suffix"; + $short = ['execution_timeout_seconds' => 30, 'timeout_cleanup_seconds' => ALLOWANCE]; + + // Admission: no worker, then only an ordinary worker, refuse without writing. + foreach (['tc-no-worker' => 'no worker on the queue', 'tc-plain-queue' => 'only a non-cooperative worker'] as $queue => $why) { + [$status, $body] = start($http, $codec, $id("admission-$queue"), 'tc.return', $queue, $short); + check('admission', "refused with $why", $status === 422 && ($body['reason'] ?? null) === 'timeout_cleanup_not_supported', [$status, $body]); + check('admission', "nothing written with $why", call($http, 'GET', '/api/workflows/'.$id("admission-$queue"))[0] === 404); + } + // Vector 12, and the other field rules. + foreach ([ + 'vector-12' => [['execution_timeout_seconds' => 10, 'timeout_cleanup_seconds' => 10], 'must be shorter than the execution timeout'], + 'no hard timeout' => [['timeout_cleanup_seconds' => 10], 'needs an execution or run timeout'], + 'zero' => [['execution_timeout_seconds' => 100, 'timeout_cleanup_seconds' => 0], 'at least 1'], + 'above 86400' => [['execution_timeout_seconds' => 100000, 'timeout_cleanup_seconds' => 86401], 'not be greater than 86400'], + ] as $name => [$options, $message]) { + [$status, $body] = start($http, $codec, $id('v12'), 'tc.return', $q, $options); + $errors = implode(' ', $body['errors']['timeout_cleanup_seconds'] ?? []); + check($name === 'vector-12' ? '12' : 'admission', "refused: $name", $status === 422 && str_contains($errors, $message), [$status, $body]); + } + + $runs = []; + foreach ([ + '1' => ['tc.return', $short], '1-rethrow' => ['tc.rethrow', $short], '2' => ['tc.fail', $short], + '3' => ['tc.linger', $short], '4-terminate' => ['tc.linger', $short], '4-cancel' => ['tc.linger', $short], + '7' => ['tc.continue', ['execution_timeout_seconds' => 50, 'timeout_cleanup_seconds' => ALLOWANCE]], + '8' => ['tc.continue', ['run_timeout_seconds' => 30, 'timeout_cleanup_seconds' => ALLOWANCE]], + '9' => ['tc.return', ['execution_timeout_seconds' => 90, 'run_timeout_seconds' => 30, 'timeout_cleanup_seconds' => ALLOWANCE]], + '10' => ['tc.linger', $short], + '11' => ['tc.plain', ['execution_timeout_seconds' => 10]], + ] as $vector => [$type, $options]) { + [$status, $body] = start($http, $codec, $id("v$vector"), $type, $q, $options); + check($vector, 'admitted', $status === 201, [$status, $body]); + $runs[$vector] = ['id' => $id("v$vector"), 'run' => (string) ($body['run_id'] ?? '')]; + $started = payload(history($http, $runs[$vector]['id'], $runs[$vector]['run']), 'WorkflowStarted'); + $runs[$vector]['started'] = $started; + } + + // Immutable admission: the allowance and work deadline in WorkflowStarted. + $w1 = $runs['1']['started']; + check('1', 'WorkflowStarted records allowance and work deadline = hard - allowance', + ($w1['timeout_cleanup']['allowance_seconds'] ?? null) === ALLOWANCE + && same($w1['timeout_cleanup']['work_deadlines']['execution'] ?? 'now', $w1['execution_deadline_at'] ?? 'now', ALLOWANCE), $w1); + check('11', 'no opt-in: WorkflowStarted has no timeout_cleanup', !array_key_exists('timeout_cleanup', $runs['11']['started']), $runs['11']['started']); + + // Vector 10: a user's cooperative request before the work deadline owns cleanup. + sleep(3); + [$status, $accepted] = call($http, 'POST', "/api/workflows/{$runs['10']['id']}/runs/{$runs['10']['run']}/request-cancellation", + ['reason' => 'user', 'cleanup_timeout_seconds' => 120]); + check('10', 'cooperative request accepted, cleanup deadline capped at the hard deadline', $status === 202 + && abs(at($accepted['cancellation_request']['cleanup_deadline_at'] ?? 'now') - at($runs['10']['started']['execution_deadline_at'])) < 1, + [$status, $accepted]); + + // Vector 4: preempt cleanup once it is running. + foreach (['4-terminate' => 'terminate', '4-cancel' => 'cancel'] as $vector => $verb) { + $run = $runs[$vector]; + waitFor($http, $run['id'], $run['run'], 'WorkflowTimeoutCleanupStarted'); + $until = time() + 20; + while (observations($run['id']) === [] && time() < $until) { + sleep(1); + } + [$status, $body] = call($http, 'POST', "/api/workflows/{$run['id']}/$verb", ['reason' => 'operator']); + check($vector, "$verb accepted during cleanup", $status === 200, [$status, $body]); + } + + foreach ($runs as $vector => $run) { + $runs[$vector]['final'] = closed($http, $run['id']); + } + + foreach (['1' => 'completed', '1-rethrow' => 'completed'] as $vector => $outcome) { + [$history, $started, $closed] = timedOut($http, $vector, $runs[$vector]['id'], $runs[$vector]['final'], $outcome, 'execution'); + check($vector, 'work deadline = hard deadline - allowance', + abs(at($started['hard_deadline_at']) - at($started['work_deadline_at']) - ALLOWANCE) < 0.001, $started); + check($vector, 'no business result: run output discarded', events($history, 'WorkflowCompleted') === []); + } + [$history, , $closed] = timedOut($http, '2', $runs['2']['id'], $runs['2']['final'], 'failed', 'execution'); + check('2', 'failed outcome links failure_id', is_string($closed['timeout_cleanup']['failure_id'] ?? null), $closed); + check('2', 'failure_category stays timeout', ($closed['failure_category'] ?? null) === 'timeout', $closed); + check('2', 'message says cleanup failed plainly', str_contains((string) ($closed['message'] ?? ''), 'Timeout cleanup failed.'), $closed); + + [$history, , $closed] = timedOut($http, '3', $runs['3']['id'], $runs['3']['final'], 'expired', 'execution'); + $types = array_column($history, 'event_type'); + $close = array_search('WorkflowTimedOut', $types, true); + $opened = count(events($history, 'TimerScheduled')); + $settled = count(array_filter(array_slice($types, 0, (int) $close), static fn (string $type): bool => in_array($type, ['TimerFired', 'TimerCancelled'], true))); + check('3', 'open timers settled before WorkflowTimedOut', $close !== false && $opened > 0 && $settled === $opened, array_slice($types, -8)); + + foreach (['4-terminate' => 'WorkflowTerminated', '4-cancel' => 'WorkflowCancelled'] as $vector => $event) { + $history = history($http, $runs[$vector]['id'], $runs[$vector]['final']); + $closed = payload($history, $event); + check($vector, "$event with outcome preempted", ($closed['timeout_cleanup']['outcome'] ?? null) === 'preempted', $closed); + check($vector, 'no WorkflowTimedOut', events($history, 'WorkflowTimedOut') === []); + } + + // Vectors 7 and 8: continue-as-new inherits the allowance and the execution clock. + foreach (['7' => 'execution', '8' => 'run'] as $vector => $kind) { + $run = $runs[$vector]; + check($vector, 'continued as new', $run['final'] !== $run['run'], $run); + [$history, $started] = timedOut($http, $vector, $run['id'], $run['final'], 'completed', $kind); + $successor = payload($history, 'WorkflowStarted'); + check($vector, 'successor keeps the allowance', ($successor['timeout_cleanup']['allowance_seconds'] ?? null) === ALLOWANCE, $successor); + if ($kind === 'execution') { + check($vector, 'successor keeps the original execution work deadline and hard cap', + ($successor['timeout_cleanup']['work_deadlines']['execution'] ?? null) === $run['started']['timeout_cleanup']['work_deadlines']['execution'] + && same($started['hard_deadline_at'], $run['started']['execution_deadline_at']), [$run['started'], $successor, $started]); + } else { + $original = at($run['started']['timeout_cleanup']['work_deadlines']['run']); + $next = at($successor['timeout_cleanup']['work_deadlines']['run'] ?? 'now'); + check($vector, 'successor run work deadline = its own run deadline - allowance, later than the original', + $next > $original && abs(at($started['hard_deadline_at']) - $next - ALLOWANCE) < 0.001, [$run['started'], $successor, $started]); + } + } + + // Vector 9: the earlier run deadline names the kind and ends cleanup. + [, $started] = timedOut($http, '9', $runs['9']['id'], $runs['9']['final'], 'completed', 'run'); + check('9', 'cleanup deadline = min(run, execution) hard deadline = run deadline', + same($started['cleanup_deadline_at'], $runs['9']['started']['run_deadline_at']), [$started, $runs['9']['started']]); + + // Vector 10: no timeout cleanup; the hard timeout wins and preempts the user's cleanup. + $history = history($http, $runs['10']['id'], $runs['10']['final']); + $closed = payload($history, 'WorkflowTimedOut'); + check('10', 'no WorkflowTimeoutCleanupStarted', events($history, 'WorkflowTimeoutCleanupStarted') === []); + check('10', 'WorkflowTimedOut records the cooperative cleanup preempted', ($closed['cancellation_cleanup']['outcome'] ?? null) === 'preempted' + && ($closed['cancellation_cleanup']['request_id'] ?? null) === ($accepted['cancellation_request']['request_id'] ?? false) + && !array_key_exists('timeout_cleanup', $closed), $closed); + $seen = observations($runs['10']['id']); + check('10', 'workflow code saw an ordinary cancellation (no timeout cause)', count($seen) === 1 && $seen[0]['cause'] !== 'timeout' + && $seen[0]['timeout_subtype'] === false, $seen); + + // Vector 11: unchanged hard timeout. + $history = history($http, $runs['11']['id'], $runs['11']['final']); + $closed = payload($history, 'WorkflowTimedOut'); + check('11', 'WorkflowTimedOut without timeout_cleanup', !isset($closed['missing']) && !array_key_exists('timeout_cleanup', $closed), $closed); + check('11', 'no cleanup entered and no workflow code after the deadline', events($history, 'WorkflowTimeoutCleanupStarted') === [] + && observations($runs['11']['id']) === []); +}; + +$state = static fn (string $name): string => EVIDENCE."/$name.json"; + +$lateStart = static function () use ($http, $codec, $suffix, $state): void { + $id = "tc-v5-$suffix"; + // A wide window: run.sh pauses the Server as soon as this returns, which + // can take a while on a loaded Docker host, and resumes it at the printed + // absolute time, five seconds after the work deadline. The first claim or + // idle wake after that notices the deadline late. + [$status, $body] = start($http, $codec, $id, 'tc.return', 'timeout-cleanup', ['execution_timeout_seconds' => 180, 'timeout_cleanup_seconds' => 90]); + check('5', 'admitted', $status === 201, [$status, $body]); + $started = payload(history($http, $id, (string) $body['run_id']), 'WorkflowStarted'); + file_put_contents($state('late'), json_encode(['id' => $id, 'run' => $body['run_id'], 'started' => $started])); + fwrite(STDOUT, (string) ((int) ceil(at($started['timeout_cleanup']['work_deadlines']['execution'])) + 5)."\n"); +}; + +$lateCheck = static function () use ($http, $state): void { + $late = json_decode(file_get_contents($state('late')), true); + $resumed = (float) trim((string) file_get_contents(EVIDENCE.'/unpaused-at')); + $paused = (float) trim((string) file_get_contents(EVIDENCE.'/paused-at')); + $work = at($late['started']['timeout_cleanup']['work_deadlines']['execution']); + check('5', 'harness paused the Server before the work deadline', $paused < $work, ['paused' => $paused, 'work' => $work]); + $final = closed($http, $late['id']); + [, $started] = timedOut($http, '5', $late['id'], $final, 'completed', 'execution'); + check('5', 'detected late (after the Server resumed, past the work deadline)', at($started['detected_at']) >= $resumed - 1 + && at($started['detected_at']) > $work + 3, ['detected_at' => $started['detected_at'], 'work' => $work, 'resumed' => $resumed]); + check('5', 'work deadline and cleanup deadline come from admission, not detection', + at($started['work_deadline_at']) === $work && same($started['cleanup_deadline_at'], $late['started']['execution_deadline_at']), $started); +}; + +$replaceStart = static function () use ($http, $codec, $suffix, $state): void { + $id = "tc-v6-$suffix"; + [$status, $body] = start($http, $codec, $id, 'tc.return', 'tc-replace', ['execution_timeout_seconds' => 80, 'timeout_cleanup_seconds' => 40]); + check('6', 'admitted', $status === 201, [$status, $body]); + $history = waitFor($http, $id, (string) $body['run_id'], 'WorkflowTimeoutCleanupStarted'); + file_put_contents($state('replace'), json_encode(['id' => $id, 'run' => $body['run_id'], + 'entered' => payload($history, 'WorkflowTimeoutCleanupStarted')])); +}; + +$replaceCheck = static function () use ($http, $state): void { + $replace = json_decode(file_get_contents($state('replace')), true); + $final = closed($http, $replace['id']); + [$history, $started] = timedOut($http, '6', $replace['id'], $final, 'completed', 'execution'); + check('6', 'replacement kept the original entry and deadlines', $started === $replace['entered'], [$started, $replace['entered']]); + $seen = observations($replace['id']); + check('6', 'only the replacement process ran cleanup to the activity', count($seen) === 1, $seen); +}; + +try { + match ($phase) { + 'main' => $main(), + 'late-start' => $lateStart(), + 'late-check' => $lateCheck(), + 'replace-start' => $replaceStart(), + 'replace-check' => $replaceCheck(), + }; +} catch (Throwable $error) { + check($phase, 'phase completed', false, $error->getMessage()); +} +exit($failures === 0 ? 0 : 1); diff --git a/scripts/conformance/timeout-cleanup/worker.php b/scripts/conformance/timeout-cleanup/worker.php new file mode 100644 index 000000000..ed7ffd79b --- /dev/null +++ b/scripts/conformance/timeout-cleanup/worker.php @@ -0,0 +1,117 @@ + gmdate('c'), 'event' => $event] + $context, JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR)."\n"); + }, + enableCooperativeCancellation: $cooperative); + +// What workflow code saw when the interruption reached it, written by an +// activity so the driver reads it without decoding payloads. +$observe = static function (WorkflowContext $context, string $vector, WorkflowCancelled $error) use ($dieOnCleanup): void { + if ($dieOnCleanup) { + posix_kill(posix_getpid(), SIGKILL); + } + $context->cancellationShield(static fn () => $context->activity('tc.observe', [[ + 'vector' => $vector, + 'class' => $error::class, + 'timeout_subtype' => $error instanceof WorkflowTimeoutCleanupRequested, + 'cause' => $error->context?->cause, + 'request_id' => $error->requestId, + ]])); +}; + +// Work waits on a long timer, so only the engine's deadline interrupts it. +$cleanup = static function (string $mode) use ($observe): Closure { + return static function (WorkflowContext $context, string $vector = '') use ($mode, $observe): string { + try { + $context->sleep(3600); + + return 'work finished'; + } catch (WorkflowCancelled $error) { + $observe($context, $vector, $error); + switch ($mode) { + case 'return': + return 'compensated'; + case 'rethrow': + throw $error; + case 'fail': + throw new RuntimeException('compensation failed'); + default: + // Cleanup that outlives every deadline. + $context->cancellationShield(static fn () => $context->sleep(3600)); + + return 'lingered'; + } + } + }; +}; + +foreach (['return', 'rethrow', 'fail', 'linger'] as $mode) { + $worker->registerWorkflow("tc.$mode", $cleanup($mode)); +} + +// Continues as new once, then waits for cleanup and compensates. +$worker->registerWorkflow('tc.continue', static function (WorkflowContext $context, string $vector = '', int $generation = 0) use ($observe): string { + if ($generation === 0) { + $context->sleep(2); + $context->continueAsNew([$vector, 1]); + } + try { + $context->sleep(3600); + + return 'work finished'; + } catch (WorkflowCancelled $error) { + $observe($context, $vector, $error); + + return 'compensated'; + } +}); + +// No opt-in: workflow code must never run again after the hard deadline. +$worker->registerWorkflow('tc.plain', static function (WorkflowContext $context, string $vector = '') use ($observe): string { + try { + $context->sleep(3600); + } catch (WorkflowCancelled $error) { + $observe($context, $vector, $error); + } + + return 'unexpected'; +}); + +$worker->registerActivity('tc.observe', static function (ActivityContext $context, array $seen) use ($observations): bool { + file_put_contents($observations, json_encode($seen + ['at' => gmdate('c')], JSON_THROW_ON_ERROR)."\n", FILE_APPEND | LOCK_EX); + + return true; +}); + +$worker->run(pollTimeoutSeconds: 2); diff --git a/tests/Fixtures/ServerParity/cluster-capabilities.json b/tests/Fixtures/ServerParity/cluster-capabilities.json index f8e399b5f..174c24374 100644 --- a/tests/Fixtures/ServerParity/cluster-capabilities.json +++ b/tests/Fixtures/ServerParity/cluster-capabilities.json @@ -484,6 +484,13 @@ "capabilities.worker_build_retirement": { "value": true, "reason": "Native serves guarded worker build and task queue retirement (Server #519): GET /api/deployments/{name}/retirement and /api/task-queues/{queue}/retirement inventory live dependencies, and POST .../retire records the terminal drained intent only when the same inventory, taken inside the serialized transition, is complete and empty. Published PHP has no such routes; its drain keeps the same emergency-stop contract on both servers." + }, + "capabilities.timeout_cleanup": { + "value": { + "supported": true, + "version": 1 + }, + "reason": "Native serves opt-in deadline-triggered timeout cleanup version 1 (Server #1201): a start or child start with timeout_cleanup_seconds reserves the end of its hard timeout, is admitted only on a queue with a live worker that advertises timeout_cleanup, enters cleanup once at the work deadline through the cooperative cancellation path with cause timeout, and closes WorkflowTimedOut with a timeout_cleanup outcome. Published PHP does not admit timeout cleanup on service starts." } } }