Files
Heimdall/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs
T
arnaud.dartois cae09e3698
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
fix(agent): cap analysis results at Central limit (#279)
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>
2026-11-07 13:42:01 +01:00

247 lines
11 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.Domain.Enums;
namespace Heimdall.Agent.Services;
/// <summary>
/// Claims one durable analysis job at a time over the agent's outbound Central connection.
/// Central owns the lease and attempt ID; a repeated result uses that same ID.
/// </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;
private readonly CameraConfigStore _cameras;
private readonly CameraStreamService _streams;
private readonly FrameAnalyzerService _analyzer;
private readonly IHttpClientFactory _clients;
private readonly ILogger<AnalysisJobPollingService> _logger;
public AnalysisJobPollingService(AgentState state, CameraConfigStore cameras,
CameraStreamService streams, FrameAnalyzerService analyzer, IHttpClientFactory clients,
ILogger<AnalysisJobPollingService> logger)
{
_state = state;
_cameras = cameras;
_streams = streams;
_analyzer = analyzer;
_clients = clients;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
if (_state.AgentId != Guid.Empty && !string.IsNullOrWhiteSpace(_state.ApiKey))
await PollOnceAsync(stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Analysis job polling failed; Central will retain or retry the leased job");
}
try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
}
}
private async Task PollOnceAsync(CancellationToken ct)
{
var agentId = _state.AgentId;
using var client = _clients.CreateClient("Central");
client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
using var response = await client.GetAsync($"api/agents/{agentId:D}/analysis-jobs/next", ct)
.ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.NoContent) return;
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Analysis job claim failed with HTTP {StatusCode}", (int)response.StatusCode);
return;
}
var job = await response.Content.ReadFromJsonAsync<LeasedJob>(Json, ct).ConfigureAwait(false);
if (job is null || job.JobId == Guid.Empty || job.CameraId == Guid.Empty || job.AttemptId == Guid.Empty)
{
_logger.LogError("Central returned an invalid analysis job lease");
return;
}
var result = await ExecuteJobAsync(job, ct).ConfigureAwait(false);
await SendResultAsync(client, agentId, job.JobId, result, ct).ConfigureAwait(false);
}
private async Task<AnalysisResult> ExecuteJobAsync(LeasedJob job, CancellationToken ct)
{
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);
if (camera is null || !_streams.IsStreamActive(job.CameraId))
return Failure(job.AttemptId, "Camera is not assigned, enabled, or streaming");
if (jobType != AnalysisJobType.MotionDetection && !_analyzer.ModelAvailable)
return Failure(job.AttemptId, "Object detection model is unavailable");
Snapshot? frame;
try
{
frame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
frame = null;
}
if (frame is null)
return Failure(job.AttemptId, "Camera frame capture failed or timed out");
if (jobType == AnalysisJobType.MotionDetection)
{
await Task.Delay(TimeSpan.FromMilliseconds(500), ct).ConfigureAwait(false);
Snapshot? nextFrame;
try
{
nextFrame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
nextFrame = null;
}
if (nextFrame is null)
return Failure(job.AttemptId, "Camera frame capture failed or timed out");
var motion = MotionDetectionAnalyzer.Compare(frame.JpegData, nextFrame.JpegData);
return new AnalysisResult(job.AttemptId, true, null, motion
.Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex))
.ToArray());
}
var confidence = TryGetMinConfidence(job.ParametersJson, out var requestedConfidence)
? requestedConfidence
: camera.DetectionProfile?.MinConfidence ?? FrameAnalyzerService.DefaultMinConfidence;
var analysis = await _analyzer.AnalyzeFrameAsync(frame.JpegData, confidence, ct).ConfigureAwait(false);
if (analysis is null)
return Failure(job.AttemptId, "Object detection was unavailable or saturated");
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());
}
internal async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId,
AnalysisResult result, CancellationToken ct)
{
var retryDelay = TimeSpan.FromSeconds(2);
while (!ct.IsCancellationRequested)
{
try
{
using var response = await client.PutAsJsonAsync(
$"api/agents/{agentId:D}/analysis-jobs/{jobId:D}/result", result, Json, ct)
.ConfigureAwait(false);
if (response.IsSuccessStatusCode) return;
if (response.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.NotFound)
{
_logger.LogInformation("Analysis job {JobId} attempt {AttemptId} is no longer current",
jobId, result.AttemptId);
return;
}
if ((int)response.StatusCode is >= 400 and < 500)
{
_logger.LogError(
"Analysis result for job {JobId} was permanently rejected with HTTP {StatusCode}; stopping retries",
jobId, (int)response.StatusCode);
return;
}
_logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying",
jobId, (int)response.StatusCode);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (HttpRequestException ex)
{
_logger.LogWarning(ex, "Analysis result delivery failed for job {JobId}; retrying", jobId);
}
catch (TaskCanceledException ex) when (!ct.IsCancellationRequested)
{
_logger.LogWarning(ex, "Analysis result delivery timed out for job {JobId}; retrying", jobId);
}
await Task.Delay(retryDelay, ct).ConfigureAwait(false);
retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 30));
}
}
internal static IReadOnlyList<DetectionResult> SelectDetections(
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections)
{
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);
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 or AnalysisJobType.MotionDetection;
private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []);
private static bool TryGetMinConfidence(string? parametersJson, out float confidence)
{
confidence = default;
if (string.IsNullOrWhiteSpace(parametersJson)) return false;
try
{
using var document = JsonDocument.Parse(parametersJson);
return document.RootElement.ValueKind == JsonValueKind.Object &&
document.RootElement.TryGetProperty("minConfidence", out var value) &&
value.ValueKind == JsonValueKind.Number && value.TryGetSingle(out confidence) &&
float.IsFinite(confidence) && confidence is >= 0 and <= 1;
}
catch (JsonException) { return false; }
}
private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType,
string? ParametersJson);
internal sealed record AnalysisDetection(string Label, float Confidence, float X, float Y,
float Width, float Height, int? ClassIndex);
internal sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error,
IReadOnlyList<AnalysisDetection> Detections);
}