---
title: "Test a replay inspector module in C#"
url: https://recursiveai.org/onescope/cookbook/test-replay-module-contracts/
description: "Check a custom OneScope module’s seek hashes, saved fork reproduction and entity-field differences with the released SDK and a deterministic counter."
version: "1.0.0"
---

# Test a replay inspector module in C#

**OneScope** is a free, open-source viewer for simulation recordings, with a desktop window or command-line control, from Recursive AI. MIT or Apache-2.0.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneScope.Sdk) · [GitHub](https://github.com/recursive-ai-oss/onescope-csharp) · [Docs](https://recursiveai.org/onescope/docs/) · [Download example (.zip)](https://recursiveai.org/onescope/cookbook/test-replay-module-contracts/test-replay-module-contracts.zip)

Check seek hashes, saved forks and entity-field differences using a deterministic counter.

```shell
dotnet add package RecursiveAI.OneScope.Sdk
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneScope.Sdk;

// CounterModule.cs comes in the zip.
var source = new CounterModule().Open(
    "[0,0,0,0,0,0]"u8.ToArray(), "counter");
var history = new History(source);
var linear = source.CreateWorld();
linear.Advance(source.Recording.InputAt(0).Span,
    TimelineSink.None);
history.Seek(1);
if (history.StateHash != linear.Hash())
    throw new Exception("Seek hash differs.");
Console.WriteLine("Seek hash agrees: True");
```

```text
Seek hash agrees: True
```

Unzip [the example](https://recursiveai.org/onescope/cookbook/test-replay-module-contracts/test-replay-module-contracts.zip), then `dotnet run`.

## The full program

The snippet at the top checks one seek against direct stepping. This program checks every recorded step, a rewind, a fork with an extra increment, the saved fork’s hashes and the planted difference. All input bytes are constructed in code: `[0,0,0,0,0,0]` means six ordinary steps. An input of `1` adds an extra increment.

```csharp
using System.Buffers;
using System.Buffers.Binary;
using System.Text.Json;
using OneScope.Sdk;

var module = new CounterModule();
var source = module.Open("[0,0,0,0,0,0]"u8.ToArray(), "counter");
var linear = source.CreateWorld();
var history = new History(source);
for (int step = 0; step <= source.Recording.EndStep; step++)
{
    history.Seek(step);
    Require(history.StateHash == linear.Hash(), "seek hash");
    if (step < source.Recording.EndStep)
        linear.Advance(source.Recording.InputAt(step).Span, TimelineSink.None);
}
history.Seek(1);
history.Seek(5);
Require(history.StateHash == ((5UL << 32) ^ 5), "rewind hash");
Console.WriteLine("Seek and linear playback agree: True");
var branch = history.Fork(3);
branch.Poke(new PokeCall("increment", []));
branch.Step();
var saved = new ArrayBufferWriter<byte>();
branch.History.Source.WriteReplay(saved);
var reopened = new History(module.Open(saved.WrittenMemory, "fork"));
for (long step = 0; step <= reopened.EndStep; step++)
{
    reopened.Seek(step);
    branch.History.Seek(step);
    Require(reopened.StateHash == branch.History.StateHash, "saved fork hash");
}
Console.WriteLine("Saved fork reproduces every hash: True");
var difference = history.Diff(reopened, 4)
    ?? throw new Exception("Missing planted difference.");
Require(difference.Entity == new EntityId(1) && difference.Field == "Value", "difference identity");
Console.WriteLine($"Difference: entity {difference.Entity}, {difference.Field}, {difference.Left} -> {difference.Right}");
static void Require(bool condition, string name)
{
    if (!condition) throw new Exception($"Failed: {name}");
}
```

```text
Seek and linear playback agree: True
Saved fork reproduces every hash: True
Difference: entity 1, Value, 4 -> 5
```

An assertion failure throws an exception and stops the program; malformed counter data throws `ScopeFormatException`.

### CounterModule.cs

This fixture is deliberately small: it has one entity and no drawing. Its snapshots store both the step and counter value; its replay stores the per-step inputs. Keep this file beside `Program.cs` when trying the snippet at the top.

```csharp
using System.Buffers;
using System.Buffers.Binary;
using System.Text.Json;
using OneScope.Sdk;

// Replay format: a JSON array of byte inputs, one per step. 0 = normal, 1 = extra increment.
public sealed class CounterModule : IScopeModule
{
    public string Id => "counter";
    public string Name => "Counter";
    public IScopeSource Open(ReadOnlyMemory<byte> data, string name)
    {
        if (data.Length > 10000) throw new ScopeFormatException(name, "Replay too large.");
        int[] inputs;
        try { inputs = JsonSerializer.Deserialize<int[]>(data.Span) ?? []; }
        catch (JsonException) { throw new ScopeFormatException(name, "Expected JSON integer input array."); }
        if (inputs.Any(x => x < 0 || x > 1)) throw new ScopeFormatException(name, "Expected inputs 0 or 1.");
        return new CounterSource(Recording.Create(ReadOnlyMemory<byte>.Empty, inputs.Select(x => (ReadOnlyMemory<byte>)new byte[] { (byte)x })));
    }
}
public sealed class CounterSource(Recording recording) : IScopeSource
{
    public SourceInfo Info { get; } = new()
    {
        ModuleId = "counter", Name = "Counter", Dimensions = 2, Unit = LengthUnit.Metre,
        Axes = [new AxisInfo(AxisIds.Time, "Time", 0)],
        EntityKinds = [new EntityKindInfo("counter", "Counter")],
        Pokes = [new PokeInfo("increment", "Extra increment", [])]
    };
    public Recording Recording => recording;
    public IScopeWorld CreateWorld() => new CounterWorld();
    public IScopeSource WithRecording(Recording other) => new CounterSource(other);
    public void WriteReplay(IBufferWriter<byte> writer)
    {
        var inputs = Enumerable.Range(0, (int)recording.StepCount)
            .Select(i => recording.InputAt(i).IsEmpty ? (byte)0 : recording.InputAt(i).Span[0]).ToArray();
        writer.Write(JsonSerializer.SerializeToUtf8Bytes(inputs.Select(x => (int)x).ToArray()));
    }
}
public sealed class CounterWorld : IScopeWorld
{
    public long Step { get; private set; }
    private long value;
    public ulong Hash() => ((ulong)Step << 32) ^ (ulong)value;
    public void Advance(ReadOnlySpan<byte> input, TimelineSink sink)
    {
        if (input.Length > 1 || (!input.IsEmpty && input[0] > 1))
            throw new ScopeFormatException("counter", "Expected empty input or one byte: 0 or 1.");
        value += 1 + (input.IsEmpty ? 0 : input[0]);
        Step++;
    }
    public void AdvanceAxis(string axis, int position, ReadOnlySpan<byte> input) => throw new ArgumentException("Time only.");
    public void WriteSnapshot(IBufferWriter<byte> writer)
    {
        BinaryPrimitives.WriteInt64LittleEndian(writer.GetSpan(8), Step); writer.Advance(8);
        BinaryPrimitives.WriteInt64LittleEndian(writer.GetSpan(8), value); writer.Advance(8);
    }
    public void Restore(ReadOnlySpan<byte> bytes)
    {
        if (bytes.Length != 16) throw new ScopeFormatException("counter", "Expected 16-byte snapshot.");
        Step = BinaryPrimitives.ReadInt64LittleEndian(bytes);
        value = BinaryPrimitives.ReadInt64LittleEndian(bytes[8..]);
    }
    public void CollectEntities(List<EntityInfo> into)
    {
        into.Clear(); into.Add(new(new EntityId(1), EntityId.None, "counter", "Counter"));
    }
    public bool Inspect(EntityId entity, PropertyList into)
    {
        into.Clear(); if (entity.Value != 1) return false;
        into.Add("State", "Value", ScopeValue.OfInteger(value)); return true;
    }
    public void Draw(DrawList into, in DrawRequest request) { }
    public void EncodePoke(in PokeCall call, IBufferWriter<byte> into)
    {
        if (call.Poke != "increment" || call.Args.Length != 0) throw new ArgumentException("Expected increment without arguments.");
        into.Write(new byte[] { 1 });
    }
    public Difference? FirstDifference(IScopeWorld other)
    {
        if (other is not CounterWorld right) throw new ArgumentException("Expected CounterWorld.");
        return value == right.value ? null : new Difference(new EntityId(1), "Value", value.ToString(), right.value.ToString());
    }
}
```

## Variations

To check a different seek order, replace the rewind check in the full program with this loop. It printed `Out-of-order seeks agree: True`.

```csharp
foreach (long step in new long[] { 6, 0, 4, 1, 6 })
{
    history.Seek(step);
    var expected = source.CreateWorld();
    for (long i = 0; i < step; i++)
        expected.Advance(source.Recording.InputAt(i).Span,
            TimelineSink.None);
    Require(history.StateHash == expected.Hash(), "seek order");
}
Console.WriteLine("Out-of-order seeks agree: True");
```

## Related recipes

- [Write a replay viewer module](https://recursiveai.org/onescope/cookbook/write-a-onescope-module/)
- [Debug a deterministic replay mismatch](https://recursiveai.org/onescope/cookbook/debug-determinism-desync/)
- [Fork and poke a replay](https://recursiveai.org/onescope/cookbook/fork-and-poke-a-replay/)

## The short answer

Test the adapter against the simulation, not against another route through the same adapter. A OneScope module has three important obligations: a seek must reconstruct the same state as linear playback, saving and reopening a fork must reproduce that fork, and a difference must identify the entity and field that changed. These are the checks recommended by the pinned [module-authoring contract](https://recursiveai.org/onescope/docs/module-authoring/).

The example uses the published SDK directly. It does not open the desktop shell or test rendering, picking or module discovery. That makes a failing hash attributable to state reconstruction rather than a window’s display settings. For your own module, replace the counter fixture with your library’s source and compare against that library’s own hash.

## How do I test a replay inspector module in C#?

Start with a short recording whose inputs and expected state you understand. Create one world through the module and advance it directly, feeding each input exactly once. Separately create a `History` and seek to each corresponding step. Compare the two hashes before advancing the direct world to the next step.

The counter’s `Hash()` includes both step and value. A hash that omits a mutable field can hide a broken snapshot: both playback paths may report equality even when that field differs. The SDK contract requires a hash of the whole simulated state, including the step. Likewise, `WriteSnapshot` and `Restore` must preserve everything needed to continue from that state, not merely what the inspector happens to display.

Check backward seeks as well as forward ones. The variation deliberately revisits steps in a different order. A module that accidentally retains state from a previous seek can pass a forward-only check and fail after a rewind. Use explicit exceptions or a test framework’s assertions; printing two numbers without comparing them leaves the test dependent on someone reading the output.

## How do I test saved replay forks?

Fork at a known step, apply one valid poke and advance the branch. Save through `branch.History.Source.WriteReplay`, then reopen the bytes through the module’s public `Open` method. Compare hashes at every step of the reopened recording against the branch, as the full program does.

This exercises serialization as well as playback. Comparing a branch only to its own current world would miss a writer that drops pokes. The counter writer includes each step’s input, so its extra increment survives reopening. The original recording remains unchanged; the SDK’s [history documentation](https://recursiveai.org/onescope/docs/history/) describes forks as separate recordings.

A production fixture should cover the inputs your module actually supports. Include enough steps to cross snapshot boundaries and at least one poke whose effect persists. The small counter is an example of the checks, not evidence that another simulation’s snapshot or replay format is correct.

## How do I find an entity-field difference in a replay?

Plant a change with a known result. Here the extra increment changes entity `1`’s `Value` from `4` to `5` at step `4`. `history.Diff(reopened, 4)` seeks both histories and asks for the first difference. The test checks both the entity ID and the field name, rather than accepting any non-null result.

Keep the order of differences deterministic. The SDK defines `FirstDifference` as the first differing entity and field in a fixed order chosen by the module. A failure that names a different field on each run is hard to investigate. Match the field name to the inspector, so someone can select the reported entity and see the value that the test reports.

These tests do not replace a shell integration check. After they pass, load the compiled module into the shell and exercise selection, replay export and module loading there. The SDK checks isolate the state contract; the shell checks establish that users can reach that contract through the viewer.
