@trillboards/edge-sdk 0.2.246 → 0.2.254

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/deploy/detector/README.md +15 -0
  2. package/deploy/detector/pyproject.toml +1 -1
  3. package/deploy/detector/tests/test_actor_tracking.py +136 -0
  4. package/deploy/detector/tests/test_actor_tracking_wire.py +11 -0
  5. package/deploy/detector/tests/test_face_identity.py +448 -0
  6. package/deploy/detector/tests/test_loader.py +28 -1
  7. package/deploy/detector/tests/test_registry.py +53 -0
  8. package/deploy/detector/trillboards_detector/_version.py +2 -2
  9. package/deploy/detector/trillboards_detector/actor_tracking.py +95 -9
  10. package/deploy/detector/trillboards_detector/face_contract.py +166 -0
  11. package/deploy/detector/trillboards_detector/face_identity.py +467 -0
  12. package/deploy/detector/trillboards_detector/loader.py +40 -0
  13. package/deploy/detector/trillboards_detector/registry.py +72 -2
  14. package/deploy/detector/trillboards_detector/server.py +48 -6
  15. package/deploy/detector/trillboards_detector/tasks.py +12 -1
  16. package/deploy/windows/build-windows.ps1 +1 -0
  17. package/deploy/windows/ci/test-detector-looks-field.ps1 +15 -3
  18. package/deploy/windows/ci/test-detector-reinstall.ps1 +173 -2
  19. package/deploy/windows/ci/test-main-stream-gpu-decode.ps1 +119 -0
  20. package/deploy/windows/ci/test-rollout-proofs.ps1 +3 -2
  21. package/deploy/windows/ensure-detector.ps1 +255 -0
  22. package/deploy/windows/install-update.ps1 +4 -3
  23. package/deploy/windows/stop-existing.ps1 +1 -0
  24. package/deploy/windows/trillboards-edge.cmd +10 -22
  25. package/dist/CloudSensingManager.d.ts +14 -0
  26. package/dist/CloudSensingManager.d.ts.map +1 -1
  27. package/dist/CloudSensingManager.js +51 -5
  28. package/dist/CloudSensingManager.js.map +1 -1
  29. package/dist/ConnectorStatusClient.d.ts +26 -1
  30. package/dist/ConnectorStatusClient.d.ts.map +1 -1
  31. package/dist/ConnectorStatusClient.js +9 -0
  32. package/dist/ConnectorStatusClient.js.map +1 -1
  33. package/dist/DetectorFields.d.ts +77 -1
  34. package/dist/DetectorFields.d.ts.map +1 -1
  35. package/dist/DetectorFields.js +34 -4
  36. package/dist/DetectorFields.js.map +1 -1
  37. package/dist/EdgeAgent.js +1 -1
  38. package/dist/FaceIdentity.d.ts +122 -0
  39. package/dist/FaceIdentity.d.ts.map +1 -0
  40. package/dist/FaceIdentity.js +256 -0
  41. package/dist/FaceIdentity.js.map +1 -0
  42. package/dist/FaceSightingUploader.d.ts +95 -0
  43. package/dist/FaceSightingUploader.d.ts.map +1 -0
  44. package/dist/FaceSightingUploader.js +214 -0
  45. package/dist/FaceSightingUploader.js.map +1 -0
  46. package/dist/FaceWatchLane.d.ts +297 -0
  47. package/dist/FaceWatchLane.d.ts.map +1 -0
  48. package/dist/FaceWatchLane.js +660 -0
  49. package/dist/FaceWatchLane.js.map +1 -0
  50. package/dist/FaceWatchPolicy.d.ts +154 -0
  51. package/dist/FaceWatchPolicy.d.ts.map +1 -0
  52. package/dist/FaceWatchPolicy.js +101 -0
  53. package/dist/FaceWatchPolicy.js.map +1 -0
  54. package/dist/LocalDetectorClient.d.ts +30 -0
  55. package/dist/LocalDetectorClient.d.ts.map +1 -1
  56. package/dist/LocalDetectorClient.js +72 -4
  57. package/dist/LocalDetectorClient.js.map +1 -1
  58. package/dist/MainStreamRing.d.ts +63 -1
  59. package/dist/MainStreamRing.d.ts.map +1 -1
  60. package/dist/MainStreamRing.js +101 -7
  61. package/dist/MainStreamRing.js.map +1 -1
  62. package/dist/NativeReadiness.d.ts +21 -2
  63. package/dist/NativeReadiness.d.ts.map +1 -1
  64. package/dist/NativeReadiness.js +32 -9
  65. package/dist/NativeReadiness.js.map +1 -1
  66. package/dist/OrderedReviewClient.d.ts +3 -0
  67. package/dist/OrderedReviewClient.d.ts.map +1 -1
  68. package/dist/OrderedReviewClient.js +3 -0
  69. package/dist/OrderedReviewClient.js.map +1 -1
  70. package/dist/ReviewPriority.d.ts +9 -0
  71. package/dist/ReviewPriority.d.ts.map +1 -1
  72. package/dist/ReviewPriority.js +6 -1
  73. package/dist/ReviewPriority.js.map +1 -1
  74. package/dist/ScopedVlmReview.d.ts +11 -2
  75. package/dist/ScopedVlmReview.d.ts.map +1 -1
  76. package/dist/ScopedVlmReview.js +43 -16
  77. package/dist/ScopedVlmReview.js.map +1 -1
  78. package/dist/SensingProfileClient.d.ts +14 -0
  79. package/dist/SensingProfileClient.d.ts.map +1 -1
  80. package/dist/SensingProfileClient.js +9 -0
  81. package/dist/SensingProfileClient.js.map +1 -1
  82. package/dist/TemporalReviewClient.d.ts +3 -0
  83. package/dist/TemporalReviewClient.d.ts.map +1 -1
  84. package/dist/TemporalReviewClient.js +3 -0
  85. package/dist/TemporalReviewClient.js.map +1 -1
  86. package/dist/UniformSceneStore.d.ts +6 -0
  87. package/dist/UniformSceneStore.d.ts.map +1 -1
  88. package/dist/UniformSceneStore.js +22 -1
  89. package/dist/UniformSceneStore.js.map +1 -1
  90. package/dist/VideoSegmentUploader.d.ts +11 -0
  91. package/dist/VideoSegmentUploader.d.ts.map +1 -1
  92. package/dist/VideoSegmentUploader.js +28 -2
  93. package/dist/VideoSegmentUploader.js.map +1 -1
  94. package/dist/VlmCandidateBuffer.d.ts +2 -0
  95. package/dist/VlmCandidateBuffer.d.ts.map +1 -1
  96. package/dist/VlmCandidateBuffer.js.map +1 -1
  97. package/dist/WatchlistClient.d.ts +55 -0
  98. package/dist/WatchlistClient.d.ts.map +1 -0
  99. package/dist/WatchlistClient.js +161 -0
  100. package/dist/WatchlistClient.js.map +1 -0
  101. package/dist/autoSense.d.ts.map +1 -1
  102. package/dist/autoSense.js +6 -0
  103. package/dist/autoSense.js.map +1 -1
  104. package/dist/cli.d.ts.map +1 -1
  105. package/dist/cli.js +6 -0
  106. package/dist/cli.js.map +1 -1
  107. package/dist/connectorUpdate.d.ts +34 -9
  108. package/dist/connectorUpdate.d.ts.map +1 -1
  109. package/dist/connectorUpdate.js +96 -9
  110. package/dist/connectorUpdate.js.map +1 -1
  111. package/dist/connectorUpdateApply.d.ts +20 -1
  112. package/dist/connectorUpdateApply.d.ts.map +1 -1
  113. package/dist/connectorUpdateApply.js +55 -1
  114. package/dist/connectorUpdateApply.js.map +1 -1
  115. package/dist/connectorUpdateApplyMac.d.ts +3 -1
  116. package/dist/connectorUpdateApplyMac.d.ts.map +1 -1
  117. package/dist/connectorUpdateApplyMac.js +6 -0
  118. package/dist/connectorUpdateApplyMac.js.map +1 -1
  119. package/dist/detectorEndpointState.d.ts +30 -0
  120. package/dist/detectorEndpointState.d.ts.map +1 -0
  121. package/dist/detectorEndpointState.js +125 -0
  122. package/dist/detectorEndpointState.js.map +1 -0
  123. package/dist/detectorLauncher.d.ts +23 -0
  124. package/dist/detectorLauncher.d.ts.map +1 -0
  125. package/dist/detectorLauncher.js +94 -0
  126. package/dist/detectorLauncher.js.map +1 -0
  127. package/dist/diagnose.d.ts +1 -1
  128. package/dist/diagnose.js +1 -1
  129. package/dist/hostCpu.d.ts +56 -0
  130. package/dist/hostCpu.d.ts.map +1 -0
  131. package/dist/hostCpu.js +113 -0
  132. package/dist/hostCpu.js.map +1 -0
  133. package/dist/localSensing.d.ts +86 -0
  134. package/dist/localSensing.d.ts.map +1 -1
  135. package/dist/localSensing.js +263 -30
  136. package/dist/localSensing.js.map +1 -1
  137. package/package.json +2 -2
  138. package/retained/ProfileAuthorityClient.cjs +4 -0
  139. package/retained/RetainedCaptureClient.cjs +6 -0
  140. package/retained/WebsiteAdmissionCaptureClient.cjs +3 -1
  141. package/retained/__tests__/website-admission-realtime.test.cjs +27 -2
@@ -1,4 +1,4 @@
1
- """The wire. Two routes, and a hard rule about what may go out of them.
1
+ """The wire. A handful of routes, and a hard rule about what may go out of them.
2
2
 
3
3
  THE CONTRACT IS FROZEN AND IT LIVES ON THE OTHER SIDE.
4
4
  `trillboards-edge-sdk/packages/edge-sdk/src/LocalDetectorClient.ts` is the only
@@ -41,6 +41,7 @@ from .actor_action_wire import parse_actor_action_request, validate_actor_action
41
41
  from .colors import validate_color_request, prepare_color_capabilities
42
42
  from .registry import validate_preparation_models
43
43
  from .vehicle_end import validate_vehicle_end_request
44
+ from .face_contract import check_faces_response, validate_faces_request
44
45
  from ._version import VERSION
45
46
  from .errors import DetectorNotReady, ModelVerificationError, UnknownClasses
46
47
 
@@ -442,6 +443,8 @@ class DetectorHandler(BaseHTTPRequestHandler):
442
443
  self._actor_actions()
443
444
  elif self._path() == "/vehicle-end":
444
445
  self._vehicle_end()
446
+ elif self._path() == "/v1/faces":
447
+ self._faces()
445
448
  elif self._path() == "/ready":
446
449
  self._ready()
447
450
  elif self._path() == "/backend":
@@ -660,13 +663,14 @@ class DetectorHandler(BaseHTTPRequestHandler):
660
663
  result = loader.estimate_appearance(jpeg, boxes, appearance_model)
661
664
  appearance = build_appearance_evidence(
662
665
  result, hashlib.sha256(jpeg).hexdigest(), frame_size, batch.detections)
663
- body["tracking"] = self.server.actor_tracker.track(
666
+ # The camera's per-track records (track_records.py) as of THIS frame, beside the
667
+ # signed tracking proof and outside its digest. They come from the same lock and
668
+ # transaction as the proof: a second request on the same camera can no longer
669
+ # commit in between and hand this frame its records, and a replayed frame gets
670
+ # the records it had then, not the live ones.
671
+ body["tracking"], body["tracks"] = self.server.actor_tracker.track_and_records(
664
672
  tracking, batch.detections, image_sha256=hashlib.sha256(jpeg).hexdigest(),
665
673
  model_hashes=body.get("model_hashes"), frame_size=frame_size, appearance=appearance)
666
- # The camera's live per-track records (track_records.py), beside the
667
- # signed tracking proof and outside its digest.
668
- body["tracks"] = [record.to_wire() for record in
669
- self.server.actor_tracker.track_records(tracking["cameraId"])]
670
674
  if detection_pose is not None:
671
675
  indices = detection_pose_indices(batch.detections, detection_pose)
672
676
  boxes = [[d.x, d.y, d.x + d.width, d.y + d.height]
@@ -769,6 +773,44 @@ class DetectorHandler(BaseHTTPRequestHandler):
769
773
  self._json(500, {"error": "refused malformed vehicle-end output"}); return
770
774
  self._json(200, result)
771
775
 
776
+ def _faces(self):
777
+ """Door faces (face_contract.py): YuNet + ArcFace alignment + EdgeFace-XS on one original JPEG.
778
+
779
+ The answer is re-checked field by field before it leaves (the `_assert_wire_safe`
780
+ rule): a face whose gate does not follow from its own measures, a vector it did
781
+ not earn, a box off the frame, an artifact that is not the one selected — each
782
+ is a 500 here rather than a plausible 200 the connector would turn into a
783
+ sighting or a watchlist match.
784
+ """
785
+ try:
786
+ raw = self._read_body()
787
+ try:
788
+ jpeg, detector, embedder, bars = validate_faces_request(json.loads(raw.decode("utf-8")))
789
+ except (ValueError, UnicodeDecodeError) as error:
790
+ raise WireError(400, str(error)) from None
791
+ except WireError as error:
792
+ self._json(error.status, {"error": error.message}); return
793
+ estimate = getattr(self.server.loader, "estimate_faces", None)
794
+ if not callable(estimate):
795
+ self._json(503, {"error": "face task is unavailable in this detector build"}); return
796
+ try:
797
+ result = estimate(jpeg, bars, detector, embedder)
798
+ except ModelVerificationError as error:
799
+ self._json(409, {"error": str(error)}); return
800
+ except DetectorNotReady as error:
801
+ self._json(503, {"error": str(error)}); return
802
+ except ValueError as error:
803
+ self._json(400, {"error": str(error)}); return
804
+ except Exception as error:
805
+ self._log(f"[detector] face inference failed: {type(error).__name__}: {error}")
806
+ self._json(500, {"error": "face inference failed"}); return
807
+ try:
808
+ check_faces_response(result, jpeg, detector, embedder, bars)
809
+ except ValueError as error:
810
+ self._log(f"[detector] REFUSING malformed face output: {error}")
811
+ self._json(500, {"error": f"refused malformed face output: {error}"}); return
812
+ self._json(200, result)
813
+
772
814
  # ── plumbing ─────────────────────────────────────────────────────────────
773
815
 
774
816
  def _read_body(self) -> bytes:
@@ -3,6 +3,8 @@ from .registry import TaskModelContract
3
3
  from .actor_identity import MODEL_ID as APPEARANCE_MODEL_ID, MODEL_SHA256 as APPEARANCE_SHA256, PREPROCESSING as APPEARANCE_PREPROCESSING
4
4
  from .actor_action_contract import ActorActionModelContract,ActorActionOutput,ActorActionWindowContract,CONTACT_PREPROCESSING
5
5
  from .vehicle_end import MODEL_ID as VEHICLE_END_MODEL_ID, MODEL_SHA256 as VEHICLE_END_SHA256, PREPROCESSING as VEHICLE_END_PREPROCESSING
6
+ from .face_contract import (FACE_DETECTOR_MODEL_ID, FACE_DETECTOR_SHA256, FACE_DETECT_PREPROCESSING, FACE_DETECT_TASK,
7
+ FACE_EMBEDDER_MODEL_ID, FACE_EMBEDDER_SHA256, FACE_EMBED_PREPROCESSING, FACE_EMBED_TASK)
6
8
 
7
9
  RTMPOSE_MODEL_ID = "rtmpose_m_body7"
8
10
  RTMPOSE_SHA256 = "5c0a4bf67953e6d2ac43ce15e77dc9d5d354ae18430a47d2c5963a7bc5683e3c"
@@ -32,7 +34,16 @@ PERSON_APPEARANCE = TaskModelContract(
32
34
  # the connector's vehicle gate turns two looks into reverse_parked_vehicle_detected.
33
35
  VEHICLE_END = TaskModelContract(
34
36
  VEHICLE_END_MODEL_ID, "vehicle_end_orientation", VEHICLE_END_SHA256, 1600 * 1024**2, VEHICLE_END_PREPROCESSING)
35
- BUILTIN_TASK_MODELS = (RTMPOSE_BODY7, PERSON_APPEARANCE, VEHICLE_END)
37
+ # The door camera's faces (face_identity.py, /v1/faces). Resident cost MEASURED on the devbox
38
+ # (proc-statm, fresh process, after a probe and the largest frame served): YuNet 29.8 MB after
39
+ # its probe, 63.2 MB at 800x448, 109.8 MB at 1280x720 and 204.4 MB at the 1920 px cap;
40
+ # EdgeFace-XS 53.1 MB after 20 vectors. Each reservation is that peak plus headroom. Neither owns a
41
+ # field: the connector's face lane turns their answers into sightings and watchlist matches.
42
+ FACE_DETECTOR = TaskModelContract(
43
+ FACE_DETECTOR_MODEL_ID, FACE_DETECT_TASK, FACE_DETECTOR_SHA256, 256 * 1024**2, FACE_DETECT_PREPROCESSING)
44
+ FACE_EMBEDDER = TaskModelContract(
45
+ FACE_EMBEDDER_MODEL_ID, FACE_EMBED_TASK, FACE_EMBEDDER_SHA256, 96 * 1024**2, FACE_EMBED_PREPROCESSING)
46
+ BUILTIN_TASK_MODELS = (RTMPOSE_BODY7, PERSON_APPEARANCE, VEHICLE_END, FACE_DETECTOR, FACE_EMBEDDER)
36
47
 
37
48
  COCO17 = ("nose", "left_eye", "right_eye", "left_ear", "right_ear",
38
49
  "left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
@@ -274,6 +274,7 @@ Copy-Item -Force "$Here\register-litertlm-task.ps1" "$Payload\bin\register-liter
274
274
  # regex over the whole file, so a comment naming it enrols a file that does not
275
275
  # exist. This paragraph is deliberately phrased so it cannot match.)
276
276
  Copy-Item -Force "$Here\setup-detector.ps1" "$Payload\bin\setup-detector.ps1"
277
+ Copy-Item -Force "$Here\ensure-detector.ps1" "$Payload\bin\ensure-detector.ps1"
277
278
  Copy-Item -Force "$Here\register-detector-task.ps1" "$Payload\bin\register-detector-task.ps1"
278
279
  # The Python package SOURCE that `uv tool install` builds into its own venv.
279
280
  # Tens of KB; the 124 MB fp32 ONNX it runs is OTA'd, never bundled. Not matched
@@ -26,6 +26,14 @@
26
26
  The connector's process tree is sampled every 10 s for its ffmpeg sessions
27
27
  and CPU (receipt.json).
28
28
 
29
+ Then two detector-restart cases (plan v7 W8 item 2), judged apart from the
30
+ window above and still with no Gemma call: the connector process frozen for
31
+ -StallMs (16.5 s) across a readiness proof's renewal window, so the proof
32
+ lapses between two looks; and a detector swap (connections refused for
33
+ -SwapSeconds, then 503 while it loads) during which the alert cameras pause
34
+ with their sessions kept, retry every 2 s, and look again within 5 s of the
35
+ detector's first answer. -StallMs 0 -SwapSeconds 0 turns them off.
36
+
29
37
  The install tree is assembled from the built workspace (bin\node.exe is the
30
38
  runner's Node 22, bin\ffmpeg.exe the pinned static build, lib\edge-sdk a
31
39
  junction to the built package) because a pull request has no published
@@ -36,7 +44,9 @@
36
44
  param(
37
45
  [ValidateRange(3, 30)][double]$ObserveMinutes = 6,
38
46
  [ValidateRange(1, 12)][int]$IdleCameras = 6,
39
- [ValidateRange(0, 2)][int]$MainCameras = 1
47
+ [ValidateRange(0, 2)][int]$MainCameras = 1,
48
+ [ValidateRange(0, 60000)][int]$StallMs = 16500,
49
+ [ValidateRange(0, 300)][int]$SwapSeconds = 100
40
50
  )
41
51
  $ErrorActionPreference = 'Stop'
42
52
  Set-StrictMode -Version Latest
@@ -206,7 +216,7 @@ $paths
206
216
  '--rtsp-base', ('rtsp://127.0.0.1:' + $rtspPort + '/'), '--mediamtx-api', ('http://127.0.0.1:' + $apiPort),
207
217
  '--idle-cameras', $IdleCameras, '--main-cameras', $MainCameras, '--data-dir', $dataDir,
208
218
  '--write-config', $configPath, '--ready-file', $readyFile,
209
- '--minutes', $ObserveMinutes) | ForEach-Object { '"' + $_ + '"' }
219
+ '--minutes', $ObserveMinutes, '--stall-ms', $StallMs, '--swap-sec', $SwapSeconds) | ForEach-Object { '"' + $_ + '"' }
210
220
  $proof = Start-Process -FilePath $systemNode -ArgumentList ($proofArgs -join ' ') -PassThru -WindowStyle Hidden `
211
221
  -RedirectStandardOutput (Join-Path $root 'proof.log') -RedirectStandardError (Join-Path $root 'proof.err.log')
212
222
  $owned.Add($proof)
@@ -229,7 +239,9 @@ $paths
229
239
  $seen = 0
230
240
  $lastTask = ''
231
241
  $samples = New-Object System.Collections.Generic.List[object]
232
- $limit = [DateTime]::UtcNow.AddMinutes(12 + $ObserveMinutes + 6)
242
+ # The restart cases add up to three freezes (~1 min each) and the swap (~2.5 min).
243
+ $restartMinutes = if ($StallMs -gt 0 -or $SwapSeconds -gt 0) { 3 + [Math]::Ceiling($SwapSeconds / 60) + 4 } else { 0 }
244
+ $limit = [DateTime]::UtcNow.AddMinutes(12 + $ObserveMinutes + 6 + $restartMinutes)
233
245
  while (-not $proof.HasExited -and [DateTime]::UtcNow -lt $limit) {
234
246
  Start-Sleep -Seconds 10
235
247
  $samples.Add((Get-ConnectorSample -Ffmpeg ([IO.Path]::GetFullPath($ffmpeg))))
@@ -24,6 +24,21 @@
24
24
  detector must have answered 200 through the whole trial.
25
25
  (c) the detector's down time inside (b): the old process's last /health 200
26
26
  to the new process's first.
27
+
28
+ Then the connector launcher's check of that detector (ensure-detector.ps1,
29
+ run under Windows PowerShell 5.1 as the launcher runs it; the provisioner
30
+ is a stub that only records that it ran, except where noted):
31
+ (d) a busy detector: /health answers 503 after 4 s. Through 0.2.252 the
32
+ launcher's 2 s curl re-provisioned exactly this. `answered`, no setup.
33
+ (e) the task registered and enabled, its process stopped: `started_task`,
34
+ the detector answers within 60 s from a new process, no setup.
35
+ (f) the task registered but unable to start (its executable renamed):
36
+ `reprovision_still_refused` after the start wait, setup ran.
37
+ (g) the task unregistered: `reprovision_task_missing`, setup ran.
38
+ (h) the provisioner running (its per-user mutex held): left alone,
39
+ `provisioning_in_progress`, no setup.
40
+ (i) a listener that never answers: three timeouts, never refused, left
41
+ alone (`no_answer_left_alone`), no setup.
27
42
  #>
28
43
  [CmdletBinding()]
29
44
  param()
@@ -455,10 +470,166 @@ try {
455
470
  if ($null -eq $receipt.cases.c.downMs) { throw '(c) the new detector never answered 200' }
456
471
  $case.passed = $true
457
472
  $receipt.cases.c.passed = $true
473
+ Write-Receipt
474
+
475
+ # --- (d)-(i) the launcher's detector check ---------------------------------
476
+ $ensure = Join-Path $deploy 'ensure-detector.ps1'
477
+ $parseErrors = $null
478
+ [Management.Automation.Language.Parser]::ParseFile($ensure, [ref]$null, [ref]$parseErrors) | Out-Null
479
+ if ($parseErrors) { throw ('ensure-detector.ps1 does not parse: ' + (@($parseErrors | ForEach-Object { $_.Message }) -join '; ')) }
480
+ $setupMarker = Join-Path $root 'setup-stub-ran.txt'
481
+ $setupStub = Join-Path $root 'setup-stub.ps1'
482
+ Write-Utf8NoBom $setupStub ("Add-Content -LiteralPath '" + $setupMarker.Replace("'", "''") + "' -Value ([DateTimeOffset]::UtcNow.ToString('o'))`r`nexit 0`r`n")
483
+ $decisionFile = Join-Path $root 'detector-launcher.json'
484
+ $slowServer = Join-Path $root 'slow_health.py'
485
+ Write-Utf8NoBom $slowServer @'
486
+ import sys, time
487
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
488
+ port, delay, status = int(sys.argv[1]), float(sys.argv[2]), int(sys.argv[3])
489
+ class Handler(BaseHTTPRequestHandler):
490
+ def do_GET(self):
491
+ time.sleep(delay)
492
+ body = b'{"state":"loading"}'
493
+ self.send_response(status)
494
+ self.send_header("Content-Type", "application/json")
495
+ self.send_header("Content-Length", str(len(body)))
496
+ self.end_headers()
497
+ self.wfile.write(body)
498
+ def log_message(self, *args):
499
+ pass
500
+ ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
501
+ '@
502
+
503
+ # One launcher check, exactly as the launcher runs it (Windows PowerShell 5.1),
504
+ # bounded; returns its decision record and whether the stub provisioner ran.
505
+ function Invoke-EnsureDetector([string[]]$Arguments, [int]$TimeoutSeconds) {
506
+ Remove-Item -LiteralPath $decisionFile, $setupMarker -Force -ErrorAction SilentlyContinue
507
+ $argumentLine = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ('"' + $ensure + '"'),
508
+ '-DecisionPath', ('"' + $decisionFile + '"')) + $Arguments
509
+ $watch = [Diagnostics.Stopwatch]::StartNew()
510
+ $process = Start-Process -FilePath 'powershell.exe' -ArgumentList ($argumentLine -join ' ') -PassThru -WindowStyle Hidden
511
+ if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
512
+ Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue
513
+ throw ('the launcher check did not finish in ' + $TimeoutSeconds + ' s')
514
+ }
515
+ $decision = if (Test-Path -LiteralPath $decisionFile) { Get-Content -LiteralPath $decisionFile -Raw | ConvertFrom-Json } else { $null }
516
+ return [pscustomobject]@{ seconds = [math]::Round($watch.Elapsed.TotalSeconds, 1); exit = $process.ExitCode
517
+ decision = $decision; setupRan = (Test-Path -LiteralPath $setupMarker) }
518
+ }
519
+
520
+ function Start-SlowHealth([int]$ListenPort, [double]$DelaySeconds, [int]$Status) {
521
+ $server = Start-Process -FilePath $py -ArgumentList @('-I', ('"' + $slowServer + '"'), $ListenPort, $DelaySeconds, $Status) -PassThru -WindowStyle Hidden
522
+ $watch = [Diagnostics.Stopwatch]::StartNew()
523
+ while (-not @(Get-NetTCPConnection -LocalPort $ListenPort -State Listen -ErrorAction SilentlyContinue).Count) {
524
+ if ($watch.Elapsed.TotalSeconds -gt 20) { throw ('the stand-in /health on ' + $ListenPort + ' did not start') }
525
+ Start-Sleep -Milliseconds 200
526
+ }
527
+ return $server
528
+ }
529
+
530
+ function Stop-RealDetector {
531
+ $null = & (Join-Path $deploy 'stop-local-ai.ps1') -Service Detector -ToolPath $detectorExe -Port 9380
532
+ Enable-ScheduledTask -TaskName 'TrillboardsDetector' -TaskPath '\' | Out-Null
533
+ if (Get-ListenerPid) { throw 'the detector still listens after its stop' }
534
+ }
535
+
536
+ function Assert-Launcher([string]$Name, $Run, [string]$Decision, [bool]$SetupRan) {
537
+ $got = if ($Run.decision) { [string]$Run.decision.decision } else { '(no decision file)' }
538
+ if ($Run.exit -ne 0) { throw ('(' + $Name + ') the launcher check exited ' + $Run.exit) }
539
+ if ($got -ne $Decision) { throw ('(' + $Name + ') decision ' + $got + ', expected ' + $Decision) }
540
+ if ($Run.setupRan -ne $SetupRan) { throw ('(' + $Name + ') the provisioner ' + $(if ($Run.setupRan) { 'ran' } else { 'did not run' })) }
541
+ }
542
+
543
+ # (d) busy: 503 after 4 s, on a stand-in port (the real detector is not involved).
544
+ $case = [ordered]@{ name = 'busy detector: /health answers 503 after 4 s' }
545
+ $receipt.cases.d = $case
546
+ $pidBefore = Get-ListenerPid
547
+ $slow = Start-SlowHealth 19381 4 503
548
+ try { $run = Invoke-EnsureDetector @('-HealthUrl', 'http://127.0.0.1:19381/health', '-SetupScript', ('"' + $setupStub + '"')) 120 }
549
+ finally { Stop-Process -Id $slow.Id -Force -ErrorAction SilentlyContinue }
550
+ $case.decision = $run.decision; $case.seconds = $run.seconds; $case.setupRan = $run.setupRan
551
+ $case.detectorPidUnchanged = ((Get-ListenerPid) -eq $pidBefore)
552
+ Write-Receipt
553
+ Assert-Launcher 'd' $run 'answered' $false
554
+ if ([int]$run.decision.probes[0].code -ne 503 -or [int]$run.decision.probes[0].ms -lt 3500) { throw '(d) the answer was not the slow 503' }
555
+ if (-not $case.detectorPidUnchanged) { throw '(d) the detector process changed' }
556
+ $case.passed = $true
557
+
558
+ # (i) a listener that never answers: three timeouts, left alone.
559
+ $case = [ordered]@{ name = 'listener that never answers: three 2 s timeouts' }
560
+ $receipt.cases.i = $case
561
+ $slow = Start-SlowHealth 19382 600 200
562
+ try { $run = Invoke-EnsureDetector @('-HealthUrl', 'http://127.0.0.1:19382/health', '-ProbeTimeoutSec', '2', '-SetupScript', ('"' + $setupStub + '"')) 120 }
563
+ finally { Stop-Process -Id $slow.Id -Force -ErrorAction SilentlyContinue }
564
+ $case.decision = $run.decision; $case.seconds = $run.seconds; $case.setupRan = $run.setupRan
565
+ Write-Receipt
566
+ Assert-Launcher 'i' $run 'no_answer_left_alone' $false
567
+ if (@($run.decision.probes | Where-Object { $_.error -eq 'timeout' }).Count -ne 3) { throw '(i) expected three timed-out probes' }
568
+ $case.passed = $true
569
+
570
+ # (h) the provisioner is running: its per-user mutex, held here.
571
+ $case = [ordered]@{ name = 'provisioner running: its mutex held' }
572
+ $receipt.cases.h = $case
573
+ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
574
+ $setupMutex = New-Object System.Threading.Mutex($false, ('Global\TrillboardsDetectorSetup-' + $sid))
575
+ if (-not $setupMutex.WaitOne(0)) { throw '(h) could not take the provisioner mutex' }
576
+ try { $run = Invoke-EnsureDetector @('-SetupScript', ('"' + $setupStub + '"')) 120 }
577
+ finally { $setupMutex.ReleaseMutex(); $setupMutex.Dispose() }
578
+ $case.decision = $run.decision; $case.seconds = $run.seconds; $case.setupRan = $run.setupRan
579
+ Write-Receipt
580
+ Assert-Launcher 'h' $run 'provisioning_in_progress' $false
581
+ $case.passed = $true
582
+
583
+ # (e) the task registered and enabled, its process stopped: the check starts it.
584
+ $case = [ordered]@{ name = 'task registered, process stopped' }
585
+ $receipt.cases.e = $case
586
+ $pidBefore = Get-ListenerPid
587
+ Stop-RealDetector
588
+ $run = Invoke-EnsureDetector @('-SetupScript', ('"' + $setupStub + '"')) 240
589
+ $case.decision = $run.decision; $case.seconds = $run.seconds; $case.setupRan = $run.setupRan
590
+ $case.pidBefore = $pidBefore; $case.pidAfter = Get-ListenerPid
591
+ Write-Receipt
592
+ Assert-Launcher 'e' $run 'started_task' $false
593
+ if ($null -eq $run.decision.answeredAfterStartMs -or [int]$run.decision.answeredAfterStartMs -gt 60000) { throw '(e) the detector did not answer within 60 s of the task start' }
594
+ if (-not $case.pidAfter -or $case.pidAfter -eq $pidBefore) { throw '(e) no new detector process listens' }
595
+ $null = Wait-HealthCode 200 180
596
+ $case.passed = $true
597
+
598
+ # (f) the task registered but unable to start: re-provisioned after the wait.
599
+ $case = [ordered]@{ name = 'task registered, executable renamed: the start fails' }
600
+ $receipt.cases.f = $case
601
+ Stop-RealDetector
602
+ $parked = $detectorExe + '.parked'
603
+ Move-Item -LiteralPath $detectorExe -Destination $parked -Force
604
+ try { $run = Invoke-EnsureDetector @('-StartWaitSec', '15', '-SetupScript', ('"' + $setupStub + '"')) 240 }
605
+ finally {
606
+ Move-Item -LiteralPath $parked -Destination $detectorExe -Force
607
+ Start-ScheduledTask -TaskName 'TrillboardsDetector' -TaskPath '\'
608
+ }
609
+ $case.decision = $run.decision; $case.seconds = $run.seconds; $case.setupRan = $run.setupRan
610
+ Write-Receipt
611
+ Assert-Launcher 'f' $run 'reprovision_still_refused' $true
612
+ if ([string]$run.decision.setupExit -ne '0') { throw ('(f) the provisioner exit was ' + $run.decision.setupExit) }
613
+ $null = Wait-HealthCode 200 180
614
+ $case.passed = $true
615
+
616
+ # (g) the task unregistered: re-provisioned at once, whatever /health says.
617
+ $case = [ordered]@{ name = 'task unregistered' }
618
+ $receipt.cases.g = $case
619
+ $taskXml = Export-ScheduledTask -TaskName 'TrillboardsDetector' -TaskPath '\'
620
+ Unregister-ScheduledTask -TaskName 'TrillboardsDetector' -TaskPath '\' -Confirm:$false
621
+ try { $run = Invoke-EnsureDetector @('-SetupScript', ('"' + $setupStub + '"')) 120 }
622
+ finally { Register-ScheduledTask -TaskName 'TrillboardsDetector' -TaskPath '\' -Xml $taskXml | Out-Null }
623
+ $case.decision = $run.decision; $case.seconds = $run.seconds; $case.setupRan = $run.setupRan
624
+ Write-Receipt
625
+ Assert-Launcher 'g' $run 'reprovision_task_missing' $true
626
+ $case.passed = $true
627
+
458
628
  $receipt.passed = $true
459
629
  Write-Receipt
460
- Write-Host ('PASS: (a) refused with the old detector serving; (b) {0} connection(s) before the cut, 0 after, [{1}] trial {2} s; (c) down {3} ms' -f
461
- $case.connectionsBeforeCut, $case.extras, $case.trialSeconds, $receipt.cases.c.downMs)
630
+ Write-Host ('PASS: (a) refused with the old detector serving; (b) {0} connection(s) before the cut, 0 after, [{1}] trial {2} s; (c) down {3} ms; (d)-(i) launcher check {4}' -f
631
+ $receipt.cases.b.connectionsBeforeCut, $receipt.cases.b.extras, $receipt.cases.b.trialSeconds, $receipt.cases.c.downMs,
632
+ ((@('d', 'e', 'f', 'g', 'h', 'i') | ForEach-Object { $_ + '=' + [string]$receipt.cases[$_].decision.decision }) -join ' '))
462
633
  } catch {
463
634
  # Keep the first error: a failure to record it must not replace it.
464
635
  $proofFailure = $_
@@ -0,0 +1,119 @@
1
+ <#
2
+ test-main-stream-gpu-decode.ps1 - on this Windows host, does a camera's
3
+ main-stream session decode on the GPU only where the d3d11va probe decoded
4
+ the main stream's codec, and does a GPU decode that fails fall back to
5
+ software without dropping the main recording? (plan v7 T1, on plan v7 W8's
6
+ probe)
7
+
8
+ Runs scripts/main-stream-gpu-decode-proof.mjs: THIS build's MainStreamSession
9
+ with the pinned static ffmpeg the installer ships, against a live RTSP main
10
+ stream shaped like Texas camera 1's (MediaMTX re-serving a 2880x1616 HEVC
11
+ pattern at 20 fps with a 1-s GOP), carrying the ring output (a stream copy)
12
+ and the face zone (a decode). It records W8's probe answer on this host, runs
13
+ the session as shipped, and, where the probe did not decode HEVC here, tells
14
+ the session it did so ffmpeg really gets -hwaccel d3d11va and fails over.
15
+ Then it restarts the session mid-way through a 10-s ring segment, as the
16
+ GPU switch does, and checks ffmpeg quit on `q` and the ring kept that
17
+ segment. PASS (proof.json) is the script's verdict. Execute only on a fresh
18
+ GitHub-hosted Windows runner.
19
+ #>
20
+ [CmdletBinding()]
21
+ param(
22
+ [ValidateRange(20, 180)][int]$Seconds = 40
23
+ )
24
+ $ErrorActionPreference = 'Stop'
25
+ Set-StrictMode -Version Latest
26
+ if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_OS -ne 'Windows' -or
27
+ $env:RUNNER_ENVIRONMENT -ne 'github-hosted' -or $PSVersionTable.PSVersion.Major -lt 7) {
28
+ throw 'The main-stream GPU decode proof requires a fresh GitHub-hosted Windows runner and PowerShell 7'
29
+ }
30
+
31
+ $Here = Split-Path -Parent $MyInvocation.MyCommand.Path # deploy\windows\ci
32
+ $PkgRoot = (Resolve-Path (Join-Path $Here '..\..\..')).Path # packages\edge-sdk
33
+ $DeployWindows = Join-Path $PkgRoot 'deploy\windows'
34
+ if (-not (Test-Path -LiteralPath (Join-Path $PkgRoot '..\edge-platform-rtsp\dist\MainStreamSession.js'))) {
35
+ throw 'Build the workspace first (npm run build): edge-platform-rtsp dist\MainStreamSession.js is missing'
36
+ }
37
+ $root = [IO.Path]::GetFullPath((Join-Path $env:RUNNER_TEMP ('tb-main-gpu-' + [Guid]::NewGuid().ToString('N'))))
38
+ New-Item -ItemType Directory -Path $root | Out-Null
39
+ if ($env:GITHUB_OUTPUT) { ('artifact_path=' + $root) | Out-File -LiteralPath $env:GITHUB_OUTPUT -Append -Encoding utf8 }
40
+ $timeline = Join-Path $root 'timeline.log'
41
+
42
+ function Note([string]$Message) {
43
+ $line = [DateTimeOffset]::UtcNow.ToString('HH:mm:ss') + ' ' + $Message
44
+ Write-Host $line
45
+ Add-Content -LiteralPath $timeline -Value $line -Encoding utf8
46
+ }
47
+
48
+ $owned = New-Object System.Collections.Generic.List[System.Diagnostics.Process]
49
+ try {
50
+ # The pinned static ffmpeg the installer ships, checksum-verified.
51
+ $pin = (& pwsh -NoProfile -File (Join-Path $DeployWindows 'build-windows.ps1') -PrintFfmpegPin | Select-Object -Last 1).ToString().Trim().Split(' ')
52
+ $ffmpeg = Join-Path $root 'ffmpeg.exe'
53
+ Invoke-WebRequest -Uri $pin[0] -OutFile $ffmpeg -UseBasicParsing
54
+ if ((Get-FileHash -LiteralPath $ffmpeg -Algorithm SHA256).Hash.ToLowerInvariant() -ne $pin[1].ToLowerInvariant()) { throw 'Pinned ffmpeg checksum mismatch' }
55
+ Note ('ffmpeg pinned at ' + $pin[0])
56
+
57
+ $rig = Join-Path $root 'rig'
58
+ New-Item -ItemType Directory -Path $rig | Out-Null
59
+ # Official MediaMTX v1.21.2 checksum, the same pin as test-detector-looks-field.ps1.
60
+ $archive = Join-Path $rig 'mediamtx.zip'
61
+ Invoke-WebRequest -Uri 'https://github.com/bluenviron/mediamtx/releases/download/v1.21.2/mediamtx_v1.21.2_windows_amd64.zip' -OutFile $archive -UseBasicParsing
62
+ if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne 'a84224f5a490855684e62ba6fb71e80ea2a5e16aed61883bb58380290e93e467') { throw 'MediaMTX checksum mismatch' }
63
+ Expand-Archive -LiteralPath $archive -DestinationPath $rig
64
+ $rtspPort = 8654; $apiPort = 9897
65
+ @"
66
+ logLevel: warn
67
+ rtspAddress: 127.0.0.1:$rtspPort
68
+ rtspTransports: [tcp]
69
+ rtmp: no
70
+ hls: no
71
+ webrtc: no
72
+ srt: no
73
+ metrics: no
74
+ pprof: no
75
+ playback: no
76
+ moq: no
77
+ api: yes
78
+ apiAddress: 127.0.0.1:$apiPort
79
+ authInternalUsers:
80
+ - user: any
81
+ pass: ""
82
+ ips: [127.0.0.1]
83
+ permissions:
84
+ - action: publish
85
+ - action: read
86
+ - action: api
87
+ paths:
88
+ main:
89
+ "@ | Set-Content -LiteralPath (Join-Path $rig 'mediamtx.yml') -Encoding utf8
90
+ $owned.Add((Start-Process -FilePath (Join-Path $rig 'mediamtx.exe') -ArgumentList ('"' + (Join-Path $rig 'mediamtx.yml') + '"') -WorkingDirectory $rig -PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $root 'mediamtx.log') -RedirectStandardError (Join-Path $root 'mediamtx.err.log')))
91
+ Start-Sleep -Seconds 2
92
+
93
+ # Texas camera 1's main stream, as its recorder sends it: 2880x1616 HEVC at 20 fps, a keyframe a second. Encoded
94
+ # once (10 s), re-served on a loop by a copy of the bundled ffmpeg so the camera never looks like the session.
95
+ $clip = Join-Path $rig 'main.mp4'
96
+ & $ffmpeg -hide_banner -loglevel error -f lavfi -i 'testsrc2=size=2880x1616:rate=20' -t 10 -c:v libx265 -preset ultrafast `
97
+ -x265-params 'log-level=error:keyint=20:min-keyint=20' -pix_fmt yuv420p -an -y $clip
98
+ if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $clip)) { throw 'Could not encode the HEVC main stream' }
99
+ $cameraFfmpeg = Join-Path $rig 'camera-ffmpeg.exe'
100
+ Copy-Item -LiteralPath $ffmpeg -Destination $cameraFfmpeg
101
+ $publishArgs = '-hide_banner -loglevel error -re -stream_loop -1 -i "' + $clip + '" -c copy -f rtsp -rtsp_transport tcp rtsp://127.0.0.1:' + $rtspPort + '/main'
102
+ $owned.Add((Start-Process -FilePath $cameraFfmpeg -ArgumentList $publishArgs -PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $root 'camera.log') -RedirectStandardError (Join-Path $root 'camera.err.log')))
103
+ $deadline = [DateTime]::UtcNow.AddSeconds(45)
104
+ $ready = $false
105
+ do {
106
+ Start-Sleep -Seconds 1
107
+ try { $ready = @((Invoke-RestMethod -Uri ('http://127.0.0.1:' + $apiPort + '/v3/paths/list') -TimeoutSec 3).items | Where-Object { $_.name -eq 'main' -and $_.ready }).Count -gt 0 } catch { $ready = $false }
108
+ } while (-not $ready -and [DateTime]::UtcNow -lt $deadline)
109
+ if (-not $ready) { throw 'The HEVC main stream never became readable' }
110
+ Note ('HEVC main stream live at rtsp://127.0.0.1:' + $rtspPort + '/main')
111
+
112
+ $node = (Get-Command node.exe -ErrorAction Stop).Source
113
+ & $node (Join-Path $PkgRoot 'scripts\main-stream-gpu-decode-proof.mjs') --ffmpeg $ffmpeg --rtsp ('rtsp://127.0.0.1:' + $rtspPort + '/main') --out $root --seconds $Seconds --gop-ms 1000
114
+ $proofExit = $LASTEXITCODE
115
+ Note ('proof exited ' + $proofExit)
116
+ if ($proofExit -ne 0) { throw ('Main-stream GPU decode proof failed (exit ' + $proofExit + '): see proof.json') }
117
+ } finally {
118
+ foreach ($p in $owned) { try { if (-not $p.HasExited) { $p.Kill($true) } } catch { } }
119
+ }
@@ -49,7 +49,8 @@
49
49
  subject is the production publisher's CN and which only this runner trusts;
50
50
  C's cli.js exits 3 whenever it is started to sense. Every .ps1/.vbs/.exe in
51
51
  bin\ keeps the release's real signatures. setup-litertlm.ps1 and
52
- setup-detector.ps1 are left out of every tree so the launcher's local-AI
52
+ setup-detector.ps1 (and the launcher's detector check, ensure-detector.ps1)
53
+ are left out of every tree so the launcher's local-AI
53
54
  repair never starts a download on the runner; the model service is a stub
54
55
  that lists the pinned Gemma id.
55
56
 
@@ -306,7 +307,7 @@ try {
306
307
  foreach ($rel in @('bin\node.exe', 'bin\apply-update.ps1', 'bin\install-update.ps1', 'lib\edge-sdk\dist\cli.js', 'lib\edge-sdk\package.json')) {
307
308
  if (-not (Test-Path -LiteralPath (Join-Path $treeA $rel))) { throw "The release payload is missing $rel" }
308
309
  }
309
- foreach ($rel in @('bin\setup-litertlm.ps1', 'bin\setup-detector.ps1')) { Remove-Item -LiteralPath (Join-Path $treeA $rel) -Force -ErrorAction SilentlyContinue }
310
+ foreach ($rel in @('bin\setup-litertlm.ps1', 'bin\setup-detector.ps1', 'bin\ensure-detector.ps1')) { Remove-Item -LiteralPath (Join-Path $treeA $rel) -Force -ErrorAction SilentlyContinue }
310
311
  $versionA = [string](Get-Content -LiteralPath (Join-Path $treeA 'lib\edge-sdk\package.json') -Raw | ConvertFrom-Json).version
311
312
  if ($versionA -notmatch '^(\d+)\.(\d+)\.(\d+)$') { throw "Unreadable release version '$versionA'" }
312
313
  $versionB = "$($Matches[1]).$($Matches[2]).$([int]$Matches[3] + 1000)"