fix(agent): bound inference work and drain ONNX before disposal #6
No files matched your search
@@ -73,6 +73,9 @@ public sealed class AnalysisJobConsumer : IConsumer<AnalysisJobRequested>
|
||||
var result = await _frameAnalyzer.AnalyzeFrameAsync(
|
||||
frameData, ct: context.CancellationToken);
|
||||
|
||||
if (result is null)
|
||||
throw new InvalidOperationException("Inference unavailable, skipped or saturated; no detection result produced");
|
||||
|
||||
stopwatch.Stop();
|
||||
|
||||
var detections = result?.Detections;
|
||||
|
||||
@@ -10,11 +10,13 @@ namespace Heimdall.Agent.Services;
|
||||
public sealed class AgentHealthCheck : IHealthCheck
|
||||
{
|
||||
private readonly AgentState _state;
|
||||
private readonly FrameAnalyzerService? _analyzer;
|
||||
private readonly PipelineDegradationManager _degradationManager;
|
||||
|
||||
public AgentHealthCheck(AgentState state, PipelineDegradationManager degradationManager)
|
||||
public AgentHealthCheck(AgentState state, PipelineDegradationManager degradationManager, FrameAnalyzerService? analyzer = null)
|
||||
{
|
||||
_state = state;
|
||||
_analyzer = analyzer;
|
||||
_degradationManager = degradationManager;
|
||||
}
|
||||
|
||||
@@ -34,11 +36,18 @@ public sealed class AgentHealthCheck : IHealthCheck
|
||||
"Agent registered but has no API key configured"));
|
||||
}
|
||||
|
||||
if (_analyzer is { ModelAvailable: false })
|
||||
return Task.FromResult(HealthCheckResult.Unhealthy("Detection model unavailable; CPU inference cannot run"));
|
||||
var level = _degradationManager.Level;
|
||||
if (level == DegradationLevel.Normal)
|
||||
{
|
||||
return Task.FromResult(HealthCheckResult.Healthy(
|
||||
"Agent is registered and operational"));
|
||||
"Agent is registered and operational", data: new Dictionary<string, object>
|
||||
{
|
||||
["executionProvider"] = _analyzer?.ExecutionProvider ?? "unknown",
|
||||
["modelAvailable"] = _analyzer?.ModelAvailable ?? false,
|
||||
["rejectedFrames"] = _analyzer?.RejectedFrames ?? 0
|
||||
}));
|
||||
}
|
||||
|
||||
if (level == DegradationLevel.CpuSaturation)
|
||||
|
||||
@@ -32,6 +32,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
private readonly SystemMetricsProvider _metrics;
|
||||
private readonly InventoryProviders _providers;
|
||||
private readonly GpuDetectorService _gpu;
|
||||
private readonly FrameAnalyzerService? _analyzer;
|
||||
private readonly Logging.LogBufferService _buffer;
|
||||
private HttpClient? _client;
|
||||
|
||||
@@ -48,7 +49,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
InventoryProviders providers,
|
||||
GpuDetectorService gpu,
|
||||
Logging.LogBufferService buffer,
|
||||
ILogger<AgentRegistrationService> logger)
|
||||
ILogger<AgentRegistrationService> logger, FrameAnalyzerService? analyzer = null)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_state = state;
|
||||
@@ -58,6 +59,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
_gpu = gpu;
|
||||
_buffer = buffer;
|
||||
_logger = logger;
|
||||
_analyzer = analyzer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -236,6 +238,9 @@ public class AgentRegistrationService : BackgroundService
|
||||
|
||||
return new HeartbeatRequest(
|
||||
_state.PublicIp,
|
||||
HasGpu: false, // The shipped ONNX package executes on CPU; hardware inventory is separate.
|
||||
CpuCores: _analyzer is { ModelAvailable: false } ? 0 : Environment.ProcessorCount,
|
||||
MemoryMb: totalMemoryMb,
|
||||
CpuUsagePercent: metrics.CpuUsagePercent,
|
||||
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
||||
DiskUsagePercent: metrics.DiskUsagePercent,
|
||||
@@ -348,6 +353,9 @@ internal sealed record HeartbeatRequest(
|
||||
[property: JsonPropertyName("diskUsagePercent")] double? DiskUsagePercent = null,
|
||||
[property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null,
|
||||
[property: JsonPropertyName("machineUptimeSeconds")] long? MachineUptimeSeconds = null,
|
||||
[property: JsonPropertyName("hasGpu")] bool? HasGpu = null,
|
||||
[property: JsonPropertyName("cpuCores")] int? CpuCores = null,
|
||||
[property: JsonPropertyName("memoryMb")] long? MemoryMb = null,
|
||||
// CPU inventory
|
||||
[property: JsonPropertyName("cpuVendor")] string? CpuVendor = null,
|
||||
[property: JsonPropertyName("cpuModel")] string? CpuModel = null,
|
||||
|
||||
@@ -29,8 +29,7 @@ public sealed record FrameAnalysisResult(
|
||||
/// Model file expected at: models/yolov8n.onnx (relative to app root)
|
||||
/// or configured via MODEL_PATH environment variable.
|
||||
///
|
||||
/// If no model file is found, runs in "passthrough" mode — returns
|
||||
/// empty detections without crashing.
|
||||
/// If no compatible model is found, analysis is unavailable (null), never a negative detection.
|
||||
///
|
||||
/// Integrates with <see cref="CircuitBreaker"/> and
|
||||
/// <see cref="PipelineDegradationManager"/> for graceful degradation:
|
||||
@@ -41,11 +40,17 @@ public sealed record FrameAnalysisResult(
|
||||
public sealed class FrameAnalyzerService : IDisposable
|
||||
{
|
||||
private readonly ILogger<FrameAnalyzerService> _logger;
|
||||
private readonly Func<byte[], float, DetectionResult[]>? _testInference;
|
||||
private readonly string _modelPath;
|
||||
private readonly bool _modelLoaded;
|
||||
private readonly InferenceSession? _session;
|
||||
private readonly string _inputName = "";
|
||||
private readonly int _numClasses;
|
||||
private readonly int _numClasses = 80;
|
||||
private readonly object _inferenceLock = new();
|
||||
private long _rejectedFrames;
|
||||
public long RejectedFrames => Interlocked.Read(ref _rejectedFrames);
|
||||
public bool ModelAvailable => _modelLoaded;
|
||||
public string ExecutionProvider => "CPUExecutionProvider";
|
||||
private readonly CircuitBreaker? _circuitBreaker;
|
||||
private readonly PipelineDegradationManager? _degradationManager;
|
||||
|
||||
@@ -98,26 +103,36 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
public FrameAnalyzerService(
|
||||
ILogger<FrameAnalyzerService> logger,
|
||||
CircuitBreaker? circuitBreaker,
|
||||
PipelineDegradationManager? degradationManager)
|
||||
PipelineDegradationManager? degradationManager) : this(logger, circuitBreaker, degradationManager, null) { }
|
||||
|
||||
internal FrameAnalyzerService(ILogger<FrameAnalyzerService> logger, CircuitBreaker? circuitBreaker,
|
||||
PipelineDegradationManager? degradationManager, Func<byte[], float, DetectionResult[]>? inference, string? modelPath = null)
|
||||
{
|
||||
_testInference = inference;
|
||||
_logger = logger;
|
||||
_circuitBreaker = circuitBreaker;
|
||||
_degradationManager = degradationManager;
|
||||
_modelPath = Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8n.onnx";
|
||||
_modelLoaded = File.Exists(_modelPath);
|
||||
_modelPath = modelPath ?? Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8n.onnx";
|
||||
_modelLoaded = inference is not null || File.Exists(_modelPath);
|
||||
|
||||
if (_modelLoaded)
|
||||
if (_modelLoaded && inference is null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions
|
||||
using var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions
|
||||
{
|
||||
InterOpNumThreads = 1,
|
||||
IntraOpNumThreads = 2, // spec §16: limit CPU threads for agent
|
||||
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
|
||||
};
|
||||
_session = new InferenceSession(_modelPath, sessionOptions);
|
||||
_inputName = _session.InputMetadata.Keys.ToArray()[0];
|
||||
_inputName = _session.InputMetadata.Keys.Single();
|
||||
var input = _session.InputMetadata[_inputName];
|
||||
var output = _session.OutputMetadata.Values.Single();
|
||||
if (input.ElementType != typeof(float) || !input.Dimensions.SequenceEqual(new[] { 1, 3, InputSize, InputSize }) ||
|
||||
output.ElementType != typeof(float) || output.Dimensions.Length != 3 || output.Dimensions[0] != 1 ||
|
||||
output.Dimensions[1] != 84 || output.Dimensions[2] <= 0)
|
||||
throw new InvalidOperationException("Expected COCO YOLOv8 float NCHW [1,3,640,640] -> [1,84,N]");
|
||||
|
||||
// Determine number of classes from output shape [1, 4+C, 8400]
|
||||
var outputMeta = _session.OutputMetadata.Values.ToArray()[0];
|
||||
@@ -135,17 +150,15 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
_modelLoaded = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
else if (!_modelLoaded)
|
||||
{
|
||||
_logger.LogWarning("FrameAnalyzer in passthrough mode — model not found at {ModelPath}", _modelPath);
|
||||
_logger.LogWarning("FrameAnalyzer unavailable — model not found at {ModelPath}", _modelPath);
|
||||
}
|
||||
|
||||
_frameQueue = Channel.CreateBounded<FrameJob>(new BoundedChannelOptions(MaxQueueSize)
|
||||
{
|
||||
// DropWrite rejects new writes when full with TryWrite=false,
|
||||
// allowing the caller to gracefully complete the TCS with null.
|
||||
// DropOldest would orphan the oldest job's TaskCompletionSource.
|
||||
FullMode = BoundedChannelFullMode.DropWrite,
|
||||
// Wait mode makes TryWrite return false on saturation; no accepted job is dropped.
|
||||
FullMode = BoundedChannelFullMode.Wait,
|
||||
SingleReader = true,
|
||||
SingleWriter = false
|
||||
});
|
||||
@@ -155,8 +168,8 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
|
||||
/// <summary>
|
||||
/// Submit a JPEG frame for analysis. Returns a task that completes when
|
||||
/// analysis is done. If the queue is full, drops the oldest frame.
|
||||
/// Returns empty detections if model not loaded (passthrough mode).
|
||||
/// analysis is done. If the queue is full, explicitly rejects the new frame.
|
||||
/// Returns null when inference is unavailable.
|
||||
/// Respects circuit breaker and degradation level.
|
||||
/// </summary>
|
||||
/// <param name="jpegData">Raw JPEG frame bytes.</param>
|
||||
@@ -186,15 +199,16 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!_modelLoaded)
|
||||
if (!_modelLoaded || _disposed)
|
||||
return null;
|
||||
|
||||
var tcs = new TaskCompletionSource<FrameAnalysisResult?>();
|
||||
var tcs = new TaskCompletionSource<FrameAnalysisResult?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var job = new FrameJob(jpegData, tcs, minConfidence);
|
||||
|
||||
// If queue is full (DropWrite rejected our write), complete TCS with fallback
|
||||
// Wait mode rejects TryWrite when full; every accepted job is completed by the reader.
|
||||
if (!_frameQueue.Writer.TryWrite(job))
|
||||
{
|
||||
Interlocked.Increment(ref _rejectedFrames);
|
||||
tcs.TrySetResult(null);
|
||||
return null;
|
||||
}
|
||||
@@ -211,33 +225,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
byte[] jpegData,
|
||||
float minConfidence = DefaultMinConfidence)
|
||||
{
|
||||
Interlocked.Increment(ref _analyzedFrameCount);
|
||||
if (!_modelLoaded) return null;
|
||||
|
||||
// Circuit breaker: skip if open
|
||||
if (_circuitBreaker is not null && !_circuitBreaker.ShouldAllowCall())
|
||||
{
|
||||
Interlocked.Increment(ref _skippedByCircuitBreaker);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Degradation: skip if level >= ExecutorDown
|
||||
if (_degradationManager is not null && !_degradationManager.ShouldUseInference())
|
||||
{
|
||||
Interlocked.Increment(ref _skippedByDegradation);
|
||||
return null;
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var detections = RunInference(jpegData, minConfidence);
|
||||
sw.Stop();
|
||||
|
||||
ReportInferenceResult(sw.ElapsedMilliseconds);
|
||||
|
||||
return new FrameAnalysisResult(
|
||||
Convert.ToBase64String(jpegData),
|
||||
detections,
|
||||
sw.ElapsedMilliseconds);
|
||||
return AnalyzeFrameAsync(jpegData, minConfidence).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
private async Task ProcessingLoopAsync(CancellationToken ct)
|
||||
@@ -299,10 +287,15 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
/// <param name="minConfidence">Minimum confidence threshold (default 0.4 per spec §16).</param>
|
||||
internal DetectionResult[] RunInference(byte[] jpegData, float minConfidence = DefaultMinConfidence)
|
||||
{
|
||||
if (_testInference is not null) return _testInference(jpegData, minConfidence);
|
||||
if (_session is null)
|
||||
return [];
|
||||
|
||||
lock (_inferenceLock)
|
||||
{
|
||||
using var image = new MagickImage(jpegData);
|
||||
var originalWidth = (int)image.Width;
|
||||
var originalHeight = (int)image.Height;
|
||||
image.Format = MagickFormat.Jpeg;
|
||||
|
||||
// Resize to model input size (640×640), ignoring aspect ratio (like ImageSharp Resize(640,640))
|
||||
@@ -315,22 +308,25 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
NamedOnnxValue.CreateFromTensor(_inputName, inputTensor)
|
||||
};
|
||||
|
||||
using var results = _session.Run(inputs);
|
||||
using var runOptions = new RunOptions();
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
using var timeoutRegistration = timeout.Token.Register(() => runOptions.Terminate = true);
|
||||
using var results = _session.Run(inputs, _session.OutputNames, runOptions);
|
||||
var output = results[0].AsTensor<float>().ToArray();
|
||||
|
||||
return ParseYoloOutput(output, (int)image.Width, (int)image.Height, minConfidence);
|
||||
return ParseYoloOutput(output, originalWidth, originalHeight, minConfidence);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert Magick.NET image to a normalized NCHW tensor [1, 3, 640, 640].
|
||||
/// YOLOv8 expects RGB channels, each normalized to [0, 1].
|
||||
/// </summary>
|
||||
private static DenseTensor<float> PreprocessImage(MagickImage image)
|
||||
internal static DenseTensor<float> PreprocessImage(MagickImage image)
|
||||
{
|
||||
var tensor = new DenseTensor<float>([1, 3, InputSize, InputSize]);
|
||||
// GetPixels().ToArray() returns contiguous interleaved RGB channel values
|
||||
// (Q16 build => ushort ranging 0..65535), row-major.
|
||||
var rgb = image.GetPixels()?.ToArray() ?? [];
|
||||
// Explicit RGB mapping handles grayscale, CMYK and alpha; byte export normalizes Q16 to 8 bits.
|
||||
var rgb = image.GetPixels().ToByteArray(PixelMapping.RGB) ?? throw new InvalidOperationException("RGB conversion failed");
|
||||
|
||||
var idx = 0;
|
||||
for (var y = 0; y < InputSize; y++)
|
||||
@@ -338,7 +334,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
for (var x = 0; x < InputSize; x++)
|
||||
{
|
||||
for (var c = 0; c < 3; c++)
|
||||
tensor[0, c, y, x] = rgb[idx++] / 65535f;
|
||||
tensor[0, c, y, x] = rgb[idx++] / 255f;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,23 +469,22 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
float X1, float Y1, float X2, float Y2,
|
||||
float Score, int ClassIdx);
|
||||
|
||||
private bool _disposed;
|
||||
private volatile bool _disposed;
|
||||
private readonly object _disposeLock = new();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_disposeLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
_frameQueue.Writer.TryComplete();
|
||||
_session?.Dispose();
|
||||
|
||||
// Log unobserved exceptions from the processing loop
|
||||
_processingLoop.ContinueWith(t =>
|
||||
{
|
||||
if (t.IsFaulted)
|
||||
_logger.LogCritical(t.Exception, "FrameAnalyzer processing loop crashed");
|
||||
}, TaskContinuationOptions.OnlyOnFaulted);
|
||||
// Drain accepted work before releasing the native session.
|
||||
_processingLoop.GetAwaiter().GetResult();
|
||||
lock (_inferenceLock)
|
||||
_session?.Dispose();
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record FrameJob(byte[] ImageData, TaskCompletionSource<FrameAnalysisResult?> Tcs, float MinConfidence);
|
||||
|
||||
@@ -73,6 +73,76 @@ public class FrameAnalyzerServiceTests
|
||||
results.ShouldAllBe(r => r == null);
|
||||
}
|
||||
|
||||
[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]
|
||||
|
||||
Reference in new issue
Block a user