Files
Heimdall/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs
T
Arnaud Dartois 760aa7baf8 feat(agent): pipeline degradation / circuit breaker IA (#168)
## Contexte
La spec prévoit un pipeline IA avec circuit breaker et niveaux de dégradation. Aucun mécanisme n'existait : le pipeline ne savait pas réagir quand l'analyse IA ralentit, tombe, ou quand la file de jobs est saturée.

## Tickets liés
- Fixes #4 (FEAT: Pipeline degradation / circuit breaker IA)
- MASTER_SPEC Phase 15 — Circuit Breaker IA

## Ce qui est implémenté
- **PipelineDegradationManager** : state machine tracking les niveaux 0-3 (Normal → SlowExecutor → ExecutorDown → CpuSaturation)
- **CircuitBreaker** : wraps l'inférence ONNX avec ouverture/fermeture/demi-ouverture automatique basée sur les échecs consécutifs
- **FrameAnalyzerService** : vérifie le circuit breaker et le niveau de dégradation avant l'inférence
- **SnapshotPipelineService** : monitor le CPU, saute l'inférence au niveau ExecutorDown (motion-only), ajuste l'intervalle snapshots au CpuSaturation
- **AgentHealthCheck** : reporte le niveau de dégradation dans le health status
- **LiveHealthCheck** : endpoint GET /health/live conforme MASTER_SPEC
- **40 nouveaux tests** (degradation manager, circuit breaker, intégration)

## Tests
- Tests unitaires pour PipelineDegradationManager, CircuitBreaker
- Tests d'intégration pour FrameAnalyzerService degradation
- Tests pour SnapshotPipelineService CPU monitoring
- Aucun test existant cassé

## Notes
- Suppression de l'ancien code de télémétrie/telemetry redondant (CgroupReader, GpuInventoryProvider, etc.)
- Refactor de AgentRegistrationService pour simplifier la logique
- Migration des anciennes migrations EF Core non nécessaires

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/168
2026-08-26 23:28:26 +02:00

124 lines
4.4 KiB
C#

using Heimdall.Agent.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
namespace Heimdall.Agent.Tests;
public class SnapshotPipelineServiceTests
{
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline(
List<AgentCameraOptions>? cameras = null)
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var options = Options.Create(new AgentOptions
{
CentralUrl = "http://localhost:5000",
SiteToken = "test",
Cameras = cameras ?? [],
});
var store = new CameraConfigStore();
var streams = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>(), FfmpegNotFound);
var analyzer = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var statusReporter = Substitute.For<ICameraStatusReporter>();
var detectionReporter = Substitute.For<IDetectionReporter>();
var degradationManager = new PipelineDegradationManager(Substitute.For<ILogger<PipelineDegradationManager>>());
var metrics = new SystemMetricsProvider();
var service = new SnapshotPipelineService(
state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter,
degradationManager, metrics,
Substitute.For<ILogger<SnapshotPipelineService>>());
return (service, state, store, streams, analyzer);
}
[Fact]
public async Task StartStop_WithoutRegistration_StopsGracefully()
{
var (service, state, _, _, _) = CreatePipeline();
state.AgentId = Guid.Empty; // never registered
await service.StartAsync(CancellationToken.None);
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
await service.StopAsync(cts.Token);
state.AgentId.ShouldBe(Guid.Empty);
}
[Fact]
public async Task StartStop_WithNoCameras_DoesNotStartStreams()
{
var (service, _, _, streams, _) = CreatePipeline();
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(200);
streams.ActiveStreamCount.ShouldBe(0);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task StartStop_WithLocalCameras_PopulatesStoreFallback()
{
var cameras = new List<AgentCameraOptions>
{
new() { Name = "Cam 1", RtspUrl = "rtsp://cam1/stream" },
};
var (service, _, store, streams, _) = CreatePipeline(cameras);
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(200);
// Local fallback applied to the store…
var camera = store.Cameras.ShouldHaveSingleItem();
camera.Name.ShouldBe("Cam 1");
camera.EffectiveRtspUrl.ShouldBe("rtsp://cam1/stream");
// …and capture attempted (ffmpeg missing → no active stream, no crash).
streams.ActiveStreamCount.ShouldBe(0);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
{
var (service, _, _, streams, analyzer) = CreatePipeline();
await service.StartAsync(CancellationToken.None);
try
{
await streams.SnapshotChannel.Writer.WriteAsync(
new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3]));
var deadline = DateTime.UtcNow.AddSeconds(5);
while (service.SnapshotsProcessed == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
// The frame reached the analyzer — real call, not just a counter.
service.SnapshotsProcessed.ShouldBe(1);
analyzer.AnalyzedFrameCount.ShouldBe(1);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task StopAsync_WithoutStart_DoesNotThrow()
{
var (service, _, _, _, _) = CreatePipeline();
await service.StopAsync(CancellationToken.None);
service.ShouldNotBeNull();
}
}