feat: support person and vehicle analysis jobs
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
Heimdall Gitea / Build and tests (pull_request) Failing after 15m37s
Heimdall Gitea / Build and scan agent image (pull_request) Skipped

This commit is contained in:
arnaud.dartois committed 2026-11-05 13:29:03 +01:00
1 parent 1b1b99641b
commit 7d1a4b6277
8 files changed
+214 -12

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
---
name: analysis-job-pipeline
description: Implement and verify analysis job types across Heimdall Central scheduling and Agent inference.
---
# Heimdall analysis job pipeline
Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet/SKILL.md`. For database behavior, also follow `skills/ef-core-persistence/SKILL.md`.
## Current supported job types
- `ObjectDetection`: return every detection produced by the configured YOLO COCO model.
- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`).
- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`). Keep the model label, confidence, box and class index in the result.
- The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result.
- Motion detection needs temporal frame comparison; face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection.
- Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types.
## Required validation
1. Unit-test Agent type parsing and the exact COCO class filtering for all three supported types, including empty results and unsupported types.
2. Run PostgreSQL scheduler tests proving CPU/RAM requirements for supported types and refusal of unsupported types. Do not substitute EF InMemory for relational behavior.
3. Run the PostgreSQL integration scenario through the Web API: create each supported job, dispatch to the assigned online Agent, claim it with the Agent API key, submit a result, and verify persisted completion. Verify unsupported type requests receive HTTP 400.
4. Build Central from the changed source in a uniquely tagged disposable Compose project with generated credentials, loopback-only ports, project-owned volumes/network, empty Sentry DSN, and OCR disabled unless the scenario explicitly needs it. Bootstrap synthetic Admin/site/camera, register and heartbeat a synthetic Agent, assign the camera, submit supported and unsupported job types, and verify the lease/result boundary where practical.
5. Tear down that exact Compose project, verify zero project containers/volumes/networks, remove every source-built image tag from this recipe and verify each exact tag is absent. Retain shared Postgres/.NET base images. Never use broad prune commands.
6. Keep hardware, camera-stream inference, and real multi-Agent deployment claims separate from synthetic database/API acceptance.
## Current local acceptance evidence
On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections; it does not prove inference from camera frames, MotionDetection, face/plate models, anomaly detection, full-scene analysis, or deployed multi-Agent behavior.
@@ -82,7 +82,7 @@ public sealed class AnalysisJobPollingService : BackgroundService
private async Task<AnalysisResult> ExecuteJobAsync(LeasedJob job, CancellationToken ct)
{
if (!IsObjectDetection(job.JobType))
if (!TryGetSupportedJobType(job.JobType, out var jobType))
return Failure(job.AttemptId, "Unsupported analysis job type");
var camera = _cameras.Cameras.FirstOrDefault(c => c.CameraId == job.CameraId && c.Enabled);
@@ -110,7 +110,8 @@ public sealed class AnalysisJobPollingService : BackgroundService
if (analysis is null)
return Failure(job.AttemptId, "Object detection was unavailable or saturated");
return new AnalysisResult(job.AttemptId, true, null, analysis.Detections
var detections = SelectDetections(jobType, analysis.Detections);
return new AnalysisResult(job.AttemptId, true, null, detections
.Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex))
.ToArray());
}
@@ -154,14 +155,37 @@ public sealed class AnalysisJobPollingService : BackgroundService
}
}
private static bool IsObjectDetection(JsonElement type) => type.ValueKind switch
internal static IReadOnlyList<DetectionResult> SelectDetections(
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections) => jobType switch
{
JsonValueKind.String => string.Equals(type.GetString(), nameof(AnalysisJobType.ObjectDetection),
StringComparison.OrdinalIgnoreCase),
JsonValueKind.Number => type.TryGetInt32(out var value) && value == (int)AnalysisJobType.ObjectDetection,
_ => false,
AnalysisJobType.ObjectDetection => detections,
AnalysisJobType.PersonDetection => detections.Where(IsPerson).ToArray(),
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle).ToArray(),
_ => [],
};
private static bool IsPerson(DetectionResult detection) =>
detection.ClassIndex == 0 || string.Equals(detection.Label, "person", StringComparison.OrdinalIgnoreCase);
private static bool IsVehicle(DetectionResult detection) =>
detection.ClassIndex is 2 or 3 or 5 or 7 || detection.Label.ToLowerInvariant() is "car" or "motorcycle" or "bus" or "truck";
internal static bool TryGetSupportedJobType(JsonElement type, out AnalysisJobType jobType)
{
if (type.ValueKind == JsonValueKind.String && Enum.TryParse(type.GetString(), true, out jobType))
return IsSupported(jobType);
if (type.ValueKind == JsonValueKind.Number && type.TryGetInt32(out var value) && Enum.IsDefined(typeof(AnalysisJobType), value))
{
jobType = (AnalysisJobType)value;
return IsSupported(jobType);
}
jobType = default;
return false;
}
private static bool IsSupported(AnalysisJobType type) => type is AnalysisJobType.ObjectDetection or
AnalysisJobType.PersonDetection or AnalysisJobType.VehicleClassification;
private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []);
private static bool TryGetMinConfidence(string? parametersJson, out float confidence)
@@ -45,8 +45,9 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
if (camera is null)
return ServiceResult<AnalysisJob>.NotFound("Camera not found");
if (jobType != AnalysisJobType.ObjectDetection)
return ServiceResult<AnalysisJob>.Failure("Only ObjectDetection jobs are currently supported");
if (jobType is not (AnalysisJobType.ObjectDetection or AnalysisJobType.PersonDetection or
AnalysisJobType.VehicleClassification))
return ServiceResult<AnalysisJob>.Failure($"Analysis jobs of type {jobType} are not currently supported");
var job = new AnalysisJob(cameraId, camera.SiteId, jobType, priority, parametersJson);
@@ -36,8 +36,9 @@ public sealed class AnalysisJobsController(
if (requester is null || requester.Kind != RequesterKind.Human ||
!await access.CameraAsync(requester, cameraId, ct)) return Forbid();
if (!Enum.TryParse<AnalysisJobType>(request.JobType, true, out var type) ||
type != AnalysisJobType.ObjectDetection)
return BadRequest(new { error = "Only ObjectDetection jobs are currently supported" });
type is not (AnalysisJobType.ObjectDetection or AnalysisJobType.PersonDetection or
AnalysisJobType.VehicleClassification))
return BadRequest(new { error = "Supported analysis job types are ObjectDetection, PersonDetection, and VehicleClassification" });
if (request.ParametersJson is { Length: > 16_384 } || !IsValidParameters(request.ParametersJson))
return BadRequest(new { error = "ParametersJson may contain only minConfidence, a number from 0 to 1, and must be at most 16 KiB" });
@@ -0,0 +1,56 @@
using System.Text.Json;
using Heimdall.Agent.Services;
using Heimdall.Domain.Enums;
namespace Heimdall.Agent.Tests;
public sealed class AnalysisJobPollingServiceTests
{
private static readonly DetectionResult[] CocoDetections =
[
new("person", 0.91f, 0.1f, 0.2f, 0.2f, 0.5f, 0),
new("bicycle", 0.82f, 0.2f, 0.2f, 0.3f, 0.4f, 1),
new("car", 0.88f, 0.4f, 0.3f, 0.4f, 0.3f, 2),
new("bus", 0.77f, 0.5f, 0.2f, 0.3f, 0.4f, 5),
];
[Fact]
public void SelectDetections_PersonDetection_ReturnsOnlyPersonClass()
{
var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.PersonDetection, CocoDetections);
result.Select(d => d.Label).ShouldBe(["person"]);
}
[Fact]
public void SelectDetections_VehicleClassification_ReturnsCocoMotorVehicles()
{
var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.VehicleClassification, CocoDetections);
result.Select(d => d.Label).ShouldBe(["car", "bus"]);
}
[Fact]
public void SelectDetections_ObjectDetection_PreservesAllModelClasses()
{
var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.ObjectDetection, CocoDetections);
result.ShouldBe(CocoDetections);
}
[Theory]
[InlineData("\"PersonDetection\"", true)]
[InlineData("\"vehicLeClassification\"", true)]
[InlineData("3", true)]
[InlineData("5", true)]
[InlineData("0", false)]
[InlineData("\"FaceRecognition\"", false)]
[InlineData("\"not-a-job\"", false)]
public void SupportedJobTypes_AcceptsOnlyImplementedContracts(string json, bool expected)
{
using var document = JsonDocument.Parse(json);
var actual = AnalysisJobPollingService.TryGetSupportedJobType(document.RootElement, out _);
actual.ShouldBe(expected);
}
}
@@ -128,6 +128,39 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
result.Data.RequiredMemoryMb.ShouldBe(2048);
}
[Theory]
[InlineData(AnalysisJobType.PersonDetection, 1024)]
[InlineData(AnalysisJobType.VehicleClassification, 1024)]
public async Task CreateJobAsync_SupportedFilteredDetectionTypes_SetsCpuRequirements(
AnalysisJobType type, int memoryMb)
{
var (_, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeTrue();
result.Data!.JobType.ShouldBe(type);
result.Data.RequiresGpu.ShouldBeFalse();
result.Data.RequiredCpuCores.ShouldBe(2);
result.Data.RequiredMemoryMb.ShouldBe(memoryMb);
}
[Theory]
[InlineData(AnalysisJobType.MotionDetection)]
[InlineData(AnalysisJobType.FaceRecognition)]
[InlineData(AnalysisJobType.LicensePlateDetection)]
[InlineData(AnalysisJobType.AnomalyDetection)]
[InlineData(AnalysisJobType.FullSceneAnalysis)]
public async Task CreateJobAsync_UnimplementedDetectionTypes_ReturnsFailure(AnalysisJobType type)
{
var (_, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeFalse();
result.Error!.ShouldContain(type.ToString());
}
// ── SelectBestAgent ─────────────────────────────────────────────
[Fact]
@@ -14,6 +14,63 @@ namespace Heimdall.IntegrationTests.Scenarios;
[Collection("Postgres")]
public sealed class AnalysisJobScenarios(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres)
{
[Theory]
[InlineData("PersonDetection")]
[InlineData("VehicleClassification")]
public async Task AnalysisJob_SupportedFilteredDetectionType_IsScheduledAndClaimed(string jobType)
{
var admin = await Factory.CreateAdminClientAsync();
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
{
name = $"Analysis {Guid.NewGuid():N}",
timezone = "UTC"
});
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var siteId = (await siteResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
var agent = await RegisterAgentAsync(admin, siteId, $"analysis-{jobType}");
var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new
{
siteId,
name = $"{jobType} camera",
rtspUrl = "rtsp://127.0.0.1/test"
});
cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var cameraId = (await cameraResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
(await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId = agent.Id }))
.StatusCode.ShouldBe(HttpStatusCode.OK);
var unsupported = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs",
new { jobType = "MotionDetection" });
unsupported.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
var created = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", new { jobType });
created.StatusCode.ShouldBe(HttpStatusCode.Accepted);
var jobId = (await created.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("jobId").GetGuid();
await DispatchPendingJobsAsync();
var claim = await ClaimNextAsync(agent);
claim.StatusCode.ShouldBe(HttpStatusCode.OK);
var lease = await claim.Content.ReadFromJsonAsync<JsonElement>();
lease.GetProperty("jobType").GetString().ShouldBe(jobType);
var completed = await AgentClient(agent.ApiKey).PutAsJsonAsync(
$"api/agents/{agent.Id}/analysis-jobs/{jobId}/result",
new
{
attemptId = lease.GetProperty("attemptId").GetGuid(),
success = true,
detections = new[] { new { label = jobType == "PersonDetection" ? "person" : "car",
confidence = 0.93, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } }
});
completed.StatusCode.ShouldBe(HttpStatusCode.NoContent);
var persisted = await admin.GetAsync($"api/cameras/{cameraId}/analysis-jobs/{jobId}");
persisted.StatusCode.ShouldBe(HttpStatusCode.OK);
var persistedJob = await persisted.Content.ReadFromJsonAsync<JsonElement>();
persistedJob.GetProperty("status").ToString().ShouldBe("Completed");
persistedJob.GetProperty("resultJson").GetString()!.ShouldContain(
jobType == "PersonDetection" ? "person" : "car");
}
[Fact]
public async Task AnalysisJob_RetriesOnReassignedAgent_AndRejectsLatePreviousAttempt()
{
+1 -1
View File
@@ -25,7 +25,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
- [x] **EF Core / règles de persistance** La PR #116 remplace l’ADO.NET des deux outboxes Agent et du catalogue caméra par EF Core SQLite, préserve les bases locales existantes avec une adoption de schéma testée, et bloque en CI les commandes directes non autorisées. Elle ajoute la skill `skills/ef-core-persistence/`, relie les règles du dépôt au skill et documente les exceptions PostgreSQL spécifiques. Son run PR #390 a passé les tests/builds, les scans serveur/Agent et `CI policy`; fusionnée sur `main` (`9e0eeb8`).
- [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées.
- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse.
- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection` et `VehicleClassification` sont maintenant acceptés par l’API et le scheduler et utilisent le même modèle YOLO COCO, filtré respectivement sur personne (classe 0) et véhicules motorisés (classes 2/3/5/7); les autres types restent refusés tant que leurs algorithmes/modèles ne sont pas implémentés. Tests ciblés Agent 10/10, scheduler PostgreSQL 10/10, scénario d’intégration des deux types 2/2. Compose source jetable `hmd-analysis-1793881315-5ba569` : Agent synthétique enregistré/heartbeaté et caméra assignée; MotionDetection rejeté HTTP 400; jobs personne/véhicule créés, dispatchés, réclamés, complétés et résultats relus via API après persistance PostgreSQL. Tag source dédié supprimé/vérifié absent, teardown zéro conteneur/volume/réseau. Reste : inférence réelle sur flux de caméra synthétique, MotionDetection temporel, reconnaissance faciale/plaque et autres modèles/types, ainsi que validation sur deux Agents déployés. Skill : `skills/analysis-job-pipeline/SKILL.md`.
- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire.
- [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces.
- [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé.