Skip to content

Deterministic, comparative and partial replay

Replay helps your application investigate a session after it ran. You can reconstruct what a trace records, or evaluate its chosen path against a target graph and inspect where the results differ. A recorded sequence of steps supplies the evidence; a final session snapshot alone does not contain all of it.

This tutorial first reconstructs a small trace, then lowers a graph limit to produce a divergence, and finally isolates the affected step. It reuses the expense request introduced in State export and historical evidence: edge 101 moves from entry node 10 to review node 20 with amount: 180. The next choice supplies amount: 120 and follows edge 102 to terminal 30 because the original condition allows amounts up to 150. The application captured both transitions, their times and the selected edge’s condition result.

Prepare the evidence and the replay runtime

Section titled “Prepare the evidence and the replay runtime”

The complete trace includes the initial context, ordered steps and recorded final state. The historical graph is the definition used to produce it. Keep that definition distinct from any proposed replacement: a historical check needs the original revision, while a comparison needs an explicitly chosen target.

ReplayScenario::fromTrace() validates the full trace and builds the request for ReplayEngine. The mode determines what that request asks the engine to do.

Mode Work performed Meaning of the result
strict Applies the recorded context changes and reconstructs the recorded path without executing conditions again. Consistency of the supplied history; supplying its historical graph adds checks against that definition.
reeval Attempts the recorded choices on the target graph using explicit times and the target runtime’s policies. A comparison with those inputs, or a counterfactual result when something changes.

In an existing PHP project using ExecKernel, load the two artifacts:

use ExecKernel\Infrastructure\Loader\JsonGraphLoader;
$trace = json_decode(
file_get_contents(__DIR__ . '/evidence-trace.json'),
true,
512,
JSON_THROW_ON_ERROR,
);
$loader = new JsonGraphLoader();
$historicalGraph = $loader->load(
__DIR__ . '/evidence-expense-graph.json',
);

ReplayEngine receives a Navigator, the component that applies choices to a graph. This example constructs a small runtime with the built-in rules and UTC date interpretation:

use ExecKernel\Domain\Engine\ConditionEvaluator;
use ExecKernel\Domain\Engine\CycleBreaker;
use ExecKernel\Domain\Engine\DateTimeEvaluator;
use ExecKernel\Domain\Engine\FixedTimeProvider;
use ExecKernel\Domain\Engine\FlowEventsDispatcher;
use ExecKernel\Domain\Engine\Navigator;
use ExecKernel\Replay\ReplayEngine;
use ExecKernel\Replay\ReplayMode;
use ExecKernel\Replay\ReplayScenario;
$dispatcher = new FlowEventsDispatcher();
$evaluator = new ConditionEvaluator(
[], $dispatcher, FixedTimeProvider::fromTimestamp(1700000000),
dateTimeEvaluator: new DateTimeEvaluator('UTC'),
sessionTtlSeconds: null,
);
$navigator = new Navigator(
$evaluator, new CycleBreaker($dispatcher), $dispatcher,
);
$replay = new ReplayEngine($navigator, engineVersion: '0.2.0');

The dispatcher connects those runtime components. The evaluator supplies the conditions, and the cycle breaker checks the traversed edges. The explicit clock and timezone make their time configuration clear. This example has no session TTL; a real comparison should use the expiry and security policies you intend to compare. See Session expiration, history and retention for their effect on a session.

For reeval, the engine creates its own isolated runtime from this navigator. It uses the trace’s step timestamps, fresh built-in rule instances and inert event and observation destinations. It does not publish to the live dispatcher’s listeners, deliver webhooks or invoke your application’s business operations. Requesting allowSideEffects: true or allowWebhooks: true is rejected. Conditions of type custom_rule and plugin-defined rule types on the selected sequence are also rejected before it runs.

Ask for strict and supply the historical graph:

$strict = $replay->replay(ReplayScenario::fromTrace(
$trace,
ReplayMode::STRICT,
historicalGraph: $historicalGraph,
));

The result contains:

Property Value in this example
finalNodeId 30
finalContext ['amount' => 120]
reconstructedHistory Nodes [10, 20, 30] and edges [101, 102].
evidenceLevel graph_consistency
terminalVerified true
divergenceReport->hasDivergences() false

Strict replay checks the step sequence, times, path continuity and recorded outcomes. With the historical graph, it also checks identity and revisions, edge origins and destinations, the recorded rule sequence and terminal status. It reconstructs the context by applying the recorded changes in order.

It does not evaluate amount <= 150 again. The successful outcome is part of the evidence you supplied. A consistent trace therefore does not prove that the recording was truthful or that the same choice would succeed under today’s policies.

You can omit historicalGraph when only the trace is available. The result then has evidenceLevel: trace_consistency and terminalVerified: null. Even if the trace says its final node was terminal, the engine cannot verify that property against a missing definition.

First establish the unchanged comparison:

$unchanged = $replay->replay(ReplayScenario::fromTrace(
$trace,
ReplayMode::REEVALUATION,
target: $historicalGraph,
historicalGraph: $historicalGraph,
engineVersion: '0.2.0',
allowSideEffects: false,
allowWebhooks: false,
));

This completes both choices at node 30 with no divergences. The result is counterfactual evidence because the runtime has evaluated a scenario; it is not a new historical record. historicalComparisonComplete is true for the selected steps and recorded boundary.

Now create a separate target definition. Keep the same topology, change its graph revision to 1.1.0 and lower the amount limit to 100:

$targetDefinition = json_decode(
file_get_contents(__DIR__ . '/evidence-expense-graph.json'),
true,
512,
JSON_THROW_ON_ERROR,
);
$targetDefinition['graph_version'] = '1.1.0';
$targetDefinition['conditions'][0]['params']['value'] = 100;
$targetGraph = $loader->load(
json_encode($targetDefinition, JSON_THROW_ON_ERROR),
);
$changed = $replay->replay(ReplayScenario::fromTrace(
$trace,
ReplayMode::REEVALUATION,
target: $targetGraph,
historicalGraph: $historicalGraph,
engineVersion: '0.2.0',
allowSideEffects: false,
allowWebhooks: false,
));

The historical graph validates the source evidence. The target graph supplies the definition to evaluate. The engine version supplied for the comparison must match the configured replay engine; the source trace retains its own recorded version separately.

The recorded second choice reaches node 30 with amount 120 under limit 150. The target limit 100 rejects that choice, leaving node 20 and the prior amount 180.

The first choice still succeeds. At step 1, the candidate amount 120 exceeds the new limit. The result stops with these values:

Property Changed target
finalNodeId 20
finalContext ['amount' => 180]
attemptedStepCount / completedStepCount 2 / 1
stopReason edge_blocked
First divergence Step 1, type edge_blocked, edge 102.
Additional rule divergence rule_outcome_mismatch: the recorded true became false.
historicalComparisonComplete false

The context stays at 180 because the failed transition did not commit its proposed update to 120. The report still identifies 120 as the value checked by the rejected condition. Your application can show the first divergence together with that input and the changed limit, instead of treating the returned node as if the entire path had completed.

The comparison follows the recorded selected edges. It compares their rule occurrences in order, and any recorded details other than measured execution duration. It does not explore every alternative or reevaluate recorded outcomes for unselected edges. A completed comparison and an empty divergence list answer a bounded question about this path, these inputs, these times and these policies.

Isolate the second step without inventing its starting state

Section titled “Isolate the second step without inventing its starting state”

To focus on the affected choice, select start: 1 and end: 1 from the complete trace. Both bounds are inclusive and use the original zero-based step numbers.

$partialRequest = ReplayScenario::fromTrace(
$trace,
ReplayMode::REEVALUATION,
target: $targetGraph,
historicalGraph: $historicalGraph,
start: 1,
end: 1,
engineVersion: '0.2.0',
allowSideEffects: false,
allowWebhooks: false,
);
$partial = $replay->replay($partialRequest);

fromTrace() reconstructs the earlier steps before preparing this request. The segment begins at node 20 with amount: 180 and history containing nodes [10, 20] and edge 101. It preserves creation time 1700000000 and the preceding transition’s time 1700000005. The selected step then supplies amount: 120 at 1700000010.

That prefix matters for conditions based on visited nodes, selected edges, session age or time since the last transition. Starting a new session at node 20 would not represent the same situation. The selected target must also admit the supplied prefix’s structure; a malformed or incompatible prefix is rejected.

This partial comparison attempts one step, completes none and reports the same step-1 divergence as the complete comparison. The original source is validated before selection, so malformed evidence in an omitted step still prevents the request from being built. Use the same range parameters with ReplayMode::STRICT to reconstruct a recorded segment instead of reevaluating it.

Recognize evidence that cannot support this replay

Section titled “Recognize evidence that cannot support this replay”

An inspection_window from DebugReplayExporter is a view for reading a trace. Passing it to fromTrace() is rejected because it no longer contains the complete prefix. Keep the full trace and select the range through the scenario builder.

A StateExporter snapshot is also rejected as a debug trace. It contains current context and the visited path, but it does not supply the per-step context changes and clocks required above. ReplayScenario::fromStateExport() can use it for an explicitly declared fixed-clock scenario: the source needs time_snapshot.mode: fixed and an absolute timestamp. That result uses scenario_only as its source evidence level and cannot establish historical agreement. It cannot start at an arbitrary intermediate step because the historical prefix context is unavailable.

Missing evidence, invalid timestamps or malformed target rules are errors to repair. They are distinct from an expected logical rejection such as the lower limit in this example, which returns a divergence report. Keep that distinction in your application’s diagnostic UI.

Place replay-example.php, evidence-trace.json and evidence-expense-graph.json in the root of your PHP project, next to vendor/. The script loads vendor/autoload.php from that root.

php replay-example.php prints the strict result, the unchanged and changed comparisons, the partial request’s starting data and the partial result. Its report() function selects the result properties into readable JSON. It also makes the target definition separately, so the trace and historical graph remain available for the next diagnosis.