@camstack/addon-pipeline-orchestrator 1.2.692 → 1.2.693

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.
package/dist/index.js CHANGED
@@ -6106,7 +6106,7 @@ var ZodIssueCode = {
6106
6106
  var ZodFirstPartyTypeKind;
6107
6107
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6108
6108
  //#endregion
6109
- //#region ../types/dist/sleep-C9EWTQr9.mjs
6109
+ //#region ../types/dist/sleep-DnhxKL99.mjs
6110
6110
  /**
6111
6111
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6112
6112
  * window to float samples (D455).
@@ -60804,6 +60804,34 @@ var OrphanListSchema = object({
60804
60804
  /** More orphans exist than {@link DEVICE_HISTORY_ORPHAN_LIST_MAX}. */
60805
60805
  truncated: boolean()
60806
60806
  });
60807
+ var DeviceHistoryRangeDeleteRefusalSchema = _enum([
60808
+ "invalid-range",
60809
+ "range-too-large",
60810
+ "series-not-found",
60811
+ "not-a-point-series"
60812
+ ]);
60813
+ var RollupRowsSchema = object({
60814
+ "5m": number$1().int(),
60815
+ "1h": number$1().int(),
60816
+ "1d": number$1().int()
60817
+ });
60818
+ /**
60819
+ * What a time-range delete did, or WOULD do (`dryRun`). `rows` is what was
60820
+ * removed: raw points inside the range, and the rollup rows covering it (those
60821
+ * are removed and rebuilt from what remains, so a gap leaves no stale value).
60822
+ * `rewritten` is how many rollup rows were rebuilt from the remaining points;
60823
+ * `null` on a dry run, which cannot know before it has deleted.
60824
+ */
60825
+ var RangeDeleteResultSchema = discriminatedUnion("ok", [object({
60826
+ ok: literal(true),
60827
+ dryRun: boolean(),
60828
+ seriesId: number$1().int(),
60829
+ rows: TierRowsSchema,
60830
+ rewritten: RollupRowsSchema.nullable()
60831
+ }), object({
60832
+ ok: literal(false),
60833
+ reason: DeviceHistoryRangeDeleteRefusalSchema
60834
+ })]);
60807
60835
  var DeviceHistoryStatusSchema = object({
60808
60836
  startedAt: number$1(),
60809
60837
  /** The store is declared, series loaded and the first reconcile has answered. */
@@ -60904,6 +60932,16 @@ method(object({ deviceId: number$1().int() }), array(SeriesInfoSchema).readonly(
60904
60932
  }), method(object({}), DeviceHistoryStatusSchema, { auth: "admin" }), method(object({}), OrphanListSchema, { auth: "admin" }), method(object({ seriesIds: array(number$1().int()).min(1).max(50) }), object({ results: array(OrphanDeleteEntrySchema).readonly() }), {
60905
60933
  kind: "mutation",
60906
60934
  auth: "admin"
60935
+ }), method(object({
60936
+ deviceId: number$1().int(),
60937
+ key: string().min(1),
60938
+ scope: string(),
60939
+ fromMs: number$1().int().nonnegative(),
60940
+ toMs: number$1().int().nonnegative(),
60941
+ dryRun: boolean()
60942
+ }), RangeDeleteResultSchema, {
60943
+ kind: "mutation",
60944
+ auth: "admin"
60907
60945
  });
60908
60946
  /**
60909
60947
  * `device-removal-hook` — the reliable way an addon learns a device was DELETED,
@@ -79359,6 +79397,82 @@ var EffectiveSharesSchema = object({
79359
79397
  nodeWeights: record(string(), number$1()),
79360
79398
  deviceWeights: record(string(), record(string(), number$1()))
79361
79399
  });
79400
+ var HealthFindingKindSchema = _enum([
79401
+ "motion-without-detections",
79402
+ "detections-under-floor",
79403
+ "inference-too-slow",
79404
+ "frames-shed",
79405
+ "inference-device-unusable"
79406
+ ]);
79407
+ var HealthSeveritySchema = _enum([
79408
+ "info",
79409
+ "warning",
79410
+ "critical"
79411
+ ]);
79412
+ var HealthSubjectSchema = discriminatedUnion("type", [
79413
+ object({
79414
+ type: literal("camera"),
79415
+ deviceId: number$1()
79416
+ }),
79417
+ object({
79418
+ type: literal("node"),
79419
+ nodeId: string()
79420
+ }),
79421
+ object({
79422
+ type: literal("inference-device"),
79423
+ nodeId: string(),
79424
+ deviceKey: string()
79425
+ })
79426
+ ]);
79427
+ var HealthFindingSchema = object({
79428
+ /** Stable across ticks for the same condition on the same subject. */
79429
+ id: string(),
79430
+ kind: HealthFindingKindSchema,
79431
+ severity: HealthSeveritySchema,
79432
+ subject: HealthSubjectSchema,
79433
+ what: string(),
79434
+ /** The numbers behind the sentence; `null` = the value could not be read. */
79435
+ evidence: record(string(), number$1().nullable()),
79436
+ action: string()
79437
+ });
79438
+ /** One in-memory source the tick read, and whether it answered. */
79439
+ var HealthSourceStatusSchema = object({
79440
+ source: string(),
79441
+ /** Entries read; `null` = the read failed. */
79442
+ entries: number$1().nullable()
79443
+ });
79444
+ var HealthNodeSummarySchema = object({
79445
+ nodeId: string(),
79446
+ sessionsNow: number$1(),
79447
+ /** `deviceKey` of every inference device the balancer excludes on this node. */
79448
+ unusableDevices: array(string()).readonly(),
79449
+ devices: array(object({
79450
+ deviceKey: string(),
79451
+ sessionsNow: number$1(),
79452
+ usable: boolean()
79453
+ })).readonly()
79454
+ });
79455
+ var HealthDigestSchema = object({
79456
+ generatedAt: number$1(),
79457
+ /** Wall time the tick took to build this digest. */
79458
+ tickMs: number$1(),
79459
+ /** Cameras known to the digest; `null` when a camera source failed to read (the union would be incomplete). */
79460
+ camerasSeen: number$1().nullable(),
79461
+ findings: array(HealthFindingSchema).readonly(),
79462
+ nodes: array(HealthNodeSummarySchema).readonly(),
79463
+ sources: array(HealthSourceStatusSchema).readonly(),
79464
+ /** Signals the digest does not cover yet, and why — never computed by scanning. */
79465
+ notCovered: array(string()).readonly()
79466
+ });
79467
+ var HealthDigestInputSchema = object({
79468
+ /** Newest first; 1 = the latest digest. */
79469
+ history: number$1().int().min(1).max(24).default(1) });
79470
+ var HealthDigestAnswerSchema = object({
79471
+ /** Null until the first tick has run. */
79472
+ latest: HealthDigestSchema.nullable(),
79473
+ /** Older digests, newest first, when `history` > 1. */
79474
+ previous: array(HealthDigestSchema).readonly()
79475
+ });
79362
79476
  var CameraPipelineConfigSchema = object({
79363
79477
  engine: PipelineEngineChoiceSchema.optional(),
79364
79478
  steps: array(PipelineStepInputSchema).readonly(),
@@ -80295,6 +80409,16 @@ var pipelineOrchestratorCapability = {
80295
80409
  */
80296
80410
  getPlacementStats: method(PlacementStatsInputSchema, PlacementStatsSchema, { auth: "admin" }),
80297
80411
  /**
80412
+ * Health digest (planning#572) — findings an operator can act on, built
80413
+ * every 5 minutes from state the orchestrator already holds in memory
80414
+ * (no log scan, no database read): motion that never becomes a detection,
80415
+ * candidates all under the class floor, inference slower than the fps it
80416
+ * must allow, shed frames, unusable inference devices. `latest` is null
80417
+ * until the first tick; `previous` holds older digests when `history` > 1.
80418
+ * In memory on the hub — a restart starts empty.
80419
+ */
80420
+ getHealthDigest: method(HealthDigestInputSchema, HealthDigestAnswerSchema, { auth: "admin" }),
80421
+ /**
80298
80422
  * Load balancing (D748, D755) — shares proportional to each node's
80299
80423
  * capacity in parallel sessions: from the latency table at the models
80300
80424
  * Auto tune picks (`hardware`), or from node benchmark results
@@ -95550,6 +95674,13 @@ Object.freeze({
95550
95674
  access: "delete",
95551
95675
  role: "admin"
95552
95676
  },
95677
+ "deviceHistory.deleteSeriesRange": {
95678
+ capName: "device-history",
95679
+ capScope: "system",
95680
+ addonId: null,
95681
+ access: "delete",
95682
+ role: "admin"
95683
+ },
95553
95684
  "deviceHistory.getDeviceEnabled": {
95554
95685
  capName: "device-history",
95555
95686
  capScope: "system",
@@ -100366,6 +100497,13 @@ Object.freeze({
100366
100497
  access: "view",
100367
100498
  role: "admin"
100368
100499
  },
100500
+ "pipelineOrchestrator.getHealthDigest": {
100501
+ capName: "pipeline-orchestrator",
100502
+ capScope: "system",
100503
+ addonId: null,
100504
+ access: "view",
100505
+ role: "admin"
100506
+ },
100369
100507
  "pipelineOrchestrator.getIngestOwner": {
100370
100508
  capName: "pipeline-orchestrator",
100371
100509
  capScope: "system",
@@ -104617,6 +104755,11 @@ Object.freeze({
104617
104755
  form: "single",
104618
104756
  optional: false
104619
104757
  }],
104758
+ "deviceHistory.deleteSeriesRange": [{
104759
+ name: "deviceId",
104760
+ form: "single",
104761
+ optional: false
104762
+ }],
104620
104763
  "deviceHistory.getDeviceEnabled": [{
104621
104764
  name: "deviceId",
104622
104765
  form: "single",
@@ -117403,6 +117546,36 @@ var DetectionBlindMonitor = class {
117403
117546
  }
117404
117547
  return out;
117405
117548
  }
117549
+ /**
117550
+ * A read-only view of every tracked camera: no transition fires, no state
117551
+ * changes. Costs one pass over the map; used by the health digest tick.
117552
+ */
117553
+ snapshot(now) {
117554
+ const window = this.config.noisyWindowMs;
117555
+ const from = now - window;
117556
+ const out = [];
117557
+ for (const [deviceId, s] of this.state) {
117558
+ let motionMs = 0;
117559
+ let opened = 0;
117560
+ for (const span of s.spans) {
117561
+ if ((span.end ?? now) <= from) continue;
117562
+ motionMs += Math.min(span.end ?? now, now) - Math.max(span.start, from);
117563
+ if (span.start >= from) opened += 1;
117564
+ }
117565
+ out.push({
117566
+ deviceId,
117567
+ motionKnown: s.motionKnown,
117568
+ sessionsInWindow: opened,
117569
+ dutyInWindow: s.motionKnown ? motionMs / window : null,
117570
+ lastDetectionAt: s.lastDetectionAt,
117571
+ lastFrameAt: s.lastFrameAt,
117572
+ belowFloorFrames: s.belowFloor,
117573
+ framesSinceOutput: s.frames,
117574
+ trackedSince: s.trackedSince
117575
+ });
117576
+ }
117577
+ return out;
117578
+ }
117406
117579
  /** Drop a device (detach / unbind), so a re-attach starts a fresh clock. */
117407
117580
  forget(deviceId) {
117408
117581
  this.state.delete(deviceId);
@@ -117412,6 +117585,314 @@ var DetectionBlindMonitor = class {
117412
117585
  }
117413
117586
  };
117414
117587
  //#endregion
117588
+ //#region src/health-digest.ts
117589
+ /** The digest runs this often. */
117590
+ var HEALTH_DIGEST_INTERVAL_MS = 5 * 6e4;
117591
+ var NOT_COVERED = [
117592
+ "decode hwaccel fallback on every session start: the counter lives in the stream-broker/decoder process, no orchestrator-side source",
117593
+ "births tossed before a track and crop misses (worker-lease-gone): runner-side counters, not mirrored in the orchestrator",
117594
+ "stationary registry absorbing most detections: runner-side registry, not mirrored in the orchestrator",
117595
+ "which model runs on which inference device: only a cross-node cap call answers it, not allowed on a light tick"
117596
+ ];
117597
+ function motionFindings(c, now) {
117598
+ const m = c.motion;
117599
+ if (m === null || !m.motionKnown) return [];
117600
+ const subject = {
117601
+ type: "camera",
117602
+ deviceId: c.deviceId
117603
+ };
117604
+ const out = [];
117605
+ const detectedRecently = m.lastDetectionAt !== null && now - m.lastDetectionAt < 60 * 6e4;
117606
+ if (m.belowFloorFrames >= 10 && !detectedRecently) out.push({
117607
+ id: `detections-under-floor:${c.deviceId}`,
117608
+ kind: "detections-under-floor",
117609
+ severity: "warning",
117610
+ subject,
117611
+ what: "The detector sees candidates on this camera but every one is below its class floor.",
117612
+ evidence: {
117613
+ belowFloorFrames: m.belowFloorFrames,
117614
+ sessionsInWindow: m.sessionsInWindow
117615
+ },
117616
+ action: "Check the class floors for this camera (a lower floor, or a better model); open a track in debug to see the discarded scores."
117617
+ });
117618
+ else if (m.sessionsInWindow >= 20 && !detectedRecently) out.push({
117619
+ id: `motion-without-detections:${c.deviceId}`,
117620
+ kind: "motion-without-detections",
117621
+ severity: "warning",
117622
+ subject,
117623
+ what: "Motion keeps starting detection sessions on this camera and none produced a detection.",
117624
+ evidence: {
117625
+ sessionsInWindow: m.sessionsInWindow,
117626
+ dutyInWindow: m.dutyInWindow,
117627
+ framesSinceOutput: m.framesSinceOutput
117628
+ },
117629
+ action: "Tighten the motion source or its zones (wind, trees, lights), or confirm the camera view is not blocked."
117630
+ });
117631
+ return out;
117632
+ }
117633
+ function metricsFindings(c, now) {
117634
+ const m = c.metrics;
117635
+ if (m === null || m.phase !== "active" || now - m.lastSeen > 6e5) return [];
117636
+ const subject = {
117637
+ type: "camera",
117638
+ deviceId: c.deviceId
117639
+ };
117640
+ const out = [];
117641
+ if (m.avgInferenceTimeMs > 0 && m.configuredFps > 0) {
117642
+ const allowedFps = 1e3 / m.avgInferenceTimeMs;
117643
+ if (allowedFps < m.configuredFps) out.push({
117644
+ id: `inference-too-slow:${c.deviceId}`,
117645
+ kind: "inference-too-slow",
117646
+ severity: allowedFps < m.configuredFps * .5 ? "critical" : "warning",
117647
+ subject,
117648
+ what: "Inference takes longer than the frame rate this camera is configured for allows.",
117649
+ evidence: {
117650
+ allowedFps,
117651
+ configuredFps: m.configuredFps,
117652
+ actualFps: m.actualFps,
117653
+ avgInferenceTimeMs: m.avgInferenceTimeMs
117654
+ },
117655
+ action: "Lower the camera detection fps, pick a faster model, or move the camera to a faster inference device."
117656
+ });
117657
+ }
117658
+ if (m.droppedSincePreviousTick !== null && m.droppedSincePreviousTick > 0 && m.queueDepth > 0) out.push({
117659
+ id: `frames-shed:${c.deviceId}`,
117660
+ kind: "frames-shed",
117661
+ severity: "warning",
117662
+ subject,
117663
+ what: "The worker is saturated: frames are being shed while a backlog waits.",
117664
+ evidence: {
117665
+ droppedSincePreviousTick: m.droppedSincePreviousTick,
117666
+ droppedFramesTotal: m.droppedFrames,
117667
+ queueDepth: m.queueDepth,
117668
+ actualFps: m.actualFps
117669
+ },
117670
+ action: "Move cameras off this device, add an inference device, or lower detection fps."
117671
+ });
117672
+ return out;
117673
+ }
117674
+ function deviceFindings(unusable) {
117675
+ return unusable.map((d) => ({
117676
+ id: `inference-device-unusable:${d.nodeId}:${d.deviceKey}`,
117677
+ kind: "inference-device-unusable",
117678
+ severity: "critical",
117679
+ subject: {
117680
+ type: "inference-device",
117681
+ nodeId: d.nodeId,
117682
+ deviceKey: d.deviceKey
117683
+ },
117684
+ what: "The balancer excludes this inference device: it stopped answering usably.",
117685
+ evidence: {},
117686
+ action: "Check the device and driver on the node; sessions run on its other devices meanwhile."
117687
+ }));
117688
+ }
117689
+ function nodeSummaries(placement, unusable) {
117690
+ const bad = unusable ?? [];
117691
+ return placement.map((n) => ({
117692
+ nodeId: n.nodeId,
117693
+ sessionsNow: n.sessionsNow,
117694
+ unusableDevices: bad.filter((d) => d.nodeId === n.nodeId).map((d) => d.deviceKey),
117695
+ devices: n.devices.map((d) => ({
117696
+ deviceKey: d.deviceKey,
117697
+ sessionsNow: d.sessionsNow,
117698
+ usable: !bad.some((b) => b.nodeId === n.nodeId && b.deviceKey === d.deviceKey)
117699
+ }))
117700
+ }));
117701
+ }
117702
+ var SEVERITY_ORDER = {
117703
+ critical: 0,
117704
+ warning: 1,
117705
+ info: 2
117706
+ };
117707
+ function buildHealthDigest(state, tickMs) {
117708
+ const findings = [];
117709
+ for (const c of state.cameras) findings.push(...motionFindings(c, state.now), ...metricsFindings(c, state.now));
117710
+ if (state.unusableDevices !== null) findings.push(...deviceFindings(state.unusableDevices));
117711
+ findings.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
117712
+ const sources = [
117713
+ {
117714
+ source: "motion",
117715
+ entries: state.motionEntries
117716
+ },
117717
+ {
117718
+ source: "metrics",
117719
+ entries: state.metricsEntries
117720
+ },
117721
+ {
117722
+ source: "placement",
117723
+ entries: state.placement === null ? null : state.placement.length
117724
+ },
117725
+ {
117726
+ source: "inference-device-usability",
117727
+ entries: state.unusableDevices === null ? null : state.unusableDevices.length
117728
+ }
117729
+ ];
117730
+ return {
117731
+ generatedAt: state.now,
117732
+ tickMs,
117733
+ camerasSeen: state.motionEntries === null || state.metricsEntries === null ? null : state.cameras.length,
117734
+ findings,
117735
+ nodes: state.placement === null ? [] : nodeSummaries(state.placement, state.unusableDevices),
117736
+ sources,
117737
+ notCovered: NOT_COVERED
117738
+ };
117739
+ }
117740
+ /** Bounded in-memory history of digests, newest first. */
117741
+ var HealthDigestKeeper = class {
117742
+ keep;
117743
+ digests = [];
117744
+ constructor(keep = 24) {
117745
+ this.keep = keep;
117746
+ }
117747
+ push(digest) {
117748
+ this.digests = [digest, ...this.digests].slice(0, this.keep);
117749
+ }
117750
+ latest() {
117751
+ return this.digests[0] ?? null;
117752
+ }
117753
+ recent(count) {
117754
+ return this.digests.slice(0, count);
117755
+ }
117756
+ };
117757
+ //#endregion
117758
+ //#region src/health-digest-tick.ts
117759
+ /** Latest metrics per camera, stamped on arrival. One entry per camera: bounded. */
117760
+ var CameraMetricsMirror = class {
117761
+ samples = /* @__PURE__ */ new Map();
117762
+ note(deviceId, metrics, at) {
117763
+ this.samples.set(deviceId, {
117764
+ phase: metrics.phase,
117765
+ configuredFps: metrics.configuredFps,
117766
+ actualFps: metrics.actualFps,
117767
+ avgInferenceTimeMs: metrics.avgInferenceTimeMs,
117768
+ queueDepth: metrics.queueDepth,
117769
+ droppedFrames: metrics.droppedFrames,
117770
+ lastSeen: at
117771
+ });
117772
+ }
117773
+ view() {
117774
+ return this.samples;
117775
+ }
117776
+ forget(deviceId) {
117777
+ this.samples.delete(deviceId);
117778
+ }
117779
+ reset() {
117780
+ this.samples.clear();
117781
+ }
117782
+ };
117783
+ /** Run one read; a throw is a `null` read (D393), logged, never a zero. */
117784
+ function attempt(deps, source, read) {
117785
+ try {
117786
+ return { value: read() };
117787
+ } catch (err) {
117788
+ deps.logger.warn("health digest: source unreadable", { meta: {
117789
+ source,
117790
+ error: err instanceof Error ? err.message : String(err)
117791
+ } });
117792
+ return { value: null };
117793
+ }
117794
+ }
117795
+ var HealthDigestTick = class {
117796
+ deps;
117797
+ keeper;
117798
+ previousIds = /* @__PURE__ */ new Map();
117799
+ /** Last `droppedFrames` counter per camera (a monotonic counter since attach). */
117800
+ previousDropped = /* @__PURE__ */ new Map();
117801
+ constructor(deps, keeper = new HealthDigestKeeper()) {
117802
+ this.deps = deps;
117803
+ this.keeper = keeper;
117804
+ }
117805
+ latest() {
117806
+ return this.keeper.latest();
117807
+ }
117808
+ recent(count) {
117809
+ return this.keeper.recent(count);
117810
+ }
117811
+ run() {
117812
+ const started = this.deps.now();
117813
+ const motion = attempt(this.deps, "motion", () => this.deps.readMotion(started));
117814
+ const metrics = attempt(this.deps, "metrics", () => this.deps.readMetrics());
117815
+ const placement = attempt(this.deps, "placement", () => this.deps.readPlacement());
117816
+ const unusable = attempt(this.deps, "inference-device-usability", () => this.deps.readUnusableDevices());
117817
+ const withDelta = this.withDropDeltas(metrics.value);
117818
+ const digest = buildHealthDigest({
117819
+ now: started,
117820
+ cameras: joinCameras(motion.value ?? [], withDelta),
117821
+ motionEntries: motion.value === null ? null : motion.value.length,
117822
+ metricsEntries: metrics.value === null ? null : metrics.value.size,
117823
+ placement: placement.value,
117824
+ unusableDevices: unusable.value
117825
+ }, this.deps.now() - started);
117826
+ this.keeper.push(digest);
117827
+ this.logChanges(digest);
117828
+ this.deps.logger.info("health digest: tick", { meta: {
117829
+ tickMs: digest.tickMs,
117830
+ calls: 4,
117831
+ findings: digest.findings.length,
117832
+ camerasSeen: digest.camerasSeen,
117833
+ unreadableSources: digest.sources.filter((s) => s.entries === null).length
117834
+ } });
117835
+ return digest;
117836
+ }
117837
+ /** Forget a camera's drop baseline (it was unregistered). */
117838
+ forget(deviceId) {
117839
+ this.previousDropped.delete(deviceId);
117840
+ }
117841
+ /** Turn the cumulative `droppedFrames` counters into per-tick deltas; prune departed cameras. */
117842
+ withDropDeltas(metrics) {
117843
+ const out = /* @__PURE__ */ new Map();
117844
+ if (metrics === null) return out;
117845
+ for (const [deviceId, m] of metrics) {
117846
+ const prev = this.previousDropped.get(deviceId);
117847
+ out.set(deviceId, {
117848
+ ...m,
117849
+ droppedSincePreviousTick: prev === void 0 || m.droppedFrames < prev ? null : m.droppedFrames - prev
117850
+ });
117851
+ this.previousDropped.set(deviceId, m.droppedFrames);
117852
+ }
117853
+ for (const id of [...this.previousDropped.keys()]) if (!metrics.has(id)) this.previousDropped.delete(id);
117854
+ return out;
117855
+ }
117856
+ /** A finding is logged when it appears and when it clears, not on every tick. */
117857
+ logChanges(digest) {
117858
+ const current = /* @__PURE__ */ new Map();
117859
+ for (const f of digest.findings) {
117860
+ const deviceId = f.subject.type === "camera" ? f.subject.deviceId : null;
117861
+ current.set(f.id, deviceId);
117862
+ if (this.previousIds.has(f.id)) continue;
117863
+ this.deps.logger.warn("health digest: finding raised", {
117864
+ ...deviceId !== null ? { tags: { deviceId } } : {},
117865
+ meta: {
117866
+ id: f.id,
117867
+ kind: f.kind,
117868
+ severity: f.severity,
117869
+ evidence: f.evidence
117870
+ }
117871
+ });
117872
+ }
117873
+ for (const [id, deviceId] of this.previousIds) {
117874
+ if (current.has(id)) continue;
117875
+ this.deps.logger.info("health digest: finding cleared", {
117876
+ ...deviceId !== null ? { tags: { deviceId } } : {},
117877
+ meta: { id }
117878
+ });
117879
+ }
117880
+ this.previousIds = current;
117881
+ }
117882
+ };
117883
+ function joinCameras(motion, metrics) {
117884
+ const ids = new Set([...motion.map((m) => m.deviceId), ...metrics.keys()]);
117885
+ const byId = new Map(motion.map((m) => [m.deviceId, m]));
117886
+ return [...ids].map((deviceId) => {
117887
+ const snap = byId.get(deviceId);
117888
+ return {
117889
+ deviceId,
117890
+ motion: snap === void 0 ? null : snap,
117891
+ metrics: metrics.get(deviceId) ?? null
117892
+ };
117893
+ });
117894
+ }
117895
+ //#endregion
117415
117896
  //#region src/device-activity-source.ts
117416
117897
  /**
117417
117898
  * How often a sustained LEVEL is re-emitted: half the camera's cooldown, the
@@ -127595,6 +128076,7 @@ async function buildOrchestratorControllers(deps) {
127595
128076
  maintenancePaused: () => deps.maintenancePaused()
127596
128077
  });
127597
128078
  const blindMonitor = new DetectionBlindMonitor();
128079
+ const cameraMetrics = new CameraMetricsMirror();
127598
128080
  const session = new SessionDispatchController({
127599
128081
  onSessionEdge: (edge) => edge.edge === "open" ? blindMonitor.noteSessionOpen(edge.deviceId, edge.at) : blindMonitor.noteSessionClose(edge.deviceId, edge.at),
127600
128082
  ledger,
@@ -128099,6 +128581,7 @@ async function buildOrchestratorControllers(deps) {
128099
128581
  },
128100
128582
  noteMetrics: (deviceId, nodeId, metrics) => {
128101
128583
  loadShed.noteMetrics(deviceId, nodeId, metrics);
128584
+ cameraMetrics.note(deviceId, metrics, Date.now());
128102
128585
  nodeStress.noteMetrics(deviceId, nodeId, metrics);
128103
128586
  },
128104
128587
  handleLazyAudioMotion: (deviceId, detected, config) => audio.handleLazyAudioMotion(deviceId, detected, config),
@@ -128158,6 +128641,8 @@ async function buildOrchestratorControllers(deps) {
128158
128641
  audio,
128159
128642
  settingsStore,
128160
128643
  loadShed,
128644
+ blindMonitor,
128645
+ cameraMetrics,
128161
128646
  nodeStress,
128162
128647
  placement,
128163
128648
  session,
@@ -130140,6 +130625,11 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
130140
130625
  nodeBenchmark = null;
130141
130626
  nodeBenchmarkStore = null;
130142
130627
  nodeBenchmarkTimer = null;
130628
+ /** Health digest (planning#572): the 5-minute tick over in-memory state, and its timer. */
130629
+ healthDigest = null;
130630
+ healthDigestTimer = null;
130631
+ blindMonitor = null;
130632
+ cameraMetrics = null;
130143
130633
  /** Measures an enabled device that has no result yet (GAP 2 of the balancing work). */
130144
130634
  autoBenchmark = null;
130145
130635
  /** How often the active run's runner is polled (a test seam). */
@@ -130471,6 +130961,9 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
130471
130961
  this.audio = controllers.audio;
130472
130962
  this.settingsStore = controllers.settingsStore;
130473
130963
  this.loadShed = controllers.loadShed;
130964
+ this.blindMonitor = controllers.blindMonitor;
130965
+ this.cameraMetrics = controllers.cameraMetrics;
130966
+ this.startHealthDigest();
130474
130967
  this.nodeStress = controllers.nodeStress;
130475
130968
  this.placement = controllers.placement;
130476
130969
  this.session = controllers.session;
@@ -130598,6 +131091,13 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
130598
131091
  clearInterval(this.nodeBenchmarkTimer);
130599
131092
  this.nodeBenchmarkTimer = null;
130600
131093
  }
131094
+ if (this.healthDigestTimer !== null) {
131095
+ clearInterval(this.healthDigestTimer);
131096
+ this.healthDigestTimer = null;
131097
+ }
131098
+ this.healthDigest = null;
131099
+ this.blindMonitor = null;
131100
+ this.cameraMetrics = null;
130601
131101
  this.autoBenchmark?.stop();
130602
131102
  this.autoBenchmark = null;
130603
131103
  this.nodeStressLts = null;
@@ -131822,6 +132322,37 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
131822
132322
  });
131823
132323
  return { success: true };
131824
132324
  }
132325
+ /** Start the 5-minute health digest tick (planning#572): in-memory reads only. */
132326
+ startHealthDigest() {
132327
+ const tick = new HealthDigestTick({
132328
+ now: () => Date.now(),
132329
+ readMotion: (now) => this.blindMonitor?.snapshot(now) ?? [],
132330
+ readMetrics: () => {
132331
+ if (this.cameraMetrics === null) throw new Error("metrics mirror not ready");
132332
+ return this.cameraMetrics.view();
132333
+ },
132334
+ readPlacement: () => this.placementStats.snapshot(60 * 6e4).nodes,
132335
+ readUnusableDevices: () => this.inferenceDeviceUsability.unusableDevices(),
132336
+ logger: this.ctx.logger
132337
+ });
132338
+ this.healthDigest = tick;
132339
+ if (this.healthDigestTimer !== null) clearInterval(this.healthDigestTimer);
132340
+ this.healthDigestTimer = setInterval(() => {
132341
+ try {
132342
+ tick.run();
132343
+ } catch (err) {
132344
+ this.ctx.logger.warn("health digest: tick failed", { meta: { error: errMsg$2(err) } });
132345
+ }
132346
+ }, HEALTH_DIGEST_INTERVAL_MS);
132347
+ this.healthDigestTimer.unref?.();
132348
+ }
132349
+ async getHealthDigest(input) {
132350
+ const digests = this.healthDigest?.recent(input.history) ?? [];
132351
+ return {
132352
+ latest: digests[0] ?? null,
132353
+ previous: digests.slice(1)
132354
+ };
132355
+ }
131825
132356
  async getPlacementStats(input) {
131826
132357
  const snap = this.placementStats.snapshot(input.windowMs);
131827
132358
  return {
@@ -132598,6 +133129,9 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
132598
133129
  }
132599
133130
  /** Stop detection and purge all persisted config for a removed device — thin delegate (S11 Task 3, C14). */
132600
133131
  async handleDeviceUnregistered(deviceId) {
133132
+ this.blindMonitor?.forget(deviceId);
133133
+ this.cameraMetrics?.forget(deviceId);
133134
+ this.healthDigest?.forget(deviceId);
132601
133135
  return this.detectionWiring.handleDeviceUnregistered(deviceId);
132602
133136
  }
132603
133137
  /** Handle a profile-slot change — thin delegate onto `DetectionWiringController` (S11 Task 3, C14). */