fix(agent): cap analysis results at Central limit (#279)
Heimdall Gitea / Detect CI scope (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Successful in 22m59s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m5s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m5s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m34s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 16m16s
Heimdall Gitea / CI policy (push) Successful in 2s

Refs #270

Caps successful analysis result payloads to Central’s 500-detection limit after type filtering, preserving input/model order for ObjectDetection, PersonDetection, and VehicleClassification. Adds >500 boundary/order tests for all three types and updates the analysis pipeline skill.

Validation: `dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore --filter FullyQualifiedName~AnalysisJobPollingServiceTests` passed 16/16; `git diff --check` passed.

Compose acceptance remains incomplete. Source-built disposable stacks were started with unique projects, generated secrets/ports/volumes and unique Central image tags. Two runs did not reach healthy Postgres; a later run reached healthy Central but the isolated bootstrap-admin returned HTTP 400 because the generated test password did not meet Identity complexity. Therefore no 501 rejection / 500 persistence assertions were made. For each project, Compose teardown completed; label queries confirmed no project containers, volumes, or networks; each exact local image tag was inspected absent. One incomplete trap's two known JSON files were individually removed with `unlink` and its empty directory with `rmdir`. A later trap had harmless unlink attempts for not-yet-created paths and reported a cleanup error; independent checks confirmed its temp directory, project resources, and exact image tag were absent.

Do not treat the Compose acceptance as passed. The server controller and readback shape were inspected in source only. Post-deployment GlitchTip validation also remains open.
Reviewed-on: #279
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #279.
This commit is contained in:
arnaud.dartois authored and Arnaud Dartois committed 2026-11-07 13:42:01 +01:00
1 parent 1b512ab040
commit cae09e3698
4 files changed
+78 -11

No files matched your search

+4 -3
View File
@@ -9,13 +9,14 @@ Read `AGENTS.md`, the PIPE-01/02 Gitea issue, and `skills/heimdall-dotnet/SKILL.
## 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.
- `ObjectDetection`: return detections produced by the configured YOLO COCO model in model order, capped at 500 because Central rejects larger successful results. The Agent truncates deterministically before serialization so the result can be persisted; detections after the first 500 are intentionally omitted.
- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`), capped at 500 after filtering while preserving model order.
- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`), capped at 500 after filtering while preserving model order. Keep the model label, confidence, box and class index in the result.
- `MotionDetection`: capture two frames from the already active RTSP stream 500 ms apart, downscale both to 32×18, and compare normalized luminance. A changed pixel must differ by at least 0.12; at least 2% changed pixels returns one `motion` detection with changed-region bounds and changed-pixel ratio as confidence. This CPU-only temporal detector does not require the YOLO model; lighting changes and camera shake may produce motion, so tune/measure it against representative cameras before relying on alerts.
- 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.
- 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.
- For every job type, cap successful result detections at Central’s 500-item limit in stable model order. For filtered types, filter first and then cap so unrelated model classes do not consume the result budget. Add boundary tests proving the output count and retained order for ObjectDetection and filtered types. This prevents Central’s permanent HTTP 400 rejection from silently discarding the whole result, while making the truncation explicit.
- Result delivery retries transport failures, timeouts and HTTP 5xx with bounded backoff. A 409/404 attempt is no longer current and stops immediately; other HTTP 4xx responses are permanent for that submission and must also stop immediately so a bad result cannot block the Agent's next poll. Log the status code and job ID only; do not read or log Central response bodies.
## Required validation
+12 -2
View File
@@ -34,6 +34,13 @@ Compose teardown cannot skip image and temporary-file cleanup. Preserve the
original status and return a failure if any cleanup verification fails:
```bash
# Initialize these exact paths before installing the trap. Omit source_copy if
# the recipe does not create a source archive.
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
compose_override="$temp_dir/compose.override.yml"
source_copy="$temp_dir/source-copy.tar"
cleanup() {
status=$?
trap - EXIT
@@ -50,7 +57,10 @@ cleanup() {
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
rm -rf -- "$temp_dir" || cleanup_failed=1
# Remove only the files this recipe generated; rmdir fails visibly if
# anything unexpected remains in the temporary directory.
rm -f -- "$env_file" "$compose_override" "$source_copy" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable recipe cleanup failed for project %s\\n' "$project" >&2
status=1
@@ -81,6 +91,6 @@ recipe that reports teardown without the image-tag check is incomplete.
3. Start the minimal Central + PostgreSQL stack from source with `docker compose -p <unique-name> --env-file <temp-env> -f docker/docker-compose.yml -f <temp-image-override> up -d --build`.
4. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path.
5. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files.
6. Install an `EXIT` trap before the first build/start operation. The trap must preserve the test command's exit status, run `docker compose ... down --volumes --remove-orphans`, verify no project containers/volumes/networks remain, remove every recorded project-unique locally built image tag and verify each is absent, then delete temporary environment, secrets, override, and copied-source files. Attempt each cleanup action even if an earlier cleanup action fails; surface any cleanup failure. Retain shared upstream/base images. Do not use Compose `--rmi all` or broad prune commands.
6. Install an `EXIT` trap before the first build/start operation. The trap must preserve the test command's exit status, run `docker compose ... down --volumes --remove-orphans`, verify no project containers/volumes/networks remain, remove every recorded project-unique locally built image tag and verify each is absent, then delete each explicitly named generated environment, secret, override, and copied-source file with `rm -f`. Finish with `rmdir` on the one temporary directory; a non-empty directory must make cleanup fail visibly. Attempt each cleanup action even if an earlier action fails. Retain shared upstream/base images. Do not use recursive deletion, Compose `--rmi all`, or broad prune commands.
If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed.
@@ -11,6 +11,7 @@ namespace Heimdall.Agent.Services;
/// </summary>
public sealed class AnalysisJobPollingService : BackgroundService
{
internal const int MaxDetectionsPerResult = 500;
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5);
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private readonly AgentState _state;
@@ -184,13 +185,18 @@ public sealed class AnalysisJobPollingService : BackgroundService
}
internal static IReadOnlyList<DetectionResult> SelectDetections(
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections) => jobType switch
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections)
{
AnalysisJobType.ObjectDetection => detections,
AnalysisJobType.PersonDetection => detections.Where(IsPerson).ToArray(),
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle).ToArray(),
_ => [],
};
IEnumerable<DetectionResult> selected = jobType switch
{
AnalysisJobType.ObjectDetection => detections,
AnalysisJobType.PersonDetection => detections.Where(IsPerson),
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle),
_ => [],
};
return selected.Take(MaxDetectionsPerResult).ToArray();
}
private static bool IsPerson(DetectionResult detection) =>
detection.ClassIndex == 0 || string.Equals(detection.Label, "person", StringComparison.OrdinalIgnoreCase);
@@ -40,6 +40,56 @@ public sealed class AnalysisJobPollingServiceTests
result.ShouldBe(CocoDetections);
}
[Fact]
public void SelectDetections_ObjectDetection_EnforcesCentralLimitInStableOrder()
{
var detections = Enumerable.Range(0, AnalysisJobPollingService.MaxDetectionsPerResult + 1)
.Select(i => new DetectionResult($"object-{i}", 0.9f, 0, 0, 0.1f, 0.1f, i))
.ToArray();
var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.ObjectDetection, detections);
result.Count.ShouldBe(AnalysisJobPollingService.MaxDetectionsPerResult);
result[0].Label.ShouldBe("object-0");
result[^1].Label.ShouldBe("object-499");
}
[Fact]
public void SelectDetections_PersonDetection_EnforcesCentralLimitAfterFilteringInStableOrder()
{
var detections = Enumerable.Range(0, AnalysisJobPollingService.MaxDetectionsPerResult + 1)
.Select(i => new DetectionResult($"person-{i}", 0.9f, 0, 0, 0.1f, 0.1f, 0))
.SelectMany((d, i) => new[]
{
new DetectionResult($"other-{i}", 0.8f, 0, 0, 0.1f, 0.1f, 1), d,
})
.ToArray();
var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.PersonDetection, detections);
result.Count.ShouldBe(AnalysisJobPollingService.MaxDetectionsPerResult);
result[0].Label.ShouldBe("person-0");
result[^1].Label.ShouldBe("person-499");
}
[Fact]
public void SelectDetections_VehicleClassification_EnforcesCentralLimitAfterFilteringInStableOrder()
{
var detections = Enumerable.Range(0, AnalysisJobPollingService.MaxDetectionsPerResult + 1)
.Select(i => new DetectionResult($"car-{i}", 0.9f, 0, 0, 0.1f, 0.1f, 2))
.SelectMany((d, i) => new[]
{
new DetectionResult($"other-{i}", 0.8f, 0, 0, 0.1f, 0.1f, 1), d,
})
.ToArray();
var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.VehicleClassification, detections);
result.Count.ShouldBe(AnalysisJobPollingService.MaxDetectionsPerResult);
result[0].Label.ShouldBe("car-0");
result[^1].Label.ShouldBe("car-499");
}
[Fact]
public void DetectionResult_UsesCentralJsonContract()
{