Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(large-pages): measure segmenter linearity as a growth exponent at 4x with 200 ms samples (stress flake root cause)

garrytan888377919b1d
diff --git a/test/helpers/cpu-time.ts b/test/helpers/cpu-time.ts
index f71e9bafb7..0beda48d13 100644
--- a/test/helpers/cpu-time.ts
+++ b/test/helpers/cpu-time.ts
@@ -14,23 +14,46 @@ export function cpuMs(fn: () => unknown): number {
/**
* CPU-time scaling ratio `large / small` for a linearity bound: after one warm-up run of each, `rounds` independent
- * ratios, each the best of `runs` calls at the large size over the best of `runs` at the small size, and their median.
- * A collection landing in one call skews one round's best at most, and the median drops that round; collecting before
- * each call made it worse, because every measured call then regrew the heap (allocation-heavy shapes went from a 2.30x
- * to a 2.98x worst case in 36 runs).
+ * ratios, each the best of `runs` samples at the large size over the best of `runs` at the small size, and their
+ * median. A sample repeats its call until the window holds at least `minWindowMs` of thread CPU and takes the mean
+ * per call: thread CPU advances in about 4 ms steps on Linux, so a single 28 ms call reads anywhere from 24 to 32 ms
+ * and a best-of-three small side alone moved a linear 2.2x to 2.66x. Small and large samples alternate, so a slow
+ * spell on a shared core has to cover both sizes to move a ratio. A collection landing in one sample skews one
+ * round's best at most, and the median drops that round; collecting before each call made it worse, because every
+ * measured call then regrew the heap (allocation-heavy shapes went from a 2.30x to a 2.98x worst case in 36 runs).
*/
-export function cpuScalingRatio(small: () => unknown, large: () => unknown, opts: { rounds?: number; runs?: number } = {}): number {
+export function cpuScalingRatio(
+ small: () => unknown,
+ large: () => unknown,
+ opts: { rounds?: number; runs?: number; minWindowMs?: number } = {},
+): number {
const rounds = opts.rounds ?? 3;
const runs = opts.runs ?? 3;
+ const minWindowMs = opts.minWindowMs ?? 200;
small();
large();
- const best = (fn: () => unknown) => {
- let ms = Infinity;
- for (let k = 0; k < runs; k++) ms = Math.min(ms, cpuMs(fn));
- return ms;
+ const sample = (fn: () => unknown) => {
+ const start = process.threadCpuUsage();
+ let calls = 0;
+ let ms = 0;
+ do {
+ fn();
+ calls++;
+ const used = process.threadCpuUsage(start);
+ ms = (used.user + used.system) / 1000;
+ } while (ms < minWindowMs);
+ return ms / calls;
};
const ratios: number[] = [];
- for (let round = 0; round < rounds; round++) ratios.push(best(large) / best(small));
+ for (let round = 0; round < rounds; round++) {
+ let s = Infinity;
+ let l = Infinity;
+ for (let k = 0; k < runs; k++) {
+ s = Math.min(s, sample(small));
+ l = Math.min(l, sample(large));
+ }
+ ratios.push(l / s);
+ }
ratios.sort((a, b) => a - b);
return ratios[Math.floor(rounds / 2)]!;
}
diff --git a/test/large-pages/segmenter-linear.slow.test.ts b/test/large-pages/segmenter-linear.slow.test.ts
index 19c00b28e0..674d59ef91 100644
--- a/test/large-pages/segmenter-linear.slow.test.ts
+++ b/test/large-pages/segmenter-linear.slow.test.ts
@@ -5,19 +5,25 @@
* 1. Protects: ingest of a 256 MB page and repeated appends to a large page
* stay O(bytes); a cut decision that rescans the open segment, or an
* append that resegments the page, would make both quadratic.
- * 2. Fails when: doubling the input more than 2.5x the CPU time (linear is
- * 2x, quadratic 4x), for prose, short lines, one newline-free line, a
- * giant fence, an unterminated protected region and key-dense text.
- * 3. Forced probes: the same ratio check run on a cut search that rescans
+ * 2. Fails when: the growth exponent k in CPU time ~ bytes^k, measured at 4x
+ * the input, reaches 1.3 (linear 1, quadratic 2), for prose, short lines,
+ * one newline-free line, a giant fence, an unterminated protected region
+ * and key-dense text, or for the resuming append.
+ * 3. Forced probes: the same exponent check run on a cut search that rescans
* everything pushed so far, and on an append path that resegments the whole
* prefix on each append (the quadratic variants), exceeds the bound, so the
* check can tell the two apart.
* 4. After one warm-up run of each size, the ratio is the median of three
- * rounds, each the best of three runs per size in thread CPU time
- * (cpuScalingRatio).
- * 5. Measured (8 runs, 4 in parallel on a 4-core machine): every shape and the
- * resuming append 1.84-2.18x; the probes, a cut search that rescans the
- * pushed input 2.85-3.04x and whole-page resegmenting per append 3.52-3.77x.
+ * rounds, each the best of three samples per size in thread CPU time; a
+ * sample repeats the call until it holds 200 ms (cpuScalingRatio).
+ * 5. Why 4x and an exponent: at 2x with a 2.5x bound, linear shapes read up to
+ * 2.54x and the rescanning probe as low as 2.66x on a loaded 4-core machine,
+ * and CI's stress gate failed 2 of 10 runs (newline-free line, whose 28 ms
+ * small call sits on the 4 ms thread-CPU step, and the unterminated region).
+ * Measuring at 4x halves the exponent error of the same noise.
+ * 6. Measured (16 runs, 4 and 8 in parallel on a 4-core machine): every shape
+ * and the resuming append 0.95-1.06; the probes, the rescanning cut search
+ * 1.59-1.68 and whole-page resegmenting per append 1.69-1.77.
*/
import { describe, expect, test } from 'bun:test';
import { initialEntryState } from '../../src/core/page-body/entry-state.ts';
@@ -27,13 +33,15 @@ import { mulberry32 } from '../helpers/seeded-random.ts';
import { bigPage, PEM_BLOCK, segmentOptions } from '../helpers/segment-bodies.ts';
const MB = 1024 * 1024;
-const BOUND = 2.5;
+const SCALE = 4;
+const MAX_EXPONENT = 1.3;
const entry = () => initialEntryState({ region: 'truth' });
-function ratio(make: (bytes: number) => string, small: number, run: (body: string) => unknown): number {
+/** The growth exponent k in time ~ bytes^k, from the CPU-time ratio at SCALE times the input (linear 1, quadratic 2). */
+function exponent(make: (bytes: number) => string, small: number, run: (body: string) => unknown): number {
const a = make(small);
- const b = make(2 * small);
- return cpuScalingRatio(() => run(a), () => run(b));
+ const b = make(SCALE * small);
+ return Math.log(cpuScalingRatio(() => run(a), () => run(b))) / Math.log(SCALE);
}
const page = bigPage(mulberry32(7), 4.5 * MB);
@@ -66,26 +74,26 @@ function segmentRescanningCuts(body: string): number {
describe('the segmenter scales linearly', () => {
const shapes: Array<[string, (bytes: number) => string, number]> = [
- ['mixed page', prefix, 2 * MB],
+ ['mixed page', prefix, 1 * MB],
['short lines', bytes => 'a\n'.repeat(bytes / 2), MB / 2],
- ['one newline-free line', bytes => 'x'.repeat(bytes), 8 * MB],
+ ['one newline-free line', bytes => 'x'.repeat(bytes), 4 * MB],
['giant fence', bytes => '```\n' + '## not a heading\n\ncode line\n'.repeat(bytes / 28), 1 * MB],
['unterminated protected region', bytes => '<!--- gbrain:takes:begin -->\n' + '## secret\n\nwords here\n'.repeat(bytes / 23), 1 * MB],
['key-dense text', bytes => PEM_BLOCK.repeat(bytes / PEM_BLOCK.length), 2 * MB],
];
for (const [name, make, small] of shapes) {
- test(`${name}: twice the input takes under ${BOUND}x the time`, () => {
- const r = ratio(make, small, segmentStreaming);
- console.log(`[segmenter-linear] ${name}: ${r.toFixed(2)}x`);
- expect(r).toBeLessThan(BOUND);
+ test(`${name}: growth exponent under ${MAX_EXPONENT}`, () => {
+ const k = exponent(make, small, segmentStreaming);
+ console.log(`[segmenter-linear] ${name}: exponent ${k.toFixed(2)}`);
+ expect(k).toBeLessThan(MAX_EXPONENT);
}, 120_000);
}
test('forced probe: a cut search that rescans the pushed input exceeds the bound', () => {
const giantFence = shapes.find(([name]) => name === 'giant fence')!;
- const r = ratio(giantFence[1], giantFence[2], segmentRescanningCuts);
- console.log(`[segmenter-linear] giant fence, rescanning cut search (quadratic probe): ${r.toFixed(2)}x`);
- expect(r).toBeGreaterThan(BOUND);
+ const k = exponent(giantFence[1], giantFence[2], segmentRescanningCuts);
+ console.log(`[segmenter-linear] giant fence, rescanning cut search (quadratic probe): exponent ${k.toFixed(2)}`);
+ expect(k).toBeGreaterThan(MAX_EXPONENT);
}, 120_000);
});
@@ -119,15 +127,15 @@ describe('appends through a stored entry state', () => {
expect(appendResuming(body).map(s => [s.byteStart, s.bytes.length, s.cutKind])).toEqual(segmentAll(body).map(s => [s.byteStart, s.bytes.length, s.cutKind]));
});
- test(`twice the appended text takes under ${BOUND}x the time`, () => {
- const r = ratio(ascii, 1 * MB, appendResuming);
- console.log(`[segmenter-linear] appends resuming: ${r.toFixed(2)}x`);
- expect(r).toBeLessThan(BOUND);
+ test(`appended text: growth exponent under ${MAX_EXPONENT}`, () => {
+ const k = exponent(ascii, 1 * MB, appendResuming);
+ console.log(`[segmenter-linear] appends resuming: exponent ${k.toFixed(2)}`);
+ expect(k).toBeLessThan(MAX_EXPONENT);
}, 120_000);
test('forced probe: resegmenting the whole page per append exceeds the bound', () => {
- const r = ratio(ascii, 1 * MB, appendResegmenting);
- console.log(`[segmenter-linear] appends resegmenting (quadratic probe): ${r.toFixed(2)}x`);
- expect(r).toBeGreaterThan(BOUND);
+ const k = exponent(ascii, MB / 4, appendResegmenting);
+ console.log(`[segmenter-linear] appends resegmenting (quadratic probe): exponent ${k.toFixed(2)}`);
+ expect(k).toBeGreaterThan(MAX_EXPONENT);
}, 120_000);
});