@vellumai/assistant 0.10.5-dev.202607052029.2d00037 → 0.10.5-dev.202607052127.b26cd90

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/openapi.yaml CHANGED
@@ -19651,6 +19651,43 @@ paths:
19651
19651
  - workingsetRefaultFile
19652
19652
  additionalProperties: false
19653
19653
  - type: "null"
19654
+ cpu:
19655
+ anyOf:
19656
+ - type: object
19657
+ properties:
19658
+ usageUsec:
19659
+ anyOf:
19660
+ - type: number
19661
+ - type: "null"
19662
+ userUsec:
19663
+ anyOf:
19664
+ - type: number
19665
+ - type: "null"
19666
+ systemUsec:
19667
+ anyOf:
19668
+ - type: number
19669
+ - type: "null"
19670
+ nrPeriods:
19671
+ anyOf:
19672
+ - type: number
19673
+ - type: "null"
19674
+ nrThrottled:
19675
+ anyOf:
19676
+ - type: number
19677
+ - type: "null"
19678
+ throttledUsec:
19679
+ anyOf:
19680
+ - type: number
19681
+ - type: "null"
19682
+ required:
19683
+ - usageUsec
19684
+ - userUsec
19685
+ - systemUsec
19686
+ - nrPeriods
19687
+ - nrThrottled
19688
+ - throttledUsec
19689
+ additionalProperties: false
19690
+ - type: "null"
19654
19691
  events:
19655
19692
  anyOf:
19656
19693
  - type: object
@@ -19731,9 +19768,47 @@ paths:
19731
19768
  - workingsetRefaultFile
19732
19769
  additionalProperties: false
19733
19770
  - type: "null"
19771
+ cpu:
19772
+ anyOf:
19773
+ - type: object
19774
+ properties:
19775
+ usageUsec:
19776
+ anyOf:
19777
+ - type: number
19778
+ - type: "null"
19779
+ userUsec:
19780
+ anyOf:
19781
+ - type: number
19782
+ - type: "null"
19783
+ systemUsec:
19784
+ anyOf:
19785
+ - type: number
19786
+ - type: "null"
19787
+ nrPeriods:
19788
+ anyOf:
19789
+ - type: number
19790
+ - type: "null"
19791
+ nrThrottled:
19792
+ anyOf:
19793
+ - type: number
19794
+ - type: "null"
19795
+ throttledUsec:
19796
+ anyOf:
19797
+ - type: number
19798
+ - type: "null"
19799
+ required:
19800
+ - usageUsec
19801
+ - userUsec
19802
+ - systemUsec
19803
+ - nrPeriods
19804
+ - nrThrottled
19805
+ - throttledUsec
19806
+ additionalProperties: false
19807
+ - type: "null"
19734
19808
  required:
19735
19809
  - events
19736
19810
  - reclaim
19811
+ - cpu
19737
19812
  additionalProperties: false
19738
19813
  - type: "null"
19739
19814
  disk:
@@ -19760,6 +19835,7 @@ paths:
19760
19835
  - memory
19761
19836
  - memoryStat
19762
19837
  - reclaim
19838
+ - cpu
19763
19839
  - events
19764
19840
  - deltas
19765
19841
  - disk
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.5-dev.202607052029.2d00037",
3
+ "version": "0.10.5-dev.202607052127.b26cd90",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,28 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { getAllDefaultPlugins } from "../plugins/defaults/index.js";
4
+ import { getAllDefaultPluginNames } from "../plugins/defaults/main.js";
5
+
6
+ /**
7
+ * Guard: the filesystem-backed default-plugin registry (`defaults/main.ts`)
8
+ * and the import-backed barrel (`defaults/index.ts`) must agree on the
9
+ * plugin set. `main.ts` is the barrel's eventual replacement; while both
10
+ * exist, a plugin added to one but not the other would silently diverge the
11
+ * consumers (e.g. per-chat plugin scoping reads names from `main.ts`, while
12
+ * bootstrap registers plugins from the barrel).
13
+ */
14
+ describe("default plugin names", () => {
15
+ test("the filesystem registry matches the barrel's manifests exactly", () => {
16
+ const fromFs = [...getAllDefaultPluginNames()].sort();
17
+ const fromBarrel = getAllDefaultPlugins()
18
+ .map((p) => p.manifest.name)
19
+ .sort();
20
+ expect(fromFs).toEqual(fromBarrel);
21
+ });
22
+
23
+ test("every name uses the default- prefix convention", () => {
24
+ for (const name of getAllDefaultPluginNames()) {
25
+ expect(name).toMatch(/^default-[a-z0-9-]+$/);
26
+ }
27
+ });
28
+ });
@@ -31,6 +31,15 @@ interface ReclaimCounters {
31
31
  workingsetRefaultFile: number | null;
32
32
  }
33
33
 
34
+ interface CpuCounters {
35
+ usageUsec: number | null;
36
+ userUsec: number | null;
37
+ systemUsec: number | null;
38
+ nrPeriods: number | null;
39
+ nrThrottled: number | null;
40
+ throttledUsec: number | null;
41
+ }
42
+
34
43
  interface LatestSample {
35
44
  ts: number;
36
45
  memory: {
@@ -49,6 +58,7 @@ interface LatestSample {
49
58
  reclaimableBytes: number | null;
50
59
  } | null;
51
60
  reclaim: ReclaimCounters | null;
61
+ cpu: CpuCounters | null;
52
62
  deltas: {
53
63
  events: {
54
64
  low: number | null;
@@ -58,6 +68,7 @@ interface LatestSample {
58
68
  oomKill: number | null;
59
69
  } | null;
60
70
  reclaim: ReclaimCounters | null;
71
+ cpu: CpuCounters | null;
61
72
  } | null;
62
73
  disk: {
63
74
  path: string;
@@ -125,7 +136,9 @@ Examples:
125
136
  .option("--json", "Emit raw JSON instead of a formatted summary")
126
137
  .action(async (_opts: { json?: boolean }, cmd: Command) => {
127
138
  const r = await cliIpcCall<StartResponse>("monitoring_start");
128
- if (!r.ok) return exitFromIpcResult(r);
139
+ if (!r.ok) {
140
+ return exitFromIpcResult(r);
141
+ }
129
142
  const res = r.result!;
130
143
 
131
144
  if (shouldOutputJson(cmd)) {
@@ -150,7 +163,9 @@ Examples:
150
163
  .option("--json", "Emit raw JSON instead of a formatted summary")
151
164
  .action(async (_opts: { json?: boolean }, cmd: Command) => {
152
165
  const r = await cliIpcCall<StopResponse>("monitoring_stop");
153
- if (!r.ok) return exitFromIpcResult(r);
166
+ if (!r.ok) {
167
+ return exitFromIpcResult(r);
168
+ }
154
169
  const res = r.result!;
155
170
 
156
171
  if (shouldOutputJson(cmd)) {
@@ -173,7 +188,9 @@ Examples:
173
188
  .option("--json", "Emit raw JSON instead of a formatted summary")
174
189
  .action(async (_opts: { json?: boolean }, cmd: Command) => {
175
190
  const r = await cliIpcCall<StatusResponse>("monitoring_status");
176
- if (!r.ok) return exitFromIpcResult(r);
191
+ if (!r.ok) {
192
+ return exitFromIpcResult(r);
193
+ }
177
194
  const res = r.result!;
178
195
 
179
196
  if (shouldOutputJson(cmd)) {
@@ -229,6 +246,17 @@ Examples:
229
246
  ` Reclaim: pgscan_direct ${counter(sample.reclaim.pgscanDirect, d?.pgscanDirect)}, pgsteal_direct ${counter(sample.reclaim.pgstealDirect, d?.pgstealDirect)}, workingset_refault_file ${counter(sample.reclaim.workingsetRefaultFile, d?.workingsetRefaultFile)}`,
230
247
  );
231
248
  }
249
+ if (sample.cpu && sample.cpu.throttledUsec != null) {
250
+ const throttleDelta = sample.deltas?.cpu?.throttledUsec;
251
+ const throttledMs = Math.round(sample.cpu.throttledUsec / 1000);
252
+ const deltaSuffix =
253
+ throttleDelta != null
254
+ ? ` (+${Math.round(throttleDelta / 1000)}ms)`
255
+ : "";
256
+ log.info(
257
+ ` CPU throttling: ${sample.cpu.nrThrottled ?? "?"} periods, ${throttledMs}ms total${deltaSuffix}`,
258
+ );
259
+ }
232
260
  if (sample.disk) {
233
261
  log.info(
234
262
  ` Disk (${sample.disk.path}): ${sample.disk.usedMb} / ${sample.disk.totalMb} MiB used`,
@@ -17,7 +17,7 @@ import type { LLMCallSite } from "../config/schemas/llm.js";
17
17
  import type { PermissionPrompter } from "../permissions/prompter.js";
18
18
  import type { SecretPrompter } from "../permissions/secret-prompter.js";
19
19
  import { getBindingByConversation } from "../persistence/external-conversation-store.js";
20
- import { getAllDefaultPlugins } from "../plugins/defaults/index.js";
20
+ import { getAllDefaultPluginNames } from "../plugins/defaults/main.js";
21
21
  import { isPluginDisabled } from "../plugins/disabled-state.js";
22
22
  import type { Message, ToolDefinition } from "../providers/types.js";
23
23
  import { assistantEventHub } from "../runtime/assistant-event-hub.js";
@@ -158,8 +158,7 @@ export function getEffectiveEnabledPluginSet(conv: {
158
158
  const effective = new Set(conv.enabledPlugins);
159
159
  // Rules 2 + 3: add a default the conversation did not already decide, unless
160
160
  // it is disabled at the workspace level.
161
- for (const plugin of getAllDefaultPlugins()) {
162
- const name = plugin.manifest.name;
161
+ for (const name of getAllDefaultPluginNames()) {
163
162
  if (!effective.has(name) && !isPluginDisabled(name)) {
164
163
  effective.add(name);
165
164
  }
@@ -27,6 +27,18 @@
27
27
  * brackets — the code that froze. For sub-threshold contributors, time the
28
28
  * subsystem's synchronous calls at their source with `timeSyncSection`.
29
29
  *
30
+ * Kernel-side stall classification is owned by the resource monitor process,
31
+ * not this watchdog — nothing here reads sysfs or /proc. Each tick touches a
32
+ * heartbeat file (one mtime update; because the touch runs on the loop, a
33
+ * stale heartbeat *is* a blocked loop). The monitor watches that heartbeat
34
+ * from its own OS process and, mid-stall, captures the daemon main thread's
35
+ * kernel stack and process state alongside its regular memory.stat / reclaim /
36
+ * cpu.stat sample deltas (`monitoring/stall-capture.ts`). When this watchdog
37
+ * fires on unblock, the report attaches the monitor's capture for the window —
38
+ * classifying freezes that are not JS at all (synchronous kernel reclaim,
39
+ * CPU-quota throttling, lock waits). When monitoring is disabled the report
40
+ * degrades to blockedMs + section trail.
41
+ *
30
42
  * A cumulative event-loop-delay histogram is separately exposed pull-based over
31
43
  * SSE diagnostics (`runtime/routes/events-routes.ts`); this watchdog is the
32
44
  * push/alert counterpart and runs unconditionally for the daemon's lifetime.
@@ -34,6 +46,11 @@
34
46
 
35
47
  import * as Sentry from "@sentry/node";
36
48
 
49
+ import { touchDaemonHeartbeat } from "../monitoring/daemon-heartbeat.js";
50
+ import {
51
+ findRecentStallCapture,
52
+ type StallCapture,
53
+ } from "../monitoring/stall-capture.js";
37
54
  import {
38
55
  getSectionTrail,
39
56
  type SectionTrailEntry,
@@ -62,6 +79,14 @@ const DEFAULT_BLOCK_THRESHOLD_MS = 5_000;
62
79
  */
63
80
  const REPORT_COOLDOWN_MS = 30_000;
64
81
 
82
+ /**
83
+ * How far before the computed block start a monitor stall capture may be
84
+ * timestamped and still be attached to the report. Absorbs the skew between
85
+ * the heartbeat mtime, the monitor's sampling cadence, and this process's
86
+ * clock.
87
+ */
88
+ const STALL_CAPTURE_MATCH_GRACE_MS = 5_000;
89
+
65
90
  let tickTimer: ReturnType<typeof setInterval> | null = null;
66
91
  let lastTickAt = 0;
67
92
  let lastReportAt = Number.NEGATIVE_INFINITY;
@@ -88,7 +113,10 @@ export function evaluateTick(
88
113
  */
89
114
  export const EVENT_LOOP_BLOCKED_CHECK_NAME = "event_loop_blocked";
90
115
 
91
- function reportBlock(blockedMs: number, thresholdMs: number): void {
116
+ async function reportBlock(
117
+ blockedMs: number,
118
+ thresholdMs: number,
119
+ ): Promise<void> {
92
120
  // Attribution breadcrumbs: the block began ~`blockedMs` before this report,
93
121
  // so the newest trail entry started at least that long ago — and not yet
94
122
  // ended by then — is the section that was running when the loop froze.
@@ -98,8 +126,27 @@ function reportBlock(blockedMs: number, thresholdMs: number): void {
98
126
  } catch {
99
127
  // Diagnostics-only — never let it escape the timer callback.
100
128
  }
129
+ // The resource monitor's mid-stall capture of this block, if it took one:
130
+ // the monitor detects the stale heartbeat within its 250ms sampling cadence,
131
+ // so a capture for a threshold-length block exists before this report fires.
132
+ // The grace ahead of the block start absorbs heartbeat-vs-clock skew. Async
133
+ // read — the report path must not add synchronous I/O to the loop.
134
+ let stallCapture: StallCapture | null = null;
135
+ try {
136
+ stallCapture = await findRecentStallCapture(
137
+ Date.now() - blockedMs - STALL_CAPTURE_MATCH_GRACE_MS,
138
+ );
139
+ } catch {
140
+ // Diagnostics-only — never let it escape the timer callback.
141
+ }
101
142
  log.warn(
102
- { blockedMs, thresholdMs, tickIntervalMs: TICK_INTERVAL_MS, sectionTrail },
143
+ {
144
+ blockedMs,
145
+ thresholdMs,
146
+ tickIntervalMs: TICK_INTERVAL_MS,
147
+ sectionTrail,
148
+ stallCapture,
149
+ },
103
150
  "event loop blocked",
104
151
  );
105
152
  // Persist a `watchdog` telemetry event so the platform can surface
@@ -116,6 +163,7 @@ function reportBlock(blockedMs: number, thresholdMs: number): void {
116
163
  threshold_ms: thresholdMs,
117
164
  tick_interval_ms: TICK_INTERVAL_MS,
118
165
  section_trail: sectionTrail,
166
+ stall_capture: stallCapture,
119
167
  },
120
168
  });
121
169
  } catch {
@@ -130,6 +178,7 @@ function reportBlock(blockedMs: number, thresholdMs: number): void {
130
178
  threshold_ms: thresholdMs,
131
179
  tick_interval_ms: TICK_INTERVAL_MS,
132
180
  section_trail: sectionTrail,
181
+ stall_capture: stallCapture,
133
182
  });
134
183
  Sentry.captureMessage(EVENT_LOOP_BLOCKED_CHECK_NAME);
135
184
  });
@@ -145,7 +194,9 @@ function reportBlock(blockedMs: number, thresholdMs: number): void {
145
194
  export function startEventLoopWatchdog(
146
195
  thresholdMs: number = DEFAULT_BLOCK_THRESHOLD_MS,
147
196
  ): void {
148
- if (tickTimer) return;
197
+ if (tickTimer) {
198
+ return;
199
+ }
149
200
  lastTickAt = performance.now();
150
201
  lastReportAt = Number.NEGATIVE_INFINITY;
151
202
  tickTimer = setInterval(() => {
@@ -156,9 +207,14 @@ export function startEventLoopWatchdog(
156
207
  thresholdMs,
157
208
  );
158
209
  lastTickAt = now;
210
+ // One mtime touch per tick — the resource monitor reads its staleness to
211
+ // detect (and capture) a blocked loop while the stall is in progress.
212
+ touchDaemonHeartbeat();
159
213
  if (exceeded && now - lastReportAt >= REPORT_COOLDOWN_MS) {
160
214
  lastReportAt = now;
161
- reportBlock(blockedMs, thresholdMs);
215
+ void reportBlock(blockedMs, thresholdMs).catch(() => {
216
+ // Diagnostics-only — never let it escape the timer callback.
217
+ });
162
218
  }
163
219
  }, TICK_INTERVAL_MS);
164
220
  tickTimer.unref?.();
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Tests for the daemon heartbeat writer/reader against the per-test workspace.
3
+ * The config loader is mocked so the `monitoring.enabled` gate can be
4
+ * exercised both ways.
5
+ */
6
+
7
+ import { existsSync, rmSync } from "node:fs";
8
+ import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
9
+
10
+ import * as actualLoader from "../../config/loader.js";
11
+
12
+ // null → delegate to the real loader. bun's mock.module persists for the
13
+ // whole process, so the mock must turn itself into a passthrough once this
14
+ // suite finishes or it would poison later test files sharing the process.
15
+ let monitoringEnabled: boolean | null = true;
16
+
17
+ mock.module("../../config/loader.js", () => ({
18
+ ...actualLoader,
19
+ getConfigReadOnly: () =>
20
+ monitoringEnabled == null
21
+ ? actualLoader.getConfigReadOnly()
22
+ : { monitoring: { enabled: monitoringEnabled } },
23
+ }));
24
+
25
+ afterAll(() => {
26
+ monitoringEnabled = null;
27
+ });
28
+
29
+ const { getDaemonHeartbeatPath, readDaemonHeartbeat, touchDaemonHeartbeat } =
30
+ await import("../daemon-heartbeat.js");
31
+
32
+ beforeEach(() => {
33
+ monitoringEnabled = true;
34
+ try {
35
+ rmSync(getDaemonHeartbeatPath());
36
+ } catch {
37
+ // Not written yet.
38
+ }
39
+ });
40
+
41
+ describe("daemon heartbeat", () => {
42
+ test("touch records this process's pid with a fresh mtime", () => {
43
+ touchDaemonHeartbeat();
44
+
45
+ const heartbeat = readDaemonHeartbeat(Date.now());
46
+ expect(heartbeat).not.toBeNull();
47
+ expect(heartbeat!.pid).toBe(process.pid);
48
+ expect(heartbeat!.ageMs).toBeGreaterThanOrEqual(0);
49
+ expect(heartbeat!.ageMs).toBeLessThan(5_000);
50
+ });
51
+
52
+ test("age grows with the reader's clock", () => {
53
+ touchDaemonHeartbeat();
54
+ const heartbeat = readDaemonHeartbeat(Date.now() + 7_000);
55
+ // Filesystem mtime can be truncated below Date.now() at sub-ms precision.
56
+ expect(heartbeat!.ageMs).toBeGreaterThanOrEqual(6_990);
57
+ });
58
+
59
+ test("recreates the file when it is removed between touches", () => {
60
+ touchDaemonHeartbeat();
61
+ rmSync(getDaemonHeartbeatPath());
62
+ touchDaemonHeartbeat();
63
+ expect(readDaemonHeartbeat(Date.now())).not.toBeNull();
64
+ });
65
+
66
+ test("no-ops when monitoring is disabled", () => {
67
+ monitoringEnabled = false;
68
+ touchDaemonHeartbeat();
69
+ expect(existsSync(getDaemonHeartbeatPath())).toBe(false);
70
+ expect(readDaemonHeartbeat(Date.now())).toBeNull();
71
+ });
72
+
73
+ test("reader returns null for a missing file", () => {
74
+ expect(readDaemonHeartbeat(Date.now())).toBeNull();
75
+ });
76
+ });
@@ -63,19 +63,20 @@ describe("getTrackedDataFiles", () => {
63
63
  mkdirSync(join(getDataDir(), "db"), { recursive: true });
64
64
  writeFileSync(dbPath, "x".repeat(64));
65
65
  writeFileSync(`${dbPath}-wal`, "x".repeat(32));
66
- // No -shm file — it must not be reported.
67
66
 
68
67
  const segments = join(getDataDir(), "qdrant", "collections", "c1");
69
68
  mkdirSync(segments, { recursive: true });
70
69
  writeFileSync(join(segments, "big.seg"), "x".repeat(100));
71
70
  writeFileSync(join(segments, "small.seg"), "x".repeat(10));
72
71
 
72
+ // Containment assertions: other suites sharing this process's workspace
73
+ // may create the -shm sidecar, so the exact list is not deterministic.
73
74
  const tracked = getTrackedDataFiles(1);
74
75
 
75
- expect(tracked).toEqual([
76
- dbPath,
77
- `${dbPath}-wal`,
78
- join(segments, "big.seg"),
79
- ]);
76
+ expect(tracked).toContain(dbPath);
77
+ expect(tracked).toContain(`${dbPath}-wal`);
78
+ expect(tracked).toContain(join(segments, "big.seg"));
79
+ // The qdrant limit of 1 keeps the smaller segment out.
80
+ expect(tracked).not.toContain(join(segments, "small.seg"));
80
81
  });
81
82
  });
@@ -17,6 +17,7 @@ function makeSample(overrides: Partial<ResourceSample>): ResourceSample {
17
17
  memory: null,
18
18
  memoryStat: null,
19
19
  reclaim: null,
20
+ cpu: null,
20
21
  events: null,
21
22
  deltas: null,
22
23
  disk: null,
@@ -25,7 +26,7 @@ function makeSample(overrides: Partial<ResourceSample>): ResourceSample {
25
26
  }
26
27
 
27
28
  describe("computeSampleDeltas", () => {
28
- test("diffs events and reclaim counters per key", () => {
29
+ test("diffs events, reclaim, and cpu counters per key", () => {
29
30
  const prev = makeSample({
30
31
  ts: 1000,
31
32
  events: { low: 0, high: 5, max: 100, oom: 0, oomKill: 0 },
@@ -34,6 +35,14 @@ describe("computeSampleDeltas", () => {
34
35
  pgstealDirect: 900_000,
35
36
  workingsetRefaultFile: 500,
36
37
  },
38
+ cpu: {
39
+ usageUsec: 4_000_000,
40
+ userUsec: 3_000_000,
41
+ systemUsec: 1_000_000,
42
+ nrPeriods: 100,
43
+ nrThrottled: 4,
44
+ throttledUsec: 200_000,
45
+ },
37
46
  });
38
47
  const current = makeSample({
39
48
  ts: 1250,
@@ -43,6 +52,14 @@ describe("computeSampleDeltas", () => {
43
52
  pgstealDirect: 1_200_000,
44
53
  workingsetRefaultFile: 800,
45
54
  },
55
+ cpu: {
56
+ usageUsec: 4_250_000,
57
+ userUsec: 3_100_000,
58
+ systemUsec: 1_150_000,
59
+ nrPeriods: 103,
60
+ nrThrottled: 6,
61
+ throttledUsec: 450_000,
62
+ },
46
63
  });
47
64
 
48
65
  expect(computeSampleDeltas(prev, current)).toEqual({
@@ -52,6 +69,14 @@ describe("computeSampleDeltas", () => {
52
69
  pgstealDirect: 300_000,
53
70
  workingsetRefaultFile: 300,
54
71
  },
72
+ cpu: {
73
+ usageUsec: 250_000,
74
+ userUsec: 100_000,
75
+ systemUsec: 150_000,
76
+ nrPeriods: 3,
77
+ nrThrottled: 2,
78
+ throttledUsec: 250_000,
79
+ },
55
80
  });
56
81
  });
57
82
 
@@ -73,8 +98,9 @@ describe("computeSampleDeltas", () => {
73
98
  });
74
99
 
75
100
  const deltas = computeSampleDeltas(prev, current);
76
- // prev.events is null, so no event deltas.
101
+ // prev.events and both cpu sides are null, so no deltas for those.
77
102
  expect(deltas.events).toBeNull();
103
+ expect(deltas.cpu).toBeNull();
78
104
  expect(deltas.reclaim).toEqual({
79
105
  pgscanDirect: 50,
80
106
  pgstealDirect: null,
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Tests for the monitor-side daemon stall capture. The heartbeat file is
3
+ * written directly (bypassing the daemon-side writer) so staleness and pid
4
+ * liveness can be controlled; kernel-stack/proc-state fields are
5
+ * environment-dependent and only asserted for shape.
6
+ */
7
+
8
+ import { mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import { beforeEach, describe, expect, test } from "bun:test";
11
+
12
+ import { getMonitoringDataDir } from "../../util/platform.js";
13
+ import { getDaemonHeartbeatPath } from "../daemon-heartbeat.js";
14
+ import type { ResourceSample } from "../resource-sampler.js";
15
+ import {
16
+ createStallCaptureMonitor,
17
+ findRecentStallCapture,
18
+ parseProcStatState,
19
+ } from "../stall-capture.js";
20
+
21
+ function makeSample(ts: number): ResourceSample {
22
+ return {
23
+ ts,
24
+ memory: null,
25
+ memoryStat: null,
26
+ reclaim: null,
27
+ cpu: null,
28
+ events: null,
29
+ deltas: null,
30
+ disk: null,
31
+ };
32
+ }
33
+
34
+ function writeHeartbeat(pid: number): void {
35
+ const path = getDaemonHeartbeatPath();
36
+ mkdirSync(dirname(path), { recursive: true });
37
+ writeFileSync(path, String(pid));
38
+ }
39
+
40
+ function stallFiles(): string[] {
41
+ try {
42
+ return readdirSync(join(getMonitoringDataDir(), "snapshots")).filter((f) =>
43
+ f.startsWith("stall-"),
44
+ );
45
+ } catch {
46
+ return [];
47
+ }
48
+ }
49
+
50
+ let dataDir: string;
51
+
52
+ beforeEach(() => {
53
+ dataDir = getMonitoringDataDir();
54
+ for (const f of stallFiles()) {
55
+ rmSync(join(dataDir, "snapshots", f));
56
+ }
57
+ });
58
+
59
+ describe("parseProcStatState", () => {
60
+ test("extracts the state field after the comm", () => {
61
+ expect(parseProcStatState("1 (bun) S 0 1 1 0 -1 4194560")).toBe("S");
62
+ expect(parseProcStatState("7 (tricky (name) x) D 1 7 7 0 -1")).toBe("D");
63
+ });
64
+
65
+ test("returns null on malformed content", () => {
66
+ expect(parseProcStatState("")).toBeNull();
67
+ expect(parseProcStatState("1 (bun)")).toBeNull();
68
+ expect(parseProcStatState("1 (bun) 123 456")).toBeNull();
69
+ });
70
+ });
71
+
72
+ describe("createStallCaptureMonitor", () => {
73
+ test("captures when the heartbeat is stale and the daemon is alive", async () => {
74
+ writeHeartbeat(process.pid);
75
+ const monitor = createStallCaptureMonitor(dataDir);
76
+ const now = Date.now() + 10_000; // heartbeat is 10s old from this clock
77
+
78
+ monitor.check(makeSample(now), now);
79
+
80
+ expect(stallFiles()).toHaveLength(1);
81
+ const capture = await findRecentStallCapture(now - 1_000);
82
+ expect(capture).not.toBeNull();
83
+ expect(capture!.daemonPid).toBe(process.pid);
84
+ expect(capture!.heartbeatAgeMs).toBeGreaterThanOrEqual(6_000);
85
+ expect(capture!.sample.ts).toBe(now);
86
+ // Environment-dependent (root-only / Linux-only) — shape, not value.
87
+ expect(capture).toHaveProperty("kernelStack");
88
+ expect(capture).toHaveProperty("processState");
89
+ });
90
+
91
+ test("does not capture on a fresh heartbeat", () => {
92
+ writeHeartbeat(process.pid);
93
+ const monitor = createStallCaptureMonitor(dataDir);
94
+ monitor.check(makeSample(0), Date.now());
95
+ expect(stallFiles()).toHaveLength(0);
96
+ });
97
+
98
+ test("cooldown bounds captures during a sustained stall", () => {
99
+ writeHeartbeat(process.pid);
100
+ const monitor = createStallCaptureMonitor(dataDir);
101
+ const now = Date.now() + 10_000;
102
+ monitor.check(makeSample(now), now);
103
+ monitor.check(makeSample(now + 250), now + 250);
104
+ expect(stallFiles()).toHaveLength(1);
105
+ });
106
+
107
+ test("skips a dead daemon (stopped, not stalled)", () => {
108
+ // A pid far above any real allocation; process.kill(pid, 0) throws.
109
+ writeHeartbeat(2 ** 30);
110
+ const monitor = createStallCaptureMonitor(dataDir);
111
+ monitor.check(makeSample(0), Date.now() + 10_000);
112
+ expect(stallFiles()).toHaveLength(0);
113
+ });
114
+ });
115
+
116
+ describe("findRecentStallCapture", () => {
117
+ test("returns null when the newest capture predates the window", async () => {
118
+ writeHeartbeat(process.pid);
119
+ const monitor = createStallCaptureMonitor(dataDir);
120
+ const now = Date.now() + 10_000;
121
+ monitor.check(makeSample(now), now);
122
+
123
+ expect(await findRecentStallCapture(now + 1)).toBeNull();
124
+ });
125
+
126
+ test("returns null when no captures exist", async () => {
127
+ expect(await findRecentStallCapture(0)).toBeNull();
128
+ });
129
+ });