Files

372 lines
15 KiB
C#
Raw Permalink Normal View History

using Heimdall.Agent.Services;
using Heimdall.Application.Metrics;
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Logging;
using NSubstitute;
namespace Heimdall.Agent.Tests;
[CollectionDefinition("Frame analyzer metrics", DisableParallelization = true)]
public sealed class FrameAnalyzerMetricsTestGroup { }
[Collection("Frame analyzer metrics")]
public class FrameAnalyzerServiceTests
{
[Fact]
public void Constructor_WhenModelNotFound_DoesNotThrow()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
service.ShouldNotBeNull();
}
[Fact]
public async Task AnalyzeFrameAsync_WhenPassthrough_ReturnsNull()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var result = await service.AnalyzeFrameAsync([1, 2, 3]);
result.ShouldBeNull();
}
[Fact]
public void AnalyzeFrame_WhenPassthrough_ReturnsNull()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var result = service.AnalyzeFrame([1, 2, 3]);
result.ShouldBeNull();
}
[Fact]
public async Task AnalyzeFrameAsync_EmptyArray_ReturnsNull()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var result = await service.AnalyzeFrameAsync([]);
result.ShouldBeNull();
}
[Fact]
public async Task AnalyzeFrameAsync_LargeBuffer_ReturnsNull()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var result = await service.AnalyzeFrameAsync(new byte[1024 * 1024]);
result.ShouldBeNull();
}
[Fact]
public void Dispose_MultipleTimes_DoesNotThrow()
{
var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
service.Dispose();
service.Dispose();
}
[Fact]
public async Task AnalyzeFrameAsync_AfterDispose_ReturnsNull()
{
var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
service.Dispose();
var result = await service.AnalyzeFrameAsync([1, 2, 3]);
result.ShouldBeNull();
}
[Fact]
public async Task AnalyzeFrameAsync_ConcurrentCalls_DoNotThrow()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var tasks = Enumerable.Range(0, 10)
.Select(_ => service.AnalyzeFrameAsync([1, 2, 3]))
.ToArray();
var results = await Task.WhenAll(tasks);
results.ShouldAllBe(r => r == null);
}
[Fact]
public async Task AnalyzeFrameAsync_EmitsInferenceDurationMetrics()
{
var yoloMeasurements = new ConcurrentBag<double>();
var overallMeasurements = new ConcurrentBag<double>();
using var listener = new MeterListener();
listener.InstrumentPublished = (instrument, meterListener) =>
{
if (instrument.Name is "heimdall.ai.yolo.inference_ms" or "heimdall.ai.inference_ms")
meterListener.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback<double>((instrument, value, _, _) =>
{
if (instrument.Name == "heimdall.ai.yolo.inference_ms") yoloMeasurements.Add(value);
if (instrument.Name == "heimdall.ai.inference_ms") overallMeasurements.Add(value);
});
listener.Start();
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>(), null, null,
(_, _) => []);
var result = await service.AnalyzeFrameAsync([1]);
result.ShouldNotBeNull();
yoloMeasurements.ShouldHaveSingleItem();
overallMeasurements.ShouldHaveSingleItem();
yoloMeasurements.Single().ShouldBeGreaterThanOrEqualTo(0);
overallMeasurements.Single().ShouldBeGreaterThanOrEqualTo(0);
}
[Fact]
public async Task InferenceQueueMetrics_ReportBacklogRejectionsAndRecovery()
{
var queueDepths = new ConcurrentBag<long>();
long rejectedFrames = 0;
using var listener = new MeterListener();
listener.InstrumentPublished = (instrument, meterListener) =>
{
if (instrument.Meter.Name == HeimdallMetrics.MeterName &&
instrument.Name is "heimdall.ai.inference.queue.depth" or "heimdall.ai.inference.queue.rejected")
meterListener.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback<long>((instrument, value, _, _) =>
{
if (instrument.Name == "heimdall.ai.inference.queue.depth") queueDepths.Add(value);
if (instrument.Name == "heimdall.ai.inference.queue.rejected") Interlocked.Add(ref rejectedFrames, value);
});
listener.Start();
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
using var analyzer = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>(), null, null,
(_, _) => { entered.Set(); release.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); return []; });
var first = analyzer.AnalyzeFrameAsync([1]);
entered.Wait(TimeSpan.FromSeconds(5)).ShouldBeTrue();
var queued = Enumerable.Range(0, 16).Select(_ => analyzer.AnalyzeFrameAsync([1])).ToArray();
(await analyzer.AnalyzeFrameAsync([1]).WaitAsync(TimeSpan.FromSeconds(2))).ShouldBeNull();
listener.RecordObservableInstruments();
queueDepths.Last().ShouldBe(16);
rejectedFrames.ShouldBe(1);
release.Set();
(await Task.WhenAll(queued.Append(first)).WaitAsync(TimeSpan.FromSeconds(10))).ShouldAllBe(result => result != null);
listener.RecordObservableInstruments();
queueDepths.ShouldContain(0);
}
[Fact]
public async Task Saturation_RejectsNewWork_AndShutdownDrainsAcceptedJobs()
{
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>(), null, null,
(_, _) => { entered.Set(); release.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); return []; });
var first = service.AnalyzeFrameAsync([1]);
entered.Wait(TimeSpan.FromSeconds(5)).ShouldBeTrue();
var queued = Enumerable.Range(0, 16).Select(_ => service.AnalyzeFrameAsync([1])).ToArray();
(await service.AnalyzeFrameAsync([1]).WaitAsync(TimeSpan.FromSeconds(2))).ShouldBeNull();
service.RejectedFrames.ShouldBe(1);
var shutdown = Task.Run(service.Dispose);
try { shutdown.IsCompleted.ShouldBeFalse(); }
finally { release.Set(); }
await shutdown.WaitAsync(TimeSpan.FromSeconds(10));
var results = await Task.WhenAll(queued.Append(first)).WaitAsync(TimeSpan.FromSeconds(5));
results.ShouldAllBe(r => r != null);
(await service.AnalyzeFrameAsync([1])).ShouldBeNull();
}
[Fact]
public void YoloCoordinates_UseOriginalFullHdDimensions()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var output = new float[84];
output[0] = 320; output[1] = 320; output[2] = 320; output[3] = 320; output[4] = .9f;
var box = service.ParseYoloOutput(output, 1920, 1080).Single();
box.X.ShouldBe(480); box.Y.ShouldBe(270); box.Width.ShouldBe(960); box.Height.ShouldBe(540);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Preprocess_NormalizesExplicitRgbChannels(bool grayscale)
{
using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Red, 640, 640);
if (grayscale) image.ColorType = ImageMagick.ColorType.Grayscale;
else image.Alpha(ImageMagick.AlphaOption.On);
var tensor = FrameAnalyzerService.PreprocessImage(image);
tensor.Dimensions.ToArray().ShouldBe(new[] { 1, 3, 640, 640 });
tensor.ToArray().ShouldAllBe(v => v >= 0 && v <= 1);
if (!grayscale) { tensor[0, 0, 0, 0].ShouldBe(1); tensor[0, 1, 0, 0].ShouldBe(0); }
}
[Fact]
public async Task RealOnnx_CpuModel_ProcessesFullHdImage()
{
var root = new DirectoryInfo(AppContext.BaseDirectory);
while (root is not null && !File.Exists(Path.Combine(root.FullName, "models/yolov8n.onnx"))) root = root.Parent;
root.ShouldNotBeNull("The repository YOLO fixture must be present");
using var analyzer = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>(), null, null, null,
Path.Combine(root.FullName, "models/yolov8n.onnx"));
analyzer.ModelAvailable.ShouldBeTrue();
analyzer.ExecutionProvider.ShouldBe("CPUExecutionProvider");
using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Black, 1920, 1080);
var result = await analyzer.AnalyzeFrameAsync(image.ToByteArray(ImageMagick.MagickFormat.Jpeg)).WaitAsync(TimeSpan.FromSeconds(30));
result.ShouldNotBeNull();
result.Detections.ShouldBeEmpty();
}
[Fact]
public async Task FaultedInference_CompletesJob_AndNextJobStillRuns()
{
using var analyzer = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>(), null, null,
(data, _) => data[0] == 0 ? throw new InvalidOperationException("fixture") : []);
(await analyzer.AnalyzeFrameAsync([0]).WaitAsync(TimeSpan.FromSeconds(5))).ShouldBeNull();
(await analyzer.AnalyzeFrameAsync([1]).WaitAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull();
}
// ── NMS unit tests ──────────────────────────────────────────────
[Fact]
public void ApplyNms_EmptyList_ReturnsEmpty()
{
var result = FrameAnalyzerService.ApplyNms([]);
result.ShouldBeEmpty();
}
[Fact]
public void ApplyNms_SingleDetection_ReturnsItUnchanged()
{
var input = new List<FrameAnalyzerService.RawDetection>
{
new(10, 10, 50, 50, 0.9f, 0)
};
var result = FrameAnalyzerService.ApplyNms(input);
result.Length.ShouldBe(1);
result[0].Label.ShouldBe("person");
result[0].Confidence.ShouldBe(0.9f, 0.001f);
}
[Fact]
public void ApplyNms_TwoOverlapping_SameClass_KeepsHigherConfidence()
{
var input = new List<FrameAnalyzerService.RawDetection>
{
new(10, 10, 50, 50, 0.9f, 0), // person, high confidence
new(12, 12, 52, 52, 0.7f, 0), // person, overlapping, lower
};
var result = FrameAnalyzerService.ApplyNms(input);
result.Length.ShouldBe(1);
result[0].Confidence.ShouldBe(0.9f, 0.001f);
}
[Fact]
public void ApplyNms_TwoOverlapping_DifferentClass_KeepsBoth()
{
var input = new List<FrameAnalyzerService.RawDetection>
{
new(10, 10, 50, 50, 0.9f, 0), // person
new(12, 12, 52, 52, 0.8f, 2), // car, overlapping but different class
};
var result = FrameAnalyzerService.ApplyNms(input);
result.Length.ShouldBe(2);
}
[Fact]
public void ApplyNms_TwoNonOverlapping_KeepsBoth()
{
var input = new List<FrameAnalyzerService.RawDetection>
{
new(10, 10, 50, 50, 0.9f, 0), // top-left
new(200, 200, 250, 250, 0.8f, 0), // bottom-right
};
var result = FrameAnalyzerService.ApplyNms(input);
result.Length.ShouldBe(2);
}
[Fact]
public void ApplyNms_ThreeDetections_MixedOverlaps_KeepsBest()
{
var input = new List<FrameAnalyzerService.RawDetection>
{
new(10, 10, 50, 50, 0.9f, 0), // person, best
new(11, 11, 51, 51, 0.8f, 0), // person, overlaps with #1 → suppressed
new(12, 12, 52, 52, 0.7f, 0), // person, overlaps with #1 → suppressed
};
var result = FrameAnalyzerService.ApplyNms(input);
result.Length.ShouldBe(1);
result[0].Confidence.ShouldBe(0.9f, 0.001f);
}
[Fact]
public void ApplyNms_BoundingBoxConvertedCorrectly()
{
// RawDetection(10, 20, 60, 80) → DetectionResult(X=10, Y=20, Width=50, Height=60)
var input = new List<FrameAnalyzerService.RawDetection>
{
new(10, 20, 60, 80, 0.95f, 0)
};
var result = FrameAnalyzerService.ApplyNms(input);
result.Length.ShouldBe(1);
result[0].X.ShouldBe(10f, 0.001f);
result[0].Y.ShouldBe(20f, 0.001f);
result[0].Width.ShouldBe(50f, 0.001f);
result[0].Height.ShouldBe(60f, 0.001f);
}
[Fact]
public void ApplyNms_ClassIndexMappedToLabel()
{
var input = new List<FrameAnalyzerService.RawDetection>
{
new(0, 0, 10, 10, 0.5f, 2), // class 2 = "car"
new(0, 0, 10, 10, 0.5f, 15), // class 15 = "cat"
new(0, 0, 10, 10, 0.5f, 79), // class 79 = "toothbrush"
};
var result = FrameAnalyzerService.ApplyNms(input);
// Different classes → all kept (IoU = 1.0 but different class)
result.Length.ShouldBe(3);
result.ShouldContain(d => d.Label == "car");
result.ShouldContain(d => d.Label == "cat");
result.ShouldContain(d => d.Label == "toothbrush");
}
[Fact]
public void ApplyNms_UnknownClassIndex_GeneratesFallbackLabel()
{
var input = new List<FrameAnalyzerService.RawDetection>
{
new(0, 0, 10, 10, 0.5f, 999)
};
var result = FrameAnalyzerService.ApplyNms(input);
result.Length.ShouldBe(1);
result[0].Label.ShouldBe("class_999");
}
// ── Spec compliance tests ─────────────────────────────────────
[Fact]
public void DefaultMinConfidence_MatchesSpec()
{
// Spec §16: CameraDetectionProfile.MinConfidence defaults to 0.4
FrameAnalyzerService.DefaultMinConfidence.ShouldBe(0.4f);
}
[Fact]
public async Task AnalyzeFrameAsync_WithCustomMinConfidence_Passthrough_ReturnsNull()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var result = await service.AnalyzeFrameAsync([1, 2, 3], minConfidence: 0.6f);
result.ShouldBeNull();
}
[Fact]
public void AnalyzeFrame_WithCustomMinConfidence_Passthrough_ReturnsNull()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var result = service.AnalyzeFrame([1, 2, 3], minConfidence: 0.6f);
result.ShouldBeNull();
}
[Fact]
public async Task AnalyzeFrameAsync_DefaultMinConfidence_Passthrough_ReturnsNull()
{
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
// Default 0.4 threshold should work identically in passthrough
var result = await service.AnalyzeFrameAsync([1, 2, 3]);
result.ShouldBeNull();
}
}