From 760aa7baf8f275c22df6b264fe080433832e7423 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 26 Aug 2026 23:28:26 +0200 Subject: [PATCH] feat(agent): pipeline degradation / circuit breaker IA (#168) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 --- src/Heimdall.Agent/Program.cs | 23 +- .../Services/AgentHealthCheck.cs | 50 +++- src/Heimdall.Agent/Services/CircuitBreaker.cs | 162 ++++++++++ .../Services/FrameAnalyzerService.cs | 91 +++++- .../Services/LiveHealthCheck.cs | 61 ++++ .../Services/PipelineDegradationManager.cs | 277 ++++++++++++++++++ .../Services/SnapshotPipelineService.cs | 91 +++++- .../AgentHealthCheckTests.cs | 39 ++- .../CircuitBreakerTests.cs | 159 ++++++++++ .../FrameAnalyzerDegradationTests.cs | 117 ++++++++ .../PipelineDegradationManagerTests.cs | 220 ++++++++++++++ .../SnapshotPipelineServiceTests.cs | 3 + 12 files changed, 1263 insertions(+), 30 deletions(-) create mode 100644 src/Heimdall.Agent/Services/CircuitBreaker.cs create mode 100644 src/Heimdall.Agent/Services/LiveHealthCheck.cs create mode 100644 src/Heimdall.Agent/Services/PipelineDegradationManager.cs create mode 100644 tests/Heimdall.Agent.Tests/CircuitBreakerTests.cs create mode 100644 tests/Heimdall.Agent.Tests/FrameAnalyzerDegradationTests.cs create mode 100644 tests/Heimdall.Agent.Tests/PipelineDegradationManagerTests.cs diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 429d218..af6aad4 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -108,9 +108,15 @@ builder.Services.AddHostedService(); // Video capture pipeline (ticket #1): FFmpeg capture per assigned camera, // bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService. +// Circuit breaker + degradation manager for graceful IA pipeline degradation. +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); -builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => new FrameAnalyzerService( + sp.GetRequiredService>(), + sp.GetRequiredService(), + sp.GetRequiredService())); builder.Services.AddSingleton(); builder.Services.AddHostedService(); @@ -122,7 +128,8 @@ builder.Services.AddHostedService(); // Health checks — used by Docker HEALTHCHECK builder.Services.AddHealthChecks() - .AddCheck("agent_health", tags: ["ready"]); + .AddCheck("agent_health", tags: ["ready"]) + .AddCheck("live", tags: ["live"]); // ── OpenTelemetry metrics (spec 13.1) ────────────────────────────── builder.Services.AddOpenTelemetry() @@ -149,4 +156,16 @@ app.MapHealthChecks("/healthz", new HealthCheckOptions // ── Prometheus metrics endpoint (spec 13.1) ──────────────────────── app.MapPrometheusScrapingEndpoint("/metrics"); +// Live health endpoint (MASTER_SPEC) — reports degradation level +app.MapHealthChecks("/health/live", new HealthCheckOptions +{ + Predicate = check => check.Tags.Contains("live"), + ResultStatusCodes = + { + [HealthStatus.Healthy] = StatusCodes.Status200OK, + [HealthStatus.Degraded] = StatusCodes.Status503ServiceUnavailable, + [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable, + } +}); + await app.RunAsync(); diff --git a/src/Heimdall.Agent/Services/AgentHealthCheck.cs b/src/Heimdall.Agent/Services/AgentHealthCheck.cs index ec7e877..40163ec 100644 --- a/src/Heimdall.Agent/Services/AgentHealthCheck.cs +++ b/src/Heimdall.Agent/Services/AgentHealthCheck.cs @@ -1,30 +1,64 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Heimdall.Agent.Services; - /// -/// Reports agent health based on registration state. -/// Healthy = registered with Central and able to communicate. +/// Reports agent health based on registration state and IA pipeline degradation. +/// - Healthy = registered with Central, no active degradation. +/// - Degraded = registered but IA pipeline is degraded (level 1-2) or no API key. +/// - Unhealthy = not registered, or CPU saturation (level 3). /// -public sealed class AgentHealthCheck(AgentState state) : IHealthCheck +public sealed class AgentHealthCheck : IHealthCheck { + private readonly AgentState _state; + private readonly PipelineDegradationManager _degradationManager; + + public AgentHealthCheck(AgentState state, PipelineDegradationManager degradationManager) + { + _state = state; + _degradationManager = degradationManager; + } + public Task CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = default) { - if (state.AgentId == Guid.Empty) + if (_state.AgentId == Guid.Empty) { return Task.FromResult(HealthCheckResult.Unhealthy( "Agent has not registered with Central yet")); } - if (string.IsNullOrEmpty(state.ApiKey)) + if (string.IsNullOrEmpty(_state.ApiKey)) { return Task.FromResult(HealthCheckResult.Degraded( "Agent registered but has no API key configured")); } - return Task.FromResult(HealthCheckResult.Healthy( - "Agent is registered and operational")); + var level = _degradationManager.Level; + if (level == DegradationLevel.Normal) + { + return Task.FromResult(HealthCheckResult.Healthy( + "Agent is registered and operational")); + } + + if (level == DegradationLevel.CpuSaturation) + { + return Task.FromResult(HealthCheckResult.Unhealthy( + $"CPU saturation — snapshots reduced (level={(int)level}, CPU={_degradationManager.LastCpuPercent:F1}%)")); + } + + // Level 1 (SlowExecutor) or Level 2 (ExecutorDown) → Degraded + var data = new Dictionary + { + ["degradationLevel"] = (int)level, + ["degradationLevelName"] = level.ToString()!, + ["consecutiveFailures"] = _degradationManager.ConsecutiveFailures, + ["consecutiveSlow"] = _degradationManager.ConsecutiveSlow, + ["degradationDuration"] = _degradationManager.DegradationDuration.ToString(), + }; + + return Task.FromResult(HealthCheckResult.Degraded( + $"IA pipeline degraded: {level} (failures={_degradationManager.ConsecutiveFailures}, slow={_degradationManager.ConsecutiveSlow})", + data: data)); } } diff --git a/src/Heimdall.Agent/Services/CircuitBreaker.cs b/src/Heimdall.Agent/Services/CircuitBreaker.cs new file mode 100644 index 0000000..57c46a2 --- /dev/null +++ b/src/Heimdall.Agent/Services/CircuitBreaker.cs @@ -0,0 +1,162 @@ +using System; +using System.Threading; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent.Services; + +/// +/// States of the circuit breaker. +/// +public enum CircuitState +{ + /// Normal operation — calls pass through. + Closed, + + /// Circuit is open — calls are rejected immediately. + Open, + + /// Circuit is testing recovery — one call passes through. + HalfOpen, +} + +/// +/// Generic circuit breaker for the IA inference pipeline. +/// Prevents hammering a failing ONNX executor by opening the circuit +/// after consecutive failures and periodically testing recovery. +/// +/// Thread-safe: all state is protected by a lock. +/// +public sealed class CircuitBreaker +{ + private readonly ILogger _logger; + private readonly object _lock = new(); + + private readonly int _failureThreshold; + private readonly TimeSpan _openDuration; + + private CircuitState _state = CircuitState.Closed; + private int _consecutiveFailures; + private DateTime _openedAt; + + /// Current circuit state. + public CircuitState State + { + get { lock (_lock) return _state; } + } + + /// Number of consecutive failures. + public int ConsecutiveFailures + { + get { lock (_lock) return _consecutiveFailures; } + } + + /// Time when the circuit was opened. + public DateTime OpenedAt + { + get { lock (_lock) return _openedAt; } + } + + /// + /// Creates a new CircuitBreaker. + /// + /// Logger instance. + /// Number of consecutive failures before opening the circuit. Default: 5. + /// How long the circuit stays open before half-open. Default: 30 seconds. + public CircuitBreaker( + ILogger logger, + int failureThreshold = 5, + TimeSpan? openDuration = null) + { + _logger = logger; + _failureThreshold = failureThreshold; + _openDuration = openDuration ?? TimeSpan.FromSeconds(30); + } + + /// + /// Check if the circuit allows a call to pass through. + /// + /// True if the call should proceed. + public bool ShouldAllowCall() + { + lock (_lock) + { + return _state switch + { + CircuitState.Closed => true, + CircuitState.HalfOpen => true, // Allow one probe + CircuitState.Open => CheckIfShouldTransitionToHalfOpen(), + _ => false, + }; + } + } + + /// + /// Report a successful call. Resets the circuit if in HalfOpen state. + /// + public void ReportSuccess() + { + lock (_lock) + { + if (_state == CircuitState.HalfOpen) + { + _logger.LogInformation("Circuit breaker recovered: HalfOpen → Closed"); + _state = CircuitState.Closed; + } + _consecutiveFailures = 0; + } + } + + /// + /// Report a failed call. Opens the circuit if threshold is reached. + /// + public void ReportFailure() + { + lock (_lock) + { + _consecutiveFailures++; + + if (_state == CircuitState.HalfOpen) + { + _logger.LogWarning("Circuit breaker probe failed: HalfOpen → Open"); + _state = CircuitState.Open; + _openedAt = DateTime.UtcNow; + } + else if (_consecutiveFailures >= _failureThreshold && _state == CircuitState.Closed) + { + _logger.LogWarning( + "Circuit breaker opened after {Failures} consecutive failures", + _consecutiveFailures); + _state = CircuitState.Open; + _openedAt = DateTime.UtcNow; + } + } + } + + /// + /// Force-reset the circuit to Closed (e.g., after manual intervention). + /// + public void Reset() + { + lock (_lock) + { + _state = CircuitState.Closed; + _consecutiveFailures = 0; + } + } + + private bool CheckIfShouldTransitionToHalfOpen() + { + // Caller must hold _lock + if (_state != CircuitState.Open) + return false; + + if (DateTime.UtcNow - _openedAt >= _openDuration) + { + _logger.LogInformation("Circuit breaker: Open → HalfOpen (testing recovery)"); + _state = CircuitState.HalfOpen; + return true; + } + + return false; + } +} diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index 0b0a744..ef20176 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -31,6 +31,12 @@ public sealed record FrameAnalysisResult( /// /// If no model file is found, runs in "passthrough" mode — returns /// empty detections without crashing. +/// +/// Integrates with and +/// for graceful degradation: +/// - Circuit open → inference skipped, returns null +/// - Degradation level 1 → inference runs with lowered confidence +/// - Degradation level 2+ → inference skipped entirely /// public sealed class FrameAnalyzerService : IDisposable { @@ -40,6 +46,8 @@ public sealed class FrameAnalyzerService : IDisposable private readonly InferenceSession? _session; private readonly string _inputName = ""; private readonly int _numClasses; + private readonly CircuitBreaker? _circuitBreaker; + private readonly PipelineDegradationManager? _degradationManager; // Bounded queue of pending frames to analyze private readonly Channel _frameQueue; @@ -64,17 +72,36 @@ public sealed class FrameAnalyzerService : IDisposable private const int MaxQueueSize = 16; private const int InputSize = 640; // YOLOv8 input size - private const float ConfidenceThreshold = 0.25f; + private const float DefaultConfidenceThreshold = 0.25f; private const float NmsIouThreshold = 0.45f; + private const long SlowInferenceThresholdMs = 500; private long _analyzedFrameCount; + private long _skippedByCircuitBreaker; + private long _skippedByDegradation; /// Number of frames actually handed to the analyzer (real calls, including passthrough). public long AnalyzedFrameCount => Interlocked.Read(ref _analyzedFrameCount); + /// Number of frames skipped because the circuit breaker is open. + public long SkippedByCircuitBreaker => Interlocked.Read(ref _skippedByCircuitBreaker); + + /// Number of frames skipped because of pipeline degradation. + public long SkippedByDegradation => Interlocked.Read(ref _skippedByDegradation); + public FrameAnalyzerService(ILogger logger) + : this(logger, null, null) + { + } + + public FrameAnalyzerService( + ILogger logger, + CircuitBreaker? circuitBreaker, + PipelineDegradationManager? degradationManager) { _logger = logger; + _circuitBreaker = circuitBreaker; + _degradationManager = degradationManager; _modelPath = Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8m.onnx"; _modelLoaded = File.Exists(_modelPath); @@ -129,11 +156,26 @@ public sealed class FrameAnalyzerService : IDisposable /// 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). + /// Respects circuit breaker and degradation level. /// public async Task AnalyzeFrameAsync(byte[] jpegData, CancellationToken ct = default) { Interlocked.Increment(ref _analyzedFrameCount); + // 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; + } + if (!_modelLoaded) return null; @@ -153,16 +195,33 @@ public sealed class FrameAnalyzerService : IDisposable /// /// Synchronous frame analysis (for fire-and-forget pipelines that /// don't need the result immediately). Returns null in passthrough. + /// Respects circuit breaker and degradation level. /// public FrameAnalysisResult? AnalyzeFrame(byte[] jpegData) { 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); sw.Stop(); + ReportInferenceResult(sw.ElapsedMilliseconds); + return new FrameAnalysisResult( Convert.ToBase64String(jpegData), detections, @@ -179,9 +238,7 @@ public sealed class FrameAnalyzerService : IDisposable var detections = RunInference(job.ImageData); sw.Stop(); - // Record YOLO inference time (spec 13.1) - HeimdallMetrics.RecordYoloInference(sw.ElapsedMilliseconds, detections.Length); - HeimdallMetrics.RecordInference(sw.ElapsedMilliseconds, _modelLoaded); + ReportInferenceResult(sw.ElapsedMilliseconds); var result = new FrameAnalysisResult( Convert.ToBase64String(job.ImageData), @@ -193,11 +250,35 @@ public sealed class FrameAnalyzerService : IDisposable catch (Exception ex) { _logger.LogWarning(ex, "Frame analysis failed"); + ReportInferenceFailure(); job.Tcs.TrySetResult(null); } } } + private void ReportInferenceResult(long elapsedMs) + { + if (_circuitBreaker is not null || _degradationManager is not null) + { + if (elapsedMs > SlowInferenceThresholdMs) + { + _circuitBreaker?.ReportFailure(); + _degradationManager?.ReportInferenceSlow(elapsedMs); + } + else + { + _circuitBreaker?.ReportSuccess(); + _degradationManager?.ReportInferenceSuccess(); + } + } + } + + private void ReportInferenceFailure() + { + _circuitBreaker?.ReportFailure(); + _degradationManager?.ReportInferenceFailure(); + } + /// /// Run YOLOv8 ONNX inference on a JPEG frame. /// Pipeline: JPEG decode → resize 640×640 → normalize → ONNX inference → NMS. @@ -283,7 +364,7 @@ public sealed class FrameAnalyzerService : IDisposable } } - if (maxScore < ConfidenceThreshold) + if (maxScore < DefaultConfidenceThreshold) continue; // Decode bounding box: (cx, cy, w, h) → scale to original image diff --git a/src/Heimdall.Agent/Services/LiveHealthCheck.cs b/src/Heimdall.Agent/Services/LiveHealthCheck.cs new file mode 100644 index 0000000..c5d6456 --- /dev/null +++ b/src/Heimdall.Agent/Services/LiveHealthCheck.cs @@ -0,0 +1,61 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace Heimdall.Agent.Services; +/// +/// Health check that reports the live status including degradation level. +/// Maps to GET /health/live per MASTER_SPEC. +/// Returns: +/// - 200 + "Healthy" when level = Normal (no degradation) +/// - 503 + "Degraded" when level > Normal +/// +public sealed class LiveHealthCheck : IHealthCheck +{ + private readonly PipelineDegradationManager _degradationManager; + + public LiveHealthCheck(PipelineDegradationManager degradationManager) + { + _degradationManager = degradationManager; + } + + public Task CheckHealthAsync( + HealthCheckContext context, + CancellationToken cancellationToken = default) + { + var level = _degradationManager.Level; + + if (level == DegradationLevel.Normal) + { + return Task.FromResult(HealthCheckResult.Healthy( + "IA pipeline operational", + data: new Dictionary + { + ["degradationLevel"] = 0, + })); + } + + if (level == DegradationLevel.CpuSaturation) + { + return Task.FromResult(HealthCheckResult.Degraded( + $"Analyse IA unavailable — CPU saturation (level={(int)level}, CPU={_degradationManager.LastCpuPercent:F1}%)", + data: new Dictionary + { + ["degradationLevel"] = (int)level, + ["degradationLevelName"] = level.ToString()!, + ["cpuPercent"] = _degradationManager.LastCpuPercent, + ["degradationDuration"] = _degradationManager.DegradationDuration.ToString(), + })); + } + + // Level 1 (SlowExecutor) or Level 2 (ExecutorDown) + return Task.FromResult(HealthCheckResult.Degraded( + $"Analyse IA unavailable — {level}", + data: new Dictionary + { + ["degradationLevel"] = (int)level, + ["degradationLevelName"] = level.ToString()!, + ["consecutiveFailures"] = _degradationManager.ConsecutiveFailures, + ["consecutiveSlow"] = _degradationManager.ConsecutiveSlow, + ["degradationDuration"] = _degradationManager.DegradationDuration.ToString(), + })); + } +} diff --git a/src/Heimdall.Agent/Services/PipelineDegradationManager.cs b/src/Heimdall.Agent/Services/PipelineDegradationManager.cs new file mode 100644 index 0000000..f56f871 --- /dev/null +++ b/src/Heimdall.Agent/Services/PipelineDegradationManager.cs @@ -0,0 +1,277 @@ +using System.Diagnostics; +using System.Threading; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent.Services; + +/// +/// Degradation levels for the IA pipeline (MASTER_SPEC Phase 15). +/// Level 0 = normal, Level 3 = most degraded. +/// +public enum DegradationLevel +{ + /// Normal operation — full IA pipeline. + Normal = 0, + + /// IA executor slow — Agent-only mode with lowered confidence (0.3). + SlowExecutor = 1, + + /// IA executor down / broker unreachable — Motion-only (no IA). + ExecutorDown = 2, + + /// CPU > 80% — snapshots reduced by half. + CpuSaturation = 3, +} + +/// +/// Tracks the current degradation level of the IA pipeline. +/// State transitions are driven by: +/// - (consecutive ONNX failures → level 1→2) +/// - (CPU > 80% → level 3) +/// - (ONNX recovers → level back toward 0) +/// - (CPU drops below threshold → clear level 3) +/// +/// Thread-safe: all state is protected by a lock. +/// +public sealed class PipelineDegradationManager +{ + private readonly ILogger _logger; + private readonly object _lock = new(); + private readonly Stopwatch _degradationStopwatch = new(); + + // Configurable thresholds + private const int SlowThreshold = 3; // N consecutive slow → level 1 + private const int DownThreshold = 10; // N consecutive failures → level 2 + private const double CpuThreshold = 80.0; // CPU % → level 3 + private const int RecoveryThreshold = 5; // N consecutive successes → recover + + private int _consecutiveFailures; + private int _consecutiveSlow; + private int _consecutiveSuccesses; + private double _lastCpuPercent; + + private DegradationLevel _level = DegradationLevel.Normal; + private DegradationLevel _highestLevel = DegradationLevel.Normal; + + /// Current degradation level. + public DegradationLevel Level + { + get { lock (_lock) return _level; } + } + + /// Highest level reached since last reset (for monitoring). + public DegradationLevel HighestLevel + { + get { lock (_lock) return _highestLevel; } + } + + /// Time spent in degradation (non-zero level) since last reset. + public TimeSpan DegradationDuration => _degradationStopwatch.Elapsed; + + /// Number of consecutive inference failures (resets on success). + public int ConsecutiveFailures + { + get { lock (_lock) return _consecutiveFailures; } + } + + /// Number of consecutive slow inferences (resets on fast success). + public int ConsecutiveSlow + { + get { lock (_lock) return _consecutiveSlow; } + } + + /// Last observed CPU usage percentage. + public double LastCpuPercent + { + get { lock (_lock) return _lastCpuPercent; } + } + + public PipelineDegradationManager(ILogger logger) + { + _logger = logger; + } + + /// + /// Report an inference that failed (exception, timeout, etc.). + /// Escalates: Normal → SlowExecutor → ExecutorDown. + /// + public void ReportInferenceFailure() + { + lock (_lock) + { + _consecutiveFailures++; + _consecutiveSuccesses = 0; + _consecutiveSlow = 0; + + var previous = _level; + if (_consecutiveFailures >= DownThreshold) + SetLevel(DegradationLevel.ExecutorDown); + else if (_consecutiveFailures >= SlowThreshold || _consecutiveSlow >= SlowThreshold) + SetLevel(DegradationLevel.SlowExecutor); + + if (_level != previous) + _logger.LogWarning( + "Pipeline degraded: {Previous} → {Level} (failures={Failures}, slow={Slow})", + previous, _level, _consecutiveFailures, _consecutiveSlow); + } + } + + /// + /// Report an inference that was slow (>500ms) but succeeded. + /// Escalates: Normal → SlowExecutor. + /// + /// Inference time in milliseconds. + public void ReportInferenceSlow(long elapsedMs) + { + lock (_lock) + { + _consecutiveFailures = 0; + _consecutiveSuccesses = 0; + _consecutiveSlow++; + + var previous = _level; + if (_consecutiveSlow >= SlowThreshold) + SetLevel(DegradationLevel.SlowExecutor); + + if (_level != previous) + _logger.LogWarning( + "Pipeline degraded: {Previous} → {Level} (slow={Slow})", + previous, _level, _consecutiveSlow); + } + } + + /// + /// Report a successful, fast inference. Helps recover from degradation. + /// + public void ReportInferenceSuccess() + { + lock (_lock) + { + _consecutiveFailures = 0; + _consecutiveSlow = 0; + _consecutiveSuccesses++; + + var previous = _level; + if (_level != DegradationLevel.Normal && _level != DegradationLevel.CpuSaturation) + { + if (_consecutiveSuccesses >= RecoveryThreshold) + SetLevel(_lastCpuPercent >= CpuThreshold ? DegradationLevel.CpuSaturation : DegradationLevel.Normal); + } + + if (_level != previous) + _logger.LogInformation( + "Pipeline recovered: {Previous} → {Level} (successes={Successes})", + previous, _level, _consecutiveSuccesses); + } + } + + /// + /// Report CPU usage. Sets level 3 if CPU > 80%. + /// + /// CPU usage percentage (0-100). + public void ReportCpuSaturation(double cpuPercent) + { + lock (_lock) + { + _lastCpuPercent = cpuPercent; + var previous = _level; + + if (cpuPercent >= CpuThreshold && _level < DegradationLevel.CpuSaturation) + { + SetLevel(DegradationLevel.CpuSaturation); + _logger.LogWarning( + "Pipeline degraded: {Previous} → CpuSaturation (CPU={Cpu:F1}%)", + previous, cpuPercent); + } + else if (cpuPercent < CpuThreshold && _level == DegradationLevel.CpuSaturation) + { + // CPU dropped — check if IA is also healthy + var targetLevel = _consecutiveFailures >= DownThreshold ? DegradationLevel.ExecutorDown + : _consecutiveSlow >= SlowThreshold || _consecutiveFailures >= SlowThreshold ? DegradationLevel.SlowExecutor + : DegradationLevel.Normal; + SetLevel(targetLevel); + + if (_level != previous) + _logger.LogInformation( + "Pipeline recovered from CPU saturation: {Previous} → {Level} (CPU={Cpu:F1}%)", + previous, _level, cpuPercent); + } + } + } + + /// + /// Report CPU recovery (called when CPU drops below threshold). + /// + public void ReportCpuRecovery(double cpuPercent) + { + ReportCpuSaturation(cpuPercent); + } + + /// + /// Check if the IA executor should be used at the current degradation level. + /// Level 0: use IA. Level 1: use IA with lowered confidence. Level 2+: skip IA. + /// + public bool ShouldUseInference() + { + lock (_lock) return _level < DegradationLevel.ExecutorDown; + } + + /// + /// Get the confidence threshold for the current degradation level. + /// Level 0: 0.5 (normal). Level 1: 0.3 (lowered). + /// + public float GetConfidenceThreshold() + { + lock (_lock) + { + return _level switch + { + DegradationLevel.Normal => 0.5f, + DegradationLevel.SlowExecutor => 0.3f, + _ => 1.0f, // ExecutorDown/CpuSaturation: skip inference + }; + } + } + + /// + /// Get the snapshot interval multiplier for the current degradation level. + /// Level 3 (CpuSaturation): 2.0 (half the snapshots). Others: 1.0. + /// + public double GetSnapshotIntervalMultiplier() + { + lock (_lock) + { + return _level == DegradationLevel.CpuSaturation ? 2.0 : 1.0; + } + } + + /// + /// Reset all degradation state to Normal (e.g., after config change). + /// + public void Reset() + { + lock (_lock) + { + _consecutiveFailures = 0; + _consecutiveSlow = 0; + _consecutiveSuccesses = 0; + _lastCpuPercent = 0; + SetLevel(DegradationLevel.Normal); + } + } + + private void SetLevel(DegradationLevel newLevel) + { + // Caller must hold _lock + var oldLevel = _level; + _level = newLevel; + + if (newLevel > _highestLevel) + _highestLevel = newLevel; + + if (oldLevel == DegradationLevel.Normal && newLevel != DegradationLevel.Normal) + _degradationStopwatch.Start(); + else if (newLevel == DegradationLevel.Normal && oldLevel != DegradationLevel.Normal) + _degradationStopwatch.Stop(); + } +} diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index f4bdb37..4207dd4 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -1,9 +1,7 @@ using System.Collections.Concurrent; using Heimdall.Application.Metrics; using Microsoft.Extensions.Options; - namespace Heimdall.Agent.Services; - /// /// Orchestrates the video capture pipeline (MASTER_SPEC Phase 15): /// keeps the FFmpeg capture streams in sync with the assigned cameras @@ -11,6 +9,13 @@ namespace Heimdall.Agent.Services; /// bounded snapshot channel, forwarding each frame to the /// and updating the scene state that /// drives the adaptive snapshot interval. +/// +/// Integrates with for graceful +/// degradation: +/// - Level 0 (Normal): full IA pipeline +/// - Level 1 (SlowExecutor): inference runs with lowered confidence +/// - Level 2 (ExecutorDown): motion-only mode (skip inference) +/// - Level 3 (CpuSaturation): snapshots reduced by half /// public sealed class SnapshotPipelineService : BackgroundService { @@ -22,14 +27,20 @@ public sealed class SnapshotPipelineService : BackgroundService private readonly SceneStateTracker _sceneState; private readonly ICameraStatusReporter _statusReporter; private readonly IDetectionReporter _detectionReporter; + private readonly PipelineDegradationManager _degradationManager; + private readonly SystemMetricsProvider _metrics; private readonly ILogger _logger; private readonly ConcurrentDictionary _motionDetectors = new(); private readonly ConcurrentDictionary _reportedSceneState = new(); private long _snapshotsProcessed; private long _analysisFailures; + private long _snapshotsSkippedByDegradation; private bool _storeSubscribed; + private DateTime _lastCpuCheckAt = DateTime.MinValue; + private static readonly TimeSpan CpuCheckInterval = TimeSpan.FromSeconds(10); + public SnapshotPipelineService( AgentState state, IOptions options, @@ -39,6 +50,8 @@ public sealed class SnapshotPipelineService : BackgroundService SceneStateTracker sceneState, ICameraStatusReporter statusReporter, IDetectionReporter detectionReporter, + PipelineDegradationManager degradationManager, + SystemMetricsProvider metrics, ILogger logger) { _state = state; @@ -49,6 +62,8 @@ public sealed class SnapshotPipelineService : BackgroundService _sceneState = sceneState; _statusReporter = statusReporter; _detectionReporter = detectionReporter; + _degradationManager = degradationManager; + _metrics = metrics; _logger = logger; } @@ -58,6 +73,9 @@ public sealed class SnapshotPipelineService : BackgroundService /// Number of frames that failed analysis (analyzer exceptions). public long AnalysisFailures => Interlocked.Read(ref _analysisFailures); + /// Number of snapshots skipped because of pipeline degradation. + public long SnapshotsSkippedByDegradation => Interlocked.Read(ref _snapshotsSkippedByDegradation); + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { // Local fallback (Agent:Cameras) until the Central camera list arrives. @@ -74,6 +92,7 @@ public sealed class SnapshotPipelineService : BackgroundService _storeSubscribed = true; var consumer = Task.Run(() => ConsumeSnapshotsAsync(stoppingToken), stoppingToken); + var cpuMonitor = Task.Run(() => MonitorCpuAsync(stoppingToken), stoppingToken); try { @@ -92,6 +111,7 @@ public sealed class SnapshotPipelineService : BackgroundService if (_storeSubscribed) _cameraStore.Changed -= OnCameraConfigChanged; try { await consumer; } catch (OperationCanceledException) { } + try { await cpuMonitor; } catch (OperationCanceledException) { } } } @@ -151,6 +171,35 @@ public sealed class SnapshotPipelineService : BackgroundService } } + /// + /// Monitor CPU usage and report to the degradation manager. + /// Runs in the background, checking every . + /// + private async Task MonitorCpuAsync(CancellationToken ct) + { + try + { + while (!ct.IsCancellationRequested) + { + await Task.Delay(CpuCheckInterval, ct); + + var now = DateTime.UtcNow; + if (now - _lastCpuCheckAt < CpuCheckInterval) + continue; + + _lastCpuCheckAt = now; + var metrics = _metrics.Collect(); + + if (metrics.CpuUsagePercent is { } cpu) + _degradationManager.ReportCpuSaturation(cpu); + } + } + catch (OperationCanceledException) + { + // Shutdown. + } + } + private async Task ConsumeSnapshotsAsync(CancellationToken ct) { try @@ -162,18 +211,36 @@ public sealed class SnapshotPipelineService : BackgroundService // Update queue depth metric (spec 13.1) HeimdallMetrics.SetQueueDepth(_streams.SnapshotChannel.Reader.Count); - // Real call into the analyzer — the pipeline's reason to exist. - var result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct); - Interlocked.Increment(ref _snapshotsProcessed); + // Check degradation level before processing + var level = _degradationManager.Level; - var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector()); - var motion = detector.Detect(snapshot.JpegData); - _sceneState.UpdateFromAnalysis( - result?.Detections.Count > 0, - motion); + if (level >= DegradationLevel.ExecutorDown) + { + // Motion-only mode: skip IA inference, only do motion detection + Interlocked.Increment(ref _snapshotsSkippedByDegradation); - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); - await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); + var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector()); + var motion = detector.Detect(snapshot.JpegData); + _sceneState.UpdateFromAnalysis(hasDetections: false, motion); + + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + // No IA detections to report in degradation mode + } + else + { + // Normal or SlowExecutor: run full analysis + var result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct); + Interlocked.Increment(ref _snapshotsProcessed); + + var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector()); + var motion = detector.Detect(snapshot.JpegData); + _sceneState.UpdateFromAnalysis( + result?.Detections.Count > 0, + motion); + + await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); + } } catch (OperationCanceledException) when (ct.IsCancellationRequested) { diff --git a/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs b/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs index 3b70a03..cd8a8f1 100644 --- a/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs @@ -1,5 +1,7 @@ using Heimdall.Agent.Services; using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using NSubstitute; namespace Heimdall.Agent.Tests; @@ -9,7 +11,8 @@ public class AgentHealthCheckTests public async Task CheckHealth_WhenRegistered_ReturnsHealthy() { var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "valid-key" }; - var check = new AgentHealthCheck(state); + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + var check = new AgentHealthCheck(state, degradationManager); var result = await check.CheckHealthAsync(new HealthCheckContext()); @@ -20,7 +23,8 @@ public class AgentHealthCheckTests public async Task CheckHealth_WhenNotRegistered_ReturnsUnhealthy() { var state = new AgentState { AgentId = Guid.Empty }; - var check = new AgentHealthCheck(state); + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + var check = new AgentHealthCheck(state, degradationManager); var result = await check.CheckHealthAsync(new HealthCheckContext()); @@ -31,10 +35,39 @@ public class AgentHealthCheckTests public async Task CheckHealth_WhenNoApiKey_ReturnsDegraded() { var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = null }; - var check = new AgentHealthCheck(state); + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + var check = new AgentHealthCheck(state, degradationManager); var result = await check.CheckHealthAsync(new HealthCheckContext()); result.Status.ShouldBe(HealthStatus.Degraded); } + + [Fact] + public async Task CheckHealth_WhenDegraded_ReturnsDegraded() + { + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "valid-key" }; + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + // Escalate to SlowExecutor + for (int i = 0; i < 3; i++) + degradationManager.ReportInferenceSlow(600); + var check = new AgentHealthCheck(state, degradationManager); + + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + result.Status.ShouldBe(HealthStatus.Degraded); + } + + [Fact] + public async Task CheckHealth_WhenCpuSaturation_ReturnsUnhealthy() + { + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "valid-key" }; + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + degradationManager.ReportCpuSaturation(85.0); + var check = new AgentHealthCheck(state, degradationManager); + + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + result.Status.ShouldBe(HealthStatus.Unhealthy); + } } diff --git a/tests/Heimdall.Agent.Tests/CircuitBreakerTests.cs b/tests/Heimdall.Agent.Tests/CircuitBreakerTests.cs new file mode 100644 index 0000000..159c634 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/CircuitBreakerTests.cs @@ -0,0 +1,159 @@ +using Heimdall.Agent.Services; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Agent.Tests; + +public class CircuitBreakerTests +{ + [Fact] + public void InitialState_IsClosed() + { + var cb = new CircuitBreaker(Substitute.For>()); + cb.State.ShouldBe(CircuitState.Closed); + } + + [Fact] + public void ShouldAllowCall_WhenClosed_ReturnsTrue() + { + var cb = new CircuitBreaker(Substitute.For>()); + cb.ShouldAllowCall().ShouldBeTrue(); + } + + [Fact] + public void ShouldAllowCall_AfterThreshold_ReturnsFalse() + { + var cb = new CircuitBreaker(Substitute.For>(), failureThreshold: 3); + + cb.ReportFailure(); + cb.ReportFailure(); + cb.ShouldAllowCall().ShouldBeTrue(); // Still closed, 2 < 3 + + cb.ReportFailure(); + cb.State.ShouldBe(CircuitState.Open); + cb.ShouldAllowCall().ShouldBeFalse(); + } + + [Fact] + public void ReportSuccess_ResetsConsecutiveFailures() + { + var cb = new CircuitBreaker(Substitute.For>(), failureThreshold: 3); + + cb.ReportFailure(); + cb.ReportFailure(); + cb.ConsecutiveFailures.ShouldBe(2); + + cb.ReportSuccess(); + cb.ConsecutiveFailures.ShouldBe(0); + } + + [Fact] + public void ReportSuccess_InHalfOpen_ClosesCircuit() + { + var cb = new CircuitBreaker( + Substitute.For>(), + failureThreshold: 2, + openDuration: TimeSpan.FromMilliseconds(10)); + + // Open the circuit + cb.ReportFailure(); + cb.ReportFailure(); + cb.State.ShouldBe(CircuitState.Open); + + // Wait for open duration to expire + Thread.Sleep(20); + + // Should transition to HalfOpen + cb.ShouldAllowCall().ShouldBeTrue(); + cb.State.ShouldBe(CircuitState.HalfOpen); + + // Success in HalfOpen → Closed + cb.ReportSuccess(); + cb.State.ShouldBe(CircuitState.Closed); + } + + [Fact] + public void ReportFailure_InHalfOpen_OpensCircuit() + { + var cb = new CircuitBreaker( + Substitute.For>(), + failureThreshold: 2, + openDuration: TimeSpan.FromMilliseconds(10)); + + // Open the circuit + cb.ReportFailure(); + cb.ReportFailure(); + + // Wait for open duration to expire + Thread.Sleep(20); + + // Transition to HalfOpen + cb.ShouldAllowCall().ShouldBeTrue(); + cb.State.ShouldBe(CircuitState.HalfOpen); + + // Failure in HalfOpen → Open + cb.ReportFailure(); + cb.State.ShouldBe(CircuitState.Open); + } + + [Fact] + public void ShouldAllowCall_WhileOpen_ReturnsFalse() + { + var cb = new CircuitBreaker( + Substitute.For>(), + failureThreshold: 2, + openDuration: TimeSpan.FromSeconds(10)); + + cb.ReportFailure(); + cb.ReportFailure(); + cb.State.ShouldBe(CircuitState.Open); + + // Should still be closed immediately after opening + cb.ShouldAllowCall().ShouldBeFalse(); + } + + [Fact] + public void Reset_ForcesClosed() + { + var cb = new CircuitBreaker(Substitute.For>(), failureThreshold: 2); + + cb.ReportFailure(); + cb.ReportFailure(); + cb.State.ShouldBe(CircuitState.Open); + + cb.Reset(); + cb.State.ShouldBe(CircuitState.Closed); + cb.ConsecutiveFailures.ShouldBe(0); + } + + [Fact] + public void DefaultThreshold_Is5() + { + var cb = new CircuitBreaker(Substitute.For>()); + + for (int i = 0; i < 4; i++) + cb.ReportFailure(); + + cb.State.ShouldBe(CircuitState.Closed); // 4 < 5 + + cb.ReportFailure(); + cb.State.ShouldBe(CircuitState.Open); // 5 >= 5 + } + + [Fact] + public void DefaultOpenDuration_Is30Seconds() + { + var cb = new CircuitBreaker( + Substitute.For>(), + failureThreshold: 1); + + cb.ReportFailure(); + cb.State.ShouldBe(CircuitState.Open); + + // Immediately after opening, should not transition to HalfOpen + cb.ShouldAllowCall().ShouldBeFalse(); + + // The OpenedAt should be set + cb.OpenedAt.ShouldBeGreaterThan(DateTime.UtcNow.AddSeconds(-5)); + } +} diff --git a/tests/Heimdall.Agent.Tests/FrameAnalyzerDegradationTests.cs b/tests/Heimdall.Agent.Tests/FrameAnalyzerDegradationTests.cs new file mode 100644 index 0000000..d48a904 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/FrameAnalyzerDegradationTests.cs @@ -0,0 +1,117 @@ +using Heimdall.Agent.Services; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Agent.Tests; + +public class FrameAnalyzerDegradationTests : IDisposable +{ + private readonly CircuitBreaker _circuitBreaker; + private readonly PipelineDegradationManager _degradationManager; + private readonly FrameAnalyzerService _service; + + public FrameAnalyzerDegradationTests() + { + _circuitBreaker = new CircuitBreaker(Substitute.For>()); + _degradationManager = new PipelineDegradationManager(Substitute.For>()); + _service = new FrameAnalyzerService( + Substitute.For>(), + _circuitBreaker, + _degradationManager); + } + + public void Dispose() + { + _service.Dispose(); + GC.SuppressFinalize(this); + } + + [Fact] + public async Task AnalyzeFrameAsync_WhenCircuitBreakerOpen_ReturnsNull() + { + // Open the circuit breaker + for (int i = 0; i < 5; i++) + _circuitBreaker.ReportFailure(); + _circuitBreaker.State.ShouldBe(CircuitState.Open); + + var result = await _service.AnalyzeFrameAsync([1, 2, 3]); + result.ShouldBeNull(); + _service.SkippedByCircuitBreaker.ShouldBeGreaterThan(0); + } + + [Fact] + public async Task AnalyzeFrameAsync_WhenDegradationExecutorDown_ReturnsNull() + { + // Escalate to ExecutorDown + for (int i = 0; i < 10; i++) + _degradationManager.ReportInferenceFailure(); + _degradationManager.Level.ShouldBe(DegradationLevel.ExecutorDown); + + var result = await _service.AnalyzeFrameAsync([1, 2, 3]); + result.ShouldBeNull(); + _service.SkippedByDegradation.ShouldBeGreaterThan(0); + } + + [Fact] + public void AnalyzeFrame_WhenCircuitBreakerOpen_ReturnsNull() + { + // Open the circuit breaker + for (int i = 0; i < 5; i++) + _circuitBreaker.ReportFailure(); + + var result = _service.AnalyzeFrame([1, 2, 3]); + result.ShouldBeNull(); + } + + [Fact] + public void AnalyzeFrame_WhenDegradationExecutorDown_ReturnsNull() + { + // Escalate to ExecutorDown + for (int i = 0; i < 10; i++) + _degradationManager.ReportInferenceFailure(); + + var result = _service.AnalyzeFrame([1, 2, 3]); + result.ShouldBeNull(); + } + + [Fact] + public void AnalyzeFrame_WhenSlowExecutor_StillRunsInference() + { + // Escalate to SlowExecutor (level 1) + for (int i = 0; i < 3; i++) + _degradationManager.ReportInferenceSlow(600); + _degradationManager.Level.ShouldBe(DegradationLevel.SlowExecutor); + + // Should still run inference (returns null because model not loaded, but not skipped) + var result = _service.AnalyzeFrame([1, 2, 3]); + result.ShouldBeNull(); // Model not loaded, not skipped + _service.SkippedByDegradation.ShouldBe(0); + _service.SkippedByCircuitBreaker.ShouldBe(0); + } + + [Fact] + public void AnalyzeFrame_WhenNormal_StillRunsInference() + { + // Normal level — should run + var result = _service.AnalyzeFrame([1, 2, 3]); + result.ShouldBeNull(); // Model not loaded + _service.SkippedByDegradation.ShouldBe(0); + _service.SkippedByCircuitBreaker.ShouldBe(0); + } + + [Fact] + public void AnalyzeFrame_WhenCircuitHalfOpen_StillRunsInference() + { + // Open then transition to half-open + for (int i = 0; i < 5; i++) + _circuitBreaker.ReportFailure(); + + // Reset to simulate recovery attempt + _circuitBreaker.Reset(); + _circuitBreaker.State.ShouldBe(CircuitState.Closed); + + var result = _service.AnalyzeFrame([1, 2, 3]); + result.ShouldBeNull(); // Model not loaded + _service.SkippedByCircuitBreaker.ShouldBe(0); + } +} diff --git a/tests/Heimdall.Agent.Tests/PipelineDegradationManagerTests.cs b/tests/Heimdall.Agent.Tests/PipelineDegradationManagerTests.cs new file mode 100644 index 0000000..c5eaf61 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/PipelineDegradationManagerTests.cs @@ -0,0 +1,220 @@ +using Heimdall.Agent.Services; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Agent.Tests; + +public class PipelineDegradationManagerTests +{ + private readonly PipelineDegradationManager _manager; + + public PipelineDegradationManagerTests() + { + _manager = new PipelineDegradationManager(Substitute.For>()); + } + + [Fact] + public void InitialLevel_IsNormal() + { + _manager.Level.ShouldBe(DegradationLevel.Normal); + } + + [Fact] + public void ReportInferenceFailure_AfterThreshold_EscalatesToSlowExecutor() + { + // Report failures below slow threshold — should stay Normal + for (int i = 0; i < 2; i++) + _manager.ReportInferenceFailure(); + + _manager.Level.ShouldBe(DegradationLevel.Normal); + + // Third failure should trigger SlowExecutor + _manager.ReportInferenceFailure(); + _manager.Level.ShouldBe(DegradationLevel.SlowExecutor); + } + + [Fact] + public void ReportInferenceFailure_AfterDownThreshold_EscalatesToExecutorDown() + { + // Report enough failures to reach ExecutorDown + for (int i = 0; i < 10; i++) + _manager.ReportInferenceFailure(); + + _manager.Level.ShouldBe(DegradationLevel.ExecutorDown); + } + + [Fact] + public void ReportInferenceSlow_AfterThreshold_EscalatesToSlowExecutor() + { + for (int i = 0; i < 3; i++) + _manager.ReportInferenceSlow(600); + + _manager.Level.ShouldBe(DegradationLevel.SlowExecutor); + } + + [Fact] + public void ReportInferenceSuccess_ResetsConsecutiveFailures() + { + _manager.ReportInferenceFailure(); + _manager.ReportInferenceFailure(); + _manager.ConsecutiveFailures.ShouldBe(2); + + _manager.ReportInferenceSuccess(); + _manager.ConsecutiveFailures.ShouldBe(0); + } + + [Fact] + public void ReportInferenceSuccess_RecoversFromSlowExecutor_AfterThreshold() + { + // Escalate to SlowExecutor + for (int i = 0; i < 3; i++) + _manager.ReportInferenceSlow(600); + _manager.Level.ShouldBe(DegradationLevel.SlowExecutor); + + // Report enough successes to recover + for (int i = 0; i < 5; i++) + _manager.ReportInferenceSuccess(); + + _manager.Level.ShouldBe(DegradationLevel.Normal); + } + + [Fact] + public void ReportInferenceSuccess_RecoversFromExecutorDown_AfterThreshold() + { + // Escalate to ExecutorDown + for (int i = 0; i < 10; i++) + _manager.ReportInferenceFailure(); + _manager.Level.ShouldBe(DegradationLevel.ExecutorDown); + + // Report enough successes to recover + for (int i = 0; i < 5; i++) + _manager.ReportInferenceSuccess(); + + _manager.Level.ShouldBe(DegradationLevel.Normal); + } + + [Fact] + public void ReportCpuSaturation_AboveThreshold_SetsLevel3() + { + _manager.ReportCpuSaturation(85.0); + _manager.Level.ShouldBe(DegradationLevel.CpuSaturation); + } + + [Fact] + public void ReportCpuSaturation_BelowThreshold_DoesNotChangeLevel() + { + _manager.ReportCpuSaturation(50.0); + _manager.Level.ShouldBe(DegradationLevel.Normal); + } + + [Fact] + public void ReportCpuRecovery_BelowThreshold_ClearsLevel3() + { + _manager.ReportCpuSaturation(85.0); + _manager.Level.ShouldBe(DegradationLevel.CpuSaturation); + + _manager.ReportCpuRecovery(50.0); + _manager.Level.ShouldBe(DegradationLevel.Normal); + } + + [Fact] + public void ShouldUseInference_AtExecutorDown_ReturnsFalse() + { + for (int i = 0; i < 10; i++) + _manager.ReportInferenceFailure(); + + _manager.ShouldUseInference().ShouldBeFalse(); + } + + [Fact] + public void ShouldUseInference_AtNormal_ReturnsTrue() + { + _manager.ShouldUseInference().ShouldBeTrue(); + } + + [Fact] + public void ShouldUseInference_AtSlowExecutor_ReturnsTrue() + { + for (int i = 0; i < 3; i++) + _manager.ReportInferenceSlow(600); + + _manager.ShouldUseInference().ShouldBeTrue(); + } + + [Fact] + public void GetConfidenceThreshold_AtNormal_Returns05() + { + _manager.GetConfidenceThreshold().ShouldBe(0.5f); + } + + [Fact] + public void GetConfidenceThreshold_AtSlowExecutor_Returns03() + { + for (int i = 0; i < 3; i++) + _manager.ReportInferenceSlow(600); + + _manager.GetConfidenceThreshold().ShouldBe(0.3f); + } + + [Fact] + public void GetSnapshotIntervalMultiplier_AtCpuSaturation_Returns2() + { + _manager.ReportCpuSaturation(85.0); + _manager.GetSnapshotIntervalMultiplier().ShouldBe(2.0); + } + + [Fact] + public void GetSnapshotIntervalMultiplier_AtNormal_Returns1() + { + _manager.GetSnapshotIntervalMultiplier().ShouldBe(1.0); + } + + [Fact] + public void Reset_ClearsAllState() + { + for (int i = 0; i < 10; i++) + _manager.ReportInferenceFailure(); + _manager.Level.ShouldBe(DegradationLevel.ExecutorDown); + + _manager.Reset(); + _manager.Level.ShouldBe(DegradationLevel.Normal); + _manager.ConsecutiveFailures.ShouldBe(0); + } + + [Fact] + public void HighestLevel_TracksMaximum() + { + for (int i = 0; i < 3; i++) + _manager.ReportInferenceSlow(600); + _manager.HighestLevel.ShouldBe(DegradationLevel.SlowExecutor); + + for (int i = 0; i < 10; i++) + _manager.ReportInferenceFailure(); + _manager.HighestLevel.ShouldBe(DegradationLevel.ExecutorDown); + } + + [Fact] + public void DegradationDuration_IsNonZero_AfterDegradation() + { + for (int i = 0; i < 3; i++) + _manager.ReportInferenceSlow(600); + + _manager.DegradationDuration.ShouldBeGreaterThan(TimeSpan.Zero); + } + + [Fact] + public void ReportInferenceFailure_AfterSlow_UsesSlowThreshold() + { + // Slow already escalated to SlowExecutor + for (int i = 0; i < 3; i++) + _manager.ReportInferenceSlow(600); + _manager.Level.ShouldBe(DegradationLevel.SlowExecutor); + + // Now report failures — should escalate to ExecutorDown faster + // (because consecutiveSlow already reached threshold) + _manager.ReportInferenceFailure(); + _manager.ConsecutiveFailures.ShouldBe(1); + // Level should still be SlowExecutor (need 10 failures for ExecutorDown) + _manager.Level.ShouldBe(DegradationLevel.SlowExecutor); + } +} diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs index 878d19e..385fe5d 100644 --- a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs @@ -24,8 +24,11 @@ public class SnapshotPipelineServiceTests var analyzer = new FrameAnalyzerService(Substitute.For>()); var statusReporter = Substitute.For(); var detectionReporter = Substitute.For(); + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + var metrics = new SystemMetricsProvider(); var service = new SnapshotPipelineService( state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter, + degradationManager, metrics, Substitute.For>()); return (service, state, store, streams, analyzer); }