using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Testing;
using static Chronos.Core.Tests.Render.RenderFixture;
namespace Chronos.Core.Tests.Render;
/// Process-wide observations (unobserved task exceptions, managed heap) that must not overlap other tests.
[Serial]
public sealed class RenderIsolationTests
{
private readonly TestContext _context;
public RenderIsolationTests(TestContext context) => _context = context;
[Test]
public async Task FailuresLeaveNoUnobservedTaskExceptions()
{
// Faulted tasks the earlier tests left for the finalizer are reported now, before this test starts counting.
GC.Collect();
GC.WaitForPendingFinalizers();
var unobserved = 0;
void Handler(object? sender, UnobservedTaskExceptionEventArgs e) => Interlocked.Increment(ref unobserved);
TaskScheduler.UnobservedTaskException += Handler;
try
{
var dir = _context.CreateTempDirectory();
var capture = new CapturingEncoderProvider("capture", new EncoderCapability(VideoCodec.PngSequence, "Capture", false, 4096, 4096, true))
{
FailAt = (2, new InvalidDataException("encoder broke")),
};
for (var i = 0; i < 3; i++)
{
await Assert.ThrowsAsync(() => Pipeline(capture).RenderAsync(Input(Source()), Target(dir, Preset("png-sequence"))));
var input = Input(Source()) with { Source = new FailingSource(Source(), failAt: 3 + i) };
await Assert.ThrowsAsync(() => Pipeline().RenderAsync(input, Target(dir, Preset("gif-preview"))));
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.Equal(0, unobserved);
Assert.Empty(Directory.GetFileSystemEntries(dir));
}
finally
{
TaskScheduler.UnobservedTaskException -= Handler;
}
}
/// BRIEF ยง20.4: peak memory does not depend on the sequence length (live managed heap sampled while rendering).
[Test]
public async Task MemoryDoesNotGrowWithSequenceLength()
{
async Task PeakAsync(int frames)
{
var dir = _context.CreateTempDirectory();
long peak = 0;
var progress = new Sink(p =>
{
if (p.Stage == RenderStage.Rendering && p.Done % 8 == 0) peak = Math.Max(peak, GC.GetTotalMemory(forceFullCollection: true));
});
var project = Plain with { Exposure = new Chronos.Core.Project.ExposureSettings { Deflicker = new Chronos.Core.Project.Auto().WithManual(true) } };
await Pipeline().RenderAsync(Input(Source(frames), project), Target(dir, Preset("mjpeg-avi")), progress: progress, cancellationToken: _context.Cancellation);
return peak;
}
await PeakAsync(16);
var shortPeak = await PeakAsync(48);
var longPeak = await PeakAsync(192);
_context.Log($"peak live heap: 48 frames {shortPeak / 1024} KiB, 192 frames {longPeak / 1024} KiB");
Assert.Less(longPeak - shortPeak, 2 << 20);
}
}