Files
Chronos/tests/Titano.Core.Tests/Decoding/FrameWindowTests.cs
T
Claude 2f978d1c80 test: run process-wide tests serially and report constructor failures as themselves
Four App tests switched the process-wide UI language inside parallel classes, so
another class's English assertion, or its constructor's reset to English, could
land in the middle of them; they now live in the serial ArchiveLanguageTests and
ImportLanguageTests. The App and Core test programs fail a test that leaves
English outside a serial class at the switch, through the new
TestContext.Current and TestContext.IsSerial.

The FrameWindow cancellation test counted unobserved task exceptions while other
classes ran beside it; it moves to the serial FrameWindowIsolationTests, and both
unobserved-exception tests drain the finalizer queue before they start counting.

The runner unwrapped TargetInvocationException only around the test method: a
skip or an assertion thrown by a test class constructor or field initializer was
reported as a failure reading "Exception has been thrown by the target of an
invocation". Constructors are unwrapped the same way now. TestRunner.Discover(Type)
and ExecuteAsync are public, so Tools.Tests checks the runner with nested fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 10:05:37 +00:00

147 lines
6.0 KiB
C#

using Titano.Core.Imaging;
using Titano.Testing;
namespace Titano.Core.Tests.Decoding;
/// <summary><see cref="FrameWindow"/>: memory bound independent of sequence length, spill round trip, read-ahead and
/// deterministic disposal (BRIEF §8.4, §20.4 memory gate; the cancellation gate is in <see cref="FrameWindowIsolationTests"/>).</summary>
public sealed class FrameWindowTests(TestContext context)
{
private const int Size = 64;
internal const long FrameBytes = Size * Size * 3 * sizeof(float);
/// <summary>Synthetic loader whose frames encode their index; records every buffer it hands out.</summary>
internal sealed class Source
{
private readonly List<ImageBuffer> _made = [];
public int Loads;
public TimeSpan Delay;
public async ValueTask<ImageBuffer> Load(int index, CancellationToken cancellationToken)
{
Interlocked.Increment(ref Loads);
if (Delay > TimeSpan.Zero) await Task.Delay(Delay, cancellationToken);
var image = new ImageBuffer(Size, Size, 3, clear: false);
image.Data.Fill(index);
image[1, 5, 7] = index + 0.25f;
lock (_made) _made.Add(image);
return image;
}
/// <summary>Loader-made buffers not yet disposed (independent of the window's own counters).</summary>
public int Live()
{
lock (_made)
{
var live = 0;
foreach (var b in _made)
{
try
{
_ = b.Storage;
live++;
}
catch (ObjectDisposedException)
{
}
}
return live;
}
}
}
private static void AssertFrame(FrameLease lease)
{
Assert.Equal((float)lease.Index, lease.Image[0, 10, 10]);
Assert.Equal(lease.Index + 0.25f, lease.Image[1, 5, 7]);
}
/// <summary>Render loop: each step moves the window and reads the frame plus its three predecessors — four frames
/// needed per step against a three-frame budget, so in-window frames must be spilled and read back.</summary>
private async Task<(FrameWindowStatistics Stats, int PeakLive, string? Spill)> Render(int frames, string spillDirectory)
{
var source = new Source();
var options = new FrameWindowOptions { Behind = 3, Ahead = 4, MemoryBudget = 3 * FrameBytes, SpillDirectory = spillDirectory };
var peakLive = 0;
FrameWindowStatistics stats;
string? spill;
await using (var window = new FrameWindow(frames, source.Load, options))
{
for (var i = 0; i < frames; i++)
{
window.MoveTo(i);
using (var current = await window.GetAsync(i)) AssertFrame(current);
for (var back = 1; back <= 3 && i - back >= 0; back++)
{
using var previous = await window.GetAsync(i - back);
AssertFrame(previous);
}
peakLive = int.Max(peakLive, source.Live());
Assert.LessOrEqual(window.Statistics.LiveBytes, options.MemoryBudget);
}
stats = window.Statistics;
spill = window.SpillPath;
Assert.FileExists(spill!);
}
Assert.Equal(0, source.Live());
return (stats, peakLive, spill);
}
[Test]
[Timeout(30_000)]
public async Task PeakMemoryIsBoundedAndIndependentOfSequenceLength()
{
var dir = context.CreateTempDirectory();
var shortRun = await Render(40, dir);
var longRun = await Render(400, dir);
context.Log($"40 frames: {shortRun.Stats}, peak live {shortRun.PeakLive}; 400 frames: {longRun.Stats}, peak live {longRun.PeakLive}");
foreach (var run in new[] { shortRun, longRun })
{
Assert.LessOrEqual(run.Stats.PeakLiveBytes, 3 * FrameBytes);
Assert.LessOrEqual(run.PeakLive, 3);
Assert.Greater(run.Stats.SpillWrites, 0);
Assert.Greater(run.Stats.SpillReads, 0);
// Spill extents are reused: only frames inside the window (3 behind + current + 4 ahead) are ever on disk.
Assert.LessOrEqual(run.Stats.SpillFileBytes, 8 * FrameBytes);
Assert.FileMissing(run.Spill!);
}
Assert.Equal(shortRun.Stats.PeakLiveBytes, longRun.Stats.PeakLiveBytes);
Assert.Equal(shortRun.PeakLive, longRun.PeakLive);
Assert.LessOrEqual(longRun.Stats.SpillFileBytes, shortRun.Stats.SpillFileBytes);
}
[Test]
[Timeout(10_000)]
public async Task ReadAheadDecodesInTheBackground()
{
var source = new Source();
await using var window = new FrameWindow(100, source.Load, new FrameWindowOptions { Ahead = 3, MemoryBudget = 10 * FrameBytes });
window.MoveTo(0);
using (var first = await window.GetAsync(0)) AssertFrame(first);
var deadline = DateTime.UtcNow.AddSeconds(5);
while (source.Loads < 4 && DateTime.UtcNow < deadline) await Task.Delay(5);
Assert.Equal(4, source.Loads);
using var ahead = await window.GetAsync(3);
AssertFrame(ahead);
Assert.Equal(4, source.Loads);
}
[Test]
public async Task LoaderFailuresSurfaceAndCanBeRetried()
{
var attempts = 0;
async ValueTask<ImageBuffer> Flaky(int index, CancellationToken ct)
{
await Task.Yield();
if (index == 2 && Interlocked.Increment(ref attempts) == 1) throw new InvalidDataException("bad frame");
var image = new ImageBuffer(8, 8, 3);
image.Data.Fill(index);
return image;
}
await using var window = new FrameWindow(5, Flaky, new FrameWindowOptions { Ahead = 0 });
await Assert.ThrowsAsync<InvalidDataException>(async () => await window.GetAsync(2));
using var retried = await window.GetAsync(2);
Assert.Equal(2f, retried.Image[0, 0, 0]);
}
}