@indigoai-us/hq-cloud 6.15.100 → 6.15.102

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 (52) hide show
  1. package/dist/bin/sync-runner-auth-wait.d.ts +21 -1
  2. package/dist/bin/sync-runner-auth-wait.d.ts.map +1 -1
  3. package/dist/bin/sync-runner-auth-wait.js +30 -1
  4. package/dist/bin/sync-runner-auth-wait.js.map +1 -1
  5. package/dist/bin/sync-runner-auth-wait.test.js +190 -1
  6. package/dist/bin/sync-runner-auth-wait.test.js.map +1 -1
  7. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  8. package/dist/bin/sync-runner-company.js +1 -0
  9. package/dist/bin/sync-runner-company.js.map +1 -1
  10. package/dist/bin/sync-runner-company.test.js +60 -0
  11. package/dist/bin/sync-runner-company.test.js.map +1 -1
  12. package/dist/bin/sync-runner-events.test.js +60 -0
  13. package/dist/bin/sync-runner-events.test.js.map +1 -1
  14. package/dist/bin/sync-runner-heap-telemetry.d.ts +344 -0
  15. package/dist/bin/sync-runner-heap-telemetry.d.ts.map +1 -0
  16. package/dist/bin/sync-runner-heap-telemetry.js +550 -0
  17. package/dist/bin/sync-runner-heap-telemetry.js.map +1 -0
  18. package/dist/bin/sync-runner-heap-telemetry.test.d.ts +2 -0
  19. package/dist/bin/sync-runner-heap-telemetry.test.d.ts.map +1 -0
  20. package/dist/bin/sync-runner-heap-telemetry.test.js +697 -0
  21. package/dist/bin/sync-runner-heap-telemetry.test.js.map +1 -0
  22. package/dist/bin/sync-runner-watch-loop.d.ts +29 -0
  23. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  24. package/dist/bin/sync-runner-watch-loop.js +160 -0
  25. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  26. package/dist/bin/sync-runner-watch-loop.test.d.ts +2 -0
  27. package/dist/bin/sync-runner-watch-loop.test.d.ts.map +1 -0
  28. package/dist/bin/sync-runner-watch-loop.test.js +62 -0
  29. package/dist/bin/sync-runner-watch-loop.test.js.map +1 -0
  30. package/dist/bin/sync-runner.d.ts +84 -0
  31. package/dist/bin/sync-runner.d.ts.map +1 -1
  32. package/dist/bin/sync-runner.js +17 -0
  33. package/dist/bin/sync-runner.js.map +1 -1
  34. package/dist/cli/share.d.ts.map +1 -1
  35. package/dist/cli/share.js +71 -18
  36. package/dist/cli/share.js.map +1 -1
  37. package/dist/cli/share.test.js +95 -1
  38. package/dist/cli/share.test.js.map +1 -1
  39. package/dist/cli/sync.d.ts +7 -1
  40. package/dist/cli/sync.d.ts.map +1 -1
  41. package/dist/cli/sync.js.map +1 -1
  42. package/dist/sync/event-sync.d.ts +6 -0
  43. package/dist/sync/event-sync.d.ts.map +1 -1
  44. package/dist/sync/event-sync.js +2 -0
  45. package/dist/sync/event-sync.js.map +1 -1
  46. package/dist/watcher.d.ts +28 -2
  47. package/dist/watcher.d.ts.map +1 -1
  48. package/dist/watcher.js +137 -13
  49. package/dist/watcher.js.map +1 -1
  50. package/dist/watcher.test.js +153 -0
  51. package/dist/watcher.test.js.map +1 -1
  52. package/package.json +1 -1
@@ -0,0 +1,697 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { HeapCensus, RunnerHeapTelemetry, sampleRunnerHeap, heapSampleCloudProperties, heapPressureStderrLine, heapRecycleStderrLine, startRunnerHeapSampling, resolveHeapPressureFraction, resolveHeapSampleIntervalMs, resolveHeapRecycleEnabled, resolveHeapRecycleFraction, resolveHeapRecycleSustainedSamples, resolveHeapRecycleMinUptimeMs, DEFAULT_HEAP_RECYCLE_FRACTION, DEFAULT_HEAP_RECYCLE_SUSTAINED_SAMPLES, DEFAULT_HEAP_RECYCLE_MIN_UPTIME_MS, } from "./sync-runner-heap-telemetry.js";
3
+ import { emitCloudTelemetry } from "../telemetry-events.js";
4
+ function mutableReaders() {
5
+ const state = {
6
+ used: 0,
7
+ total: 0,
8
+ limit: 1000,
9
+ externalV8: 0,
10
+ rss: 0,
11
+ external: 0,
12
+ arrayBuffers: 0,
13
+ now: 0,
14
+ };
15
+ const readers = {
16
+ getHeapStatistics: () => ({
17
+ used_heap_size: state.used,
18
+ total_heap_size: state.total,
19
+ heap_size_limit: state.limit,
20
+ external_memory: state.externalV8,
21
+ }),
22
+ memoryUsage: () => ({
23
+ rss: state.rss,
24
+ heapTotal: state.total,
25
+ heapUsed: state.used,
26
+ external: state.external,
27
+ arrayBuffers: state.arrayBuffers,
28
+ }),
29
+ monotonicNowMs: () => state.now,
30
+ };
31
+ return { state, readers };
32
+ }
33
+ function fakeScheduler() {
34
+ let handler = null;
35
+ let cleared = false;
36
+ let unrefCalls = 0;
37
+ const scheduler = {
38
+ setInterval: (fn) => {
39
+ handler = fn;
40
+ return {
41
+ unref: () => {
42
+ unrefCalls += 1;
43
+ },
44
+ };
45
+ },
46
+ clearInterval: () => {
47
+ cleared = true;
48
+ handler = null;
49
+ },
50
+ };
51
+ return {
52
+ scheduler,
53
+ tick: () => handler?.(),
54
+ isCleared: () => cleared,
55
+ unrefCalls: () => unrefCalls,
56
+ };
57
+ }
58
+ describe("sampleRunnerHeap", () => {
59
+ it("maps injected v8/process readings to a flat numeric record", () => {
60
+ const census = new HeapCensus();
61
+ census.register("mapA", () => 3);
62
+ census.register("setB", () => 5);
63
+ const { state, readers } = mutableReaders();
64
+ Object.assign(state, {
65
+ used: 111,
66
+ total: 222,
67
+ limit: 2048,
68
+ externalV8: 33,
69
+ rss: 444,
70
+ external: 55,
71
+ arrayBuffers: 66,
72
+ now: 5000,
73
+ });
74
+ const sample = sampleRunnerHeap({ readers, census, sessionStartedAtMs: 1000 });
75
+ expect(sample).toMatchObject({
76
+ usedHeapBytes: 111,
77
+ totalHeapBytes: 222,
78
+ heapLimitBytes: 2048,
79
+ externalV8Bytes: 33,
80
+ rssBytes: 444,
81
+ externalBytes: 55,
82
+ arrayBuffersBytes: 66,
83
+ uptimeMs: 4000,
84
+ censusTotal: 8,
85
+ });
86
+ expect(sample.census).toEqual([
87
+ { site: "mapA", count: 3 },
88
+ { site: "setB", count: 5 },
89
+ ]);
90
+ });
91
+ it("emits only numeric properties that survive the real telemetry sanitizer", async () => {
92
+ const census = new HeapCensus();
93
+ // Deliberately register a site whose token contains the blocked substring
94
+ // "content": it must still survive BECAUSE its value is numeric.
95
+ census.register("publishedContentHashGenerations", () => 12345);
96
+ census.register("knownKinds", () => 10);
97
+ const { state, readers } = mutableReaders();
98
+ Object.assign(state, {
99
+ used: 1,
100
+ total: 2,
101
+ limit: 3,
102
+ externalV8: 4,
103
+ rss: 5,
104
+ external: 6,
105
+ arrayBuffers: 7,
106
+ now: 10,
107
+ });
108
+ const props = heapSampleCloudProperties(sampleRunnerHeap({ readers, census, sessionStartedAtMs: 0 }));
109
+ for (const value of Object.values(props)) {
110
+ expect(typeof value).toBe("number");
111
+ }
112
+ const captured = [];
113
+ const client = {
114
+ postTelemetryEvents: async (batch) => {
115
+ for (const event of batch.events)
116
+ captured.push(event);
117
+ return { accepted: batch.events.length };
118
+ },
119
+ };
120
+ await emitCloudTelemetry(client, {
121
+ eventName: "sync_runner_heap_sample",
122
+ source: "sync-runner-heap",
123
+ properties: props,
124
+ });
125
+ const survived = captured[0]?.properties ?? {};
126
+ expect(survived.census_publishedContentHashGenerations).toBe(12345);
127
+ expect(survived.heap_used_bytes).toBe(1);
128
+ // No property was dropped by the sanitizer.
129
+ expect(Object.keys(survived).length).toBe(Object.keys(props).length);
130
+ });
131
+ });
132
+ describe("HeapCensus", () => {
133
+ it("rejects non-fixed census tokens and overwrites duplicates so the registry stays bounded", () => {
134
+ const census = new HeapCensus();
135
+ expect(() => census.register("has space", () => 1)).toThrow();
136
+ expect(() => census.register("../path", () => 1)).toThrow();
137
+ census.register("dupe", () => 1);
138
+ census.register("dupe", () => 2);
139
+ expect(census.siteCount).toBe(1);
140
+ expect(census.snapshot()).toEqual([{ site: "dupe", count: 2 }]);
141
+ });
142
+ it("reports 0 for a faulty reader rather than throwing", () => {
143
+ const census = new HeapCensus();
144
+ census.register("ok", () => 4);
145
+ census.register("boom", () => {
146
+ throw new Error("reader exploded");
147
+ });
148
+ expect(census.snapshot()).toEqual([
149
+ { site: "ok", count: 4 },
150
+ { site: "boom", count: 0 },
151
+ ]);
152
+ });
153
+ });
154
+ describe("RunnerHeapTelemetry", () => {
155
+ it("computes census growth against the session's first sample", () => {
156
+ let a = 1;
157
+ const b = 100;
158
+ const census = new HeapCensus();
159
+ census.register("aMap", () => a);
160
+ census.register("bMap", () => b);
161
+ const { state, readers } = mutableReaders();
162
+ state.limit = 1000;
163
+ state.used = 10;
164
+ const controller = new RunnerHeapTelemetry({
165
+ readers,
166
+ census,
167
+ sessionStartedAtMs: 0,
168
+ pressureThresholdFraction: 0.75,
169
+ });
170
+ controller.sample(); // baseline a=1, b=100
171
+ a = 5000;
172
+ state.used = 800; // 0.8 of limit -> crosses 0.75
173
+ const { pressure } = controller.sample();
174
+ expect(pressure?.topSites[0]).toMatchObject({ site: "aMap", growth: 4999 });
175
+ });
176
+ it("keeps only baseline and latest across many samples (no unbounded history)", () => {
177
+ let n = 0;
178
+ const census = new HeapCensus();
179
+ census.register("n", () => n);
180
+ const { state, readers } = mutableReaders();
181
+ state.limit = 1000;
182
+ state.used = 1;
183
+ const controller = new RunnerHeapTelemetry({
184
+ readers,
185
+ census,
186
+ sessionStartedAtMs: 0,
187
+ pressureThresholdFraction: 0.99,
188
+ });
189
+ for (n = 0; n < 100; n += 1) {
190
+ state.now = n;
191
+ controller.sample();
192
+ }
193
+ expect(controller.baselineSample?.census).toEqual([{ site: "n", count: 0 }]);
194
+ expect(controller.latestSample?.census).toEqual([{ site: "n", count: 99 }]);
195
+ });
196
+ it("emits the pressure record exactly once per rising crossing, calibrated to the injected heap limit", () => {
197
+ const census = new HeapCensus();
198
+ census.register("x", () => 1);
199
+ const { state, readers } = mutableReaders();
200
+ state.limit = 2048 * 1024 * 1024; // desktop-injected 2048 MB ceiling
201
+ const controller = new RunnerHeapTelemetry({
202
+ readers,
203
+ census,
204
+ sessionStartedAtMs: 0,
205
+ pressureThresholdFraction: 0.75,
206
+ });
207
+ state.used = state.limit * 0.5;
208
+ expect(controller.sample().pressure).toBeNull(); // below threshold
209
+ state.used = Math.round(state.limit * 0.76);
210
+ const crossing = controller.sample().pressure; // rising crossing -> one record
211
+ expect(crossing).not.toBeNull();
212
+ expect(crossing?.thresholdFraction).toBe(0.75);
213
+ expect(crossing?.usedFraction).toBeCloseTo(0.76, 2);
214
+ state.used = Math.round(state.limit * 0.8);
215
+ expect(controller.sample().pressure).toBeNull(); // still above -> no repeat
216
+ state.used = Math.round(state.limit * 0.5);
217
+ expect(controller.sample().pressure).toBeNull(); // dropped below -> re-arm
218
+ state.used = Math.round(state.limit * 0.9);
219
+ expect(controller.sample().pressure).not.toBeNull(); // second crossing -> record
220
+ });
221
+ });
222
+ describe("startRunnerHeapSampling", () => {
223
+ it("unrefs the timer, clears it on stop, and never lets a fault reach the caller", () => {
224
+ const census = new HeapCensus();
225
+ // A faulty reader must be swallowed to 0, never thrown out of the sampler.
226
+ census.register("x", () => {
227
+ throw new Error("reader boom");
228
+ });
229
+ const { state, readers } = mutableReaders();
230
+ state.limit = 1000;
231
+ state.used = 900; // 0.9 -> above the 0.75 threshold -> pressure fires
232
+ const fake = fakeScheduler();
233
+ const onSample = vi.fn(() => {
234
+ throw new Error("sample emit boom");
235
+ });
236
+ const onPressure = vi.fn(() => {
237
+ throw new Error("pressure emit boom");
238
+ });
239
+ const handle = startRunnerHeapSampling({
240
+ readers,
241
+ census,
242
+ sessionStartedAtMs: 0,
243
+ pressureThresholdFraction: 0.75,
244
+ intervalMs: 60_000,
245
+ scheduler: fake.scheduler,
246
+ onSample,
247
+ onPressure,
248
+ log: () => { },
249
+ });
250
+ expect(fake.unrefCalls()).toBe(1);
251
+ // A tick with a throwing reader AND throwing emit callbacks must not throw.
252
+ expect(() => fake.tick()).not.toThrow();
253
+ expect(onSample).toHaveBeenCalledTimes(1);
254
+ expect(onPressure).toHaveBeenCalledTimes(1);
255
+ handle.stop();
256
+ expect(fake.isCleared()).toBe(true);
257
+ // Ticks after stop are inert.
258
+ fake.tick();
259
+ expect(onSample).toHaveBeenCalledTimes(1);
260
+ });
261
+ it("drives repeated samples so at least two heap records reach the sink", () => {
262
+ const census = new HeapCensus();
263
+ census.register("x", () => 1);
264
+ const { state, readers } = mutableReaders();
265
+ state.limit = 1000;
266
+ state.used = 1; // never crosses -> only heap samples, no pressure
267
+ const fake = fakeScheduler();
268
+ const samples = [];
269
+ startRunnerHeapSampling({
270
+ readers,
271
+ census,
272
+ sessionStartedAtMs: 0,
273
+ pressureThresholdFraction: 0.75,
274
+ intervalMs: 1,
275
+ scheduler: fake.scheduler,
276
+ onSample: (sample) => samples.push(sample.usedHeapBytes),
277
+ onPressure: () => {
278
+ throw new Error("no crossing expected");
279
+ },
280
+ });
281
+ fake.tick();
282
+ fake.tick();
283
+ expect(samples).toHaveLength(2);
284
+ });
285
+ it("primes the growth baseline at start, so a first crossing already above the threshold still reports real growth", () => {
286
+ let count = 100;
287
+ const census = new HeapCensus();
288
+ census.register("x", () => count);
289
+ const { state, readers } = mutableReaders();
290
+ state.limit = 1000;
291
+ state.used = 900; // already above the 0.75 threshold at the very first tick
292
+ const fake = fakeScheduler();
293
+ const pressures = [];
294
+ startRunnerHeapSampling({
295
+ readers,
296
+ census,
297
+ sessionStartedAtMs: 0,
298
+ pressureThresholdFraction: 0.75,
299
+ intervalMs: 1000,
300
+ scheduler: fake.scheduler,
301
+ onSample: () => { },
302
+ onPressure: (record) => pressures.push(record),
303
+ });
304
+ // Baseline was primed at count=100 before the first interval. Grow, then the
305
+ // first scheduled sample crosses the threshold.
306
+ count = 5000;
307
+ fake.tick();
308
+ expect(pressures).toHaveLength(1);
309
+ // Without priming the baseline would equal the crossing sample and growth
310
+ // would be reported as 0, losing the attribution.
311
+ expect(pressures[0].topSites[0]).toMatchObject({ site: "x", growth: 4900 });
312
+ });
313
+ });
314
+ describe("resolveHeapPressureFraction", () => {
315
+ it("parses a valid fraction and falls back to the default on garbage or out-of-range input", () => {
316
+ expect(resolveHeapPressureFraction("0.6")).toBe(0.6);
317
+ expect(resolveHeapPressureFraction("1")).toBe(1);
318
+ expect(resolveHeapPressureFraction("")).toBe(0.75);
319
+ expect(resolveHeapPressureFraction("2")).toBe(0.75);
320
+ expect(resolveHeapPressureFraction("-1")).toBe(0.75);
321
+ expect(resolveHeapPressureFraction("0.5x")).toBe(0.75); // trailing junk rejected
322
+ expect(resolveHeapPressureFraction(undefined)).toBe(0.75);
323
+ });
324
+ });
325
+ describe("resolveHeapSampleIntervalMs", () => {
326
+ it("parses whole milliseconds and rejects a malformed value like '60s' rather than accepting its prefix", () => {
327
+ expect(resolveHeapSampleIntervalMs("60000")).toBe(60_000);
328
+ expect(resolveHeapSampleIntervalMs("500")).toBe(500);
329
+ // The natural-but-invalid "60s" must NOT become a 60 ms interval.
330
+ expect(resolveHeapSampleIntervalMs("60s")).toBe(60_000);
331
+ expect(resolveHeapSampleIntervalMs("1_000")).toBe(60_000);
332
+ expect(resolveHeapSampleIntervalMs("")).toBe(60_000);
333
+ expect(resolveHeapSampleIntervalMs("0")).toBe(60_000);
334
+ expect(resolveHeapSampleIntervalMs(undefined)).toBe(60_000);
335
+ });
336
+ });
337
+ describe("heapPressureStderrLine", () => {
338
+ it("renders a compact numeric-only pressure line with fixed-token sites", () => {
339
+ const line = heapPressureStderrLine({
340
+ usedHeapBytes: 100,
341
+ heapLimitBytes: 200,
342
+ usedFraction: 0.5,
343
+ thresholdFraction: 0.75,
344
+ rssBytes: 300,
345
+ externalBytes: 40,
346
+ uptimeMs: 1000,
347
+ topSites: [{ site: "knownKinds", count: 5, growth: 3 }],
348
+ });
349
+ expect(line).toContain("used=100");
350
+ expect(line).toContain("limit=200");
351
+ expect(line).toContain("uptime_ms=1000");
352
+ expect(line).toContain("top=knownKinds:3");
353
+ });
354
+ });
355
+ // --- Self-recycling governor -------------------------------------------------
356
+ const MB = 1024 * 1024;
357
+ const ONE_HOUR_MS = 60 * 60_000;
358
+ /**
359
+ * Drive a controller with a FIXED used/limit for `samples` samples at a given
360
+ * uptime, and return the LAST recycle verdict produced (or null). The census
361
+ * reader is a constant unless `census` is supplied.
362
+ */
363
+ function runToRecycle(opts) {
364
+ const census = opts.census ?? new HeapCensus();
365
+ if (!opts.census)
366
+ census.register("knownKinds", () => 1);
367
+ const { state, readers } = mutableReaders();
368
+ state.limit = opts.limitBytes;
369
+ state.used = opts.usedBytes;
370
+ state.now = opts.uptimeMs ?? ONE_HOUR_MS;
371
+ const controller = new RunnerHeapTelemetry({
372
+ readers,
373
+ census,
374
+ sessionStartedAtMs: 0,
375
+ pressureThresholdFraction: opts.overrides?.pressureThresholdFraction ?? 0.75,
376
+ recycleFraction: opts.overrides?.recycleFraction ?? 0.78,
377
+ recycleSustainedSamples: opts.overrides?.recycleSustainedSamples ?? 2,
378
+ recycleMinUptimeMs: opts.overrides?.recycleMinUptimeMs ?? 30 * 60_000,
379
+ recycleEnabled: opts.overrides?.recycleEnabled ?? true,
380
+ });
381
+ let last = null;
382
+ let count = 0;
383
+ for (let i = 0; i < (opts.samples ?? 5); i += 1) {
384
+ const { recycle } = controller.sample();
385
+ if (recycle) {
386
+ last = recycle;
387
+ count += 1;
388
+ }
389
+ }
390
+ return { recycle: last, recycleCount: count };
391
+ }
392
+ describe("RunnerHeapTelemetry — recycle governor", () => {
393
+ it("never recycles on a single spike; only a sustained run of over-fraction samples does", () => {
394
+ const census = new HeapCensus();
395
+ census.register("knownKinds", () => 1);
396
+ const { state, readers } = mutableReaders();
397
+ state.limit = 2048 * MB;
398
+ state.now = ONE_HOUR_MS; // well past the floor
399
+ const controller = new RunnerHeapTelemetry({
400
+ readers,
401
+ census,
402
+ sessionStartedAtMs: 0,
403
+ pressureThresholdFraction: 0.75,
404
+ recycleFraction: 0.78,
405
+ recycleSustainedSamples: 2,
406
+ recycleMinUptimeMs: 30 * 60_000,
407
+ });
408
+ // One spike above the fraction, then a dip below: the streak resets, so no
409
+ // recycle can ever accumulate from a single excursion.
410
+ state.used = Math.round(2048 * MB * 0.9);
411
+ expect(controller.sample().recycle).toBeNull(); // 1 consecutive
412
+ state.used = Math.round(2048 * MB * 0.5);
413
+ expect(controller.sample().recycle).toBeNull(); // dip -> streak reset
414
+ state.used = Math.round(2048 * MB * 0.9);
415
+ expect(controller.sample().recycle).toBeNull(); // 1 consecutive again
416
+ // Now a genuine sustained run of two consecutive over-fraction samples.
417
+ const second = controller.sample().recycle; // 2 consecutive -> recycle
418
+ expect(second).not.toBeNull();
419
+ expect(second?.observedSustainedSamples).toBe(2);
420
+ expect(second?.sustainedSamples).toBe(2);
421
+ });
422
+ it("never recycles before the uptime floor, however high the heap climbs", () => {
423
+ // Heap pinned at 0.99 of the ceiling for many samples, but uptime is below
424
+ // the 30-minute floor: the desktop's fast-fail (60s) and slow-death
425
+ // (30-min) counters can never be advanced by a recycle.
426
+ const belowFloor = runToRecycle({
427
+ limitBytes: 2048 * MB,
428
+ usedBytes: Math.round(2048 * MB * 0.99),
429
+ uptimeMs: 30 * 60_000 - 1, // one ms below the floor
430
+ samples: 12,
431
+ });
432
+ expect(belowFloor.recycle).toBeNull();
433
+ expect(belowFloor.recycleCount).toBe(0);
434
+ // At the floor, the sustained streak (already satisfied) lets it recycle.
435
+ const atFloor = runToRecycle({
436
+ limitBytes: 2048 * MB,
437
+ usedBytes: Math.round(2048 * MB * 0.99),
438
+ uptimeMs: 30 * 60_000,
439
+ samples: 12,
440
+ });
441
+ expect(atFloor.recycle).not.toBeNull();
442
+ });
443
+ it("emits at most one recycle verdict per session", () => {
444
+ const many = runToRecycle({
445
+ limitBytes: 2048 * MB,
446
+ usedBytes: Math.round(2048 * MB * 0.95),
447
+ samples: 20,
448
+ });
449
+ expect(many.recycle).not.toBeNull();
450
+ expect(many.recycleCount).toBe(1);
451
+ });
452
+ it("ties the default fraction + worst-case sustained-window growth strictly below the 0.873 abort ratio", () => {
453
+ // Literals pinned from the two production aborts so a future threshold
454
+ // change that would lose the race to V8 fails HERE.
455
+ const CEILING_MB = 2048; // hq-desktop-app #549 declared --max-old-space-size
456
+ const ABORT_USED_MB = 1788; // both aborts landed at ~1788 MB used
457
+ const GROWTH_MB_PER_MIN = 32; // ~1.79 GB in ~56 min
458
+ const SAMPLE_INTERVAL_MS = 60_000; // sampler default cadence
459
+ const abortRatio = ABORT_USED_MB / CEILING_MB; // 0.873...
460
+ expect(abortRatio).toBeCloseTo(0.873, 3);
461
+ // Worst case: the fraction is crossed, then the sustained window must still
462
+ // confirm across `sustainedSamples` samples before the verdict fires.
463
+ const confirmMs = DEFAULT_HEAP_RECYCLE_SUSTAINED_SAMPLES * SAMPLE_INTERVAL_MS;
464
+ const worstCaseGrowthMb = (GROWTH_MB_PER_MIN * confirmMs) / 60_000;
465
+ const triggerUsedMb = DEFAULT_HEAP_RECYCLE_FRACTION * CEILING_MB + worstCaseGrowthMb;
466
+ expect(DEFAULT_HEAP_RECYCLE_FRACTION).toBeLessThan(abortRatio);
467
+ expect(DEFAULT_HEAP_RECYCLE_FRACTION).toBeGreaterThan(0.75); // above the warn fraction
468
+ expect(triggerUsedMb).toBeLessThan(ABORT_USED_MB); // wins the race to V8
469
+ expect(triggerUsedMb / CEILING_MB).toBeLessThan(abortRatio);
470
+ });
471
+ it("scales the trigger with the reported heap limit, so a larger ceiling never recycles prematurely", () => {
472
+ // 1700 MB used is 0.83 of a 2048 MB ceiling (recycles) but only 0.415 of a
473
+ // 4096 MB ceiling (never recycles) — thresholds are fractions of the
474
+ // injected heap_size_limit, not an absolute figure.
475
+ const usedBytes = 1700 * MB;
476
+ const onSmall = runToRecycle({ limitBytes: 2048 * MB, usedBytes });
477
+ expect(onSmall.recycle).not.toBeNull();
478
+ const onLarge = runToRecycle({ limitBytes: 4096 * MB, usedBytes, samples: 12 });
479
+ expect(onLarge.recycle).toBeNull();
480
+ // A proportionally larger used level DOES recycle on the larger ceiling, and
481
+ // at a higher absolute used figure than the small ceiling did.
482
+ const onLargeProportional = runToRecycle({ limitBytes: 4096 * MB, usedBytes: 3400 * MB });
483
+ expect(onLargeProportional.recycle).not.toBeNull();
484
+ expect(onLargeProportional.recycle.usedHeapBytes).toBeGreaterThan(onSmall.recycle.usedHeapBytes);
485
+ });
486
+ it("the kill switch disables the governor entirely; pressure still behaves as base", () => {
487
+ const census = new HeapCensus();
488
+ census.register("knownKinds", () => 1);
489
+ const { state, readers } = mutableReaders();
490
+ state.limit = 2048 * MB;
491
+ state.now = ONE_HOUR_MS;
492
+ state.used = Math.round(2048 * MB * 0.99); // far above any fraction
493
+ const controller = new RunnerHeapTelemetry({
494
+ readers,
495
+ census,
496
+ sessionStartedAtMs: 0,
497
+ pressureThresholdFraction: 0.75,
498
+ recycleEnabled: false,
499
+ });
500
+ let recycles = 0;
501
+ let pressures = 0;
502
+ for (let i = 0; i < 20; i += 1) {
503
+ const { pressure, recycle } = controller.sample();
504
+ if (recycle)
505
+ recycles += 1;
506
+ if (pressure)
507
+ pressures += 1;
508
+ }
509
+ expect(recycles).toBe(0); // governor off — never recycles
510
+ expect(pressures).toBe(1); // pressure record still fires once per crossing
511
+ });
512
+ it("a recycle record and stderr line carry only fixed tokens and integers — never a runner byte", () => {
513
+ // A census whose backing structure is keyed by REAL-looking absolute paths,
514
+ // a company slug, and a filename. Only its numeric COUNT may ever be emitted.
515
+ const SECRET_PATH = "/Users/hassaan/hq/companies/acme-corp/vault/report.md";
516
+ const SLUG = "acme-corp";
517
+ const FILENAME = "report.md";
518
+ const backing = new Map();
519
+ backing.set(SECRET_PATH, 1);
520
+ backing.set(`companies/${SLUG}/notes`, 2);
521
+ backing.set(FILENAME, 3);
522
+ const census = new HeapCensus();
523
+ census.register("watcherJournalStores", () => backing.size);
524
+ census.register("publishedContentHashGenerations", () => backing.size);
525
+ const { recycle } = runToRecycle({
526
+ limitBytes: 2048 * MB,
527
+ usedBytes: Math.round(2048 * MB * 0.95),
528
+ census,
529
+ });
530
+ expect(recycle).not.toBeNull();
531
+ const line = heapRecycleStderrLine(recycle);
532
+ const json = JSON.stringify(recycle);
533
+ for (const secret of [SECRET_PATH, SLUG, FILENAME, "/Users/", "companies/"]) {
534
+ expect(line).not.toContain(secret);
535
+ expect(json).not.toContain(secret);
536
+ }
537
+ // The FIXED census tokens are allowed; the runner bytes are not.
538
+ expect(json).toContain("watcherJournalStores");
539
+ });
540
+ it("the recycle stderr line matches NONE of hq-desktop-app's fatal stderr markers", () => {
541
+ // The exact marker vocabulary of classify_runner_fatal_class /
542
+ // is_disk_exhaustion_failure in hq-desktop-app crates/hq-desktop-core.
543
+ const DESKTOP_FATAL_MARKERS = [
544
+ "javascript heap out of memory",
545
+ "ineffective mark-compacts",
546
+ "fatal error",
547
+ "uncaught exception",
548
+ "unhandledrejection",
549
+ "panicked at",
550
+ "assertion failed",
551
+ "npm error ",
552
+ "npm err! ",
553
+ "enospc",
554
+ "permission denied",
555
+ "no such file or directory",
556
+ "command not found",
557
+ ];
558
+ const census = new HeapCensus();
559
+ // Register the real production census tokens so the `top=` list is realistic.
560
+ for (const token of [
561
+ "pendingAppliedUpserts",
562
+ "watcherJournalStores",
563
+ "publishedContentHashGenerations",
564
+ "knownKinds",
565
+ "deleteSnapshotEpochs",
566
+ ]) {
567
+ census.register(token, () => 7);
568
+ }
569
+ const { recycle } = runToRecycle({
570
+ limitBytes: 2048 * MB,
571
+ usedBytes: Math.round(2048 * MB * 0.95),
572
+ census,
573
+ });
574
+ const line = heapRecycleStderrLine(recycle);
575
+ const lowered = line.toLowerCase();
576
+ for (const marker of DESKTOP_FATAL_MARKERS) {
577
+ expect(lowered).not.toContain(marker);
578
+ }
579
+ // NodeCheckAbort keys on a leading '#'; the recycle line never starts with one.
580
+ expect(line.trimStart().startsWith("#")).toBe(false);
581
+ // Sanity: the line still carries its own recognizable, benign shape.
582
+ expect(line).toContain("hq-sync-runner: heap-recycle");
583
+ expect(line).toContain("sustained=");
584
+ });
585
+ });
586
+ describe("startRunnerHeapSampling — recycle callback", () => {
587
+ it("drives the governor to a recycle and never lets a throwing onRecycle reach the caller", () => {
588
+ const census = new HeapCensus();
589
+ census.register("x", () => 1);
590
+ const { state, readers } = mutableReaders();
591
+ state.limit = 1000;
592
+ state.used = 950; // 0.95 -> above both the 0.75 pressure and 0.78 recycle fractions
593
+ state.now = ONE_HOUR_MS; // past the floor
594
+ const fake = fakeScheduler();
595
+ const recycles = [];
596
+ startRunnerHeapSampling({
597
+ readers,
598
+ census,
599
+ sessionStartedAtMs: 0,
600
+ pressureThresholdFraction: 0.75,
601
+ recycleFraction: 0.78,
602
+ recycleSustainedSamples: 2,
603
+ recycleMinUptimeMs: 30 * 60_000,
604
+ intervalMs: 1,
605
+ scheduler: fake.scheduler,
606
+ onSample: () => { },
607
+ onPressure: () => { },
608
+ onRecycle: (record) => {
609
+ recycles.push(record);
610
+ throw new Error("recycle emit boom"); // must be swallowed
611
+ },
612
+ log: () => { },
613
+ });
614
+ // First tick: 1 consecutive over-fraction sample -> no recycle yet.
615
+ expect(() => fake.tick()).not.toThrow();
616
+ expect(recycles).toHaveLength(0);
617
+ // Second tick: 2 consecutive -> recycle fires (and its throw is swallowed).
618
+ expect(() => fake.tick()).not.toThrow();
619
+ expect(recycles).toHaveLength(1);
620
+ // At most once per session, even as ticks continue.
621
+ expect(() => fake.tick()).not.toThrow();
622
+ expect(recycles).toHaveLength(1);
623
+ });
624
+ it("produces no recycle when the governor is disabled by option", () => {
625
+ const census = new HeapCensus();
626
+ census.register("x", () => 1);
627
+ const { state, readers } = mutableReaders();
628
+ state.limit = 1000;
629
+ state.used = 999;
630
+ state.now = ONE_HOUR_MS;
631
+ const fake = fakeScheduler();
632
+ const recycles = [];
633
+ startRunnerHeapSampling({
634
+ readers,
635
+ census,
636
+ sessionStartedAtMs: 0,
637
+ pressureThresholdFraction: 0.75,
638
+ recycleEnabled: false,
639
+ recycleMinUptimeMs: 0,
640
+ intervalMs: 1,
641
+ scheduler: fake.scheduler,
642
+ onSample: () => { },
643
+ onPressure: () => { },
644
+ onRecycle: (record) => recycles.push(record),
645
+ log: () => { },
646
+ });
647
+ for (let i = 0; i < 10; i += 1)
648
+ fake.tick();
649
+ expect(recycles).toHaveLength(0);
650
+ });
651
+ });
652
+ describe("resolveHeapRecycleEnabled", () => {
653
+ it("is ON by default and disabled only by an explicit whole-string off value", () => {
654
+ expect(resolveHeapRecycleEnabled(undefined)).toBe(true);
655
+ expect(resolveHeapRecycleEnabled("")).toBe(true);
656
+ expect(resolveHeapRecycleEnabled("1")).toBe(true);
657
+ expect(resolveHeapRecycleEnabled("true")).toBe(true);
658
+ expect(resolveHeapRecycleEnabled("0")).toBe(false);
659
+ expect(resolveHeapRecycleEnabled("false")).toBe(false);
660
+ expect(resolveHeapRecycleEnabled("NO")).toBe(false);
661
+ expect(resolveHeapRecycleEnabled(" off ")).toBe(false);
662
+ // A typo keeps the governor armed rather than silently disabling it.
663
+ expect(resolveHeapRecycleEnabled("disabled")).toBe(true);
664
+ });
665
+ });
666
+ describe("resolveHeapRecycleFraction", () => {
667
+ it("parses a valid fraction and falls back to 0.78 on garbage or out-of-range input", () => {
668
+ expect(resolveHeapRecycleFraction("0.8")).toBe(0.8);
669
+ expect(resolveHeapRecycleFraction("1")).toBe(1);
670
+ expect(resolveHeapRecycleFraction(undefined)).toBe(DEFAULT_HEAP_RECYCLE_FRACTION);
671
+ expect(resolveHeapRecycleFraction("")).toBe(DEFAULT_HEAP_RECYCLE_FRACTION);
672
+ expect(resolveHeapRecycleFraction("2")).toBe(DEFAULT_HEAP_RECYCLE_FRACTION);
673
+ expect(resolveHeapRecycleFraction("-1")).toBe(DEFAULT_HEAP_RECYCLE_FRACTION);
674
+ expect(resolveHeapRecycleFraction("0.8x")).toBe(DEFAULT_HEAP_RECYCLE_FRACTION); // trailing junk
675
+ });
676
+ });
677
+ describe("resolveHeapRecycleSustainedSamples", () => {
678
+ it("parses a whole count >= 1 and refuses a degenerate 0 or garbage", () => {
679
+ expect(resolveHeapRecycleSustainedSamples("3")).toBe(3);
680
+ expect(resolveHeapRecycleSustainedSamples("1")).toBe(1);
681
+ expect(resolveHeapRecycleSustainedSamples(undefined)).toBe(DEFAULT_HEAP_RECYCLE_SUSTAINED_SAMPLES);
682
+ expect(resolveHeapRecycleSustainedSamples("0")).toBe(DEFAULT_HEAP_RECYCLE_SUSTAINED_SAMPLES);
683
+ expect(resolveHeapRecycleSustainedSamples("2s")).toBe(DEFAULT_HEAP_RECYCLE_SUSTAINED_SAMPLES);
684
+ expect(resolveHeapRecycleSustainedSamples("")).toBe(DEFAULT_HEAP_RECYCLE_SUSTAINED_SAMPLES);
685
+ });
686
+ });
687
+ describe("resolveHeapRecycleMinUptimeMs", () => {
688
+ it("parses whole ms >= 0 (0 disables the floor) and rejects '60s' rather than its prefix", () => {
689
+ expect(resolveHeapRecycleMinUptimeMs("60000")).toBe(60_000);
690
+ expect(resolveHeapRecycleMinUptimeMs("0")).toBe(0); // 0 is a valid floor
691
+ expect(resolveHeapRecycleMinUptimeMs(undefined)).toBe(DEFAULT_HEAP_RECYCLE_MIN_UPTIME_MS);
692
+ expect(resolveHeapRecycleMinUptimeMs("60s")).toBe(DEFAULT_HEAP_RECYCLE_MIN_UPTIME_MS);
693
+ expect(resolveHeapRecycleMinUptimeMs("-1")).toBe(DEFAULT_HEAP_RECYCLE_MIN_UPTIME_MS);
694
+ expect(resolveHeapRecycleMinUptimeMs("")).toBe(DEFAULT_HEAP_RECYCLE_MIN_UPTIME_MS);
695
+ });
696
+ });
697
+ //# sourceMappingURL=sync-runner-heap-telemetry.test.js.map