From 6b2a37823bac860b23ae6fe68483885c6bbd0d5f Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 20:33:40 +0100 Subject: [PATCH 1/3] test(health): cover readiness and agent degradation --- .../AgentHealthCheckTests.cs | 36 +++++++++++ .../Controllers/HealthControllerTests.cs | 64 +++++++++++++++++++ todo.md | 2 +- 3 files changed, 101 insertions(+), 1 deletion(-) diff --git a/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs b/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs index cd8a8f1..17cec24 100644 --- a/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs @@ -70,4 +70,40 @@ public class AgentHealthCheckTests result.Status.ShouldBe(HealthStatus.Unhealthy); } + + [Fact] + public async Task CheckHealth_WhenDetectionModelIsUnavailable_ReturnsUnhealthy() + { + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "valid-key" }; + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + using var analyzer = new FrameAnalyzerService( + Substitute.For>(), null, degradationManager, null, + Path.Combine(Path.GetTempPath(), $"missing-model-{Guid.NewGuid():N}.onnx")); + var check = new AgentHealthCheck(state, degradationManager, analyzer); + + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + result.Status.ShouldBe(HealthStatus.Unhealthy); + result.Description.ShouldContain("Detection model unavailable"); + } + + [Fact] + public async Task CheckHealth_WhenAssignedCameraHasNoActiveStream_ReturnsCaptureDiagnostics() + { + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "valid-key" }; + var degradationManager = new PipelineDegradationManager(Substitute.For>()); + var cameraStore = new CameraConfigStore(); + var cameraId = Guid.NewGuid(); + cameraStore.SetLocalFallback( + [new AgentCameraConfig(cameraId, "Test camera", "rtsp://camera/stream", null, true)]); + var check = new AgentHealthCheck(state, degradationManager, cameraStore: cameraStore); + + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + result.Status.ShouldBe(HealthStatus.Degraded); + result.Data["assignedCameraCount"].ShouldBe(1); + result.Data["activeStreamCount"].ShouldBe(0); + result.Data["pipelineStale"].ShouldBe(true); + ((string[])result.Data["staleCameraIds"]).ShouldContain(cameraId.ToString("D")); + } } diff --git a/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs index bbaeacf..350c94e 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs @@ -1,5 +1,8 @@ using System.Net.Http.Json; using System.Text.Json; +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Microsoft.Extensions.DependencyInjection; using Shouldly; namespace Heimdall.IntegrationTests.Controllers; @@ -27,4 +30,65 @@ public class HealthControllerTests : PostgresTestBase var content = await response.Content.ReadFromJsonAsync(); content.TryGetProperty("timestamp", out _).ShouldBeTrue(); } + + [Fact] + public async Task Readiness_ReturnsHealthy_WhenPostgresAndActiveStorageAreAvailable() + { + var storageRoot = Path.Combine(Path.GetTempPath(), "heimdall-readiness", Guid.NewGuid().ToString("N")); + await SetSettingsAsync( + new AppSetting("storage.provider", "Local"), + new AppSetting("storage.local.path", storageRoot)); + + try + { + var response = await Factory.CreateClient().GetAsync("/readyz"); + + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var body = await response.Content.ReadFromJsonAsync(); + body.GetProperty("status").GetString().ShouldBe("healthy"); + } + finally + { + if (Directory.Exists(storageRoot)) Directory.Delete(storageRoot, recursive: true); + } + } + + [Fact] + public async Task Readiness_ReturnsUnavailableWithoutLeakingStorageConfiguration() + { + const string privateProviderValue = "unknown-provider-should-not-appear"; + await SetSettingsAsync(new AppSetting("storage.provider", privateProviderValue)); + + var response = await Factory.CreateClient().GetAsync("/readyz"); + var body = await response.Content.ReadAsStringAsync(); + + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.ServiceUnavailable); + body.ShouldContain("unhealthy"); + body.ShouldContain("unavailable or misconfigured"); + body.ShouldNotContain(privateProviderValue); + } + + [Fact] + public async Task Live_ReturnsHealthyWhenOptionalAiBackendsAreNotConfigured() + { + // Empty DB values deliberately override any runner environment fallbacks. + await SetSettingsAsync( + new AppSetting("ai.cpaiUrl", string.Empty), + new AppSetting("ai.ollamaUrl", string.Empty)); + + var response = await Factory.CreateClient().GetAsync("/health/live"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var body = await response.Content.ReadFromJsonAsync(); + body.GetProperty("status").GetString().ShouldBe("healthy"); + body.GetProperty("degradationLevel").GetInt32().ShouldBe(0); + } + + private async Task SetSettingsAsync(params AppSetting[] settings) + { + await using var scope = Factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.AppSettings.AddRange(settings); + await db.SaveChangesAsync(); + } } diff --git a/todo.md b/todo.md index a565d20..301e599 100644 --- a/todo.md +++ b/todo.md @@ -46,7 +46,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La jauge de viewers existe, mais aucun producteur WebRTC n'existe avant FEAT-01. Restent la validation de scraping sur un déploiement et l'évolution réelle des mesures. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. -- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif (settings DB/env), avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. Les scénarios réels de panne restent à valider. +- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif (settings DB/env), avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR en cours ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque. Les scénarios réels de panne restent à valider. - [ ] Actualiser les guides après chaque changement d'infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Vérifier une installation depuis la documentation. ## Corrections déjà livrées à préserver -- 2.54.1 From 435f8c4a05c98925f86e51c9c1db5811247cc7db Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 20:39:21 +0100 Subject: [PATCH 2/3] test(health): assert model failure description --- tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs b/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs index 17cec24..9a3a5e7 100644 --- a/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentHealthCheckTests.cs @@ -84,7 +84,7 @@ public class AgentHealthCheckTests var result = await check.CheckHealthAsync(new HealthCheckContext()); result.Status.ShouldBe(HealthStatus.Unhealthy); - result.Description.ShouldContain("Detection model unavailable"); + result.Description!.ShouldContain("Detection model unavailable"); } [Fact] -- 2.54.1 From 1d5f995af474aaf070b3b9c39e1529e9953bdeda Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 20:44:31 +0100 Subject: [PATCH 3/3] test(health): update seeded settings in integration tests --- .../Controllers/HealthControllerTests.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs index 350c94e..6810913 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs @@ -2,6 +2,7 @@ using System.Net.Http.Json; using System.Text.Json; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Shouldly; @@ -88,7 +89,12 @@ public class HealthControllerTests : PostgresTestBase { await using var scope = Factory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - db.AppSettings.AddRange(settings); + foreach (var setting in settings) + { + var current = await db.AppSettings.FirstOrDefaultAsync(candidate => candidate.Key == setting.Key); + if (current is null) db.AppSettings.Add(setting); + else current.UpdateValue(setting.Value); + } await db.SaveChangesAsync(); } } -- 2.54.1