From 1a34e2f2ac5611189db60ce69db46e3801a362ec Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 12 Nov 2026 13:26:28 +0100 Subject: [PATCH 1/4] fix(agent): reconcile camera config changes immediately --- skills/camera-toggle-acceptance/SKILL.md | 13 +- skills/camera-toggle-acceptance/acceptance.sh | 234 ++++++++++++++++++ .../Services/SnapshotPipelineService.cs | 17 +- .../SnapshotPipelineServiceTests.cs | 55 +++- 4 files changed, 306 insertions(+), 13 deletions(-) create mode 100755 skills/camera-toggle-acceptance/acceptance.sh diff --git a/skills/camera-toggle-acceptance/SKILL.md b/skills/camera-toggle-acceptance/SKILL.md index 0521c8f..4a5b55e 100644 --- a/skills/camera-toggle-acceptance/SKILL.md +++ b/skills/camera-toggle-acceptance/SKILL.md @@ -14,6 +14,7 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn - `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest. - `GetEffectiveAgentConfigQuery` emits `camera..enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`. - `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera. +- `SnapshotPipelineService` reconciles configuration on `CameraConfigStore.Changed`, while retaining a one-second config-change poll and the existing 30-second full resync as recovery. Coalesce notifications and ensure there is only one waiter on the config signal. - Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled. - Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state. @@ -31,6 +32,8 @@ These tests cover session idempotence, process termination, and synchronization ## Central + Agent disposable acceptance +Run `skills/camera-toggle-acceptance/acceptance.sh` from the repository root. It builds both application images from source, bootstraps synthetic Central/site/camera data, registers the real Agent container, repeats three ON/OFF cycles, checks the OFF PID bound, restarts Agent and Central while OFF, correlates the final applied config digest, and verifies exact project/tag cleanup in its EXIT trap. + - Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images. - Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials. - Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent. @@ -54,7 +57,15 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel ## Sixth source-built run -The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold. +The sixth historical run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound and did not run restart-OFF acceptance. The subsequent 2026-11-12 acceptance below supersedes that incomplete result for current source. + +## Immediate config reconciliation regression test + +`SnapshotPipelineServiceTests.CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync` starts the pipeline, lets its initial synchronization complete, then changes the Central snapshot and requires the assigned camera's Error report (FFmpeg deliberately unavailable) within 500ms. This proves event-driven reconciliation ahead of the one-second config-change poll and 30-second full resync; it does not prove process termination or the full camera lifecycle. Run it with the focused camera stream suite before Compose acceptance. + +## Source-built acceptance — 2026-11-12 + +`acceptance.sh` passed with project `heimdall-157-1794486043-22368`, Central tag `heimdall:heimdall-157-1794486043-22368-central`, and Agent tag `heimdall-agent:heimdall-157-1794486043-22368-agent`. It exercised three ON/OFF cycles with FFmpeg release at 1,232ms, 309ms, and 359ms, then a final OFF at 1,134ms before restart. Each transition verified the exact Central config digest ACK and the expected `camera..enabled` value. The process monitor rejected counts above one. Agent restart while ON preserved its identity and resumed capture; Agent and Central restart while OFF preserved Disabled and produced no FFmpeg process. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing. ## Camera status contract acceptance diff --git a/skills/camera-toggle-acceptance/acceptance.sh b/skills/camera-toggle-acceptance/acceptance.sh new file mode 100755 index 0000000..c227a07 --- /dev/null +++ b/skills/camera-toggle-acceptance/acceptance.sh @@ -0,0 +1,234 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +umask 077 + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +stamp="$(date +%s)-$RANDOM" +project="heimdall-157-${stamp}" +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") +env_file="$temp_dir/acceptance.env" +env_next="$temp_dir/acceptance.env.next" +compose_override="$temp_dir/compose.override.yml" +config_headers="$temp_dir/config.headers" +config_body="$temp_dir/config.json" +local_image_tags=("heimdall:${project}-central" "heimdall-agent:${project}-agent") +compose_files=(-f "$root/docker/docker-compose.yml" -f "$compose_override") +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + if (( status != 0 )); then + docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --no-color --tail 250 heimdall-agent 2>/dev/null | + grep -E 'Config update received: config\.invalidated|Full configuration fetched successfully|Stream stopped for camera|camera config ACK' | tail -40 || true + fi + docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1 + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + [[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1 + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1 + done + rm -f -- "$env_file" "$env_next" "$compose_override" "$config_headers" "$config_body" || cleanup_failed=1 + rmdir -- "$temp_dir" || cleanup_failed=1 + if (( cleanup_failed )); then + printf 'cleanup verification failed for %s\n' "$project" >&2 + status=1 + else + printf 'cleanup verified: project resources absent; exact local tags absent\n' + fi + exit "$status" +} + +port=$((20000 + RANDOM % 20000)) +pg_port=$((port + 1)) +db_password=$(openssl rand -hex 24) +jwt_key=$(openssl rand -hex 48) +jwt_refresh=$(openssl rand -hex 48) +cat >"$env_file" <"$compose_override" <<'EOF' +services: + heimdall: + image: heimdall:${ACCEPTANCE_PROJECT}-central + heimdall-agent: + image: heimdall-agent:${ACCEPTANCE_PROJECT}-agent + build: + context: .. + dockerfile: docker/Dockerfile.agent + user: "1654:1654" + environment: + Agent__CentralUrl: http://heimdall:8080 + Agent__AllowInsecureHttp: "true" + Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:?token required} + Agent__AgentName: camera-157-agent + Agent__HeartbeatIntervalSeconds: "5" + Agent__StateDirectory: /var/lib/heimdall + Agent__DiscoveryEnabled: "false" + volumes: + - agent_state:/var/lib/heimdall + depends_on: + heimdall: + condition: service_healthy + synthetic-camera-publisher: + condition: service_started + networks: + - heimdall-net + synthetic-camera: + image: bluenviron/mediamtx:1.21.3 + volumes: + - ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro + networks: + - heimdall-net + synthetic-camera-publisher: + image: jrottenberg/ffmpeg:7.1-alpine + entrypoint: ["/bin/sh", "-c"] + command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 1; done"] + depends_on: + - synthetic-camera + networks: + - heimdall-net +volumes: + agent_state: +EOF + +# The cleanup trap is installed before any image build or Compose start. +trap cleanup EXIT +chmod 600 "$env_file" +api="http://127.0.0.1:$port" +compose() { docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" "$@"; } +contract_failures=0 +wait_http() { + for _ in $(seq 1 90); do + if curl -fsS --max-time 2 "$api/healthz" >/dev/null 2>&1; then return 0; fi + sleep 2 + done + return 1 +} +request() { curl -fsS --max-time 10 -H "Authorization: Bearer $admin_token" -H 'Content-Type: application/json' "$@"; } +ffmpeg_count() { + compose exec -T heimdall-agent sh -c 'n=0; for f in /proc/[0-9]*/comm; do IFS= read -r p < "$f" || continue; [ "$p" = ffmpeg ] && n=$((n+1)); done; printf "%s\n" "$n"' +} +wait_count() { + expected=$1; seconds=$2 + for _ in $(seq 1 "$((seconds * 20))"); do + count=$(ffmpeg_count) + (( count <= 1 )) || return 1 + [[ "$count" == "$expected" ]] && return 0 + sleep 0.05 + done + return 1 +} +wait_ack() { + expected_enabled=$1 + for _ in $(seq 1 100); do + request -D "$config_headers" "$api/api/settings/agent/$agent_id" >"$config_body" + wanted=$(awk 'BEGIN{IGNORECASE=1} /^X-Camera-Config-Version:/ {gsub("\r", "", $2); print $2}' "$config_headers") + actual_enabled=$(jq -r --arg key "camera.$camera_id.enabled" '.[$key] // empty' "$config_body") + agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") + applied=$(jq -r "[.items[]? | select(.id==\"$agent_id\")][0].lastAppliedCameraConfigVersion // empty" <<<"$agents") + [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]] && return 0 + sleep 0.1 + done + return 1 +} + +printf 'project=%s central_tag=%s agent_tag=%s\n' "$project" "${local_image_tags[0]}" "${local_image_tags[1]}" +compose build heimdall heimdall-agent +compose up -d postgresql heimdall +wait_http +admin_password="Tst!$(openssl rand -hex 20)A9" +bootstrap=$(curl -fsS --max-time 10 -H 'Content-Type: application/json' -d "{\"email\":\"admin-${stamp}@heimdall.test\",\"password\":\"$admin_password\",\"displayName\":\"Acceptance Admin\"}" "$api/api/auth/bootstrap-admin") +admin_token=$(jq -er '.accessToken' <<<"$bootstrap") +printf 'synthetic Admin bootstrap accepted\n' +site=$(request -X POST -d '{"name":"Camera toggle acceptance","timezone":"UTC"}' "$api/api/sites") +site_id=$(jq -er '.id' <<<"$site") +printf 'synthetic site created\n' +site_token=$(request -X POST "$api/api/sites/$site_id/tokens" | jq -er '.token') +grep -v '^HEIMDALL_TEST_SITE_TOKEN=' "$env_file" >"$env_next" +printf 'HEIMDALL_TEST_SITE_TOKEN=%s\n' "$site_token" >>"$env_next" +mv "$env_next" "$env_file" +camera=$(request -X POST -d "{\"siteId\":\"$site_id\",\"name\":\"Synthetic camera\",\"rtspUrl\":\"rtsp://synthetic-camera:8554/synthetic\"}" "$api/api/cameras") +camera_id=$(jq -er '.id' <<<"$camera") +[[ $(jq -r '.status' <<<"$camera") == Disabled ]] +printf 'synthetic camera created\n' +compose up -d synthetic-camera synthetic-camera-publisher heimdall-agent +agent_id= +for _ in $(seq 1 60); do + agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") + agent_id=$(jq -r '[.items[]? | select(.name=="camera-157-agent")][0].id // empty' <<<"$agents") + [[ -n "$agent_id" ]] && break + sleep 1 +done +[[ -n "$agent_id" ]] +printf 'Agent registered\n' +request -X POST -d "{\"cameraId\":\"$camera_id\",\"agentId\":\"$agent_id\",\"reason\":\"synthetic acceptance\"}" "$api/api/assignments" >/dev/null +request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null +wait_count 1 10 + +off_once() { + started=$(date +%s%N) + result=$(request -X POST "$api/api/cameras/$camera_id/toggle-status") + response_ms=$((( $(date +%s%N) - started ) / 1000000)) + [[ $(jq -r '.status' <<<"$result") == Disabled ]] + within_contract=1 + if ! wait_count 0 2; then + within_contract=0 + wait_count 0 10 || return 1 + fi + elapsed_ms=$((( $(date +%s%N) - started ) / 1000000)) + printf 'OFF API response=%sms; process release=%sms; under-2s=%s\n' "$response_ms" "$elapsed_ms" "$within_contract" + if (( ! within_contract || elapsed_ms >= 2000 )); then + contract_failures=$((contract_failures + 1)) + fi + wait_ack false +} +for iteration in 1 2 3; do + off_once + request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null + wait_count 1 10 + wait_ack true + count=$(ffmpeg_count) + [[ "$count" == 1 ]] +done +compose restart heimdall-agent +wait_count 1 10 +agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") +old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") +[[ "$old_agent_id" == "$agent_id" ]] +wait_ack true +off_once +agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") +old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") +compose restart heimdall-agent +wait_count 0 10 +agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") +new_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") +[[ "$old_agent_id" == "$new_agent_id" && "$new_agent_id" == "$agent_id" ]] +compose restart heimdall +wait_http +sleep 2 +[[ $(ffmpeg_count) == 0 ]] +camera=$(request "$api/api/cameras/$camera_id") +[[ $(jq -r '.status' <<<"$camera") == Disabled ]] +wait_ack false +printf 'restart OFF persisted; camera config digest acknowledged\n' +if (( contract_failures > 0 )); then + printf 'contract failures=%s\n' "$contract_failures" >&2 + exit 1 +fi diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index 832cd4e..123ddf0 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -53,6 +53,7 @@ public sealed class SnapshotPipelineService : BackgroundService private readonly FrameResizer? _resizer; private readonly ILogger _logger; private readonly SemaphoreSlim _syncLock = new(1, 1); + private readonly SemaphoreSlim _configChanged = new(0, 1); private readonly Dictionary _streamUrls = new(); private readonly ConcurrentDictionary _motionDetectors = new(); private readonly ConcurrentDictionary _reportedSceneState = new(); @@ -154,8 +155,18 @@ public sealed class SnapshotPipelineService : BackgroundService // (e.g. camera settings applied before we subscribed). while (!stoppingToken.IsCancellationRequested) { - await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); - if (Interlocked.Exchange(ref _configDirty, 0) != 0 || DateTime.UtcNow.Second % 30 == 0) + var periodicSyncDue = false; + using (var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken)) + { + wait.CancelAfter(TimeSpan.FromSeconds(1)); + try { await _configChanged.WaitAsync(wait.Token); } + catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) + { + periodicSyncDue = true; + } + } + + if (Interlocked.Exchange(ref _configDirty, 0) != 0 || periodicSyncDue && DateTime.UtcNow.Second % 30 == 0) await SyncStreamsAsync(stoppingToken); } } @@ -181,6 +192,8 @@ public sealed class SnapshotPipelineService : BackgroundService private void OnCameraConfigChanged(object? sender, EventArgs e) { Interlocked.Exchange(ref _configDirty, 1); + try { _configChanged.Release(); } + catch (SemaphoreFullException) { } } private async Task SyncStreamsAsync(CancellationToken ct) diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs index 26b5843..f5a886b 100644 --- a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs @@ -9,7 +9,7 @@ public class SnapshotPipelineServiceTests { private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg"; - private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline( + private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer, ICameraStatusReporter StatusReporter) CreatePipeline( List? cameras = null, AnalysisMode analysisMode = AnalysisMode.Local, string? brokerUrl = null) @@ -34,13 +34,13 @@ public class SnapshotPipelineServiceTests state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter, Substitute.For>(), DegradationManager: degradationManager, Metrics: metrics)); - return (service, state, store, streams, analyzer); + return (service, state, store, streams, analyzer, statusReporter); } [Fact] public async Task StartStop_WithoutRegistration_StopsGracefully() { - var (service, state, _, _, _) = CreatePipeline(); + var (service, state, _, _, _, _) = CreatePipeline(); state.AgentId = Guid.Empty; // never registered await service.StartAsync(CancellationToken.None); @@ -52,7 +52,7 @@ public class SnapshotPipelineServiceTests [Fact] public async Task StartStop_WithNoCameras_DoesNotStartStreams() { - var (service, _, _, streams, _) = CreatePipeline(); + var (service, _, _, streams, _, _) = CreatePipeline(); await service.StartAsync(CancellationToken.None); try { @@ -72,7 +72,7 @@ public class SnapshotPipelineServiceTests { new() { Name = "Cam 1", RtspUrl = "rtsp://cam1/stream" }, }; - var (service, _, store, streams, _) = CreatePipeline(cameras); + var (service, _, store, streams, _, _) = CreatePipeline(cameras); await service.StartAsync(CancellationToken.None); try @@ -93,10 +93,45 @@ public class SnapshotPipelineServiceTests } } + [Fact] + public async Task CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync() + { + var (service, _, store, streams, _, statusReporter) = CreatePipeline(); + var cameraId = Guid.NewGuid(); + await service.StartAsync(CancellationToken.None); + try + { + await Task.Delay(TimeSpan.FromMilliseconds(1100)); + statusReporter.ClearReceivedCalls(); + store.ReplaceCentral(new Dictionary + { + [$"camera.{cameraId}.enabled"] = "true", + [$"camera.{cameraId}.rtsp"] = "rtsp://camera/test", + }); + + // The full periodic resync runs every 30 seconds. A config event + // must instead reconcile this transition on the event signal. + var deadline = DateTime.UtcNow.AddMilliseconds(500); + while (DateTime.UtcNow < deadline && !statusReporter.ReceivedCalls().Any()) + await Task.Delay(10); + + streams.ActiveStreamCount.ShouldBe(0); // FFmpeg is intentionally absent. + // Error is reported only after the enabled assignment is reconciled. + statusReporter.ReceivedCalls().Any(call => + call.GetMethodInfo().Name == nameof(ICameraStatusReporter.ReportAsync) && + Equals(call.GetArguments()[0], cameraId) && + Equals(call.GetArguments()[1], "Error")).ShouldBeTrue(); + } + finally + { + await service.StopAsync(CancellationToken.None); + } + } + [Fact] public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer() { - var (service, _, store, streams, analyzer) = CreatePipeline(); + var (service, _, store, streams, analyzer, _) = CreatePipeline(); var id = Guid.NewGuid(); store.ReplaceCentral(new Dictionary { @@ -128,7 +163,7 @@ public class SnapshotPipelineServiceTests [Fact] public async Task StopAsync_WithoutStart_DoesNotThrow() { - var (service, _, _, _, _) = CreatePipeline(); + var (service, _, _, _, _, _) = CreatePipeline(); await service.StopAsync(CancellationToken.None); service.ShouldNotBeNull(); } @@ -136,7 +171,7 @@ public class SnapshotPipelineServiceTests [Fact] public void IsRemoteMode_LocalMode_ReturnsFalse() { - var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local); + var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local); service.IsRemoteMode.ShouldBeFalse(); } @@ -144,14 +179,14 @@ public class SnapshotPipelineServiceTests public void IsRemoteMode_RemoteMode_NoBroker_ReturnsFalse() { // Remote mode but no broker service injected → not actually remote - var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote); + var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote); service.IsRemoteMode.ShouldBeFalse(); } [Fact] public void RemoteSubmissions_InitiallyZero() { - var (service, _, _, _, _) = CreatePipeline(); + var (service, _, _, _, _, _) = CreatePipeline(); service.RemoteSubmissions.ShouldBe(0); service.RemoteFallbacks.ShouldBe(0); } -- 2.54.1 From 6e68045f1e8b8755df656b409208e28a7d498a59 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 12 Nov 2026 13:41:54 +0100 Subject: [PATCH 2/4] test(camera): isolate and validate toggle acceptance --- skills/camera-toggle-acceptance/SKILL.md | 4 ++-- skills/camera-toggle-acceptance/acceptance.sh | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/skills/camera-toggle-acceptance/SKILL.md b/skills/camera-toggle-acceptance/SKILL.md index 4a5b55e..55e7454 100644 --- a/skills/camera-toggle-acceptance/SKILL.md +++ b/skills/camera-toggle-acceptance/SKILL.md @@ -49,7 +49,7 @@ This acceptance proves the source-built Central/Agent software lifecycle with a - Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines. - Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result. - On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above. -- Current disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but have not yet proved toggle timing or restart persistence. Treat #59/#199 as open until a corrected process measurement completes the whole cycle. +- Earlier disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but did not prove toggle timing or restart persistence. The completed source-built run below supersedes those incomplete attempts; physical camera and deployed-host validation remain external. ## Latest source-built run @@ -65,7 +65,7 @@ The sixth historical run kept the FFmpeg process deadline separate from the conf ## Source-built acceptance — 2026-11-12 -`acceptance.sh` passed with project `heimdall-157-1794486043-22368`, Central tag `heimdall:heimdall-157-1794486043-22368-central`, and Agent tag `heimdall-agent:heimdall-157-1794486043-22368-agent`. It exercised three ON/OFF cycles with FFmpeg release at 1,232ms, 309ms, and 359ms, then a final OFF at 1,134ms before restart. Each transition verified the exact Central config digest ACK and the expected `camera..enabled` value. The process monitor rejected counts above one. Agent restart while ON preserved its identity and resumed capture; Agent and Central restart while OFF preserved Disabled and produced no FFmpeg process. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing. +`acceptance.sh` passed with project `heimdall-157-1794487097-5472`, Central tag `heimdall:heimdall-157-1794487097-5472-central`, and Agent tag `heimdall-agent:heimdall-157-1794487097-5472-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,153ms, 309ms, and 333ms, then a final OFF at 907ms before restart. Each transition verified the exact Central config digest ACK and expected `camera..enabled` value. The process monitor rejected counts above one. Agent restart while ON preserved its identity and resumed capture; Agent and Central restart while OFF preserved Disabled and produced no FFmpeg process. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing. ## Camera status contract acceptance diff --git a/skills/camera-toggle-acceptance/acceptance.sh b/skills/camera-toggle-acceptance/acceptance.sh index c227a07..c63c9da 100755 --- a/skills/camera-toggle-acceptance/acceptance.sh +++ b/skills/camera-toggle-acceptance/acceptance.sh @@ -11,6 +11,7 @@ env_next="$temp_dir/acceptance.env.next" compose_override="$temp_dir/compose.override.yml" config_headers="$temp_dir/config.headers" config_body="$temp_dir/config.json" +stage=setup local_image_tags=("heimdall:${project}-central" "heimdall-agent:${project}-agent") compose_files=(-f "$root/docker/docker-compose.yml" -f "$compose_override") cleanup() { @@ -18,7 +19,8 @@ cleanup() { trap - EXIT cleanup_failed=0 if (( status != 0 )); then - docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --no-color --tail 250 heimdall-agent 2>/dev/null | + printf 'acceptance failed at stage=%s\n' "$stage" >&2 + docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --timestamps --no-color --tail 250 heimdall-agent 2>/dev/null | grep -E 'Config update received: config\.invalidated|Full configuration fetched successfully|Stream stopped for camera|camera config ACK' | tail -40 || true fi docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1 @@ -50,13 +52,13 @@ cat >"$env_file" </dev/null +stage=initial-on request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null wait_count 1 10 +wait_ack true off_once() { started=$(date +%s%N) @@ -199,19 +207,23 @@ off_once() { wait_ack false } for iteration in 1 2 3; do + stage="cycle-${iteration}-off" off_once + stage="cycle-${iteration}-on" request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null wait_count 1 10 wait_ack true count=$(ffmpeg_count) [[ "$count" == 1 ]] done +stage=agent-restart-on compose restart heimdall-agent wait_count 1 10 agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") [[ "$old_agent_id" == "$agent_id" ]] wait_ack true +stage=final-off off_once agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") @@ -220,6 +232,7 @@ wait_count 0 10 agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") new_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") [[ "$old_agent_id" == "$new_agent_id" && "$new_agent_id" == "$agent_id" ]] +stage=central-restart-off compose restart heimdall wait_http sleep 2 -- 2.54.1 From aedc1900db3f245c02041a6b14983d2a6a0c9317 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 12 Nov 2026 13:48:49 +0100 Subject: [PATCH 3/4] test(camera): verify fresh agent ack after restart --- skills/camera-toggle-acceptance/SKILL.md | 2 +- skills/camera-toggle-acceptance/acceptance.sh | 33 ++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/skills/camera-toggle-acceptance/SKILL.md b/skills/camera-toggle-acceptance/SKILL.md index 55e7454..a3236c4 100644 --- a/skills/camera-toggle-acceptance/SKILL.md +++ b/skills/camera-toggle-acceptance/SKILL.md @@ -65,7 +65,7 @@ The sixth historical run kept the FFmpeg process deadline separate from the conf ## Source-built acceptance — 2026-11-12 -`acceptance.sh` passed with project `heimdall-157-1794487097-5472`, Central tag `heimdall:heimdall-157-1794487097-5472-central`, and Agent tag `heimdall-agent:heimdall-157-1794487097-5472-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,153ms, 309ms, and 333ms, then a final OFF at 907ms before restart. Each transition verified the exact Central config digest ACK and expected `camera..enabled` value. The process monitor rejected counts above one. Agent restart while ON preserved its identity and resumed capture; Agent and Central restart while OFF preserved Disabled and produced no FFmpeg process. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing. +`acceptance.sh` passed with project `heimdall-157-1794487528-14373`, Central tag `heimdall:heimdall-157-1794487528-14373-central`, and Agent tag `heimdall-agent:heimdall-157-1794487528-14373-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,242ms, 310ms, and 328ms, then a final OFF at 1,076ms before restart. Each transition verified the exact Central config digest ACK and expected `camera..enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the restart; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing. ## Camera status contract acceptance diff --git a/skills/camera-toggle-acceptance/acceptance.sh b/skills/camera-toggle-acceptance/acceptance.sh index c63c9da..8834e51 100755 --- a/skills/camera-toggle-acceptance/acceptance.sh +++ b/skills/camera-toggle-acceptance/acceptance.sh @@ -144,11 +144,35 @@ wait_ack() { actual_enabled=$(jq -r --arg key "camera.$camera_id.enabled" '.[$key] // empty' "$config_body") agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") applied=$(jq -r "[.items[]? | select(.id==\"$agent_id\")][0].lastAppliedCameraConfigVersion // empty" <<<"$agents") - [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]] && return 0 + if [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]]; then + acknowledged_version=$wanted + return 0 + fi sleep 0.1 done return 1 } +wait_agent_reconnected_and_ack() { + restarted_at_ns=$1 + expected_version=$2 + for _ in $(seq 1 60); do + agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") + agent=$(jq -cer "[.items[]? | select(.id==\"$agent_id\")][0]" <<<"$agents") + status=$(jq -r '.status // empty' <<<"$agent") + heartbeat=$(jq -r '.lastHeartbeat // empty' <<<"$agent") + applied_version=$(jq -r '.lastAppliedCameraConfigVersion // empty' <<<"$agent") + applied_at=$(jq -r '.lastAppliedCameraConfigAt // empty' <<<"$agent") + if [[ "$status" == Online && -n "$heartbeat" && -n "$applied_at" && "$applied_version" == "$expected_version" ]]; then + heartbeat_ns=$(date -u -d "$heartbeat" +%s%N) + applied_at_ns=$(date -u -d "$applied_at" +%s%N) + if (( heartbeat_ns > restarted_at_ns && applied_at_ns > restarted_at_ns )); then + return 0 + fi + fi + sleep 1 + done + return 1 +} printf 'project=%s central_tag=%s agent_tag=%s\n' "$project" "${local_image_tags[0]}" "${local_image_tags[1]}" stage=build @@ -227,12 +251,12 @@ stage=final-off off_once agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") +post_off_restart_started_ns=$(date +%s%N) compose restart heimdall-agent wait_count 0 10 -agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") -new_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") -[[ "$old_agent_id" == "$new_agent_id" && "$new_agent_id" == "$agent_id" ]] +wait_agent_reconnected_and_ack "$post_off_restart_started_ns" "$acknowledged_version" stage=central-restart-off +central_restart_started_ns=$(date +%s%N) compose restart heimdall wait_http sleep 2 @@ -240,6 +264,7 @@ sleep 2 camera=$(request "$api/api/cameras/$camera_id") [[ $(jq -r '.status' <<<"$camera") == Disabled ]] wait_ack false +wait_agent_reconnected_and_ack "$central_restart_started_ns" "$acknowledged_version" printf 'restart OFF persisted; camera config digest acknowledged\n' if (( contract_failures > 0 )); then printf 'contract failures=%s\n' "$contract_failures" >&2 -- 2.54.1 From 6664e5065bc8f0a9a738361d056017a79eb3a789 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 12 Nov 2026 14:00:00 +0100 Subject: [PATCH 4/4] test(camera): close restart acceptance timing gaps --- skills/camera-toggle-acceptance/SKILL.md | 2 +- skills/camera-toggle-acceptance/acceptance.sh | 16 ++++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/skills/camera-toggle-acceptance/SKILL.md b/skills/camera-toggle-acceptance/SKILL.md index a3236c4..c67d2cd 100644 --- a/skills/camera-toggle-acceptance/SKILL.md +++ b/skills/camera-toggle-acceptance/SKILL.md @@ -65,7 +65,7 @@ The sixth historical run kept the FFmpeg process deadline separate from the conf ## Source-built acceptance — 2026-11-12 -`acceptance.sh` passed with project `heimdall-157-1794487528-14373`, Central tag `heimdall:heimdall-157-1794487528-14373-central`, and Agent tag `heimdall-agent:heimdall-157-1794487528-14373-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,242ms, 310ms, and 328ms, then a final OFF at 1,076ms before restart. Each transition verified the exact Central config digest ACK and expected `camera..enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the restart; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing. +`acceptance.sh` passed with project `heimdall-157-1794488199-31533`, Central tag `heimdall:heimdall-157-1794488199-31533-central`, and Agent tag `heimdall-agent:heimdall-157-1794488199-31533-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,386ms, 555ms, and 410ms, then a final OFF at 810ms before restart. Each transition verified the exact Central config digest ACK and expected `camera..enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the Compose restart command's return; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest newer than the restart command's return. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing. ## Camera status contract acceptance diff --git a/skills/camera-toggle-acceptance/acceptance.sh b/skills/camera-toggle-acceptance/acceptance.sh index 8834e51..994efb4 100755 --- a/skills/camera-toggle-acceptance/acceptance.sh +++ b/skills/camera-toggle-acceptance/acceptance.sh @@ -130,8 +130,12 @@ wait_count() { expected=$1; seconds=$2 for _ in $(seq 1 "$((seconds * 20))"); do count=$(ffmpeg_count) + observed_at_ns=$(date +%s%N) (( count <= 1 )) || return 1 - [[ "$count" == "$expected" ]] && return 0 + if [[ "$count" == "$expected" ]]; then + count_observed_at_ns=$observed_at_ns + return 0 + fi sleep 0.05 done return 1 @@ -223,7 +227,7 @@ off_once() { within_contract=0 wait_count 0 10 || return 1 fi - elapsed_ms=$((( $(date +%s%N) - started ) / 1000000)) + elapsed_ms=$((( count_observed_at_ns - started ) / 1000000)) printf 'OFF API response=%sms; process release=%sms; under-2s=%s\n' "$response_ms" "$elapsed_ms" "$within_contract" if (( ! within_contract || elapsed_ms >= 2000 )); then contract_failures=$((contract_failures + 1)) @@ -251,20 +255,20 @@ stage=final-off off_once agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20") old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents") -post_off_restart_started_ns=$(date +%s%N) compose restart heimdall-agent +post_off_restart_returned_ns=$(date +%s%N) wait_count 0 10 -wait_agent_reconnected_and_ack "$post_off_restart_started_ns" "$acknowledged_version" +wait_agent_reconnected_and_ack "$post_off_restart_returned_ns" "$acknowledged_version" stage=central-restart-off -central_restart_started_ns=$(date +%s%N) compose restart heimdall +central_restart_returned_ns=$(date +%s%N) wait_http sleep 2 [[ $(ffmpeg_count) == 0 ]] camera=$(request "$api/api/cameras/$camera_id") [[ $(jq -r '.status' <<<"$camera") == Disabled ]] wait_ack false -wait_agent_reconnected_and_ack "$central_restart_started_ns" "$acknowledged_version" +wait_agent_reconnected_and_ack "$central_restart_returned_ns" "$acknowledged_version" printf 'restart OFF persisted; camera config digest acknowledged\n' if (( contract_failures > 0 )); then printf 'contract failures=%s\n' "$contract_failures" >&2 -- 2.54.1