diff --git a/docs/audits/2026-10-20-pipeline-preuves.md b/docs/audits/2026-10-20-pipeline-preuves.md new file mode 100644 index 0000000..47eecbf --- /dev/null +++ b/docs/audits/2026-10-20-pipeline-preuves.md @@ -0,0 +1,39 @@ +# Lot 3 — preuves et limites de livraison + +Périmètre : PIPE-03 à PIPE-08, plus PIPE-11 isolé. Référence : [audit complet](2026-10-20-audit-complet.md). Aucun changement de sécurité des hubs/claims, d’authentification, de CI ou de déploiement. + +## Découpage de revue + +1. Exécution : refus explicite à saturation (compteur), continuations asynchrones, drainage avant libération ONNX, timeout natif de 15 s par inférence, validation du contrat COCO YOLOv8, RGB explicite et coordonnées originales, erreurs de jobs et capacités CPU effectives. +2. Configuration : profil version 1, migration additive nullable, mise à jour via PUT caméra, motion gate pixel avec seuil de pixels changés, amplitude minimale et zone normalisée, intervalles, classes et confiance appliqués ; remplacement complet de la configuration après connexion/reconnexion et toutes les 30 s, invalidation après sauvegarde. +3. Affectations : historique et AgentId cohérents, attente sans remplaçant, réconciliation périodique après reprise, cohérence du statut offline avant failover. + +## Contrat et compatibilité + +Le champ optionnel `DetectionProfile` du PUT caméra contient le DTO `DetectionProfileDto`. `Version=1`, modèle `yolov8n`, classes personne/véhicule/animal, seuil de confiance, motion gate et intervalles de capture sont pris en charge. Les seuils/coordonnées de zone sont dans [0,1]. `MotionThreshold` est la proportion minimale de pixels ayant changé ; `MotionPixelThreshold` est leur amplitude RGB moyenne minimale. Première image ou changement de profil : nouvelle référence de mouvement. `RequireMotionForAI=false` autorise l’analyse sans mouvement. Un profil invalide ou de version inconnue est refusé et le snapshot précédent est conservé. + +Les profils historiques sans JSON utilisent leurs valeurs existantes. La migration ajoute seulement `ExecutionProfileJson` nullable ; rollback : supprimer cette colonne (les valeurs historiques restent, les nouveaux profils JSON sont perdus). Les options package, modèles alternatifs et analyses visage/OCR ne sont pas annoncées comme capacités exécutables. Le binaire actuel utilise ONNX CPU ; l’inventaire GPU reste matériel et `HasGpu=false` décrit la capacité d’inférence effective. Sans modèle, les cœurs d’inférence annoncés valent zéro et la santé devient unhealthy ; aucun job n’est publié completed à partir d’un résultat indisponible. + +## Dépendance lot 2 + +Les invalidations réutilisent `IConfigBroadcastService.NotifyAllAgentsReload`, sans URLs ni secrets dans le message. Chaque agent recharge son snapshot par l’API existante. Le lot 2 doit garantir l’identité agent, l’autorisation des abonnements et de cette API, ainsi que le filtrage AgentScoped. Aucun remplacement de sa politique ni de ses claims dans ces PR. Le raccordement du PUT caméra ajoute seulement le DTO, sans modifier la politique d’accès. + +La notification est best effort après la transaction implicite de SaveChangesAsync ; la reconnexion et le polling récupèrent les notifications perdues. Les appels actuels n’utilisent pas de transaction explicite englobante ; un futur appel sous transaction explicite devra différer la notification jusqu’à son commit externe. Une outbox durable relève du lot 5. + +## Validation + +Premier passage final infrastructure : **56 réussis, 0 échec, 0 ignoré**, PostgreSQL 17 Testcontainers, filtre `CameraAssignmentServiceTests|AnalysisJobSchedulerServiceTests` (58 s de tests, compilation comprise séparément). La matrice GPU couvre chaque type de job, même/autre site et vide/en charge. Le passage précédent avait échoué sur une fixture de reprise désactivée par défaut ; fixture corrigée en caméra Online puis suite relancée. + +Commande : `dotnet test tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj --no-restore --filter 'FullyQualifiedName~CameraAssignmentServiceTests|FullyQualifiedName~AnalysisJobSchedulerServiceTests' --nologo -v minimal -m:1 -p:UseSharedCompilation=false`. + +Validation de reprise du 20 octobre 2026 : + +- Suite agent complète : **363 réussis, 0 échec, 0 ignoré** (38 s). Le test SignalR démarre un serveur HTTP local, coupe le transport HTTP et vérifie la réinscription au groupe ainsi que le remplacement complet du snapshot après reconnexion, y compris la suppression de l’ancienne caméra et la désactivation de la nouvelle. Un premier essai utilisant HubCallerContext.Abort ne simulait pas correctement la perte de transport ; la fixture utilise désormais HttpContext.Abort. +- Infrastructure ciblée : **57 réussis, 0 échec, 0 ignoré** (9 s), avec le même filtre ci-dessus. Inclut l’aller-retour PUT/profil persisté/configuration effective et le refus d’une version inconnue sans modification du nom de caméra. Le namespace du substitut ICredentialProtector a été corrigé avant ce passage. +- ReportCameraStatusCommandTests : **6 réussis, 0 échec, 0 ignoré** (542 ms), dont le refus de réactivation d’une caméra désactivée par un rapport en vol. + +Commande agent : `dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore --nologo -v minimal -m:1 -p:UseSharedCompilation=false`. + +Commande application : `dotnet test tests/Heimdall.Application.Tests/Heimdall.Application.Tests.csproj --no-restore --filter FullyQualifiedName~ReportCameraStatusCommandTests --nologo -v minimal -m:1 -p:UseSharedCompilation=false`. + +Les tests GPU de scoring utilisent des capacités persistées simulées ; ils ne prouvent pas une exécution CUDA. Une campagne matérielle RTSP/GPU et une réception SignalR sur réseau dégradé restent distinctes des tests automatiques locaux. Aucun lien de PR n’est consigné à ce stade. diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 223ca46..b1f26ef 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -93,6 +93,19 @@ public class AppDbContext : IdentityDbContext, IApplicat public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { ChangeTracker.DetectChanges(); + // Keep history consistent for direct camera writes (including discovery). + var changedCameras = ChangeTracker.Entries() + .Where(e => e.State == EntityState.Added || e.Property(c => c.AgentId).IsModified).ToArray(); + foreach (var entry in changedCameras) + { + var camera = entry.Entity; + var active = await CameraAssignments.AsTracking() + .Where(a => a.CameraId == camera.Id && a.ReleasedAt == null).ToListAsync(cancellationToken); + foreach (var assignment in active.Where(a => a.AgentId != camera.AgentId)) assignment.Release(); + var pending = CameraAssignments.Local.Any(a => a.CameraId == camera.Id && a.AgentId == camera.AgentId && a.ReleasedAt == null); + if (camera.AgentId is { } agentId && !pending) + CameraAssignments.Add(new CameraAssignment(camera.Id, agentId, "camera-config")); + } var invalidate = ChangeTracker.Entries().Any(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted && e.Entity is Camera or CameraAssignment or CameraDetectionProfile); diff --git a/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs b/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs index 693fb4f..0d61b62 100644 --- a/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs @@ -53,6 +53,7 @@ public sealed class AgentFailoverJob agent.Id, agent.Name, agent.LastHeartbeat); agent.MarkOffline(); + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); try { @@ -72,6 +73,13 @@ public sealed class AgentFailoverJob await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + // Reconcile waiting cameras on every sweep, including after an agent reconnects. + var waitingSites = await db.Cameras.AsNoTracking() + .Where(c => !c.IsDeleted && c.Status != CameraStatus.Disabled && c.AgentId == null) + .Select(c => c.SiteId).Distinct().ToListAsync(ct); + foreach (var siteId in waitingSites) + await _assignmentService.AssignSiteCamerasAsync(siteId, AssignmentStrategy.Failover, ct); + if (staleAgents.Count > 0) { _logger.LogInformation( diff --git a/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs b/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs index 08a76b2..4e23923 100644 --- a/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs @@ -38,6 +38,9 @@ public sealed class CameraAssignmentService : ICameraAssignmentService if (agent is null) return ServiceResult.NotFound("Agent not found"); + if (camera.SiteId != agent.SiteId || agent.Status != AgentStatus.Online) + return ServiceResult.Failure("Agent must be online in the camera site"); + // Release any current active assignment for this camera var current = await db.CameraAssignments .AsTracking() @@ -68,7 +71,7 @@ public sealed class CameraAssignmentService : ICameraAssignmentService var cameras = await db.Cameras .AsTracking() - .Where(c => c.SiteId == siteId && !c.IsDeleted) + .Where(c => c.SiteId == siteId && !c.IsDeleted && c.Status != CameraStatus.Disabled) .ToListAsync(ct); var agents = await db.Agents @@ -115,7 +118,10 @@ public sealed class CameraAssignmentService : ICameraAssignmentService { var currentAgent = agents.FirstOrDefault(a => a.Id == currentAssignment.AgentId); if (currentAgent is not null) + { + camera.AssignAgent(currentAgent.Id); continue; + } currentAssignment.Release(); existingAssignments.Remove(camera.Id); @@ -164,8 +170,10 @@ public sealed class CameraAssignmentService : ICameraAssignmentService .Where(a => a.AgentId == offlineAgentId && a.ReleasedAt == null) .ToListAsync(ct); - if (affectedAssignments.Count == 0) - return ServiceResult>.Success(Array.Empty()); + var affectedCameras = await db.Cameras.AsTracking() + .Where(c => c.AgentId == offlineAgentId && !c.IsDeleted).ToListAsync(ct); + foreach (var camera in affectedAssignments.Select(a => a.Camera)) + if (!affectedCameras.Any(c => c.Id == camera.Id)) affectedCameras.Add(camera); // Release all assignments for the offline agent foreach (var assignment in affectedAssignments) @@ -181,12 +189,18 @@ public sealed class CameraAssignmentService : ICameraAssignmentService .ToListAsync(ct); var reassignedCameras = new List(); - var workload = new Dictionary(); + var workload = await db.CameraAssignments.Where(a => a.ReleasedAt == null && a.AgentId != offlineAgentId) + .GroupBy(a => a.AgentId).Select(g => new { AgentId = g.Key, Count = g.Count() }) + .ToDictionaryAsync(x => x.AgentId, x => x.Count, ct); - foreach (var cam in affectedAssignments.Select(a => a.Camera)) + foreach (var cam in affectedCameras) { var bestAgent = PickBestAgent(onlineAgents, workload, cam, AssignmentStrategy.Failover); - if (bestAgent is null) continue; + if (bestAgent is null) + { + cam.AssignAgent(null); // Waiting; periodic reconciliation retries when an agent returns. + continue; + } var newAssignment = new CameraAssignment(cam.Id, bestAgent.Id, "failover"); db.CameraAssignments.Add(newAssignment); @@ -245,10 +259,7 @@ public sealed class CameraAssignmentService : ICameraAssignmentService .AsTracking() .FirstOrDefaultAsync(a => a.CameraId == cameraId && a.ReleasedAt == null, ct); - if (active is null) - return ServiceResult.Success(); // Already unassigned - - active.Release(); + active?.Release(); var camera = await db.Cameras.AsTracking() .FirstOrDefaultAsync(c => c.Id == cameraId, ct); @@ -257,7 +268,7 @@ public sealed class CameraAssignmentService : ICameraAssignmentService await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); - _logger.LogInformation("Camera {CameraId} released from agent {AgentId}", cameraId, active.AgentId); + _logger.LogInformation("Camera {CameraId} released from agent {AgentId}", cameraId, active?.AgentId); return ServiceResult.Success(); } diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index da440f9..e8816f9 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -1,3 +1,6 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.SignalR; using System.Reflection; using Heimdall.Agent.Services; using Heimdall.Application.DTOs; @@ -17,12 +20,13 @@ public class ConfigReceiverServiceTests RuntimeLogLevel? runtimeLogLevel = null, IHttpClientFactory? httpFactory = null, CameraConfigStore? cameraStore = null, + string centralUrl = "http://localhost:5000", ILogger? logger = null) { state ??= new AgentState { AgentId = Guid.Empty }; var options = Options.Create(new AgentOptions { - CentralUrl = "http://localhost:5000", + CentralUrl = centralUrl, SiteToken = "test" }); logger ??= Substitute.For>(); @@ -51,6 +55,47 @@ public class ConfigReceiverServiceTests return (new RuntimeLogLevel(factory, options), factory); } + [Fact] + public async Task SignalRReconnect_Rejoins_AndReplacesCompleteCameraSnapshot() + { + var initialId = Guid.NewGuid(); + var nextId = Guid.NewGuid(); + IReadOnlyDictionary config = new Dictionary + { [$"camera.{initialId}.rtsp"] = "rtsp://initial" }; + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddSignalR(); + await using var app = builder.Build(); + app.MapHub("/hubs/config"); + app.MapGet("/api/settings/agent/{id}", () => Volatile.Read(ref config)); + await app.StartAsync(); + var factory = Substitute.For(); + factory.CreateClient("Central").Returns(_ => new HttpClient()); + var store = new CameraConfigStore(); + using var receiver = CreateService(new AgentState { AgentId = Guid.NewGuid(), ApiKey = "fixture" }, + httpFactory: factory, cameraStore: store, centralUrl: app.Urls.Single()); + await receiver.StartAsync(CancellationToken.None); + try + { + await WaitForAsync(() => store.Cameras.Any(c => c.CameraId == initialId)); + Volatile.Write(ref config, new Dictionary + { [$"camera.{nextId}.rtsp"] = "rtsp://next", [$"camera.{nextId}.enabled"] = "false" }); + // Abort the HTTP transport without sending a SignalR close message. + ReconnectFixtureHub.AbortTransport!(); + await WaitForAsync(() => store.Cameras.Count == 1 && store.Cameras[0].CameraId == nextId && + ReconnectFixtureHub.JoinCount >= 2); + store.Cameras.Single().Enabled.ShouldBeFalse(); + } + finally { await receiver.StopAsync(CancellationToken.None); } + } + + private static async Task WaitForAsync(Func condition) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + while (!condition()) await Task.Delay(50, timeout.Token); + } + [Fact] public void Sensitive_setting_values_are_never_logged_even_when_invalid_or_unknown() { @@ -503,3 +548,16 @@ public class ConfigReceiverServiceTests } } } + +public sealed class ReconnectFixtureHub : Hub +{ + public static Action? AbortTransport { get; private set; } + private static int _joinCount; + public static int JoinCount => Volatile.Read(ref _joinCount); + public Task JoinAgentGroup(string agentId) + { + Interlocked.Increment(ref _joinCount); + AbortTransport = Context.GetHttpContext()!.Abort; + return Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}"); + } +} diff --git a/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs b/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs index 2bf6e63..677b98d 100644 --- a/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs +++ b/tests/Heimdall.Application.Tests/Cameras/Commands/ReportCameraStatusCommandTests.cs @@ -35,6 +35,17 @@ public class ReportCameraStatusCommandTests return (agent, camera); } + [Fact] + public async Task Handle_DisabledCamera_InFlightOnlineReportCannotReenableIt() + { + var (agent, camera) = Seed(Guid.NewGuid(), CameraStatus.Disabled); + var result = await _handler.Handle(new ReportCameraStatusCommand(agent.Id, camera.Id, CameraStatus.Online), CancellationToken.None); + result.IsSuccess.ShouldBeTrue(); + camera.Status.ShouldBe(CameraStatus.Disabled); + await _db.DidNotReceiveWithAnyArgs().SaveChangesWithRetryAsync(default, default); + await _monitoring.DidNotReceiveWithAnyArgs().NotifyCameraStatusChanged(default, default, default!, default); + } + [Fact] public async Task Handle_CameraBelongsToAgentSite_UpdatesStatusAndBroadcasts() { diff --git a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs index 3ba9e22..b6d0579 100644 --- a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs @@ -141,6 +141,90 @@ public class CameraAssignmentServiceTests : IAsyncLifetime result.IsSuccess.ShouldBeFalse(); } + [Fact] + public async Task FailoverWithoutReplacement_ClearsAgent_ThenReconcilesOnRecovery() + { + var service = new CameraAssignmentService(_dbFactory, _logger); + var (siteId, agentId, cameraId) = await SeedAsync(); + (await service.AssignCameraAsync(cameraId, agentId, "initial", CancellationToken.None)).IsSuccess.ShouldBeTrue(); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + var agent = await db.Agents.FindAsync(agentId); + agent!.MarkOffline(); + await db.SaveChangesAsync(); + } + await service.FailoverAgentAsync(agentId, CancellationToken.None); + (await service.GetActiveAssignmentAsync(cameraId, CancellationToken.None)).ShouldBeNull(); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + (await db.Cameras.FindAsync(cameraId))!.AgentId.ShouldBeNull(); + (await db.Agents.FindAsync(agentId))!.UpdateHeartbeat(null); + await db.SaveChangesAsync(); + } + (await service.AssignSiteCamerasAsync(siteId, AssignmentStrategy.Failover, CancellationToken.None)).IsSuccess.ShouldBeTrue(); + (await service.GetActiveAssignmentAsync(cameraId, CancellationToken.None))!.AgentId.ShouldBe(agentId); + await using var verify = await _dbFactory.CreateDbContextAsync(); + (await verify.Cameras.FindAsync(cameraId))!.AgentId.ShouldBe(agentId); + } + + [Fact] + public async Task CameraInvalidation_IsPublishedAfterSave_AndNotOnFailedSave() + { + var (_, _, cameraId) = await SeedAsync(); + await using var source = await _dbFactory.CreateDbContextAsync(); + var options = new DbContextOptionsBuilder() + .UseNpgsql(source.Database.GetConnectionString()).Options; + var broadcast = Substitute.For(); + string? observedName = null; + broadcast.NotifyAllAgentsReload(Arg.Any()).Returns(async _ => + { + await using var verify = await _dbFactory.CreateDbContextAsync(); + observedName = (await verify.Cameras.FindAsync(cameraId))!.Name; + }); + await using (var db = new AppDbContext(options, new Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor(), broadcast)) + { + (await db.Cameras.FindAsync(cameraId))!.Update("committed", null, null, null); + await db.SaveChangesAsync(); + } + observedName.ShouldBe("committed"); + await broadcast.Received(1).NotifyAllAgentsReload(Arg.Any()); + broadcast.ClearReceivedCalls(); + await using (var db = new AppDbContext(options, new Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor(), broadcast)) + { + db.Cameras.Add(new Camera(Guid.NewGuid(), "invalid-site", "rtsp://invalid")); + await Should.ThrowAsync(() => db.SaveChangesAsync()); + } + await broadcast.DidNotReceive().NotifyAllAgentsReload(Arg.Any()); + } + + [Fact] + public async Task DetectionProfile_UpdatePersists_AndEffectiveConfigCarriesVersionedContract() + { + var (_, agentId, cameraId) = await SeedAsync(); + var assignment = new CameraAssignmentService(_dbFactory, _logger); + await assignment.AssignCameraAsync(cameraId, agentId, "profile-test", CancellationToken.None); + var profile = new Heimdall.Application.DTOs.DetectionProfileDto + { MinConfidence = .85f, DetectVehicle = false, ZoneX = .5, ZoneWidth = .5, IdleIntervalMs = 2000 }; + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + var handler = new Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandHandler(db); + var result = await handler.Handle(new(cameraId, "configured", null, null, DetectionProfile: profile), CancellationToken.None); + result.IsSuccess.ShouldBeTrue(); + } + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + var query = new Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig.GetEffectiveAgentConfigQueryHandler(db, + Substitute.For()); + var result = await query.Handle(new(agentId), CancellationToken.None); + result.IsSuccess.ShouldBeTrue(); + System.Text.Json.JsonSerializer.Deserialize(result.Data![$"camera.{cameraId}.profile"]).ShouldBe(profile); + var handler = new Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandHandler(db); + var invalid = await handler.Handle(new(cameraId, "invalid", null, null, DetectionProfile: profile with { Version = 2 }), CancellationToken.None); + invalid.IsSuccess.ShouldBeFalse(); + (await db.Cameras.FindAsync(cameraId))!.Name.ShouldBe("configured"); + } + } + // ─── Seed Helpers ──────────────────────────────────────────────── private async Task<(Guid siteId, Guid agentId, Guid cameraId)> SeedAsync() @@ -156,6 +240,7 @@ public class CameraAssignmentServiceTests : IAsyncLifetime await db.SaveChangesAsync(); var camera = new Camera(site.Id, "Cam-1", "rtsp://192.168.1.100:554/stream1"); + camera.SetStatus(CameraStatus.Online); camera.SetDiscoveryInfo(CameraDiscoveryMethod.Manual, DetectedCameraType.Standard, null, "192.168.1.100"); db.Cameras.Add(camera); await db.SaveChangesAsync(); @@ -177,6 +262,7 @@ public class CameraAssignmentServiceTests : IAsyncLifetime { await using var db = await _dbFactory.CreateDbContextAsync(); var camera = new Camera(siteId, name, $"rtsp://{ip}:554/stream1"); + camera.SetStatus(CameraStatus.Online); camera.SetDiscoveryInfo(CameraDiscoveryMethod.Manual, DetectedCameraType.Standard, null, ip); db.Cameras.Add(camera); await db.SaveChangesAsync();