@hearsay-tools/squawk 0.18.0-pr4321.8395 → 0.18.0-pr4322.8406

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hearsay-tools/squawk",
3
- "version": "0.18.0-pr4321.8395",
3
+ "version": "0.18.0-pr4322.8406",
4
4
  "description": "Local cockpit for running and tracking AI agent tasks in your repo. Uses your logged-in `claude` CLI and `gh` — zero config, zero database.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -68,8 +68,8 @@
68
68
  "devDependencies": {
69
69
  "@babel/parser": "^8.0.8",
70
70
  "@babel/types": "^8.0.8",
71
- "@open-mercato/cezar-api-client": "0.18.0-pr4321.8395",
72
- "@open-mercato/cezar-contract": "0.18.0-pr4321.8395",
71
+ "@open-mercato/cezar-api-client": "0.18.0-pr4322.8406",
72
+ "@open-mercato/cezar-contract": "0.18.0-pr4322.8406",
73
73
  "@types/node": "^24.19.1",
74
74
  "@types/ws": "^8.18.1",
75
75
  "esbuild": "^0.28.1",
@@ -86,5 +86,5 @@
86
86
  "publishConfig": {
87
87
  "access": "public"
88
88
  },
89
- "gitHead": "9b55868d99e593ff519ef550718c37b7f1028e7e"
89
+ "gitHead": "547c2ef1c36ca07910d68a8adac96ed96bbf169f"
90
90
  }
@@ -8,7 +8,8 @@ import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { join } from 'node:path';
10
10
  import { setTimeout as delay } from 'node:timers/promises';
11
- import { timingSnapshot, timingDelta, blockingBudget, prepareOpenTiming } from './transcript-facts-timing.mjs';
11
+ import { PerformanceObserver } from 'node:perf_hooks';
12
+ import { timingSnapshot, timingDelta, blockingBudget, prepareOpenTiming, hookCalls, callsWithin } from './transcript-facts-timing.mjs';
12
13
  import { seedColdHistories, verifyFacts } from './transcript-facts-fixture.mjs';
13
14
 
14
15
  const root = mkdtempSync(join(process.platform === 'win32' ? tmpdir() : '/tmp', 'cez-facts-health-'));
@@ -23,6 +24,8 @@ let dataDir;
23
24
  let store;
24
25
  let bootStore;
25
26
  let server;
27
+ let unhookCalls;
28
+ let gcObserver;
26
29
  const watchdog = setTimeout(() => { console.error('health measurement exceeded 30s'); process.exitCode = 1; server?.closeAllConnections(); server?.close(); store?.close(); bootStore?.close(); }, 30_000);
27
30
  try {
28
31
  const { RunStore } = await import(new URL('runs/store.js', runtime.url));
@@ -76,13 +79,25 @@ try {
76
79
  assert.equal((await prime.json()).version, 'task4-measurement');
77
80
  const primingLatencyMs = performance.now() - primingStart;
78
81
  assert.equal(readdirSync(join(dataDir, 'runs')).filter(name => name.endsWith('.facts.json')).length, 0);
82
+ // Diagnostics only: name the main-thread calls and GC pauses inside each sample.
83
+ const { TranscriptFactsIndex } = await import(new URL('runs/transcript-facts.js', runtime.url));
84
+ const { TranscriptFactsQueue } = await import(new URL('runs/transcript-facts-queue.js', runtime.url));
85
+ const { RunQueriesTopic } = await import(new URL('runs/run-queries.js', runtime.url));
86
+ const calls = [];
87
+ unhookCalls = hookCalls([[RunQueriesTopic.prototype, 'listConversationRootIds'], [RunQueriesTopic.prototype, 'listFamilyRunIds'],
88
+ [RunQueriesTopic.prototype, 'listRunIds'], [TranscriptFactsIndex.prototype, 'warm'], [TranscriptFactsIndex.prototype, 'peek'],
89
+ [TranscriptFactsIndex.prototype, 'accept'], [TranscriptFactsIndex.prototype, 'persist'],
90
+ [TranscriptFactsQueue.prototype, 'start'], [TranscriptFactsQueue.prototype, 'createWorker']], calls);
91
+ const gcPauses = [];
92
+ gcObserver = new PerformanceObserver(list => { for (const entry of list.getEntries()) gcPauses.push(entry); });
93
+ gcObserver.observe({ entryTypes: ['gc'] });
79
94
  const start = performance.now();
80
95
  let end;
81
96
  let warming;
82
97
  const samples = [];
83
98
  const pauseMs = 5;
84
99
  // Each sample after the first also covers the pause before its request, so blocking
85
- // between requests is measured too; blockingBudget subtracts the planned pause.
100
+ // between requests is measured too; the pause is loop idle time, which blockingBudget excludes.
86
101
  let pauseStart;
87
102
  for (;;) {
88
103
  const measurementStart = pauseStart ?? timingSnapshot();
@@ -101,12 +116,22 @@ try {
101
116
  // Include EVERY request begun while cold warm-up was active, even one ending after it.
102
117
  const measurement = timingDelta(measurementStart, timingSnapshot());
103
118
  samples.push({ fromMs: measurementStart.at - start, startMs: requestStart - start, endMs: requestEnd - start,
104
- latencyMs: requestEnd - requestStart, plannedMs, ...measurement, ...blockingBudget(measurement, plannedMs) });
119
+ latencyMs: requestEnd - requestStart, plannedMs, ...measurement, ...blockingBudget(measurement) });
105
120
  if (end !== undefined) break;
106
121
  pauseStart = timingSnapshot();
107
122
  await delay(pauseMs);
108
123
  }
109
124
  await warming;
125
+ unhookCalls();
126
+ for (const entry of gcObserver.takeRecords()) gcPauses.push(entry);
127
+ gcObserver.disconnect();
128
+ for (const sample of samples) {
129
+ const from = start + sample.fromMs;
130
+ const to = from + sample.elapsedMs;
131
+ const gc = gcPauses.filter(entry => entry.startTime >= from && entry.startTime < to);
132
+ Object.assign(sample, { calls: callsWithin(calls, from, to),
133
+ gc: { count: gc.length, durationMs: gc.reduce((sum, entry) => sum + entry.duration, 0) } });
134
+ }
110
135
  assert.ok(samples.length > 0, 'health requests must overlap cold warming');
111
136
  assert.ok(samples.every(sample => sample.fromMs < end - start && sample.endMs > 0));
112
137
  // Keep first-open and repeated-open costs separate. Reopening must not rescan clean history.
@@ -121,12 +146,16 @@ try {
121
146
  ...verifyFacts(dataDir, fixtures, store), durationMs: end - start,
122
147
  maxBlockingMs: Math.max(...samples.map(sample => sample.blockingMs)),
123
148
  maxMainThreadCpuMs: Math.max(...samples.map(sample => sample.mainThreadCpuMs)),
149
+ maxLoopIdleMs: Math.max(...samples.map(sample => sample.loopIdleMs)),
124
150
  sampleCount: samples.length, maxLatencyMs: Math.max(...samples.map(sample => sample.latencyMs)), samples };
125
151
  console.log(JSON.stringify(result));
126
- // Exclude run-queue delay, but retain synchronous blocking and request latency.
152
+ // Exclude run-queue delay and loop idle time: a response that waits on the thread pool, a worker
153
+ // or the kernel is latency (kept in maxLatencyMs), not main-thread blocking. Synchronous work counts.
127
154
  assert.ok(result.maxBlockingMs < 50, `max health blocking ${result.maxBlockingMs.toFixed(3)}ms must be <50ms`);
128
155
  } finally {
129
156
  clearTimeout(watchdog);
157
+ unhookCalls?.();
158
+ gcObserver?.disconnect();
130
159
  let cleanupTimer;
131
160
  try {
132
161
  if (server) await Promise.race([server.shutdownForRestart(), new Promise((_, reject) => {
@@ -2,7 +2,7 @@
2
2
  * node --expose-gc --import tsx packages/cezar/scripts/measure-transcript-facts-lag.mjs
3
3
  * Built runtime: pass an absolute dist directory. Baseline source: pass its src directory and ts.
4
4
  * A separate process removes test-runner loop work, NOT unrelated host CPU scheduling.
5
- * Gate loop CPU and blocking time; exclude host run-queue delay.
5
+ * Gate loop CPU and blocking time; exclude loop idle time and host run-queue delay.
6
6
  */
7
7
  import assert from 'node:assert/strict';
8
8
  import { mkdtempSync, rmSync } from 'node:fs';
@@ -30,7 +30,7 @@ try {
30
30
  timer = setInterval(() => {
31
31
  const current = timingSnapshot();
32
32
  const sample = timingDelta(previous, current);
33
- ticks.push({ at: current.at, lagMs: Math.max(0, sample.elapsedMs - periodMs), ...sample, ...blockingBudget(sample, periodMs) });
33
+ ticks.push({ at: current.at, lagMs: Math.max(0, sample.elapsedMs - periodMs), ...sample, ...blockingBudget(sample) });
34
34
  previous = current;
35
35
  }, periodMs);
36
36
  // Establish a real interval before starting; retain the first tick after completion too.
@@ -69,7 +69,7 @@ try {
69
69
  assert.ok(result.trailingTicks > 0, 'must retain a trailing tick after warming');
70
70
  assert.ok(overlapping.length > 0, 'must sample during cold warm-up');
71
71
  assert.ok(result.durationMs > 0);
72
- // Exclude planned timer sleep and run-queue delay, but retain synchronous blocking.
72
+ // Exclude loop idle time (the planned timer sleep) and run-queue delay, but retain synchronous blocking.
73
73
  assert.ok(result.maxBlockingMs < 20, `max interval blocking ${result.maxBlockingMs.toFixed(3)}ms must be <20ms`);
74
74
  } finally {
75
75
  clearInterval(timer);
@@ -11,34 +11,99 @@ export function readQueueWaitMs({ read = readFileSync, platform = process.platfo
11
11
  catch { return null; /* Optional diagnostic on restricted procfs mounts. */ }
12
12
  }
13
13
 
14
+ /** Linux per-thread major page faults and voluntary context switches: optional diagnostics
15
+ * that tell a disk page-in from a lock or I/O wait. Null where procfs cannot answer. */
16
+ export function readThreadStats({ read = readFileSync, platform = process.platform } = {}) {
17
+ if (platform !== 'linux') return null;
18
+ try {
19
+ const stat = read('/proc/thread-self/stat', 'utf8');
20
+ // Field 12 (majflt); the command name in field 2 may contain spaces, so count after ')'.
21
+ const majorFaults = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[9]);
22
+ const switches = /^voluntary_ctxt_switches:\s*(\d+)$/m.exec(read('/proc/thread-self/status', 'utf8'));
23
+ return Number.isFinite(majorFaults) && switches ? { majorFaults, voluntarySwitches: Number(switches[1]) } : null;
24
+ }
25
+ catch { return null; /* Optional diagnostic on restricted procfs mounts. */ }
26
+ }
27
+
28
+ /** libuv idle time: the loop waited in its poll phase for I/O, a timer or another thread. */
29
+ export function readLoopIdleMs() {
30
+ return performance.eventLoopUtilization().idle;
31
+ }
32
+
14
33
  export function timingSnapshot({ now = () => performance.now(), readQueue = readQueueWaitMs,
15
- readCpu = () => process.threadCpuUsage() } = {}) {
34
+ readCpu = () => process.threadCpuUsage(), readLoopIdle = readLoopIdleMs, readThread = readThreadStats } = {}) {
35
+ const thread = readThread();
16
36
  const cpu = readCpu();
37
+ const loopIdleMs = readLoopIdle();
17
38
  const queueBeforeMs = readQueue();
18
39
  const at = now();
19
40
  const queueAfterMs = readQueue();
20
- return { at, cpuMs: (cpu.user + cpu.system) / 1000, queueBeforeMs, queueAfterMs };
41
+ return { at, cpuMs: (cpu.user + cpu.system) / 1000, loopIdleMs, queueBeforeMs, queueAfterMs, thread };
21
42
  }
22
43
 
23
44
  export function timingDelta(start, end) {
24
45
  const elapsedMs = end.at - start.at;
25
46
  const mainThreadCpuMs = end.cpuMs - start.cpuMs;
47
+ // Snapshots run JavaScript, never inside the poll phase, so the idle delta lies in the interval.
48
+ const loopIdleMs = Math.max(0, Math.min(elapsedMs, end.loopIdleMs - start.loopIdleMs));
26
49
  // Previous AFTER -> next BEFORE is contained in the wall-clock interval.
27
50
  // Subtract only this inner queue-wait delta. A pause between a scheduler
28
51
  // read and the clock must never credit wait from outside the interval.
29
52
  const queueWaitMs = start.queueAfterMs === null || end.queueBeforeMs === null ? null
30
53
  : Math.max(0, Math.min(elapsedMs, end.queueBeforeMs - start.queueAfterMs));
31
- // Residual includes timer/IO sleep and measurement overhead, not just IO.
32
- return { elapsedMs, mainThreadCpuMs, queueWaitMs,
33
- blockedMs: queueWaitMs === null ? null : Math.max(0, elapsedMs - mainThreadCpuMs - queueWaitMs) };
54
+ // Residual: off-CPU time outside the poll phase (synchronous disk I/O, locks, Atomics.wait)
55
+ // plus measurement overhead. See blockingBudget for why the larger wait is subtracted once.
56
+ return { elapsedMs, mainThreadCpuMs, loopIdleMs, queueWaitMs,
57
+ blockedMs: queueWaitMs === null ? null : Math.max(0, elapsedMs - mainThreadCpuMs - Math.max(loopIdleMs, queueWaitMs)),
58
+ ...(start.thread && end.thread ? { majorFaults: end.thread.majorFaults - start.thread.majorFaults,
59
+ voluntarySwitches: end.thread.voluntarySwitches - start.thread.voluntarySwitches } : {}) };
34
60
  }
35
61
 
36
- /** Timer samples exclude their planned sleep; requests have no planned sleep. */
37
- export function blockingBudget(sample, periodMs = 0) {
62
+ /** Main-thread blocking is loop-active time without run-queue wait. Loop idle time is excluded:
63
+ * a planned timer sleep, and a request waiting on the thread pool, a worker or the kernel, are
64
+ * latency but do not block the loop. CPU, synchronous disk I/O and Atomics.wait still count.
65
+ * libuv counts a run-queue wait after a poll wake-up as idle time too, and the two cannot be
66
+ * told apart, so only the larger of idle and run-queue wait is subtracted. Subtracting both
67
+ * could hide a synchronous stall; this choice can only over-count, never above elapsed minus
68
+ * run-queue wait. It never drops below main-thread CPU. */
69
+ export function blockingBudget(sample) {
38
70
  const mode = sample.queueWaitMs === null ? 'cpu-only' : 'scheduler-adjusted';
39
71
  const blockingMs = sample.queueWaitMs === null ? sample.mainThreadCpuMs
40
- : Math.max(0, sample.elapsedMs - periodMs - sample.queueWaitMs);
41
- return { mode, blockingMs: Math.max(0, periodMs > 0 ? Math.max(sample.mainThreadCpuMs, blockingMs) : blockingMs) };
72
+ : Math.max(sample.mainThreadCpuMs, sample.elapsedMs - Math.max(sample.loopIdleMs, sample.queueWaitMs));
73
+ return { mode, blockingMs: Math.max(0, blockingMs) };
74
+ }
75
+
76
+ /** Light per-call timing (clock and thread CPU only), so many hooked calls add little loop time.
77
+ * Each call records its start; nested hooked calls are recorded too, under their own phase. */
78
+ export function hookCalls(hooks, calls) {
79
+ const restore = hooks.map(([target, name]) => {
80
+ const original = target[name];
81
+ target[name] = function (...args) {
82
+ const at = performance.now();
83
+ const cpu = process.threadCpuUsage();
84
+ try { return original.apply(this, args); }
85
+ finally {
86
+ const used = process.threadCpuUsage(cpu);
87
+ calls.push({ phase: name, at, elapsedMs: performance.now() - at, mainThreadCpuMs: (used.user + used.system) / 1000 });
88
+ }
89
+ };
90
+ return () => { target[name] = original; };
91
+ });
92
+ return () => { for (const undo of restore) undo(); };
93
+ }
94
+
95
+ /** Per-phase totals of the calls that started in [from, to). */
96
+ export function callsWithin(calls, from, to) {
97
+ const phases = {};
98
+ for (const call of calls) {
99
+ if (call.at < from || call.at >= to) continue;
100
+ const total = phases[call.phase] ??= { count: 0, elapsedMs: 0, mainThreadCpuMs: 0, maxElapsedMs: 0 };
101
+ total.count++;
102
+ total.elapsedMs += call.elapsedMs;
103
+ total.mainThreadCpuMs += call.mainThreadCpuMs;
104
+ total.maxElapsedMs = Math.max(total.maxElapsedMs, call.elapsedMs);
105
+ }
106
+ return phases;
42
107
  }
43
108
 
44
109
  /** Instrument only the synchronous open call. Imports and hook setup are outside its budget.