Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: CPU-bound timing asserts measure thread CPU time, not wall clock

garrytandef24fc38a1c
diff --git a/test/attendance-retrieval.test.ts b/test/attendance-retrieval.test.ts
index e70443b0ce..4b4fcea80a 100644
--- a/test/attendance-retrieval.test.ts
+++ b/test/attendance-retrieval.test.ts
@@ -18,6 +18,7 @@ import { loadActivePackForLocalEngine } from '../src/core/schema-pack/best-effor
import { installFixtureChunks } from './helpers/page-projection.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
const sourceId = 'attendance-fixture';
const person = 'people/alice-example';
@@ -893,10 +894,11 @@ for (const kind of testBackends()) {
describe('shared and filesystem canonical attendance grammar', () => {
test('large malformed lists are bounded and never accept a valid prefix', async () => {
const { attendanceEvidenceRanges } = await import('../src/core/link-extraction.ts');
- const started = performance.now();
- expect(attendanceEvidenceRanges(`${positive} ${'['.repeat(65_536)}`)).toEqual([]);
- expect(attendanceEvidenceRanges('Attendees: [nested[Alice](../people/alice-example.md)]')).toEqual([]);
- expect(performance.now() - started).toBeLessThan(500);
+ const elapsed = cpuMs(() => {
+ expect(attendanceEvidenceRanges(`${positive} ${'['.repeat(65_536)}`)).toEqual([]);
+ expect(attendanceEvidenceRanges('Attendees: [nested[Alice](../people/alice-example.md)]')).toEqual([]);
+ });
+ expect(elapsed).toBeLessThan(500);
});
const types = new Map([[person, 'person'], ['people/company-example', 'company'], [meeting, 'meeting']]);
const resolver = { async resolve(value: string) { return types.has(value) ? value : null; } };
diff --git a/test/bounded-lead.test.ts b/test/bounded-lead.test.ts
index 9ebb6b8344..e945684a46 100644
--- a/test/bounded-lead.test.ts
+++ b/test/bounded-lead.test.ts
@@ -33,6 +33,7 @@ import { extractCandidates } from '../src/core/context/entity-salience.ts';
import { lookupEntityNames, pageLead } from '../src/core/verbs/entity-names.ts';
import { runGather } from '../src/core/think/gather.ts';
import { installFixtureChunks } from './helpers/page-projection.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
const SENTINEL = 'PRIVATE-TAKE-SENTINEL';
const FACTS = renderFactsTable([
@@ -81,6 +82,13 @@ function bestMs(fn: () => unknown): number {
return best;
}
+/** Best of three runs, in ms of process CPU time: it measures the work rather than how long the scheduler made it wait. */
+function bestCpuMs(fn: () => unknown): number {
+ let best = Infinity;
+ for (let i = 0; i < 3; i++) best = Math.min(best, cpuMs(fn));
+ return best;
+}
+
let engine: PGLiteEngine;
beforeAll(async () => {
@@ -228,8 +236,9 @@ describe('bounded work on a 4 MB page', () => {
const body = await pageBody('people/erin-example');
const row = { slug: 'people/erin-example', source_id: 'default', title: 'Erin Example', type: 'person', frontmatter: null, compiled_truth: body };
const whole = bestMs(() => sanitizeRemoteBody(body));
- expect(bestMs(() => safeSynopsis(row))).toBeLessThan(whole / 4);
- expect(bestMs(() => pageLead(body))).toBeLessThan(whole / 4);
+ const wholeCpu = bestCpuMs(() => sanitizeRemoteBody(body));
+ expect(bestCpuMs(() => safeSynopsis(row))).toBeLessThan(wholeCpu / 4);
+ expect(bestCpuMs(() => pageLead(body))).toBeLessThan(wholeCpu / 4);
expect(pageLead(body).length).toBeLessThanOrEqual(200);
let lead = '';
let best = Infinity;
diff --git a/test/chunker-spans-linear.slow.test.ts b/test/chunker-spans-linear.slow.test.ts
index fee325f1a4..9064a3fe69 100644
--- a/test/chunker-spans-linear.slow.test.ts
+++ b/test/chunker-spans-linear.slow.test.ts
@@ -6,10 +6,13 @@
* Doubling the input must roughly double the time with spans on, for chat-log
* text and for a page of one-word paragraphs (the most pieces per chunk). The
* bound is generous (linear is 2x, quadratic 4x) and each size takes its best
- * of three runs, so a busy machine does not fail it.
+ * of three runs, so a busy machine does not fail it. Each run is timed in
+ * process CPU time, which measures the work rather than how long the
+ * scheduler made it wait.
*/
import { describe, test, expect } from 'bun:test';
import { chunkText } from '../src/core/chunkers/recursive.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
function chatLog(chars: number): string {
let a = 0x9e3779b9;
@@ -38,9 +41,8 @@ function chatLog(chars: number): string {
function bestMs(text: string): number {
let best = Infinity;
for (let k = 0; k < 3; k++) {
- const t0 = performance.now();
- const chunks = chunkText(text, { spans: true });
- best = Math.min(best, performance.now() - t0);
+ let chunks: ReturnType<typeof chunkText> = [];
+ best = Math.min(best, cpuMs(() => { chunks = chunkText(text, { spans: true }); }));
expect(chunks.every(c => c.byte_start !== undefined)).toBe(true);
}
return best;
diff --git a/test/cycle-synthesize-verify.test.ts b/test/cycle-synthesize-verify.test.ts
index f7b74244a9..db0f3661ca 100644
--- a/test/cycle-synthesize-verify.test.ts
+++ b/test/cycle-synthesize-verify.test.ts
@@ -23,6 +23,7 @@ import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importFromContent } from '../src/core/import-file.ts';
import { renderMaterializedBullet } from '../src/core/persistence/canonical-projections.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
function grounded(content: string) {
const { norm, map } = normalizeForGrounding(content);
@@ -422,10 +423,10 @@ describe('groundQuote — CPU bounds (performance-review regression)', () => {
const transcript = ('routine words about scheduling and lunch orders and build status. '.repeat(5000));
const t = grounded(transcript);
const fabricated = 'entirely novel strategic manifesto sentence '.repeat(80); // ~3.5K chars > cap
- const started = Date.now();
- const g = groundQuote(fabricated, t);
+ let g!: ReturnType<typeof groundQuote>;
+ const ms = cpuMs(() => { g = groundQuote(fabricated, t); });
expect(g.status).toBe('none');
- expect(Date.now() - started).toBeLessThan(1000);
+ expect(ms).toBeLessThan(1000);
});
});
diff --git a/test/eval-capture-scrub.test.ts b/test/eval-capture-scrub.test.ts
index 3b6fa5db96..bde9aa4b69 100644
--- a/test/eval-capture-scrub.test.ts
+++ b/test/eval-capture-scrub.test.ts
@@ -6,6 +6,7 @@
import { describe, expect, test } from 'bun:test';
import { scrubPii } from '../src/core/eval-capture-scrub.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
describe('scrubPii', () => {
test('passes empty input through unchanged', () => {
@@ -94,9 +95,8 @@ describe('scrubPii', () => {
// stay linear-time on all input. 10k char limit is well under the
// CHECK-constrained 50KB cap enforced at DB level.
const adversarial = 'a'.repeat(10000) + '!';
- const start = Date.now();
- const out = scrubPii(adversarial);
- const elapsed = Date.now() - start;
+ let out = '';
+ const elapsed = cpuMs(() => { out = scrubPii(adversarial); });
expect(elapsed).toBeLessThan(1000); // generous cap, realistic target <50ms
expect(out).toContain('a'.repeat(100)); // output still visible
});
diff --git a/test/fence-extraction.test.ts b/test/fence-extraction.test.ts
index dccd319531..8e774e42c9 100644
--- a/test/fence-extraction.test.ts
+++ b/test/fence-extraction.test.ts
@@ -10,6 +10,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importFromContent } from '../src/core/import-file.ts';
import { scanFencedBlocks } from '../src/core/fence-scan.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
describe('Layer 8 D2 — markdown fence extraction', () => {
let engine: PGLiteEngine;
@@ -183,9 +184,10 @@ echo hi
// ~1000x headroom for a pure O(lines) pass even on a heavily loaded box
// (an end-to-end import timing assertion proved too load-sensitive:
// chunking + PGLite inserts dominate and vary wildly under parallel CI).
- const t0 = Date.now();
- const { fences } = scanFencedBlocks(md);
- expect(Date.now() - t0).toBeLessThan(2_000);
+ // CPU time measures the scan's work rather than how long the scheduler made it wait.
+ let fences!: ReturnType<typeof scanFencedBlocks>['fences'];
+ const ms = cpuMs(() => { ({ fences } = scanFencedBlocks(md)); });
+ expect(ms).toBeLessThan(2_000);
expect(fences.length).toBe(1);
// End-to-end: the fence still lands as a fenced_code chunk.
await importFromContent(engine, 'guides/fence-autolink-flood', md, { noEmbed: true });
diff --git a/test/fence-marker-code-context.test.ts b/test/fence-marker-code-context.test.ts
index f725483ebe..a42f460ca1 100644
--- a/test/fence-marker-code-context.test.ts
+++ b/test/fence-marker-code-context.test.ts
@@ -13,6 +13,7 @@ import { compileCanonicalProjections } from '../src/core/persistence/canonical-p
import { withdrawalFenceBlocks } from '../src/core/facts/withdrawal-overlay.ts';
import { splitBody } from '../src/core/markdown.ts';
import type { ParsedPage } from '../src/core/import-file.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
const take = (claim: string) => ({ claim, kind: 'take' as const, holder: 'alice-example', weight: 0.5, active: true });
const realTakes = (claim: string) => upsertTakeRow('', take(claim)).body;
@@ -83,38 +84,36 @@ describe('markdown code map', () => {
// A per-line search that runs to EOF on every line lacking a backtick is
// quadratic: ~200 ms per MB of plain prose. Linear is ~1 ms.
const prose = 'Plain prose with no code at all, just words.\n'.repeat(45_000);
- const start = performance.now();
- expect(scanMarkdownCode(prose).fenced).toEqual([]);
- expect(performance.now() - start).toBeLessThan(150);
+ const ms = cpuMs(() => expect(scanMarkdownCode(prose).fenced).toEqual([]));
+ expect(ms).toBeLessThan(150);
});
test('stays linear with thousands of quoted markers on one long line', () => {
// Inline spans are computed per marker line on demand; a line's spans must
// be computed once, not once per marker on it.
const line = `\`${TAKES_FENCE_BEGIN}\` `.repeat(20_000);
- const start = performance.now();
- expect(indexOfOutsideCode(line, TAKES_FENCE_BEGIN)).toBe(-1);
- expect(performance.now() - start).toBeLessThan(150);
+ const ms = cpuMs(() => expect(indexOfOutsideCode(line, TAKES_FENCE_BEGIN)).toBe(-1));
+ expect(ms).toBeLessThan(150);
});
test('stays linear across many marker lines on a page with no backticks', () => {
// A facts/takes-heavy page without inline code: judging each marker line
// must not search the rest of the body for a backtick.
const body = `${FACTS_FENCE_BEGIN}\n${'x'.repeat(80)}\n`.repeat(20_000);
- const start = performance.now();
- const code = scanMarkdownCode(body);
- let n = 0;
- for (let at = indexOfOutsideCode(body, FACTS_FENCE_BEGIN); at !== -1; at = indexOfOutsideCode(body, FACTS_FENCE_BEGIN, at + 1, code)) n++;
- expect(n).toBe(20_000);
- expect(performance.now() - start).toBeLessThan(150);
+ const ms = cpuMs(() => {
+ const code = scanMarkdownCode(body);
+ let n = 0;
+ for (let at = indexOfOutsideCode(body, FACTS_FENCE_BEGIN); at !== -1; at = indexOfOutsideCode(body, FACTS_FENCE_BEGIN, at + 1, code)) n++;
+ expect(n).toBe(20_000);
+ });
+ expect(ms).toBeLessThan(150);
});
test('stays linear when a lone CR sits far before many marker lines', () => {
// Finding a marker's line must never search toward the start of the body.
const body = 'head\r' + `plain line of prose here\n\`${TAKES_FENCE_BEGIN}\`\n`.repeat(20_000);
- const start = performance.now();
- expect(indexOfOutsideCode(body, TAKES_FENCE_BEGIN)).toBe(-1);
- expect(performance.now() - start).toBeLessThan(150);
+ const ms = cpuMs(() => expect(indexOfOutsideCode(body, TAKES_FENCE_BEGIN)).toBe(-1));
+ expect(ms).toBeLessThan(150);
});
test('indexOfOutsideCode skips quoted occurrences and finds the live one', () => {
diff --git a/test/frontmatter-alias-bomb.test.ts b/test/frontmatter-alias-bomb.test.ts
index c736965748..316bddf1e5 100644
--- a/test/frontmatter-alias-bomb.test.ts
+++ b/test/frontmatter-alias-bomb.test.ts
@@ -10,6 +10,7 @@
import { describe, expect, test } from 'bun:test';
import { autoFixFrontmatter } from '../src/core/brain-writer.ts';
import { parseMarkdown, yamlAliasesWithinLimit } from '../src/core/markdown.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
const fence = '---';
function bomb(key: string, depth = 26): string {
@@ -23,25 +24,21 @@ describe('frontmatter alias bomb (W5.1 security review)', () => {
for (const key of ['tags', 'aliases', 'related']) {
test(`autoFixFrontmatter returns fast and rewrites nothing on a ${key}: bomb`, () => {
const input = page(bomb(key));
- const started = performance.now();
- const { content } = autoFixFrontmatter(input);
- expect(performance.now() - started).toBeLessThan(1000);
+ let content = '';
+ expect(cpuMs(() => { ({ content } = autoFixFrontmatter(input)); })).toBeLessThan(1000);
expect(content).toBe(input);
});
}
test('validation of a bomb in a non-tag key returns fast', () => {
- const started = performance.now();
- parseMarkdown(page(bomb('related')), undefined, { validate: true });
- expect(performance.now() - started).toBeLessThan(1000);
+ expect(cpuMs(() => parseMarkdown(page(bomb('related')), undefined, { validate: true }))).toBeLessThan(1000);
});
// Pre-existing on master (not from #6157): tag extraction stringified nested
// tag arrays, which expands the same bomb. Only scalar tags are kept.
test('parsing a tags: bomb returns fast; nested tag arrays are not tags', () => {
- const started = performance.now();
- const parsed = parseMarkdown(page(bomb('tags')));
- expect(performance.now() - started).toBeLessThan(1000);
+ let parsed!: ReturnType<typeof parseMarkdown>;
+ expect(cpuMs(() => { parsed = parseMarkdown(page(bomb('tags'))); })).toBeLessThan(1000);
expect(parsed.tags).toEqual([]);
expect(parseMarkdown(page('tags: [yc, 2025, "w25"]')).tags).toEqual(['yc', '2025', 'w25']);
});
diff --git a/test/helpers/cpu-time.ts b/test/helpers/cpu-time.ts
new file mode 100644
index 0000000000..e459595c4f
--- /dev/null
+++ b/test/helpers/cpu-time.ts
@@ -0,0 +1,13 @@
+/**
+ * CPU time of a synchronous call on the calling thread, in milliseconds. A bound or scaling ratio over CPU time
+ * measures the work rather than how long the scheduler made it wait, so load on a shared CI VM does not move it.
+ * `process.threadCpuUsage` (as in test/entity-card-perf.slow.test.ts and src/core/progress.ts) leaves out the
+ * engine's GC and JIT threads and any other concurrent work in the process. It does not see time spent waiting on
+ * I/O, a subprocess, a timer or another thread: a test that bounds those keeps the wall clock.
+ */
+export function cpuMs(fn: () => unknown): number {
+ const start = process.threadCpuUsage();
+ fn();
+ const used = process.threadCpuUsage(start);
+ return (used.user + used.system) / 1000;
+}
diff --git a/test/line-grammar.test.ts b/test/line-grammar.test.ts
index 6dfa4cb2ee..8e2121c303 100644
--- a/test/line-grammar.test.ts
+++ b/test/line-grammar.test.ts
@@ -180,9 +180,10 @@ describe('@effective qualifier', () => {
test('adversarial input stays linear (bounded child process)', () => {
const script = `
const { parseLineGrammar } = await import(${JSON.stringify(new URL('../src/core/line-grammar.ts', import.meta.url).pathname)});
+ const { cpuMs } = await import(${JSON.stringify(new URL('./helpers/cpu-time.ts', import.meta.url).pathname)});
const evil = ['- ' + '['.repeat(20000) + 'x', '- works_at ' + '('.repeat(20000), '- [a] ' + '(('.repeat(10000) + ')',
'- t ' + '[[a]] '.repeat(5000), '- [idea] @effective[' + ','.repeat(20000)].join('\\n');
- const t = performance.now(); parseLineGrammar(evil.repeat(5)); console.log(Math.round(performance.now() - t));`;
+ console.log(Math.round(cpuMs(() => parseLineGrammar(evil.repeat(5)))));`;
const run = spawnSync(process.execPath, ['-e', script], { timeout: 20_000, encoding: 'utf-8' });
expect(run.status, run.stderr).toBe(0);
expect(Number(run.stdout.trim())).toBeLessThan(5_000);
@@ -193,10 +194,13 @@ test('long comma, bracket and space runs are parsed in linear time (#6186)', ()
const { parseLineGrammar } = await import(${JSON.stringify(new URL('../src/core/line-grammar.ts', import.meta.url).pathname)});
const lines = (n) => ['- [idea] @effective[' + ','.repeat(n), '- t ' + '[['.repeat(n / 2), '- t ' + '[x]('.repeat(n / 4),
'- [idea] a' + ' '.repeat(n) + 'b', '- [idea] a [Source:' + ' '.repeat(n) + 'b'].join('\\n');
- const time = (n) => { const text = lines(n); const t = performance.now(); parseLineGrammar(text); return performance.now() - t; };
+ // Process CPU, not cpuMs: thread CPU advances in ~4 ms steps here (small side read 4.0 or 8.0 ms, ratio 3.0-7.0 over 10 idle runs;
+ // process CPU 6.5 ms vs 27.6 ms, ratio 4.2-4.8), and 8 parses per window to clear 40 ms overran the 5 s child timeout under load.
+ const processCpuMs = (fn) => { const s = process.cpuUsage(); fn(); const u = process.cpuUsage(s); return (u.user + u.system) / 1000; };
+ const time = (n) => { const text = lines(n); return processCpuMs(() => parseLineGrammar(text)); };
time(1000);
// Interleaved samples so CPU contention hits both sizes alike; n vs 4n so linear (x4) and quadratic (x16)
- // sit a factor of 2 either side of the bound.
+ // sit a factor of 2 either side of the bound. CPU time measures the work rather than how long the scheduler made it wait.
const smalls = [], larges = [];
for (let i = 0; i < 5; i++) { smalls.push(time(50_000)); larges.push(time(200_000)); }
console.log(JSON.stringify({ small: Math.min(...smalls), large: Math.min(...larges) }));`;
diff --git a/test/mentions-policy-aliases.test.ts b/test/mentions-policy-aliases.test.ts
index 03dc93b845..e3f23cafb3 100644
--- a/test/mentions-policy-aliases.test.ts
+++ b/test/mentions-policy-aliases.test.ts
@@ -18,6 +18,7 @@ import {
import { aliasRejection, captureName, declarationsIn, declaredNames, deriveEntityAliases, titleSubject } from '../src/core/mentions/aliases.ts';
import { aliasDeclarations } from '../src/core/ops/search.ts';
import { isShortCode, SHORT_CODE_STOPLIST } from '../src/core/mentions/short-codes.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
const none = { typeAdds: [], typeRemoves: [] };
const pack = async (name: string) => (await loadResolvedPackByName(name)).manifest;
@@ -188,9 +189,7 @@ describe('declared-name grammar (alias conventions spec)', () => {
test('parsing stays linear on adversarial lines', () => {
const line = `aka ${'A '.repeat(5000)}` + `\n| ${'Nickname '.repeat(3000)}|` + `\nNickname: ${'"'.repeat(5000)}`;
- const t0 = performance.now();
- declaredNames(line, 'Widget Co');
- expect(performance.now() - t0).toBeLessThan(200);
+ expect(cpuMs(() => declaredNames(line, 'Widget Co'))).toBeLessThan(200);
});
});
diff --git a/test/redos-hardening.test.ts b/test/redos-hardening.test.ts
index 2bdd7edaa4..ce8b9626e4 100644
--- a/test/redos-hardening.test.ts
+++ b/test/redos-hardening.test.ts
@@ -18,6 +18,7 @@ import { inferLinkTypeFromPack } from '../src/core/schema-pack/link-inference.ts
import { linkRegexCatastrophicBacktrack } from '../src/core/schema-pack/lint-rules.ts';
import type { SchemaPackManifest } from '../src/core/schema-pack/manifest-v1.ts';
import { surfaceFileSource, surfaceSource } from './helpers/source-surface.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
describe('#1569 input-length cap', () => {
test('runRegexBounded throws RegexInputTooLargeError over the cap', () => {
@@ -44,11 +45,11 @@ describe('#1569 input-length cap', () => {
link_types: [{ name: 'founded', inference: { regex: '(a+)+$' } }],
} as unknown as Pick<SchemaPackManifest, 'link_types'>;
const huge = 'a'.repeat(MAX_REGEX_INPUT_CHARS + 100) + '!';
- const t0 = Date.now();
- const result = inferLinkTypeFromPack(pack, 'company', huge);
+ let result!: ReturnType<typeof inferLinkTypeFromPack>;
+ const ms = cpuMs(() => { result = inferLinkTypeFromPack(pack, 'company', huge); });
// Skipped via the cap → no match, and fast (no catastrophic backtrack).
expect(result).toBeNull();
- expect(Date.now() - t0).toBeLessThan(2_000);
+ expect(ms).toBeLessThan(2_000);
});
});
@@ -89,9 +90,10 @@ describe('megawave vm-watchdog removal (bootstrap-verify freeze)', () => {
const pack = {
link_types: [{ name: 'evil', inference: { regex: '(a+)+$' } }],
} as unknown as Pick<SchemaPackManifest, 'link_types'>;
- const t0 = Date.now();
- expect(inferLinkTypeFromPack(pack, 'company', 'a'.repeat(64) + '!')).toBeNull();
- expect(Date.now() - t0).toBeLessThan(1_000);
+ let result!: ReturnType<typeof inferLinkTypeFromPack>;
+ const ms = cpuMs(() => { result = inferLinkTypeFromPack(pack, 'company', 'a'.repeat(64) + '!'); });
+ expect(result).toBeNull();
+ expect(ms).toBeLessThan(1_000);
});
});
diff --git a/test/relational-plan.test.ts b/test/relational-plan.test.ts
index 86ae4fcd51..dd2adbf477 100644
--- a/test/relational-plan.test.ts
+++ b/test/relational-plan.test.ts
@@ -10,6 +10,7 @@
*/
import { describe, test, expect } from 'bun:test';
import { parseRelationalPlan, isRelationalQuery } from '../src/core/search/relational-plan.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
type Hop = [string, 'object' | 'subject'];
const shape = (q: string) => {
@@ -147,9 +148,7 @@ describe('single-relation and non-relational queries stay with the one-hop parse
test('linear time on a long adversarial input', () => {
const q = `${'founders of investors of '.repeat(20)}x`.slice(0, 512);
- const started = performance.now();
- parseRelationalPlan(q);
- expect(performance.now() - started).toBeLessThan(50);
+ expect(cpuMs(() => parseRelationalPlan(q))).toBeLessThan(50);
});
});
diff --git a/test/remote-body.test.ts b/test/remote-body.test.ts
index 7cf89362e3..262ae88799 100644
--- a/test/remote-body.test.ts
+++ b/test/remote-body.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';
import { sanitizeRemoteBody } from '../src/core/remote-body.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, renderFactsTable } from '../src/core/facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
function facts(world: string, privateClaim: string): string {
return renderFactsTable([
@@ -27,9 +28,8 @@ describe('strict remote body sanitizer', () => {
// Facts markers took seconds here; a forward scan has ample headroom.
const blockCount = 16_000;
const body = `${TAKES_FENCE_BEGIN}\nx\n${TAKES_FENCE_END}\n`.repeat(blockCount);
- const start = performance.now();
- const result = sanitizeRemoteBody(body);
- const elapsedMs = performance.now() - start;
+ let result = '';
+ const elapsedMs = cpuMs(() => { result = sanitizeRemoteBody(body); });
expect(result).toBe('\n'.repeat(blockCount));
expect(elapsedMs).toBeLessThan(1_000);
});
diff --git a/test/search/output-redaction.test.ts b/test/search/output-redaction.test.ts
index 3d5be478d1..0c3f4730e1 100644
--- a/test/search/output-redaction.test.ts
+++ b/test/search/output-redaction.test.ts
@@ -6,6 +6,7 @@ import {
} from '../../src/core/search/output-redaction.ts';
import type { OperationContext } from '../../src/core/ops/contract.ts';
import { encodeDeepResearchId } from '../../src/core/deep-research-id.ts';
+import { cpuMs } from '../helpers/cpu-time.ts';
const key = 'sk-proj-' + 'syntheticfixture19'.repeat(3);
const bearer = 'syntheticbareecho19'.repeat(3);
@@ -103,9 +104,8 @@ describe('bounded retrieval display redaction', () => {
const text = ('redis://:-eyJ-'.repeat(2000) + '@ ' + 'Bearer ' + 'A'.repeat(4000));
let deep: unknown = { text: key };
for (let i = 0; i < 1000; i++) deep = { nested: deep };
- const start = performance.now();
- const output = redactRetrievalOutput([{ chunk_text: text }], { deep });
- expect(performance.now() - start).toBeLessThan(2000);
+ let output!: { results: { chunk_text: string }[]; meta: { deep: unknown } };
+ expect(cpuMs(() => { output = redactRetrievalOutput([{ chunk_text: text }], { deep }); })).toBeLessThan(2000);
expect(JSON.stringify(output.meta)).toContain(OUTPUT_REDACTION_LIMIT);
expect(output.results[0].chunk_text.includes('A'.repeat(4000))).toBe(false);
});
@@ -138,6 +138,8 @@ const keyLabel = ['PRIVATE', 'KEY'].join(' ');
const begin = (label = keyLabel) => `${fence}BEGIN ${label}${fence}`;
const end = (label = keyLabel) => `${fence}END ${label}${fence}`;
const redact = (text: string) => redactRetrievalOutput([{ chunk_text: text }], {}).results[0]!.chunk_text;
+// Process CPU, not cpuMs's thread CPU: an injected allocating PEM-scan regression read 2151 ms thread vs 3582 ms process (GC threads), under this 2000 ms bound on the thread.
+function processCpuMs(fn: () => unknown): number { const s = process.cpuUsage(); fn(); const u = process.cpuUsage(s); return (u.user + u.system) / 1000; }
describe('retrieval output: assignment rule and #5348 shapes (B1/B2)', () => {
test('KEY=value assignments reach the caller redacted, with no fragment of the value', () => {
@@ -249,9 +251,7 @@ describe('retrieval output: assignment rule and #5348 shapes (B1/B2)', () => {
test('20k unterminated fences and END-only fences scan in linear time when uncapped', () => {
for (const input of [`${begin('PUBLIC KEY')}\n`.repeat(20_000), `${begin()}\n`.repeat(20_000), `${end()}\n`.repeat(20_000)]) {
- const t0 = performance.now();
- redactRetrievalOutput([{ chunk_text: input }], {}, { uncapped: true });
- expect(performance.now() - t0).toBeLessThan(2000);
+ expect(processCpuMs(() => redactRetrievalOutput([{ chunk_text: input }], {}, { uncapped: true }))).toBeLessThan(2000);
}
});
});
diff --git a/test/secret-scan-perf.test.ts b/test/secret-scan-perf.test.ts
index fd933dbe1a..69c25e4d94 100644
--- a/test/secret-scan-perf.test.ts
+++ b/test/secret-scan-perf.test.ts
@@ -22,9 +22,10 @@
* ECHO_MAX_VALUE_CHARS, 4096-char values), so what they guard is a constant
* factor, which a size ratio cannot see.
*
- * Every timing, ratio or bound, is process CPU time, which measures the work
- * rather than how long the scheduler made it wait (a wall-clock 400 ms bound
- * read 409 ms at 32 busy slots on a shared CI VM).
+ * Every timing, ratio or bound, is CPU time on the test's thread
+ * (helpers/cpu-time.ts), which measures the work rather than how long the
+ * scheduler made it wait (a wall-clock 400 ms bound read 409 ms at 32 busy
+ * slots on a shared CI VM).
*
* Every credential-shaped value is synthetic and runtime-joined from >= 2
* fragments; constant names keep scanner keywords away from the `=`.
@@ -41,32 +42,36 @@
import { describe, expect, test } from 'bun:test';
import { createHash } from 'crypto';
import { ECHO_MAX_UNIQUE, ECHO_MAX_VALUE_CHARS, privateKeySpans, redactFindings, scanText } from '../src/core/secret-scan.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
const SCALE = 10;
const MAX_RATIO = 30;
const RATIO_TIMEOUT_MS = 60_000;
-function cpuMs(fn: () => void): number {
- const start = process.cpuUsage();
- fn();
- const used = process.cpuUsage(start);
- return (used.user + used.system) / 1000;
-}
+// Process CPU, not cpuMs's thread CPU, for the repetitive-tail bound: an injected allocating echo-sweep regression
+// passed it 3 of 3 on thread CPU (standalone: 1712 ms thread vs 3231 ms process, GC threads) and failed at 2386 ms on process CPU.
+function processCpuMs(fn: () => unknown): number { const s = process.cpuUsage(); fn(); const u = process.cpuUsage(s); return (u.user + u.system) / 1000; }
+
+/** Thread CPU time advances in scheduler ticks (~4 ms on Linux), so each timed window repeats its call until it holds at least this much. */
+const MIN_WINDOW_MS = 40;
/**
- * cpu(large) / cpu(small) for one call on inputs SCALE apart, timed back to back in this process. Process CPU
- * time, not wall clock: a run that waits for a busy CPU accrues none, so load on a shared VM moves neither side
- * (under 6 busy loops at nice 10, wall-clock ratios of the same pair ranged 0-376x, CPU-time ratios 5-18x).
- * `small` runs SCALE times per window so its sub-millisecond time is well above the clock's resolution. The best
- * of up to 3 pairs, stopping at the first under MAX_RATIO; a regression that grows with the input is over
- * MAX_RATIO in every pair. The caller's correctness run warms `large`.
+ * cpu(large) / cpu(small) per call on inputs SCALE apart, timed back to back on this thread. CPU time, not wall
+ * clock: a run that waits for a busy CPU accrues none, so load on a shared VM moves neither side (under 6 busy
+ * loops at nice 10, wall-clock ratios of the same pair ranged 0-376x, CPU-time ratios 5-18x). `large` repeats
+ * `reps` times per window, the smallest power of two that fills MIN_WINDOW_MS, and `small` SCALE times as often,
+ * so both windows are about as long. The best of up to 3 pairs, stopping at the first under MAX_RATIO; a
+ * regression that grows with the input is over MAX_RATIO in every pair. The caller's correctness run warms `large`.
*/
function scalingRatio(small: () => unknown, large: () => unknown): number {
small();
+ const repeat = (fn: () => unknown, n: number) => cpuMs(() => { for (let k = 0; k < n; k++) fn(); }) / n;
+ let reps = 1;
+ while (repeat(large, reps) * reps < MIN_WINDOW_MS) reps *= 2;
let best = Infinity;
for (let pair = 0; pair < 3 && !(best < MAX_RATIO); pair++) {
- const t = cpuMs(() => { for (let k = 0; k < SCALE; k++) small(); }) / SCALE;
- best = Math.min(best, cpuMs(() => { large(); }) / Math.max(t, 0.05));
+ const t = repeat(small, SCALE * reps);
+ best = Math.min(best, repeat(large, reps) / Math.max(t, 0.005));
}
return best;
}
@@ -370,7 +375,7 @@ describe(`the echo pass is at most ${ECHO_MAX_UNIQUE} substring sweeps over the
gc?.(true);
const before = process.memoryUsage();
let result!: ReturnType<typeof redactFindings>;
- const ms = cpuMs(() => { result = redactFindings(text); });
+ const ms = processCpuMs(() => { result = redactFindings(text); });
const after = process.memoryUsage();
expect(result.redactions.length).toBe(ECHO_MAX_UNIQUE);
expect(/A{20}/.test(result.text)).toBe(false);
diff --git a/test/timeline-citations.test.ts b/test/timeline-citations.test.ts
index 59a9bfad35..e98822e204 100644
--- a/test/timeline-citations.test.ts
+++ b/test/timeline-citations.test.ts
@@ -6,6 +6,7 @@ import { parseTimelineEntries } from '../src/core/link-extraction.ts';
import { extractTimelineFromContent, hasExtractorDetail, retractRemovedTimelineEntries } from '../src/core/timeline-extract.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { renderMaterializedBullet } from '../src/core/persistence/canonical-projections.ts';
+import { cpuMs } from './helpers/cpu-time.ts';
describe('#6184 inline-citation timeline parsing', () => {
test('a comment-only line after a citation is a paragraph boundary, not the summary', () => {
@@ -42,17 +43,15 @@ describe('#6184 write-back guard', () => {
describe('#6184 comment handling stays linear (security review: a remote put_page body must not stall the parser)', () => {
test('lines of empty comment runs that end in text parse in milliseconds', () => {
const body = `Met alice-example. [Source: Slack import, 2026-10-04]\n${Array.from({ length: 20 }, () => `${'<!---->'.repeat(40)}x`).join('\n')}`;
- const started = performance.now();
- const entries = parseInlineCitationTimelineEntries(body);
- expect(performance.now() - started).toBeLessThan(1500);
+ let entries: ReturnType<typeof parseInlineCitationTimelineEntries> = [];
+ expect(cpuMs(() => { entries = parseInlineCitationTimelineEntries(body); })).toBeLessThan(1500);
expect(entries.map(e => e.date)).toEqual(['2026-10-04']);
}, 60_000);
test('many unclosed comment openers strip in linear time with the same result as before', () => {
const opened = `${'<!--'.repeat(60_000)} tail`;
- const started = performance.now();
- const stripped = stripHtmlComments(opened);
- expect(performance.now() - started).toBeLessThan(1500);
+ let stripped = '';
+ expect(cpuMs(() => { stripped = stripHtmlComments(opened); })).toBeLessThan(1500);
expect(stripped.trim()).toBe('tail');
expect(stripHtmlComments('a <!-- x --> b <!-- y')).toBe('a b y');
expect(stripHtmlComments('<!---->a<!-->b-->c')).toBe(' a c');
@@ -97,9 +96,7 @@ describe('#6226 multi-source citations and emphasis', () => {
test('emphasis unwrapping stays linear on adversarial input', () => {
const inputs = ['**a'.repeat(50_000), '*x '.repeat(50_000), '__a_'.repeat(50_000), '_'.repeat(150_000)];
for (const input of inputs) {
- const started = performance.now();
- parseInlineCitationTimelineEntries(`${input} [Source: s, 2026-01-02]`);
- expect(performance.now() - started).toBeLessThan(1_000);
+ expect(cpuMs(() => parseInlineCitationTimelineEntries(`${input} [Source: s, 2026-01-02]`))).toBeLessThan(1_000);
}
});