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
5 changes: 5 additions & 0 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
55 changes: 55 additions & 0 deletions conformance/replay-clock/README.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions conformance/replay-clock/php/composer.json.in
Original file line number Diff line number Diff line change
@@ -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
}
}
81 changes: 81 additions & 0 deletions conformance/replay-clock/php/embedded-runner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

declare(strict_types=1);

// Replay the shared replay-clock vectors through the installed Workflow
// package's worker-protocol runner (WorkflowFiberRunner, used by external PHP
// workers). The embedded executor itself reads the run row's started_at, the
// column the carrier is built from; this runner receives it as replayClock.

require_once __DIR__.'/vendor/autoload.php';

use Composer\InstalledVersions;
use Workflow\V2\Support\WorkflowFiberRunner;
use Workflow\V2\Workflow;

final class ReplayClockConformanceWorkflow extends Workflow
{
public static string $activity = '';

public static int $seconds = 0;

/** @return array<string, mixed> */
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";
83 changes: 83 additions & 0 deletions conformance/replay-clock/php/sdk-runner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

// Replay the shared replay-clock vectors through the installed PHP service SDK.
// Reads vectors-v1.json from argv[1]; 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.

require_once __DIR__.'/vendor/autoload.php';

use Composer\InstalledVersions;
use DurableWorkflow\Client;
use DurableWorkflow\Codec\AvroPayloadCodec;
use DurableWorkflow\Exception\ReplayClockUnavailable;
use DurableWorkflow\Testing\InMemoryTransport;
use DurableWorkflow\Testing\WorkerTestHarness;
use DurableWorkflow\Worker;
use DurableWorkflow\Worker\WorkflowContext;

$vectors = json_decode((string) file_get_contents($argv[1]), true, flags: JSON_THROW_ON_ERROR);
$spec = $vectors['workflow'];

$read = static function (WorkflowContext $context): ?string {
try {
return $context->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";
83 changes: 83 additions & 0 deletions conformance/replay-clock/python/runner.py
Original file line number Diff line number Diff line change
@@ -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))
Loading
Loading