diff --git a/conformance/README.md b/conformance/README.md index f42e278..1272b2c 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -9,6 +9,11 @@ a maintainer from the published-artifact command below. Every result is recorded as a concise update on the active release issue so the tuple, outcome, and next action remain visible without creating a second backlog. +The [replay-safe clock v1 case](replay-clock/README.md) replays one history +and `WorkerReplayClock` carrier through the published Python, Rust and PHP +SDKs and the embedded worker-protocol runner, and requires identical clock +values at entry and after each durable step. + The [payload protection v1 contract](payload-protection/README.md) fixes the portable protected envelope, authenticated context, deterministic vector and initial supported/refused call-site inventory. It is an implementation contract, diff --git a/conformance/replay-clock/README.md b/conformance/replay-clock/README.md new file mode 100644 index 0000000..474dc7b --- /dev/null +++ b/conformance/replay-clock/README.md @@ -0,0 +1,55 @@ +# Replay-safe clock, version 1 + +Cross-SDK conformance case for [issue 215](https://github.com/durable-workflow/.github/issues/215). +The same history and the same `replay_clock` carrier +([`WorkerReplayClock` v1](https://github.com/durable-workflow/server/blob/main/docs/contracts/worker-replay-entry-clock.md)) +must give the same replay-safe clock values in every binding: + +| Binding | Clock | Replayed through | +| --- | --- | --- | +| `python` | `ctx.replay_now()` | `durable_workflow.testing.replay_history(..., replay_clock_entry=...)` | +| `rust` | `WorkflowContext::replay_now()` | `WorkflowHistory::replay_clock(...)` and `WorkflowEnvironment::replay` | +| `php` | `WorkflowContext::replayNow()` | `WorkerTestHarness::runWorkflow(..., task: ['replay_clock' => ...])` | +| `embedded-worker-protocol` | `Workflow::now()` | `WorkflowFiberRunner::forClass(..., replayClock: ...)` | + +[`vectors-v1.json`](vectors-v1.json) holds: +- one history: a start, an activity and a two-second timer. Its `WorkflowStarted` insertion time is deliberately not the run's start; +- the cases; +- the expected observations. + +Each runner reads the clock at entry (twice), after the activity and after the timer. Times are UTC RFC 3339 with six fractional digits and `Z`, and an unavailable read is `null`. The orchestrator computes the elapsed time between the two durable steps from the observed values. + +## What the cases pin + +- `carrier`: entry is the carrier's `started_at`, the run's canonical start. It is not the history insertion time. Repeated reads before a durable step return the same value. The activity and timer reads are their recorded times, so the elapsed time between the two steps is measurable. +- `no-carrier`: without a carrier the service SDKs report entry as unavailable, and later reads are unchanged. +- `carrier-for-another-run`, `carrier-low-precision` and `redrive-source-on-ordinary-history`: an unproved carrier is absent. No other time is substituted. The Rust offline history builder refuses the other-run and low-precision carriers up front, and the runner replays those cases without a carrier. It accepts the redrive-source carrier, and replay then leaves entry unavailable because the history is ordinary. + +The embedded engine itself reads the run row's `started_at`, the column the carrier is built from, so its entry already equals the carrier. + +`embedded-worker-protocol` covers `WorkflowFiberRunner`, the runner used by external PHP workers. It keeps the `WorkflowStarted` time when it gets no proved carrier, so runs already in flight replay unchanged. `binding_overrides` records that difference. + +Applications should still order emitted events by stream offset, outbox sequence or a workflow-local counter rather than by timestamp. + +## Run against published releases + +The runner needs Python 3, Docker and network access to PyPI, crates.io and Packagist. Set each exact version from the selected release tuple: + +```sh +DW_PYTHON_SDK_VERSION=... DW_RUST_SDK_VERSION=... \ +DW_PHP_SDK_VERSION=... DW_WORKFLOW_PHP_VERSION=... \ +python3 conformance/replay-clock/run.py --result-dir "$(mktemp -d)" +``` + +What the runner does: +- It installs each release in a throwaway `--rm` container (`python:3.12-slim`, `rust:1.86.0`, `composer:2.10.3` and `php:8.4-cli`), runs the binding's runner and compares every observation with the vectors. +- `--only` selects bindings. +- Each container runs as the invoking user with a private `--tmpfs /scratch` (mode 0700) holding the venv, source copy, `HOME`, `CARGO_HOME` and `COMPOSER_HOME`. +- A binding whose container fails or prints no observations is recorded as `"status": "error"` and the other bindings still run. +- The exit status is non-zero on any mismatch or error. +- `--container-prefix` sets the container name prefix (default `dw-replay-clock`). +- `requires_newer_than` names the last release of each binding that lacks the entry carrier. A release at or below it is reported as `not_yet_released` rather than failed, so the case can be run before the release round. + +`--source BINDING=PATH` replays an unreleased checkout. It is for development only and is not release evidence. + +Record the exact tuple and the per-binding `result.json` statuses on the release issue. `not_yet_released` is not a pass. diff --git a/conformance/replay-clock/php/composer.json.in b/conformance/replay-clock/php/composer.json.in new file mode 100644 index 0000000..90d9188 --- /dev/null +++ b/conformance/replay-clock/php/composer.json.in @@ -0,0 +1,12 @@ +{ + "name": "durable-workflow/replay-clock-conformance", + "description": "run.py writes composer.json from this template with the exact package constraints.", + "type": "project", + "license": "MIT", + "require": @REQUIRE@, + "repositories": @REPOSITORIES@, + "config": { + "allow-plugins": false, + "sort-packages": true + } +} diff --git a/conformance/replay-clock/php/embedded-runner.php b/conformance/replay-clock/php/embedded-runner.php new file mode 100644 index 0000000..831c19c --- /dev/null +++ b/conformance/replay-clock/php/embedded-runner.php @@ -0,0 +1,81 @@ + */ + public function handle(): array + { + $read = static fn (): string => Workflow::now()->utc()->format('Y-m-d\TH:i:s.u\Z'); + $entry = $read(); + $repeated = $read() === $entry; + Workflow::activity(self::$activity); + $afterActivity = $read(); + Workflow::timer(self::$seconds); + + return [ + 'entry' => $entry, + 'repeated_reads_equal' => $repeated, + 'after_activity' => $afterActivity, + 'after_timer' => $read(), + ]; + } +} + +$vectors = json_decode((string) file_get_contents($argv[1]), true, flags: JSON_THROW_ON_ERROR); +$spec = $vectors['workflow']; +ReplayClockConformanceWorkflow::$activity = $spec['activity_type']; +ReplayClockConformanceWorkflow::$seconds = $spec['timer_seconds']; + +$micros = static function (?string $text): ?int { + if ($text === null) { + return null; + } + $time = DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.u\Z', $text, new DateTimeZone('UTC')); + + return $time === false ? null : (int) $time->format('U') * 1_000_000 + (int) $time->format('u'); +}; + +$observations = []; +foreach ($vectors['cases'] as $case) { + $step = WorkflowFiberRunner::forClass( + ReplayClockConformanceWorkflow::class, + $spec['workflow_id'], + $spec['run_id'], + $spec['input'], + $spec['payload_codec'], + $vectors['history'], + replayClock: $case['replay_clock'] ?? null, + )->step(); + if (! $step->completed || ! is_array($step->result)) { + fwrite(STDERR, "{$case['id']}: the runner did not complete\n"); + exit(1); + } + $observed = $step->result; + $start = $micros($observed['after_activity']); + $end = $micros($observed['after_timer']); + $observed['elapsed_microseconds'] = $start === null || $end === null ? null : $end - $start; + $observations[$case['id']] = $observed; +} + +echo json_encode([ + 'binding' => 'embedded-worker-protocol', + 'sdk_version' => InstalledVersions::getPrettyVersion('durable-workflow/workflow'), + 'observations' => $observations, +], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), "\n"; diff --git a/conformance/replay-clock/php/sdk-runner.php b/conformance/replay-clock/php/sdk-runner.php new file mode 100644 index 0000000..8839747 --- /dev/null +++ b/conformance/replay-clock/php/sdk-runner.php @@ -0,0 +1,83 @@ +replayNow()->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d\TH:i:s.u\Z'); + } catch (ReplayClockUnavailable) { + return null; + } +}; + +$client = new Client('http://durable-workflow.test', transport: new InMemoryTransport()); +$worker = (new Worker($client, 'conformance', workerId: 'conformance')) + ->registerWorkflow($spec['type'], static function (WorkflowContext $context) use ($read, $spec): array { + $entry = $read($context); + $repeated = $read($context) === $entry; + $context->activity($spec['activity_type'], []); + $afterActivity = $read($context); + $context->sleep($spec['timer_seconds']); + + return [ + 'entry' => $entry, + 'repeated_reads_equal' => $repeated, + 'after_activity' => $afterActivity, + 'after_timer' => $read($context), + ]; + }); +$harness = new WorkerTestHarness($worker); +$codec = new AvroPayloadCodec(); + +$micros = static function (?string $text): ?int { + if ($text === null) { + return null; + } + $time = DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.u\Z', $text, new DateTimeZone('UTC')); + + return $time === false ? null : (int) $time->format('U') * 1_000_000 + (int) $time->format('u'); +}; + +$observations = []; +foreach ($vectors['cases'] as $case) { + $task = ['workflow_id' => $spec['workflow_id'], 'run_id' => $spec['run_id']]; + if (array_key_exists('replay_clock', $case)) { + $task['replay_clock'] = $case['replay_clock']; + } + $result = $harness->runWorkflow($spec['type'], $spec['input'], $vectors['history'], $task); + $last = $result->commands[array_key_last($result->commands)] ?? null; + if (count($result->commands) !== 1 || ($last['type'] ?? null) !== 'complete_workflow') { + fwrite(STDERR, "{$case['id']}: expected one complete_workflow command\n"); + exit(1); + } + $observed = $codec->decodeEnvelope($last['result']); + $start = $micros($observed['after_activity']); + $end = $micros($observed['after_timer']); + $observed['elapsed_microseconds'] = $start === null || $end === null ? null : $end - $start; + $observations[$case['id']] = $observed; +} + +echo json_encode([ + 'binding' => 'php', + 'sdk_version' => InstalledVersions::getPrettyVersion('durable-workflow/sdk'), + 'observations' => $observations, +], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), "\n"; diff --git a/conformance/replay-clock/python/runner.py b/conformance/replay-clock/python/runner.py new file mode 100644 index 0000000..959ef8b --- /dev/null +++ b/conformance/replay-clock/python/runner.py @@ -0,0 +1,83 @@ +"""Replay the shared replay-clock vectors through the installed Python SDK. + +Reads the case's vectors-v1.json (argv[1] may name it; it must resolve to +that file beside this runner's directory) and prints one JSON object mapping +each case id to its observations. Times are UTC RFC 3339 with six fractional +digits and Z; an unavailable read is null. +""" + +from __future__ import annotations + +import json +import sys +from datetime import UTC, datetime +from importlib import metadata +from pathlib import Path +from typing import Any + +from durable_workflow import ReplayClockUnavailable, workflow +from durable_workflow.testing import replay_history + +CASE_VECTORS = Path(__file__).resolve().parent.parent / "vectors-v1.json" + + +def _vectors_path(argv: list[str]) -> Path: + """Only the case's own vectors file is read; any other path is refused.""" + if len(argv) > 1 and Path(argv[1]).resolve() != CASE_VECTORS: + raise SystemExit(f"vectors must be {CASE_VECTORS}, got {argv[1]!r}") + if not CASE_VECTORS.is_file(): + raise SystemExit(f"{CASE_VECTORS} is not a regular file") + return CASE_VECTORS + + +VECTORS = json.loads(_vectors_path(sys.argv).read_text(encoding="utf-8")) +SPEC = VECTORS["workflow"] + + +def _read(ctx: Any) -> str | None: + try: + value: datetime = ctx.replay_now() + except ReplayClockUnavailable: + return None + return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +@workflow.defn(name=SPEC["type"]) +class ReplayClockConformance: + def run(self, ctx: Any): # type: ignore[no-untyped-def] + entry = _read(ctx) + repeated = _read(ctx) == entry + yield ctx.schedule_activity(SPEC["activity_type"], []) + after_activity = _read(ctx) + yield ctx.start_timer(SPEC["timer_seconds"]) + after_timer = _read(ctx) + return {"entry": entry, "repeated_reads_equal": repeated, + "after_activity": after_activity, "after_timer": after_timer} + + +def _elapsed(start: str | None, end: str | None) -> int | None: + if start is None or end is None: + return None + parse = lambda text: datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%fZ") # noqa: E731 + delta = parse(end) - parse(start) + return delta.days * 86_400_000_000 + delta.seconds * 1_000_000 + delta.microseconds + + +observations: dict[str, Any] = {} +for case in VECTORS["cases"]: + outcome = replay_history( + ReplayClockConformance, VECTORS["history"], SPEC["input"], run_id=SPEC["run_id"], + payload_codec=SPEC["payload_codec"], replay_clock_entry=case.get("replay_clock"), + ) + try: + commands = outcome.commands + if len(commands) != 1 or type(commands[0]).__name__ != "CompleteWorkflow": + raise SystemExit(f"{case['id']}: expected one CompleteWorkflow, got {commands!r}") + result = dict(commands[0].result) + finally: + outcome.close() + result["elapsed_microseconds"] = _elapsed(result["after_activity"], result["after_timer"]) + observations[case["id"]] = result + +print(json.dumps({"binding": "python", "sdk_version": metadata.version("durable-workflow"), + "observations": observations}, sort_keys=True)) diff --git a/conformance/replay-clock/run.py b/conformance/replay-clock/run.py new file mode 100644 index 0000000..2b60e06 --- /dev/null +++ b/conformance/replay-clock/run.py @@ -0,0 +1,226 @@ +"""Run the replay-clock conformance case against exact published SDK releases. + +Each binding replays the shared vectors-v1.json history with each case's +WorkerReplayClock v1 carrier and reports replay_now() at entry, after an +activity and after a timer. This script installs the selected releases in +throwaway containers, runs the thin per-binding runners and compares every +observation with the vectors. A release that predates the entry carrier is +reported as not yet released rather than failed. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +HERE = Path(__file__).resolve().parent +VECTORS = HERE / "vectors-v1.json" +BINDINGS = ("python", "rust", "php", "embedded-worker-protocol") +VERSION_ENV = { + "python": "DW_PYTHON_SDK_VERSION", + "rust": "DW_RUST_SDK_VERSION", + "php": "DW_PHP_SDK_VERSION", + "embedded-worker-protocol": "DW_WORKFLOW_PHP_VERSION", +} +_VERSION = re.compile(r"\d+\.\d+\.\d+") +# Same patched pip the published cancellation runners pin before installing. +_PIP = ("pip @ https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/" + "pip-26.2.2-py3-none-any.whl#sha256=fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70") + + +def load_vectors(path: Path = VECTORS) -> dict[str, Any]: + vectors = json.loads(path.read_text(encoding="utf-8")) + if vectors.get("schema") != "durable-workflow.replay-clock-conformance/v1": + raise SystemExit(f"{path}: unexpected schema {vectors.get('schema')!r}") + return vectors + + +def version_tuple(version: str) -> tuple[int, int, int]: + if not isinstance(version, str) or _VERSION.fullmatch(version) is None: + raise ValueError(f"exact release version required, got {version!r}") + major, minor, patch = (int(part) for part in version.split(".")) + return major, minor, patch + + +def released(vectors: dict[str, Any], binding: str, version: str) -> bool: + """Whether this exact release is newer than the last one without the carrier.""" + return version_tuple(version) > version_tuple(vectors["requires_newer_than"][binding]) + + +def expected_for(vectors: dict[str, Any], binding: str, case_id: str) -> dict[str, Any]: + case = next(case for case in vectors["cases"] if case["id"] == case_id) + override = vectors.get("binding_overrides", {}).get(binding, {}).get(case_id, {}) + return {**case["expected"], **override} + + +def compare(vectors: dict[str, Any], binding: str, observations: dict[str, Any]) -> list[str]: + """Return every mismatch between a binding's observations and the vectors.""" + mismatches: list[str] = [] + case_ids = [case["id"] for case in vectors["cases"]] + if sorted(observations) != sorted(case_ids): + mismatches.append(f"{binding}: observed cases {sorted(observations)} != {sorted(case_ids)}") + for case_id in case_ids: + observed = observations.get(case_id) + if not isinstance(observed, dict): + continue + for key, value in expected_for(vectors, binding, case_id).items(): + if observed.get(key, "") != value: + actual = observed.get(key, "") + mismatches.append(f"{binding}/{case_id}/{key}: expected {value!r}, observed {actual!r}") + return mismatches + + +# Each container gets a private tmpfs owned by the invoking user. The venv, the +# source copy, HOME and the package caches live there, never in a shared, +# world-writable directory. +SCRATCH = "/scratch" +PROJECT = "/project" +CASE_VECTORS = "/case/vectors-v1.json" + + +def _docker(name: str, image: str, mounts: list[tuple[Path, str, str]], script: str, env: dict[str, str]) -> str: + uid, gid = os.getuid(), os.getgid() + command = ["docker", "run", "--rm", "--init", "--cpus", "2", "--memory", "4g", "--name", name, + "-u", f"{uid}:{gid}", + "--tmpfs", f"{SCRATCH}:rw,exec,nosuid,nodev,size=2g,mode=0700,uid={uid},gid={gid}", + "-e", f"HOME={SCRATCH}"] + for key, value in env.items(): + command += ["-e", f"{key}={value}"] + for source, target, mode in mounts: + command += ["-v", f"{source}:{target}:{mode}"] + command += [image, "sh", "-ec", script] + result = subprocess.run(command, check=False, capture_output=True, text=True) + if result.returncode != 0: + # PHP CLI reports fatal errors on stdout, so keep the tail of both streams. + raise RuntimeError(f"{name} failed ({result.returncode}):\n{result.stdout[-2000:]}\n{result.stderr[-4000:]}") + lines = result.stdout.strip().splitlines() + return lines[-1] if lines else "" + + +def _run_python(name: str, version: str | None, source: Path | None) -> str: + case = (HERE, "/case", "ro") + install = f"{SCRATCH}/sdk" if source else f"durable-workflow=={version}" + mounts = [case] + ([(source, "/sdk", "ro")] if source else []) + # A source build writes metadata, so it builds from a private copy. + copy = (f"mkdir {SCRATCH}/sdk && tar -C /sdk --exclude=./.venv --exclude=./.git -cf - . | " + f"tar -C {SCRATCH}/sdk -xf - && " if source else "") + venv = f"{SCRATCH}/venv" + script = (f"{copy}python -m venv {venv} && {venv}/bin/pip -q install --disable-pip-version-check " + f"--no-deps --upgrade '{_PIP}' && {venv}/bin/pip -q install --no-cache-dir '{install}' && " + f"{venv}/bin/python -I /case/python/runner.py {CASE_VECTORS}") + return _docker(name, "python:3.12-slim", mounts, script, {}) + + +def _run_rust(name: str, version: str | None, source: Path | None, work: Path) -> str: + project = work / "rust" + shutil.copytree(HERE / "rust", project) + dependency = '{ path = "/sdk" }' if source else f'"={version}"' + (project / "Cargo.toml").write_text( + (project / "Cargo.toml.in").read_text(encoding="utf-8").replace("@DURABLE_WORKFLOW@", dependency), + encoding="utf-8") + mounts = [(HERE, "/case", "ro"), (project, PROJECT, "rw")] + ([(source, "/sdk", "ro")] if source else []) + script = f"cd {PROJECT} && cargo run -q --release -- {CASE_VECTORS}" + return _docker(name, "rust:1.86.0", mounts, script, + {"CARGO_HOME": f"{SCRATCH}/cargo", "DW_RUST_SDK_VERSION": version or "source"}) + + +def _run_php(name: str, binding: str, version: str | None, source: Path | None, work: Path) -> str: + package = "durable-workflow/sdk" if binding == "php" else "durable-workflow/workflow" + project = work / binding + shutil.copytree(HERE / "php", project) + repositories = [{"type": "path", "url": "/sdk", "options": {"symlink": False}}] if source else [] + (project / "composer.json").write_text( + (project / "composer.json.in").read_text(encoding="utf-8") + .replace("@REQUIRE@", json.dumps({package: "*@dev" if source else version})) + .replace("@REPOSITORIES@", json.dumps(repositories)), encoding="utf-8") + mounts = [(project, PROJECT, "rw")] + ([(source, "/sdk", "ro")] if source else []) + _docker(f"{name}-install", "composer:2.10.3", mounts, + f"cd {PROJECT} && composer install -q --no-interaction --no-dev --ignore-platform-req=ext-*", + {"COMPOSER_HOME": f"{SCRATCH}/composer"}) + runner = "sdk-runner.php" if binding == "php" else "embedded-runner.php" + return _docker(name, "php:8.4-cli", [(HERE, "/case", "ro"), (project, PROJECT, "ro")], + f"cd {PROJECT} && php {runner} {CASE_VECTORS}", {}) + + +def _run_binding(binding: str, version: str | None, source: Path | None, work: Path, + prefix: str = "dw-replay-clock") -> dict[str, Any]: + name = f"{prefix}-{binding}-{os.getpid()}" + if binding == "python": + output = _run_python(name, version, source) + elif binding == "rust": + output = _run_rust(name, version, source, work) + else: + output = _run_php(name, binding, version, source, work) + report = json.loads(output) + if not isinstance(report, dict) or not isinstance(report.get("observations"), dict): + raise ValueError(f"{binding}: runner printed no observations") + return report + + +def evaluate(vectors: dict[str, Any], binding: str, version: str | None, source: Path | None, work: Path, + prefix: str = "dw-replay-clock") -> dict[str, Any]: + """Run one binding and record its outcome; a crashed binding is an error, not an abort.""" + label = "source" if source else version + if source is None and not released(vectors, binding, version or ""): + return {"status": "not_yet_released", "version": version, + "requires_newer_than": vectors["requires_newer_than"][binding]} + try: + report = _run_binding(binding, version, source, work, prefix) + except (OSError, RuntimeError, ValueError) as error: + return {"status": "error", "version": label, "error": str(error)} + mismatches = compare(vectors, binding, report["observations"]) + return {"status": "fail" if mismatches else "pass", "version": label, + "reported_version": report.get("sdk_version"), "mismatches": mismatches, + "observations": report["observations"]} + + +def _selected(only: str, sources: dict[str, str]) -> list[tuple[str, str | None, Path | None]]: + selected = [] + for binding in [item for item in only.split(",") if item]: + if binding not in BINDINGS: + raise SystemExit(f"unknown binding {binding!r}") + source = Path(sources[binding]).resolve() if binding in sources else None + version = os.environ.get(VERSION_ENV[binding]) + if source is None and not version: + raise SystemExit(f"set {VERSION_ENV[binding]} to the exact published release, or omit {binding}") + if source is None: + try: + version_tuple(version) + except ValueError as error: + raise SystemExit(f"{VERSION_ENV[binding]}: {error}") from None + selected.append((binding, version, source)) + return selected + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--only", default=",".join(BINDINGS), help="comma-separated bindings to run") + parser.add_argument("--source", action="append", default=[], metavar="BINDING=PATH", + help="development only: replay an unreleased checkout instead of a release") + parser.add_argument("--result-dir", type=Path, help="write result.json here") + parser.add_argument("--container-prefix", default="dw-replay-clock", help="name prefix for the containers") + args = parser.parse_args(argv) + vectors = load_vectors() + sources = {binding: path for binding, path in (item.split("=", 1) for item in args.source)} + selected = _selected(args.only, sources) + with tempfile.TemporaryDirectory(prefix="dw-replay-clock-") as temporary: + results = {binding: evaluate(vectors, binding, version, source, Path(temporary), args.container_prefix) + for binding, version, source in selected} + document = json.dumps({"schema": vectors["schema"], "bindings": results}, indent=2, sort_keys=True) + if args.result_dir: + args.result_dir.mkdir(parents=True, exist_ok=True) + (args.result_dir / "result.json").write_text(document + "\n", encoding="utf-8") + print(document) + return 1 if any(result["status"] in {"fail", "error"} for result in results.values()) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/conformance/replay-clock/rust/Cargo.toml.in b/conformance/replay-clock/rust/Cargo.toml.in new file mode 100644 index 0000000..40027cd --- /dev/null +++ b/conformance/replay-clock/rust/Cargo.toml.in @@ -0,0 +1,12 @@ +# run.py writes Cargo.toml from this template with the exact SDK dependency. +[package] +name = "replay-clock-conformance" +version = "0.0.0" +edition = "2021" +publish = false + +[dependencies] +durable-workflow = @DURABLE_WORKFLOW@ +chrono = { version = "0.4", default-features = false, features = ["std"] } +serde_json = "1" +tokio = { version = "1", features = ["rt", "macros"] } diff --git a/conformance/replay-clock/rust/src/main.rs b/conformance/replay-clock/rust/src/main.rs new file mode 100644 index 0000000..9af047b --- /dev/null +++ b/conformance/replay-clock/rust/src/main.rs @@ -0,0 +1,94 @@ +//! Replay the shared replay-clock vectors through the installed Rust SDK. +//! +//! Reads vectors-v1.json from the path in argv[1] and prints one JSON object +//! mapping each case id to its observations. Times are UTC RFC 3339 with six +//! fractional digits and Z; an unavailable read is null. +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use durable_workflow::testing::{WorkflowEnvironment, WorkflowHistory}; +use durable_workflow::{Client, Error, Worker, WorkflowContext}; +use serde_json::{json, Map, Value}; + +/// Carriers the offline history builder refuses up front: another run's +/// carrier and a low-precision `started_at`. Every other carrier is accepted +/// by the builder; an unproved one (the redrive source on ordinary history) +/// is then left absent during replay. +const BUILDER_REFUSES: [&str; 2] = ["carrier-for-another-run", "carrier-low-precision"]; + +/// Only an unavailable clock is reported as null; any other error fails the run. +fn read(ctx: &WorkflowContext) -> Result { + match ctx.replay_now() { + Ok(time) => Ok(json!(time.to_rfc3339_opts(chrono::SecondsFormat::Micros, true))), + Err(Error::ReplayClockUnavailable) => Ok(Value::Null), + Err(error) => Err(error), + } +} + +fn micros(text: &Value) -> Option { + let parsed = chrono::DateTime::parse_from_rfc3339(text.as_str()?).ok()?; + Some(parsed.timestamp_micros()) +} + +fn main() { + let path = std::env::args().nth(1).expect("vectors path"); + let vectors: Value = serde_json::from_str(&std::fs::read_to_string(path).expect("vectors")).expect("json"); + let spec = vectors["workflow"].clone(); + let seen: Arc>> = Arc::new(Mutex::new(None)); + + let mut worker = Worker::new(Client::new("http://127.0.0.1:9").expect("client"), "conformance"); + let (activity, seconds) = (spec["activity_type"].as_str().unwrap().to_owned(), spec["timer_seconds"].as_u64().unwrap()); + let sink = seen.clone(); + worker.register_workflow(spec["type"].as_str().unwrap(), move |ctx: WorkflowContext, _args: Value| { + let (activity, sink) = (activity.clone(), sink.clone()); + async move { + let entry = read(&ctx)?; + let repeated = read(&ctx)? == entry; + ctx.activity(activity, json!([])).await?; + let after_activity = read(&ctx)?; + ctx.sleep(Duration::from_secs(seconds)).await?; + let after_timer = read(&ctx)?; + let observed = json!({"entry":entry,"repeated_reads_equal":repeated, + "after_activity":after_activity,"after_timer":after_timer}); + *sink.lock().unwrap() = Some(observed.clone()); + Ok(observed) + } + }); + let environment = WorkflowEnvironment::from_worker(worker); + + let mut observations = Map::new(); + for case in vectors["cases"].as_array().unwrap() { + let id = case["id"].as_str().unwrap(); + let history = WorkflowHistory::from_history( + spec["type"].as_str().unwrap(), + (), + json!({"workflow_id":spec["workflow_id"],"run_id":spec["run_id"],"events":vectors["history"]}), + ) + .expect("history"); + // The builder refuses only the other-run and low-precision carriers; + // replay then runs without one, the same absence a worker applies. + let history = match case.get("replay_clock") { + Some(carrier) if BUILDER_REFUSES.contains(&id) => { + let refused = history.clone().replay_clock(carrier.clone()); + assert!(refused.is_err(), "{id}: the builder accepted a carrier it must refuse"); + history + } + Some(carrier) => history + .replay_clock(carrier.clone()) + .unwrap_or_else(|error| panic!("{id}: carrier refused: {error}")), + None => history, + }; + *seen.lock().unwrap() = None; + let report = environment.replay(&history).unwrap_or_else(|error| panic!("{id}: {error}")); + assert!(report.completed, "{id}: replay did not complete"); + let mut observed = seen.lock().unwrap().take().unwrap_or_else(|| panic!("{id}: no observation")); + let elapsed = match (micros(&observed["after_activity"]), micros(&observed["after_timer"])) { + (Some(start), Some(end)) => json!(end - start), + _ => Value::Null, + }; + observed["elapsed_microseconds"] = elapsed; + observations.insert(id.to_owned(), observed); + } + println!("{}", json!({"binding":"rust","sdk_version":std::env::var("DW_RUST_SDK_VERSION").unwrap_or_default(), + "observations":observations})); +} diff --git a/conformance/replay-clock/vectors-v1.json b/conformance/replay-clock/vectors-v1.json new file mode 100644 index 0000000..e0d1637 --- /dev/null +++ b/conformance/replay-clock/vectors-v1.json @@ -0,0 +1,168 @@ +{ + "schema": "durable-workflow.replay-clock-conformance/v1", + "requires_newer_than": { + "python": "2.23.1", + "rust": "4.24.0", + "php": "3.31.0", + "embedded-worker-protocol": "2.41.0" + }, + "workflow": { + "type": "conformance.replay-clock", + "workflow_id": "conformance-replay-clock", + "run_id": "conformance-replay-clock-run", + "input": [], + "payload_codec": "avro", + "activity_type": "conformance.step", + "timer_seconds": 2 + }, + "history": [ + { + "sequence": 1, + "event_type": "WorkflowStarted", + "recorded_at": "2026-11-01T00:00:00.123456Z", + "payload": { + "workflow_type": "conformance.replay-clock", + "workflow_instance_id": "conformance-replay-clock", + "workflow_run_id": "conformance-replay-clock-run", + "workflow_command_id": "conformance-replay-clock-start" + } + }, + { + "sequence": 2, + "event_type": "ActivityScheduled", + "recorded_at": "2026-11-01T00:00:00.200000Z", + "payload": { + "sequence": 1, + "activity_execution_id": "conformance-activity-1", + "activity_type": "conformance.step" + } + }, + { + "sequence": 3, + "event_type": "ActivityCompleted", + "recorded_at": "2026-11-01T00:00:03.123456Z", + "payload": { + "sequence": 1, + "activity_execution_id": "conformance-activity-1", + "activity_type": "conformance.step", + "result": "wwHioz3/VYAiNwoKZmlyc3Q=", + "payload_codec": "avro" + } + }, + { + "sequence": 4, + "event_type": "TimerScheduled", + "recorded_at": "2026-11-01T00:00:03.200000Z", + "payload": { + "sequence": 2, + "timer_id": "conformance-timer-2", + "timer_kind": "durable_timer", + "delay_seconds": 2 + } + }, + { + "sequence": 5, + "event_type": "TimerFired", + "recorded_at": "2026-11-01T00:00:05.654321Z", + "payload": { + "sequence": 2, + "timer_id": "conformance-timer-2", + "timer_kind": "durable_timer", + "delay_seconds": 2 + } + } + ], + "cases": [ + { + "id": "carrier", + "replay_clock": { + "schema": "durable-workflow.worker-replay-clock/v1", + "workflow_run_id": "conformance-replay-clock-run", + "started_at": "2026-11-01T00:00:00.000000Z", + "source": "run_started_at" + }, + "expected": { + "entry": "2026-11-01T00:00:00.000000Z", + "repeated_reads_equal": true, + "after_activity": "2026-11-01T00:00:03.123456Z", + "after_timer": "2026-11-01T00:00:05.654321Z", + "elapsed_microseconds": 2530865 + } + }, + { + "id": "no-carrier", + "expected": { + "entry": null, + "repeated_reads_equal": true, + "after_activity": "2026-11-01T00:00:03.123456Z", + "after_timer": "2026-11-01T00:00:05.654321Z", + "elapsed_microseconds": 2530865 + } + }, + { + "id": "carrier-for-another-run", + "replay_clock": { + "schema": "durable-workflow.worker-replay-clock/v1", + "workflow_run_id": "another-run", + "started_at": "2026-11-01T00:00:00.000000Z", + "source": "run_started_at" + }, + "expected": { + "entry": null, + "repeated_reads_equal": true, + "after_activity": "2026-11-01T00:00:03.123456Z", + "after_timer": "2026-11-01T00:00:05.654321Z", + "elapsed_microseconds": 2530865 + } + }, + { + "id": "carrier-low-precision", + "replay_clock": { + "schema": "durable-workflow.worker-replay-clock/v1", + "workflow_run_id": "conformance-replay-clock-run", + "started_at": "2026-11-01T00:00:00Z", + "source": "run_started_at" + }, + "expected": { + "entry": null, + "repeated_reads_equal": true, + "after_activity": "2026-11-01T00:00:03.123456Z", + "after_timer": "2026-11-01T00:00:05.654321Z", + "elapsed_microseconds": 2530865 + } + }, + { + "id": "redrive-source-on-ordinary-history", + "replay_clock": { + "schema": "durable-workflow.worker-replay-clock/v1", + "workflow_run_id": "conformance-replay-clock-run", + "started_at": "2026-11-01T00:00:00.000000Z", + "source": "redrive_replayed_started_at" + }, + "expected": { + "entry": null, + "repeated_reads_equal": true, + "after_activity": "2026-11-01T00:00:03.123456Z", + "after_timer": "2026-11-01T00:00:05.654321Z", + "elapsed_microseconds": 2530865 + } + } + ], + "binding_overrides": { + "embedded-worker-protocol": { + "_note": "WorkflowFiberRunner keeps the WorkflowStarted time when no proved carrier is passed, so runs in flight replay unchanged.", + "no-carrier": { + "entry": "2026-11-01T00:00:00.123456Z" + }, + "carrier-for-another-run": { + "entry": "2026-11-01T00:00:00.123456Z" + }, + "carrier-low-precision": { + "entry": "2026-11-01T00:00:00.123456Z" + }, + "redrive-source-on-ordinary-history": { + "entry": "2026-11-01T00:00:00.123456Z" + } + } + } +} diff --git a/sonar-project.properties b/sonar-project.properties index d9261a2..dd3028c 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -12,4 +12,7 @@ sonar.test.exclusions=**/vendor/**,**/node_modules/**,**/target/**,**/.venv/** sonar.sca.enabled=false sonar.python.version=3.13 sonar.python.coverage.reportPaths=coverage.xml +# Docker-only maintainer runners. Their unit test cannot join the reviewed +# ci.yml/sonar.yml bytes without a runtime review, so no report covers them. +sonar.coverage.exclusions=conformance/replay-clock/** sonar.php.coverage.reportPaths=build/composer-trust-coverage.xml diff --git a/tests/test_replay_clock_conformance.py b/tests/test_replay_clock_conformance.py new file mode 100644 index 0000000..fd24d9d --- /dev/null +++ b/tests/test_replay_clock_conformance.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import copy +import importlib.util +import json +import subprocess +import tempfile +import unittest +from datetime import datetime +from pathlib import Path +from unittest import mock + +from scripts.regression_corpus import CorpusError, _worker_replay_clock + +ROOT = Path(__file__).resolve().parents[1] +CASE = ROOT / "conformance/replay-clock" +_SPEC = importlib.util.spec_from_file_location("replay_clock_run", CASE / "run.py") +assert _SPEC is not None +assert _SPEC.loader is not None +run = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(run) + + +def _micros(text: str) -> int: + delta = datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%fZ") - datetime(1970, 1, 1) + return delta.days * 86_400_000_000 + delta.seconds * 1_000_000 + delta.microseconds + + +class ReplayClockConformanceTest(unittest.TestCase): + def setUp(self) -> None: + self.vectors = run.load_vectors() + + def observations(self, binding: str) -> dict[str, dict[str, object]]: + return {case["id"]: run.expected_for(self.vectors, binding, case["id"]) for case in self.vectors["cases"]} + + def test_vectors_are_internally_consistent(self) -> None: + ids = [case["id"] for case in self.vectors["cases"]] + self.assertEqual(len(ids), len(set(ids))) + self.assertEqual(set(run.BINDINGS), set(self.vectors["requires_newer_than"])) + run_id = self.vectors["workflow"]["run_id"] + for case in self.vectors["cases"]: + expected = case["expected"] + self.assertTrue(expected["repeated_reads_equal"]) + self.assertEqual( + _micros(expected["after_timer"]) - _micros(expected["after_activity"]), + expected["elapsed_microseconds"], + ) + carrier = case.get("replay_clock") + if case["id"] == "carrier": + # Only a carrier for this run whose source matches ordinary history is adopted. + self.assertEqual(_worker_replay_clock(carrier, case["id"])["workflow_run_id"], run_id) + self.assertEqual(carrier["started_at"].replace("Z", ""), expected["entry"].replace("Z", "")) + else: + self.assertIsNone(expected["entry"]) + for binding, overrides in self.vectors["binding_overrides"].items(): + self.assertIn(binding, run.BINDINGS) + self.assertLessEqual(set(overrides) - {"_note"}, set(ids)) + + def test_unproved_carriers_are_exactly_the_documented_refusals(self) -> None: + cases = {case["id"]: case.get("replay_clock") for case in self.vectors["cases"]} + with self.assertRaises(CorpusError): + _worker_replay_clock(cases["carrier-low-precision"], "low-precision") + self.assertNotEqual(self.vectors["workflow"]["run_id"], cases["carrier-for-another-run"]["workflow_run_id"]) + self.assertEqual(cases["redrive-source-on-ordinary-history"]["source"], "redrive_replayed_started_at") + self.assertNotIn("no-carrier", {key for key, value in cases.items() if value is not None}) + + def test_matching_observations_pass_and_every_drift_is_reported(self) -> None: + for binding in run.BINDINGS: + self.assertEqual([], run.compare(self.vectors, binding, self.observations(binding))) + drifted = self.observations("python") + drifted["carrier"]["entry"] = "2026-11-01T00:00:00.123456Z" + mismatches = run.compare(self.vectors, "python", drifted) + self.assertEqual(1, len(mismatches)) + self.assertIn("python/carrier/entry", mismatches[0]) + missing = self.observations("rust") + del missing["no-carrier"] + self.assertTrue(run.compare(self.vectors, "rust", missing)) + + def test_embedded_keeps_the_started_event_time_only_where_documented(self) -> None: + embedded = self.observations("embedded-worker-protocol") + self.assertEqual("2026-11-01T00:00:00.000000Z", embedded["carrier"]["entry"]) + self.assertEqual(self.vectors["history"][0]["recorded_at"], embedded["no-carrier"]["entry"]) + self.assertTrue(run.compare(self.vectors, "python", embedded)) + + def test_releases_without_the_carrier_are_not_yet_released(self) -> None: + for binding, last in self.vectors["requires_newer_than"].items(): + self.assertFalse(run.released(self.vectors, binding, last)) + major, minor, patch = run.version_tuple(last) + self.assertTrue(run.released(self.vectors, binding, f"{major}.{minor}.{patch + 1}")) + for invalid in ("2.24", "v2.24.0", "2.24.0-rc1", "latest"): + with self.assertRaises(ValueError): + run.version_tuple(invalid) + + def test_vectors_file_is_canonical_json(self) -> None: + text = (CASE / "vectors-v1.json").read_text(encoding="utf-8") + self.assertEqual(json.dumps(json.loads(text), indent=2) + "\n", text) + self.assertEqual(copy.deepcopy(self.vectors), json.loads(text)) + + +class ReplayClockRunnerTest(unittest.TestCase): + def setUp(self) -> None: + self.vectors = run.load_vectors() + self.work = Path(self.enterContext(tempfile.TemporaryDirectory())) + + def test_containers_use_a_private_scratch_mount_not_a_shared_temporary_directory(self) -> None: + completed = subprocess.CompletedProcess([], 0, stdout='{"observations": {}}\n', stderr="") + with mock.patch.object(run.subprocess, "run", return_value=completed) as docker: + run._run_binding("python", "9.9.9", None, self.work, prefix="test-prefix") + command = docker.call_args.args[0] + self.assertEqual(["docker", "run", "--rm", "--init"], command[:4]) + self.assertTrue(command[command.index("--name") + 1].startswith("test-prefix-python-")) + scratch = command[command.index("--tmpfs") + 1] + self.assertTrue(scratch.startswith("/scratch:")) + self.assertIn("mode=0700", scratch) + self.assertIn("HOME=/scratch", command) + self.assertNotIn("/tmp", command[-1]) + + def test_a_crashed_binding_is_recorded_as_an_error_and_the_run_continues(self) -> None: + failed = subprocess.CompletedProcess([], 125, stdout="", stderr="no such image") + garbage = subprocess.CompletedProcess([], 0, stdout="not json\n", stderr="") + with mock.patch.object(run.subprocess, "run", side_effect=[failed, garbage]): + crashed = run.evaluate(self.vectors, "python", "9.9.9", None, self.work) + unparsable = run.evaluate(self.vectors, "python", "9.9.9", None, self.work) + self.assertEqual("error", crashed["status"]) + self.assertIn("no such image", crashed["error"]) + self.assertEqual("error", unparsable["status"]) + + def test_a_matching_report_passes_and_an_old_release_is_not_run(self) -> None: + observations = {case["id"]: run.expected_for(self.vectors, "python", case["id"]) + for case in self.vectors["cases"]} + report = {"observations": observations, "sdk_version": "9.9.9"} + with mock.patch.object(run, "_run_binding", return_value=report): + self.assertEqual("pass", run.evaluate(self.vectors, "python", "9.9.9", None, self.work)["status"]) + with mock.patch.object(run, "_run_binding") as never: + last = self.vectors["requires_newer_than"]["python"] + result = run.evaluate(self.vectors, "python", last, None, self.work) + never.assert_not_called() + self.assertEqual("not_yet_released", result["status"]) + + def test_selection_refuses_unknown_bindings_and_inexact_versions(self) -> None: + with mock.patch.dict(run.os.environ, {"DW_PYTHON_SDK_VERSION": "latest"}), self.assertRaises(SystemExit): + run._selected("python", {}) + with self.assertRaises(SystemExit): + run._selected("go", {}) + with mock.patch.dict(run.os.environ, {"DW_PYTHON_SDK_VERSION": "9.9.9"}): + self.assertEqual([("python", "9.9.9", None)], run._selected("python", {})) + + +if __name__ == "__main__": + unittest.main()