Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

entity-card-perf: re-time a call when hypervisor steal crossed it

garrytan7aef3fd2bf08
diff --git a/test/entity-card-perf.slow.test.ts b/test/entity-card-perf.slow.test.ts
index 31d3705002..0e5db0351c 100644
--- a/test/entity-card-perf.slow.test.ts
+++ b/test/entity-card-perf.slow.test.ts
@@ -55,6 +55,7 @@
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
import { heapSize } from 'bun:jsc';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { measureWithoutSteal } from './helpers/hypervisor-steal.ts';
import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
import {
assembleContextPack,
@@ -96,24 +97,29 @@ const HUB_RATIO_CEILING = 8;
// Catastrophe backstop only; the ratio is the gate.
const HUB_ABSOLUTE_CEILING_MS = 1000 * (Number(process.env.GBRAIN_TEST_PERF_BUDGET_MULTIPLIER) || 1);
-interface Sample { name: string; wall: number; cpu: number; heapDeltaMB: number }
+interface Sample { name: string; wall: number; cpu: number; heapDeltaMB: number; steal: Array<number | null> }
/**
* One call's wall time, this thread's CPU time (user + system) across it, in ms, and the JS heap change (a large
* change means a GC ran inside it). The gates read `cpu`: the code path's own work, including the queries PGLite
* runs on this thread and GC on it, but not time this process spent waiting for a CPU while other test processes ran.
+ * A call across which hypervisor steal advanced is timed again (test/helpers/hypervisor-steal.ts): on guest kernels
+ * without paravirt time accounting, steal is billed to this thread's CPU time too.
*/
async function sample(name: string, fn: () => Promise<unknown>): Promise<Sample> {
- const h0 = heapSize(), c0 = process.threadCpuUsage(), t0 = performance.now();
- await fn();
- const wall = performance.now() - t0, c = process.threadCpuUsage(c0);
- return { name, wall, cpu: (c.user + c.system) / 1000, heapDeltaMB: (heapSize() - h0) / 2 ** 20 };
+ const { value, steal } = await measureWithoutSteal(async () => {
+ const h0 = heapSize(), c0 = process.threadCpuUsage(), t0 = performance.now();
+ await fn();
+ const wall = performance.now() - t0, c = process.threadCpuUsage(c0);
+ return { wall, cpu: (c.user + c.system) / 1000, heapDeltaMB: (heapSize() - h0) / 2 ** 20 };
+ });
+ return { name, ...value, steal };
}
-/** The five slowest samples for the log: cpu well under wall is scheduler wait, a heap jump is a GC, cpu≈wall with neither is a slower CPU. */
+/** The five slowest samples for the log: cpu well under wall is scheduler wait, a heap jump is a GC, steal ticks per attempt show re-timed calls, cpu≈wall with none of these is a slower CPU. */
function slowest(samples: Sample[]): string {
return [...samples].sort((a, b) => b.cpu - a.cpu).slice(0, 5)
- .map(s => `${s.name} wall=${s.wall.toFixed(1)} cpu=${s.cpu.toFixed(1)} heapΔ=${s.heapDeltaMB.toFixed(1)}MB`).join(' | ');
+ .map(s => `${s.name} wall=${s.wall.toFixed(1)} cpu=${s.cpu.toFixed(1)} heapΔ=${s.heapDeltaMB.toFixed(1)}MB steal=${s.steal.join('/')}`).join(' | ');
}
function percentile(sorted: number[], p: number): number {
diff --git a/test/helpers/hypervisor-steal.ts b/test/helpers/hypervisor-steal.ts
new file mode 100644
index 0000000000..826ddd2b92
--- /dev/null
+++ b/test/helpers/hypervisor-steal.ts
@@ -0,0 +1,41 @@
+/**
+ * Hypervisor steal guard for timing tests.
+ *
+ * On guest kernels without CONFIG_PARAVIRT_TIME_ACCOUNTING (Ubuntu's generic
+ * kernels, the GitHub and Ubicloud runners included), vCPU time the host
+ * steals is billed to whichever thread was current, so both wall time and
+ * thread CPU time of a window grow with it. A window across which the VM-wide
+ * steal counter moved is an invalid reading, not slower code: measure it again.
+ * Same mechanism as test/progress.test.ts (#6644).
+ */
+import { readFileSync } from 'node:fs';
+
+/** VM-wide steal in USER_HZ ticks (field 8 of /proc/stat's aggregate cpu line), or null where there is no /proc/stat. */
+export function stealTicks(readStat: () => string = () => readFileSync('/proc/stat', 'utf8')): number | null {
+ try {
+ const fields = (readStat().split('\n')[0] ?? '').trim().split(/\s+/);
+ if (fields[0] !== 'cpu' || fields.length <= 8) return null;
+ const ticks = Number(fields[8]);
+ return Number.isFinite(ticks) ? ticks : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Runs `measure` until steal did not advance across it, at most `attempts` times, and returns the last
+ * reading with the steal ticks seen per attempt (null: unknown). A slowdown in the code itself has no
+ * steal, so its first reading is the one kept.
+ */
+export async function measureWithoutSteal<T>(measure: () => Promise<T>, attempts = 5,
+ steal: () => number | null = stealTicks): Promise<{ value: T; steal: Array<number | null> }> {
+ const seen: Array<number | null> = [];
+ for (;;) {
+ const before = steal();
+ const value = await measure();
+ const after = steal();
+ const delta = before === null || after === null ? null : after - before;
+ seen.push(delta);
+ if (delta === null || delta === 0 || seen.length >= attempts) return { value, steal: seen };
+ }
+}
diff --git a/test/hypervisor-steal.test.ts b/test/hypervisor-steal.test.ts
new file mode 100644
index 0000000000..f54e107e1f
--- /dev/null
+++ b/test/hypervisor-steal.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, test } from 'bun:test';
+import { measureWithoutSteal, stealTicks } from './helpers/hypervisor-steal.ts';
+
+const stat = (steal: number) => `cpu 4705 356 584 3699 23 23 0 ${steal} 0 0\ncpu0 1393 70 152 913 5 6 0 0 0 0\n`;
+
+/** A steal counter that returns the given readings in order. */
+const counter = (...readings: Array<number | null>) => () => readings.shift() ?? null;
+
+describe('stealTicks', () => {
+ test('reads field 8 of the aggregate cpu line', () => {
+ expect(stealTicks(() => stat(17))).toBe(17);
+ });
+
+ test('is null without /proc/stat or with a line it does not know', () => {
+ expect(stealTicks(() => { throw new Error('ENOENT'); })).toBeNull();
+ expect(stealTicks(() => 'cpu 1 2 3\n')).toBeNull();
+ expect(stealTicks(() => 'intr 1 2 3 4 5 6 7 8 9\n')).toBeNull();
+ });
+});
+
+describe('measureWithoutSteal', () => {
+ test('keeps the first reading when steal did not move', async () => {
+ let calls = 0;
+ const r = await measureWithoutSteal(async () => ++calls * 10, 5, counter(3, 3));
+ expect(r).toEqual({ value: 10, steal: [0] });
+ });
+
+ test('measures again after a window steal crossed and keeps the clean one', async () => {
+ let calls = 0;
+ const r = await measureWithoutSteal(async () => (++calls === 1 ? 116 : 24), 5, counter(3, 9, 9, 9));
+ expect(r).toEqual({ value: 24, steal: [6, 0] });
+ });
+
+ test('stops at the bound and keeps the last reading when steal never stops', async () => {
+ let calls = 0;
+ const r = await measureWithoutSteal(async () => ++calls, 3, counter(0, 1, 1, 2, 2, 3, 3, 4));
+ expect(r).toEqual({ value: 3, steal: [1, 1, 1] });
+ });
+
+ test('a slowdown with no steal is the reading kept: one attempt, never re-measured away', async () => {
+ let calls = 0;
+ const r = await measureWithoutSteal(async () => { calls++; return 113; }, 5, counter(5, 5));
+ expect(r).toEqual({ value: 113, steal: [0] });
+ expect(calls).toBe(1);
+ });
+
+ test('without /proc/stat the first reading is kept', async () => {
+ let calls = 0;
+ const r = await measureWithoutSteal(async () => ++calls, 5, () => null);
+ expect(r).toEqual({ value: 1, steal: [null] });
+ });
+});