@camstack/addon-pipeline 1.2.144 → 1.2.145

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 (33) hide show
  1. package/dist/audio-analyzer/index.js +2 -2
  2. package/dist/audio-analyzer/index.mjs +2 -2
  3. package/dist/detection-pipeline/index.js +5 -5
  4. package/dist/detection-pipeline/index.mjs +4 -4
  5. package/dist/{dist-Dpy1KP1q.js → dist-DML3mpn9.js} +6 -6
  6. package/dist/{dist-uX-YDOrc.mjs → dist-cZopp8Xm.mjs} +6 -6
  7. package/dist/{event-loop-stall-monitor-6YKQeg7_.mjs → event-loop-stall-monitor-DH_vFYWu.mjs} +1 -1
  8. package/dist/{event-loop-stall-monitor-D947d97M.js → event-loop-stall-monitor-DaV4Zdsz.js} +1 -1
  9. package/dist/{lazy-sharp-zDl97I3e.js → lazy-sharp-BzXIjfN8.js} +1 -1
  10. package/dist/motion-wasm/index.js +2 -2
  11. package/dist/motion-wasm/index.mjs +1 -1
  12. package/dist/{node-DuMWMV01.mjs → node-Br6p9KvD.mjs} +1 -1
  13. package/dist/{node-v9ZAGK2b.js → node-OvVqe9eh.js} +1 -1
  14. package/dist/pipeline-runner/index.js +5 -5
  15. package/dist/pipeline-runner/index.mjs +4 -4
  16. package/dist/{process-memory-CNISjywZ.mjs → process-memory-DX25Z60Q.mjs} +1 -1
  17. package/dist/{process-memory-ClAfQ1Nl.js → process-memory-NWKrKfmi.js} +1 -1
  18. package/dist/recorder/index.js +549 -41
  19. package/dist/recorder/index.mjs +549 -41
  20. package/dist/{segment-demux-js-Bpedn-T8.js → segment-demux-js-CerfMroc.js} +1 -1
  21. package/dist/{segment-demux-js-CCMG51zw.mjs → segment-demux-js-DGmFQ1Zj.mjs} +1 -1
  22. package/dist/session-decode/decode-worker-child.js +2 -2
  23. package/dist/session-decode/decode-worker-child.mjs +1 -1
  24. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-MRLUZgkR.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-DQNgiTjz.mjs} +3 -3
  25. package/dist/stream-broker/demux-worker-child.js +1 -1
  26. package/dist/stream-broker/demux-worker-child.mjs +1 -1
  27. package/dist/stream-broker/{hostInit-w0ytBmjx.mjs → hostInit-NShcJE25.mjs} +3 -3
  28. package/dist/stream-broker/index.js +3 -3
  29. package/dist/stream-broker/index.mjs +3 -3
  30. package/dist/stream-broker/remoteEntry.js +1 -1
  31. package/dist/{worker-protocol-Cd-G92Qt.mjs → worker-protocol-CUCQ1IPR.mjs} +1 -1
  32. package/dist/{worker-protocol-Cn5x8dbW.js → worker-protocol-Dt3zWCQY.js} +1 -1
  33. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- const require_dist = require("../dist-Dpy1KP1q.js");
2
- const require_node = require("../node-v9ZAGK2b.js");
1
+ const require_dist = require("../dist-DML3mpn9.js");
2
+ const require_node = require("../node-OvVqe9eh.js");
3
3
  const require_hub_hostname = require("../hub-hostname-DAJXlOgV.js");
4
4
  const require_restream_intent = require("../restream-intent-Cv9x3jmu.js");
5
5
  const require_retire_root_keys = require("../retire-root-keys-KE6D6Xh_.js");
@@ -1072,6 +1072,45 @@ var RecordingIndex = class {
1072
1072
  };
1073
1073
  }
1074
1074
  /**
1075
+ * How many materialised sorted views exist and how many row slots they hold.
1076
+ *
1077
+ * The question this answers: **what is in `large_object_space`?** Production
1078
+ * on 2026-08-29 read ~490 MB there, stable across four samples five minutes
1079
+ * apart — retained, not churn — against 110 MB on hub-main with a comparable
1080
+ * total heap. V8 only puts an object there when it does not fit a normal
1081
+ * page (~256 KB and up), and a sorted view is the recorder's obvious
1082
+ * candidate: one `SegmentRow[]` per (device, profile-or-all), materialised
1083
+ * on first read and then kept live. At ~296 k archive rows a single
1084
+ * all-profiles view is a contiguous array of hundreds of thousands of
1085
+ * pointers — megabytes, in one allocation, per device.
1086
+ *
1087
+ * Slots, not bytes: the array's own allocation is `rowSlots × 8 B` on a
1088
+ * 64-bit heap, and the rows it points at are counted once in `byDevice`
1089
+ * regardless. Reporting a byte estimate would be inventing precision this
1090
+ * cannot have; the slot count is the thing that is actually known and it is
1091
+ * what a reader needs to decide whether the views are the 490 MB.
1092
+ */
1093
+ sortedViewCensus() {
1094
+ let views = 0;
1095
+ let rowSlots = 0;
1096
+ let largestRows = 0;
1097
+ let largestDeviceId = 0;
1098
+ for (const [deviceId, byKey] of this.sortedByDevice) for (const rows of byKey.values()) {
1099
+ views += 1;
1100
+ rowSlots += rows.length;
1101
+ if (rows.length > largestRows) {
1102
+ largestRows = rows.length;
1103
+ largestDeviceId = deviceId;
1104
+ }
1105
+ }
1106
+ return {
1107
+ views,
1108
+ rowSlots,
1109
+ largestRows,
1110
+ largestDeviceId
1111
+ };
1112
+ }
1113
+ /**
1075
1114
  * Ordered insert of ONE NEW row into every live view it belongs to (the
1076
1115
  * all-profiles view and its own profile's view). Views not yet materialised
1077
1116
  * stay unmaterialised — their first read pays the one build. PRECONDITION:
@@ -2029,7 +2068,7 @@ var SegmentStore = class SegmentStore {
2029
2068
  return counts;
2030
2069
  };
2031
2070
  const chunkSize = this.deps.evictChunkSize ?? SegmentStore.DEFAULT_EVICT_CHUNK;
2032
- const yieldBetween = this.deps.yieldBetween ?? macrotask$2;
2071
+ const yieldBetween = this.deps.yieldBetween ?? macrotask$3;
2033
2072
  let bucketsRemoved = 0;
2034
2073
  let handled = 0;
2035
2074
  for (const [bucketDir, bucketRows] of byBucket) {
@@ -2167,7 +2206,7 @@ var SegmentStore = class SegmentStore {
2167
2206
  return indexedInBucket === indexedVictims.size;
2168
2207
  }
2169
2208
  };
2170
- var macrotask$2 = () => new Promise((resolve) => {
2209
+ var macrotask$3 = () => new Promise((resolve) => {
2171
2210
  setImmediate(resolve);
2172
2211
  });
2173
2212
  //#endregion
@@ -7195,7 +7234,7 @@ async function resolveRecordingsLocations(api, logger) {
7195
7234
  * (best-effort), so one bad volume never blocks the rest of the hydrate.
7196
7235
  */
7197
7236
  async function hydrateDeviceFromStorage(_api, index, deviceId, locations, logger, options = {}) {
7198
- const yieldBetween = options.yieldBetween ?? macrotask$1;
7237
+ const yieldBetween = options.yieldBetween ?? macrotask$2;
7199
7238
  const chunkSize = options.chunkSize ?? HYDRATE_CHUNK;
7200
7239
  for (const [root, aliases] of aliasesByRoot(locations)) {
7201
7240
  const deviceDir = node_path.default.join(root, String(deviceId));
@@ -7263,7 +7302,7 @@ async function hydrateDeviceFromStorage(_api, index, deviceId, locations, logger
7263
7302
  }
7264
7303
  /** Entries classified between yields in {@link hydrateDeviceFromStorage}. */
7265
7304
  var HYDRATE_CHUNK = 2e4;
7266
- var macrotask$1 = () => new Promise((resolve) => {
7305
+ var macrotask$2 = () => new Promise((resolve) => {
7267
7306
  setImmediate(resolve);
7268
7307
  });
7269
7308
  /** `<deviceId>/<profile>/YYYY/MM/DD/HH` for an hour bucket (paths are UTC). */
@@ -7289,9 +7328,56 @@ var HOUR_MS$2 = 36e5;
7289
7328
  *
7290
7329
  * Hours already walked are skipped, so a drag across an hour costs nothing the
7291
7330
  * second time.
7292
- */
7293
- async function hydrateWindowFromStorage(index, deviceId, fromMs, toMs, locations, logger) {
7331
+ *
7332
+ * ## The ledger is the first stop for a CLOSED hour (D287)
7333
+ *
7334
+ * Boot no longer replays the archive into the index, so a ledger-known hour
7335
+ * arrives here `unknown` and pays ONE point read of its hour row instead of a
7336
+ * `readdir` — measured at ~650 ms per hour directory on the live share under
7337
+ * load, against the array the scrub feeder is competing for. Hours the ledger
7338
+ * does not know, and every hour if the read fails, fall through to the walk
7339
+ * exactly as before: the failure direction is toward the disk, never toward an
7340
+ * hour that renders empty because nobody read it.
7341
+ *
7342
+ * **The live hour is never served from the ledger.** It is the one hour whose
7343
+ * durable row is knowably behind the disk: a segment finalized after the last
7344
+ * persist and before a crash is on the array and not in the row. Boot used to
7345
+ * mark every ledger hour `hydrated`, which made that tail invisible to
7346
+ * playback and the timeline FOREVER, not merely under-reported. Excluding the
7347
+ * live hour costs exactly one hour-directory read per process — the walk marks
7348
+ * it, so the second reader pays nothing — and it is what turns a lost tail
7349
+ * back into a recoverable one.
7350
+ *
7351
+ * A CLOSED hour already walked is skipped, which is what makes that exclusion
7352
+ * affordable: without it, every window touching the live hour would re-walk
7353
+ * all of its hours. The past is immutable, so re-reading a closed hour
7354
+ * directory can only ever return what the index already holds; eviction
7355
+ * removes rows through the index directly.
7356
+ */
7357
+ async function hydrateWindowFromStorage(index, deviceId, fromMs, toMs, locations, logger, ledger) {
7294
7358
  if (index.hydrationOf(deviceId, fromMs, toMs) === "hydrated") return;
7359
+ const liveHour = Math.floor(Date.now() / HOUR_MS$2) * HOUR_MS$2;
7360
+ if (ledger !== void 0) {
7361
+ const startedMs = Date.now();
7362
+ const hours = await ledger.detailForWindow(deviceId, fromMs, toMs);
7363
+ let segments = 0;
7364
+ let served = 0;
7365
+ for (const hour of hours) {
7366
+ if (hour.hourStartMs >= liveHour) continue;
7367
+ index.hydrateHour(deviceId, hour.locationId, hour.hourStartMs, hour.paths);
7368
+ segments += hour.paths.length;
7369
+ served += 1;
7370
+ }
7371
+ if (served > 0) logger.info("recorder: hydrated a window from the hour ledger", {
7372
+ tags: { deviceId },
7373
+ meta: {
7374
+ hours: served,
7375
+ segments,
7376
+ ms: Date.now() - startedMs
7377
+ }
7378
+ });
7379
+ if (index.hydrationOf(deviceId, fromMs, toMs) === "hydrated") return;
7380
+ }
7295
7381
  for (const [root, aliases] of aliasesByRoot(locations)) {
7296
7382
  const deviceDir = node_path.default.join(root, String(deviceId));
7297
7383
  let profiles;
@@ -7310,16 +7396,26 @@ async function hydrateWindowFromStorage(index, deviceId, fromMs, toMs, locations
7310
7396
  const first = Math.floor(fromMs / HOUR_MS$2) * HOUR_MS$2;
7311
7397
  const reuseBefore = index.hydrateReuseStats();
7312
7398
  let hoursRead = 0;
7313
- for (let hour = first; hour < toMs; hour += HOUR_MS$2) for (const profile of profiles) {
7314
- const rel = hourDirRelPath(deviceId, profile, hour);
7315
- let files;
7316
- try {
7317
- files = await node_fs.promises.readdir(node_path.default.join(root, rel));
7318
- } catch {
7319
- continue;
7399
+ let repaired = 0;
7400
+ for (let hour = first; hour < toMs; hour += HOUR_MS$2) {
7401
+ if (hour < liveHour && index.hydrationOf(deviceId, hour, hour + HOUR_MS$2) === "hydrated") continue;
7402
+ for (const profile of profiles) {
7403
+ const rel = hourDirRelPath(deviceId, profile, hour);
7404
+ let files;
7405
+ try {
7406
+ files = await node_fs.promises.readdir(node_path.default.join(root, rel));
7407
+ } catch {
7408
+ continue;
7409
+ }
7410
+ hoursRead += 1;
7411
+ const locationId = locationForHydratedProfile(aliases, profile).id;
7412
+ const relPaths = files.filter((f) => f.endsWith(".m4s")).map((f) => `${rel}/${f}`);
7413
+ index.hydrateHour(deviceId, locationId, hour, relPaths);
7414
+ if (ledger !== void 0 && relPaths.length > 0 && hour + HOUR_MS$2 <= Date.now() && !ledger.knowsHour(deviceId, profile, locationId, hour)) {
7415
+ repaired += 1;
7416
+ await ledger.adoptRebuiltHour(deviceId, profile, locationId, hour, relPaths);
7417
+ }
7320
7418
  }
7321
- hoursRead += 1;
7322
- index.hydrateHour(deviceId, locationForHydratedProfile(aliases, profile).id, hour, files.filter((f) => f.endsWith(".m4s")).map((f) => `${rel}/${f}`));
7323
7419
  }
7324
7420
  index.markHydrated(deviceId, fromMs, toMs);
7325
7421
  if (hoursRead === 0) continue;
@@ -7331,6 +7427,7 @@ async function hydrateWindowFromStorage(index, deviceId, fromMs, toMs, locations
7331
7427
  meta: {
7332
7428
  root,
7333
7429
  hoursRead,
7430
+ repaired,
7334
7431
  reused,
7335
7432
  allocated
7336
7433
  }
@@ -11612,6 +11709,9 @@ var DurableLedger = class DurableLedger {
11612
11709
  //#endregion
11613
11710
  //#region src/recorder/addon/segment-hour-ledger.ts
11614
11711
  var HOUR_MS$1 = 36e5;
11712
+ var macrotask$1 = () => new Promise((resolve) => {
11713
+ setImmediate(resolve);
11714
+ });
11615
11715
  /**
11616
11716
  * @durable class=mirror owner=recorder
11617
11717
  * write="write-behind on every finalized segment (hour-row upsert); eviction drops paths; the archive walk reconciles disk into the row set"
@@ -11759,6 +11859,7 @@ function hourAggregate(paths) {
11759
11859
  function segmentHourRow(base) {
11760
11860
  return {
11761
11861
  ...base,
11862
+ pathsResident: true,
11762
11863
  ...hourAggregate(base.paths)
11763
11864
  };
11764
11865
  }
@@ -11814,6 +11915,44 @@ var OLDEST_PROBE_COLUMNS = [
11814
11915
  var REPAIR_PROBE_COLUMNS = ["segments"];
11815
11916
  /** Rows repaired per boot. The live archive is ~19 k hour rows. */
11816
11917
  var REPAIR_MAX_ROWS = 5e4;
11918
+ /**
11919
+ * The boot projection (D287): everything the recorder's always-resident tier
11920
+ * needs, and deliberately NOT `paths`.
11921
+ *
11922
+ * `paths` is ~55 B per segment and the archive is the only thing that grows:
11923
+ * ~16 MB of JSON today, a projected ~460 MB at 28 TB of today's bitrate mix
11924
+ * and ~5.9 GB at a low-bitrate mix — one tRPC response, parsed on the main
11925
+ * thread, before the index exists. The summary half is O(writers × days) and
11926
+ * stays ~10–15 MB at any archive size.
11927
+ */
11928
+ var SEGMENT_HOUR_SUMMARY_COLUMNS = [
11929
+ "deviceId",
11930
+ "profile",
11931
+ "locationId",
11932
+ "hourStartMs",
11933
+ "bytes",
11934
+ "segments",
11935
+ "minStartMs",
11936
+ "maxStartMs"
11937
+ ];
11938
+ /** Summary rows folded into the mirror between yields. */
11939
+ var LOAD_CHUNK = 5e3;
11940
+ /** Hour rows materialised per point-read page. One page covers a day of one
11941
+ * camera's three profiles with room to spare. */
11942
+ var HOUR_DETAIL_PAGE = 64;
11943
+ /**
11944
+ * The live tail materialised at boot: the current hour and the one before it.
11945
+ *
11946
+ * `recordSegment` must gate from RAM (D49), and the hour it appends to at boot
11947
+ * is exactly the hour the previous process was writing. Two hours × the active
11948
+ * writers is ~60 rows — one point-read page — and it is what makes the write
11949
+ * path's materialise a case that essentially never happens.
11950
+ */
11951
+ var LIVE_TAIL_HOURS = 2;
11952
+ /** Rows the one-shot aggregate repair may materialise in a single boot. The
11953
+ * backfill is bounded so it cannot re-become the whole-archive read D287
11954
+ * removed; a partial pass finishes on the next boot. */
11955
+ var REPAIR_MAX_MATERIALIZE = 2e3;
11817
11956
  /** The four scalars an accounting answer is made of, asked in one statement. */
11818
11957
  var ACCOUNTING_FIELDS = [
11819
11958
  {
@@ -11906,6 +12045,44 @@ function recordToRow(key, data) {
11906
12045
  paths: raw
11907
12046
  });
11908
12047
  }
12048
+ /** The paths of a summary row: one shared empty array, never a per-row
12049
+ * allocation, and never mistakable for "this hour holds nothing". */
12050
+ var NO_PATHS = Object.freeze([]);
12051
+ function finiteOr0(raw) {
12052
+ const n = Number(raw);
12053
+ return Number.isFinite(n) ? n : 0;
12054
+ }
12055
+ /**
12056
+ * One row of the boot projection ({@link SEGMENT_HOUR_SUMMARY_COLUMNS}).
12057
+ *
12058
+ * The identity half is validated exactly as {@link recordToRow} validates it —
12059
+ * a row that cannot say which camera, profile, location and hour it is about
12060
+ * is skipped, because a summary keyed on garbage would refuse the write path
12061
+ * for an hour that is perfectly fine. The aggregate half is taken as the
12062
+ * database wrote it: a row that predates the aggregate columns reports zeros,
12063
+ * which UNDER-reports its disk (prunes less, never more) until
12064
+ * {@link SegmentHourLedger.repairAggregates} rewrites it.
12065
+ */
12066
+ function summaryToRow(key, data) {
12067
+ const deviceId = Number(data["deviceId"]);
12068
+ const profile = data["profile"];
12069
+ const locationId = data["locationId"];
12070
+ const hour = Number(data["hourStartMs"]);
12071
+ if (!Number.isFinite(deviceId) || deviceId <= 0 || typeof profile !== "string" || profile.length === 0 || typeof locationId !== "string" || locationId.length === 0 || !Number.isFinite(hour)) return null;
12072
+ return {
12073
+ key,
12074
+ deviceId,
12075
+ profile,
12076
+ locationId,
12077
+ hourStartMs: hour,
12078
+ paths: NO_PATHS,
12079
+ pathsResident: false,
12080
+ bytes: finiteOr0(data["bytes"]),
12081
+ segments: finiteOr0(data["segments"]),
12082
+ minStartMs: finiteOr0(data["minStartMs"]),
12083
+ maxStartMs: finiteOr0(data["maxStartMs"])
12084
+ };
12085
+ }
11909
12086
  var SPEC = {
11910
12087
  collection: RECORDING_SEGMENT_HOURS_COLLECTION,
11911
12088
  columns: RECORDING_SEGMENT_HOURS_COLUMNS,
@@ -11926,10 +12103,18 @@ var SegmentHourLedger = class {
11926
12103
  * accounting number is not a gate. */
11927
12104
  store;
11928
12105
  isLocationUsable;
12106
+ now;
12107
+ loadChunk;
12108
+ yieldBetween;
12109
+ rowCap;
11929
12110
  constructor(deps) {
11930
12111
  this.logger = deps.logger;
11931
12112
  this.store = deps.store;
11932
12113
  this.isLocationUsable = deps.isLocationUsable ?? (() => true);
12114
+ this.now = deps.now ?? (() => Date.now());
12115
+ this.loadChunk = deps.loadPacing?.chunkSize ?? LOAD_CHUNK;
12116
+ this.yieldBetween = deps.loadPacing?.yieldBetween ?? macrotask$1;
12117
+ this.rowCap = deps.loadPacing?.rowCap ?? 25e4;
11933
12118
  this.ledger = new DurableLedger({
11934
12119
  spec: SPEC,
11935
12120
  store: deps.store,
@@ -11942,26 +12127,270 @@ var SegmentHourLedger = class {
11942
12127
  declare() {
11943
12128
  return this.ledger.declare();
11944
12129
  }
12130
+ /**
12131
+ * Boot load — **T1 only** (D287).
12132
+ *
12133
+ * One projected query over {@link SEGMENT_HOUR_SUMMARY_COLUMNS}, folded into
12134
+ * the mirror in chunks with a yield between them, then one point-read page
12135
+ * that materialises the live tail so the write path can gate from RAM.
12136
+ *
12137
+ * It replaces `DurableLedger.load`, which fetches whole rows and therefore
12138
+ * the whole archive's path strings, and it keeps that primitive's two rules:
12139
+ * a failed read RETURNS WHAT IS ALREADY MIRRORED rather than clearing it,
12140
+ * and a malformed row is skipped rather than repaired.
12141
+ *
12142
+ * It deliberately does NOT replay the archive into {@link RecordingIndex}.
12143
+ * `hydrated` now means "the rows are resident", so a ledger-known hour is
12144
+ * merely *hydratable from T3*: the first read of it pays one point read
12145
+ * ({@link detailForWindow}), and an hour whose tail the ledger is missing is
12146
+ * no longer permanently invisible to playback.
12147
+ */
11945
12148
  async load() {
11946
- const rows = await this.ledger.load();
12149
+ const startedMs = this.now();
12150
+ let records;
12151
+ try {
12152
+ records = await this.store.query.query({
12153
+ collection: RECORDING_SEGMENT_HOURS_COLLECTION,
12154
+ columns: SEGMENT_HOUR_SUMMARY_COLUMNS,
12155
+ filter: { limit: this.rowCap }
12156
+ });
12157
+ } catch (err) {
12158
+ this.logger.warn("recorder: segment-hour ledger load failed — keeping the hours already held", { meta: {
12159
+ collection: RECORDING_SEGMENT_HOURS_COLLECTION,
12160
+ held: this.ledger.size,
12161
+ error: String(err)
12162
+ } });
12163
+ return this.ledger.snapshot();
12164
+ }
12165
+ const queriedMs = this.now();
12166
+ let skipped = 0;
12167
+ for (let i = 0; i < records.length; i += this.loadChunk) {
12168
+ const end = Math.min(i + this.loadChunk, records.length);
12169
+ for (let j = i; j < end; j += 1) {
12170
+ const record = records[j];
12171
+ const row = summaryToRow(record.id, record.data);
12172
+ if (row === null) {
12173
+ skipped += 1;
12174
+ continue;
12175
+ }
12176
+ this.ledger.stage(row);
12177
+ }
12178
+ if (end < records.length) await this.yieldBetween();
12179
+ }
12180
+ if (skipped > 0) this.logger.warn("recorder: segment-hour summaries skipped as malformed — they gate NOTHING", { meta: {
12181
+ collection: RECORDING_SEGMENT_HOURS_COLLECTION,
12182
+ skipped
12183
+ } });
12184
+ if (records.length >= this.rowCap) this.logger.warn("recorder: segment-hour ledger load hit its row cap — hours past the cap are UNKNOWN to this process and will be walked from disk", { meta: {
12185
+ limit: this.rowCap,
12186
+ loaded: records.length
12187
+ } });
12188
+ const tail = await this.materializeLiveTail();
11947
12189
  this.logger.info("recorder: segment-hour ledger loaded", { meta: {
11948
- hours: rows.length,
12190
+ hours: this.ledger.size,
12191
+ pathsLoaded: false,
12192
+ liveTailHours: tail,
12193
+ skipped,
12194
+ queryMs: queriedMs - startedMs,
12195
+ ms: this.now() - startedMs,
11949
12196
  collection: RECORDING_SEGMENT_HOURS_COLLECTION
11950
12197
  } });
11951
- return rows;
12198
+ return this.ledger.snapshot();
11952
12199
  }
12200
+ /** Every hour the ledger knows — summaries included. A row whose
12201
+ * `pathsResident` is false carries real aggregates and empty `paths`. */
11953
12202
  snapshot() {
11954
12203
  return this.ledger.snapshot();
11955
12204
  }
12205
+ /** Does the ledger hold a row for this hour at all? Pure RAM — the gate the
12206
+ * storage-walk repair consults before it upserts a rebuilt hour. */
12207
+ knowsHour(deviceId, profile, locationId, hour) {
12208
+ return this.ledger.has(segmentHourKey(deviceId, profile, locationId, hour));
12209
+ }
11956
12210
  /**
11957
- * Seed {@link RecordingIndex} from the mirrored hour rows.
12211
+ * The hours of `[fromMs, toMs)` the ledger knows, with their paths — the
12212
+ * cold-hour detail read that replaces the boot replay (D287).
12213
+ *
12214
+ * One bounded point read against the settings store, never the media array:
12215
+ * a `readdir` of one hour directory was measured at ~650 ms under load on
12216
+ * the live share, and the array is the resource the scrub feeder is
12217
+ * competing for. Hours the ledger does NOT know are absent from the result,
12218
+ * and the caller walks those from disk exactly as it always did.
11958
12219
  *
11959
- * Hours present in the ledger become `hydrated` so a seek in those windows
11960
- * does not pay for a disk walk. Hours the ledger never held stay `unknown`
11961
- * — that is the fail-toward-walk direction.
12220
+ * **A read that fails returns what it already had** (D49). The caller sees
12221
+ * fewer hours, the index stays `unknown` for the rest, and the window falls
12222
+ * through to the walk nothing is destroyed and nothing renders as an
12223
+ * empty hour that was merely unread.
11962
12224
  */
11963
- hydrateIndex(index) {
11964
- for (const hour of this.ledger.snapshot()) index.hydrateHour(hour.deviceId, hour.locationId, hour.hourStartMs, hour.paths);
12225
+ async detailForWindow(deviceId, fromMs, toMs) {
12226
+ const first = hourStartMs(fromMs);
12227
+ const out = [];
12228
+ const wanted = [];
12229
+ for (const row of this.ledger.snapshot()) {
12230
+ if (row.deviceId !== deviceId) continue;
12231
+ if (row.hourStartMs < first || row.hourStartMs >= toMs) continue;
12232
+ if (row.pathsResident) {
12233
+ out.push({
12234
+ locationId: row.locationId,
12235
+ hourStartMs: row.hourStartMs,
12236
+ paths: row.paths
12237
+ });
12238
+ continue;
12239
+ }
12240
+ wanted.push(row.key);
12241
+ }
12242
+ for (const row of await this.materialize(wanted, deviceId)) out.push({
12243
+ locationId: row.locationId,
12244
+ hourStartMs: row.hourStartMs,
12245
+ paths: row.paths
12246
+ });
12247
+ return out;
12248
+ }
12249
+ /**
12250
+ * Adopt an hour the storage walk rebuilt and the ledger never held.
12251
+ *
12252
+ * The reader repairs the durable index it just reconstructed, so the next
12253
+ * cold read of this hour is a point read instead of another `readdir`
12254
+ * (`docs/design/2026-08-29-scrypted-nvr-recording-model.md` §4.2). Two
12255
+ * constraints, both enforced by the caller and re-stated here because
12256
+ * getting either wrong turns a READ into durable damage: the hour must be
12257
+ * CLOSED (a live hour's directory races the writer, so a walk of it is a
12258
+ * lower bound, not the truth), and the ledger must hold no row for it (an
12259
+ * existing row is the authority; replacing it with a walk's view is the
12260
+ * D148 prune this ledger refuses to do on its own evidence).
12261
+ */
12262
+ async adoptRebuiltHour(deviceId, profile, locationId, hour, paths) {
12263
+ const key = segmentHourKey(deviceId, profile, locationId, hour);
12264
+ if (paths.length === 0 || this.ledger.has(key)) return;
12265
+ const row = segmentHourRow({
12266
+ key,
12267
+ deviceId,
12268
+ profile,
12269
+ locationId,
12270
+ hourStartMs: hour,
12271
+ paths: uniquePaths(paths)
12272
+ });
12273
+ await this.ledger.put(row);
12274
+ this.logger.info("recorder: adopted a closed hour the disk walk rebuilt and the ledger never held", {
12275
+ tags: { deviceId },
12276
+ meta: {
12277
+ profile,
12278
+ locationId,
12279
+ hourStartMs: hour,
12280
+ segments: row.segments,
12281
+ bytes: row.bytes
12282
+ }
12283
+ });
12284
+ }
12285
+ /**
12286
+ * Fetch whole rows for `keys` and promote them in the mirror.
12287
+ *
12288
+ * Paged and yielding: an export window can name thousands of hours, and one
12289
+ * `whereIn` over all of them would rebuild the very whole-archive response
12290
+ * D287 removed. A page that FAILS ends the materialise and returns what
12291
+ * landed — partial detail is real detail, and the caller's fallback (a disk
12292
+ * walk, or refusing a write) is strictly safer than a guess.
12293
+ *
12294
+ * A row the store returns but this cannot parse is EVICTED from the mirror
12295
+ * rather than left as a summary that can never become resident: it re-seeds
12296
+ * cold on the next write, which is `DurableLedger`'s rule 4 and the only
12297
+ * escape from an hour permanently frozen against its own writer.
12298
+ */
12299
+ async materialize(keys, deviceId) {
12300
+ const out = [];
12301
+ if (keys.length === 0) return out;
12302
+ const tags = deviceId === void 0 ? {} : { tags: { deviceId } };
12303
+ for (let i = 0; i < keys.length; i += HOUR_DETAIL_PAGE) {
12304
+ const page = keys.slice(i, i + HOUR_DETAIL_PAGE);
12305
+ let records;
12306
+ try {
12307
+ records = await this.store.query.query({
12308
+ collection: RECORDING_SEGMENT_HOURS_COLLECTION,
12309
+ filter: {
12310
+ whereIn: { key: page },
12311
+ limit: page.length
12312
+ }
12313
+ });
12314
+ } catch (err) {
12315
+ this.logger.warn("recorder: hour-detail point read failed — these hours stay summaries, and the caller walks the disk or declines the write", {
12316
+ ...tags,
12317
+ meta: {
12318
+ collection: RECORDING_SEGMENT_HOURS_COLLECTION,
12319
+ asked: page.length,
12320
+ materialized: out.length,
12321
+ error: String(err)
12322
+ }
12323
+ });
12324
+ return out;
12325
+ }
12326
+ for (const record of records) {
12327
+ const row = recordToRow(record.id, record.data);
12328
+ if (row === null) {
12329
+ this.ledger.evict(record.id);
12330
+ this.logger.warn("recorder: hour row is unparseable — dropping the summary so the hour re-seeds cold instead of freezing its writer", {
12331
+ ...tags,
12332
+ meta: { key: record.id }
12333
+ });
12334
+ continue;
12335
+ }
12336
+ this.ledger.stage(row);
12337
+ out.push(row);
12338
+ }
12339
+ if (i + HOUR_DETAIL_PAGE < keys.length) await this.yieldBetween();
12340
+ }
12341
+ return out;
12342
+ }
12343
+ /**
12344
+ * Materialise every hour these devices hold, and report how many stayed
12345
+ * summaries.
12346
+ *
12347
+ * The reconcile is the one path that DELETES durable rows, so it may not run
12348
+ * against a mirror that only half knows what it holds. This is a whole-device
12349
+ * read and it is deliberately confined here: `reconcileFromIndex` follows an
12350
+ * operator-armed rescan of that same device — a recursive `readdir` over
12351
+ * >1M files — so a paged point read alongside it is noise, and it is the one
12352
+ * caller whose correctness depends on completeness.
12353
+ */
12354
+ async materializeDevices(deviceIds) {
12355
+ const keys = [];
12356
+ for (const row of this.ledger.snapshot()) if (!row.pathsResident && deviceIds.has(row.deviceId)) keys.push(row.key);
12357
+ if (keys.length === 0) return;
12358
+ await this.materialize(keys);
12359
+ const stillSummary = /* @__PURE__ */ new Map();
12360
+ for (const row of this.ledger.snapshot()) {
12361
+ if (row.pathsResident || !deviceIds.has(row.deviceId)) continue;
12362
+ stillSummary.set(row.deviceId, (stillSummary.get(row.deviceId) ?? 0) + 1);
12363
+ }
12364
+ for (const [deviceId, unreadable] of stillSummary) this.logger.warn("recorder: hours without readable detail take NO part in this reconcile — they are neither pruned nor unioned", {
12365
+ tags: { deviceId },
12366
+ meta: {
12367
+ asked: keys.length,
12368
+ unreadable
12369
+ }
12370
+ });
12371
+ }
12372
+ /** The hour a write path may touch: current + previous. Materialised at boot
12373
+ * so {@link recordSegment}'s dedup gate answers from RAM (D49). */
12374
+ async materializeLiveTail() {
12375
+ const oldest = hourStartMs(this.now()) - (LIVE_TAIL_HOURS - 1) * HOUR_MS$1;
12376
+ const keys = [];
12377
+ for (const row of this.ledger.snapshot()) if (row.hourStartMs >= oldest && !row.pathsResident) keys.push(row.key);
12378
+ return (await this.materialize(keys)).length;
12379
+ }
12380
+ /**
12381
+ * Promote one HELD row to paths-resident, or answer `null`.
12382
+ *
12383
+ * `null` means "this hour is known and its detail could not be had" — the
12384
+ * only honest answer to a failed point read, and every caller turns it into
12385
+ * "do nothing". It is deliberately distinct from `this.ledger.get(key) ===
12386
+ * undefined`, which means "no such hour" and is what licenses a fresh row.
12387
+ */
12388
+ async resident(key, deviceId) {
12389
+ const held = this.ledger.get(key);
12390
+ if (held !== void 0 && held.pathsResident) return held;
12391
+ await this.materialize([key], deviceId);
12392
+ const after = this.ledger.get(key);
12393
+ return after !== void 0 && after.pathsResident ? after : null;
11965
12394
  }
11966
12395
  /**
11967
12396
  * Bytes / count / oldest / newest across a SET of storage locations, as ONE
@@ -12062,6 +12491,7 @@ var SegmentHourLedger = class {
12062
12491
  for (const record of full) {
12063
12492
  const hour = recordToRow(record.id, record.data);
12064
12493
  if (hour === null) continue;
12494
+ this.ledger.stage(hour);
12065
12495
  for (const path of hour.paths) {
12066
12496
  const parsed = parseSegmentPath(path);
12067
12497
  if (parsed === null) continue;
@@ -12091,6 +12521,12 @@ var SegmentHourLedger = class {
12091
12521
  * empties). So `segments = 0` IS the backfill predicate, and after one pass
12092
12522
  * it selects nothing. A partial repair finishes on the next boot; until then
12093
12523
  * the affected disks UNDER-report, which prunes less and never more.
12524
+ *
12525
+ * Since D287 the boot load carries no `paths`, and `paths` is the authority
12526
+ * this repair derives from — so the stale rows are MATERIALISED first, at
12527
+ * most {@link REPAIR_MAX_MATERIALIZE} per boot. That bound is the point: an
12528
+ * unbounded materialise here would be the whole-archive read this stage
12529
+ * removed, wearing a different name.
12094
12530
  */
12095
12531
  async repairAggregates() {
12096
12532
  let repaired = 0;
@@ -12103,9 +12539,15 @@ var SegmentHourLedger = class {
12103
12539
  limit: REPAIR_MAX_ROWS
12104
12540
  }
12105
12541
  });
12542
+ const pending = stale.map((record) => record.id).filter((key) => this.ledger.get(key)?.pathsResident === false);
12543
+ if (pending.length > REPAIR_MAX_MATERIALIZE) this.logger.info("recorder: segment-hour aggregate backfill is bounded this boot — the rest is repaired on the next one", { meta: {
12544
+ pending: pending.length,
12545
+ perBoot: REPAIR_MAX_MATERIALIZE
12546
+ } });
12547
+ await this.materialize(pending.slice(0, REPAIR_MAX_MATERIALIZE));
12106
12548
  for (const record of stale) {
12107
12549
  const held = this.ledger.get(record.id);
12108
- if (held === void 0 || held.segments === 0) continue;
12550
+ if (held === void 0 || !held.pathsResident || held.segments === 0) continue;
12109
12551
  await this.ledger.put(held);
12110
12552
  repaired += 1;
12111
12553
  }
@@ -12133,8 +12575,7 @@ var SegmentHourLedger = class {
12133
12575
  */
12134
12576
  async recordSegment(row) {
12135
12577
  const { key, hourStartMs: hour } = hourOf(row);
12136
- const held = this.ledger.get(key);
12137
- if (held === void 0) {
12578
+ if (!this.ledger.has(key)) {
12138
12579
  await this.ledger.put(segmentHourRow({
12139
12580
  key,
12140
12581
  deviceId: row.deviceId,
@@ -12145,6 +12586,17 @@ var SegmentHourLedger = class {
12145
12586
  }));
12146
12587
  return;
12147
12588
  }
12589
+ const held = await this.resident(key, row.deviceId);
12590
+ if (held === null) {
12591
+ this.logger.warn("recorder: hour detail unavailable — this finalized segment is NOT in the durable hour row yet", {
12592
+ tags: { deviceId: row.deviceId },
12593
+ meta: {
12594
+ key,
12595
+ path: row.path
12596
+ }
12597
+ });
12598
+ return;
12599
+ }
12148
12600
  if (held.paths.includes(row.path)) return;
12149
12601
  await this.ledger.put(appendSegmentPath(held, row.path));
12150
12602
  }
@@ -12156,16 +12608,29 @@ var SegmentHourLedger = class {
12156
12608
  const doomed = /* @__PURE__ */ new Map();
12157
12609
  for (const row of rows) {
12158
12610
  const { key } = hourOf(row);
12159
- let set = doomed.get(key);
12160
- if (!set) {
12161
- set = /* @__PURE__ */ new Set();
12162
- doomed.set(key, set);
12611
+ const entry = doomed.get(key);
12612
+ if (entry === void 0) {
12613
+ doomed.set(key, {
12614
+ deviceId: row.deviceId,
12615
+ paths: new Set([row.path])
12616
+ });
12617
+ continue;
12163
12618
  }
12164
- set.add(row.path);
12619
+ entry.paths.add(row.path);
12165
12620
  }
12166
- for (const [key, paths] of doomed) {
12167
- const held = this.ledger.get(key);
12168
- if (held === void 0) continue;
12621
+ for (const [key, { deviceId, paths }] of doomed) {
12622
+ if (!this.ledger.has(key)) continue;
12623
+ const held = await this.resident(key, deviceId);
12624
+ if (held === null) {
12625
+ this.logger.warn("recorder: hour detail unavailable — these evicted paths stay in the durable hour row until a walk or the next eviction confirms them", {
12626
+ tags: { deviceId },
12627
+ meta: {
12628
+ key,
12629
+ paths: paths.size
12630
+ }
12631
+ });
12632
+ continue;
12633
+ }
12169
12634
  const next = held.paths.filter((p) => !paths.has(p));
12170
12635
  if (next.length === 0) {
12171
12636
  await this.ledger.forget(key);
@@ -12194,10 +12659,17 @@ var SegmentHourLedger = class {
12194
12659
  * And a walk this ledger does not TRUST prunes nothing at all — see
12195
12660
  * {@link refusedPrunes}. What such a walk FOUND is still real, so its paths
12196
12661
  * are unioned in; what it did not find decides nothing (D49).
12662
+ *
12663
+ * Since D287 the walked devices' hours are MATERIALISED first: every
12664
+ * comparison below reads `row.paths`, and a summary's empty `paths` would
12665
+ * read as "the ledger holds nothing here" — which is the union collapsing to
12666
+ * the walk's own view, i.e. the prune the refusal machinery exists to
12667
+ * prevent. An hour whose detail could not be read is left additive-only.
12197
12668
  */
12198
12669
  async reconcileFromIndex(index, deviceIds, nowMs) {
12199
12670
  const walked = new Set(deviceIds);
12200
12671
  const currentHour = hourStartMs(nowMs);
12672
+ await this.materializeDevices(walked);
12201
12673
  const fromIndex = /* @__PURE__ */ new Map();
12202
12674
  for (const deviceId of deviceIds) for (const seg of index.segments(deviceId)) {
12203
12675
  const { key, hourStartMs: hour } = hourOf(seg);
@@ -12215,6 +12687,7 @@ var SegmentHourLedger = class {
12215
12687
  const refused = this.refusedPrunes(walked, fromIndex);
12216
12688
  for (const row of this.ledger.snapshot()) {
12217
12689
  if (!walked.has(row.deviceId)) continue;
12690
+ if (!row.pathsResident) continue;
12218
12691
  const disk = fromIndex.get(row.key);
12219
12692
  const additiveOnly = row.hourStartMs === currentHour || refused.devices.has(row.deviceId) || refused.locations.has(locationKey(row.deviceId, row.locationId));
12220
12693
  if (disk === void 0) {
@@ -13302,7 +13775,7 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
13302
13775
  },
13303
13776
  calendar: this.calendar,
13304
13777
  mfraFor: (deviceId, profile, startMs) => this.mfraTables.get(deviceId, profile, startMs),
13305
- hydrateWindow: (deviceId, fromMs, toMs) => hydrateWindowFromStorage(this.index, deviceId, fromMs, toMs, this.resolvedLocations, this.ctx.logger),
13778
+ hydrateWindow: (deviceId, fromMs, toMs) => hydrateWindowFromStorage(this.index, deviceId, fromMs, toMs, this.resolvedLocations, this.ctx.logger, this.segmentHours ?? void 0),
13306
13779
  onConfigChanged: async (deviceId) => {
13307
13780
  await this.refreshSensorTriggerBindings();
13308
13781
  await (this.controller?.onConfigChanged(deviceId) ?? Promise.resolve());
@@ -13401,7 +13874,7 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
13401
13874
  state: exportsState,
13402
13875
  engine: this.exportEngine,
13403
13876
  index: { segmentsInWindow: async (deviceId, profile, fromMs, toMs) => {
13404
- if (this.index.hydrationOf(deviceId, fromMs, toMs) !== "hydrated") await hydrateWindowFromStorage(this.index, deviceId, fromMs, toMs, this.resolvedLocations, this.ctx.logger);
13877
+ if (this.index.hydrationOf(deviceId, fromMs, toMs) !== "hydrated") await hydrateWindowFromStorage(this.index, deviceId, fromMs, toMs, this.resolvedLocations, this.ctx.logger, this.segmentHours ?? void 0);
13405
13878
  return this.index.segments(deviceId, profile);
13406
13879
  } },
13407
13880
  now: () => Date.now(),
@@ -13628,7 +14101,6 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
13628
14101
  }
13629
14102
  try {
13630
14103
  await this.segmentHours?.load();
13631
- this.segmentHours?.hydrateIndex(this.index);
13632
14104
  this.segmentHours?.repairAggregates();
13633
14105
  } catch (err) {
13634
14106
  this.ctx.logger.warn("recorder: segment-hour ledger load failed — hours stay unknown until a read walks them", { meta: { error: require_dist.errMsg(err) } });
@@ -13764,6 +14236,7 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
13764
14236
  }
13765
14237
  if (this.exportSweepTimer === null) {
13766
14238
  const sweep = () => {
14239
+ this.logIndexCensus();
13767
14240
  sweepExpiredExports(Date.now(), this.exportJanitorDeps()).catch((err) => {
13768
14241
  this.ctx.logger.warn("recorder: export expiry sweep failed", { meta: { error: require_dist.errMsg(err) } });
13769
14242
  });
@@ -13774,6 +14247,41 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
13774
14247
  }
13775
14248
  }
13776
14249
  /**
14250
+ * What the RAM index is actually holding, on the 5-minute cadence the
14251
+ * `[mem]` heartbeat already samples on.
14252
+ *
14253
+ * `RecordingIndex` has exposed `sortedViewStats` and `hydrateReuseStats`
14254
+ * since the churn work and NOTHING has ever read them — so the two numbers
14255
+ * that would have told us where the recorder's heap goes have never appeared
14256
+ * in a log line. Production on 2026-08-29 reads ~490 MB in
14257
+ * `large_object_space`, stable across four samples five minutes apart
14258
+ * (retained, not churn) against 110 MB on hub-main; the sorted views are the
14259
+ * shape that lands there, and `rowSlots × 8 B` is the arithmetic that either
14260
+ * accounts for it or rules it out.
14261
+ *
14262
+ * `tags: { deviceId }` names the camera with the LARGEST view, because
14263
+ * "which camera" is the only form the follow-up question ever takes. Absent
14264
+ * when nothing is materialised — a device id of 0 is not a camera.
14265
+ */
14266
+ logIndexCensus() {
14267
+ const census = this.index.sortedViewCensus();
14268
+ const views = this.index.sortedViewStats();
14269
+ const reuse = this.index.hydrateReuseStats();
14270
+ this.ctx.logger.info("recorder: index census", {
14271
+ ...census.largestDeviceId > 0 ? { tags: { deviceId: census.largestDeviceId } } : {},
14272
+ meta: {
14273
+ sortedViews: census.views,
14274
+ rowSlots: census.rowSlots,
14275
+ largestViewRows: census.largestRows,
14276
+ fullRebuilds: views.fullRebuilds,
14277
+ incrementalInserts: views.incrementalInserts,
14278
+ rowsReused: reuse.rowsReused,
14279
+ rowsAllocated: reuse.rowsAllocated,
14280
+ ledgerHours: this.segmentHours?.snapshot().length ?? 0
14281
+ }
14282
+ });
14283
+ }
14284
+ /**
13777
14285
  * One-time boot cleanup of the retired sprite-sheet scrub-thumbnail dirs
13778
14286
  * (`<locationRoot>/.thumbs`). Scrub previews now use the WebCodecs keyframe
13779
14287
  * packs + the on-demand still route, so the sheets are dead weight on the
@@ -14157,7 +14665,7 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
14157
14665
  const started = now;
14158
14666
  const liveHour = Math.floor(now / HOUR_MS) * HOUR_MS;
14159
14667
  for (const deviceId of deviceIds) try {
14160
- await hydrateWindowFromStorage(this.index, deviceId, liveHour, liveHour + HOUR_MS, this.resolvedLocations, this.ctx.logger);
14668
+ await hydrateWindowFromStorage(this.index, deviceId, liveHour, liveHour + HOUR_MS, this.resolvedLocations, this.ctx.logger, this.segmentHours ?? void 0);
14161
14669
  } catch {}
14162
14670
  this.ctx.logger.info("recorder: today warmed", { meta: {
14163
14671
  devices: deviceIds.length,