Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(large-pages): bound segmenter and body-scan work by deterministic counts, not CPU time
garrytan44310050c5b9
diff --git a/src/core/page-body/body-scan.ts b/src/core/page-body/body-scan.tsindex 424270cb97..b0fde899cd 100644--- a/src/core/page-body/body-scan.ts+++ b/src/core/page-body/body-scan.ts@@ -121,8 +121,21 @@ type Token = FenceToken | null;/** stepFenceWalk's state with the opener as its run, so a run longer than the line buffer needs no string. */interface RunWalk { open: FenceToken | null; mispaired: boolean }+/**+ * @internal Work pass 1 does, for the linearity test: bytes the line split+ * searches and the head readers read (`bytes`); bytes copied to join or keep+ * a line's carry, a long line's code-point tail or the head (`carry`); lines+ * read (`lines`); UTF-16 units the per-line passes read (`chars`: decode, NUL+ * and content endpoints, the line-head classifiers, fence tokens, the region+ * walks' held text, the long-line readers, the title readers); and region-walk+ * steps and copies (`walks`). Counts, not time, so a busy machine cannot move+ * them.+ */+export const bodyScanWork = { bytes: 0, carry: 0, lines: 0, chars: 0, walks: 0 };+/** The token stepFenceWalk reads in `s` (a trailing CR is its line ending). */function fenceToken(s: string): Token {+ bodyScanWork.chars += s.length;const c0 = s.charCodeAt(0);if (c0 !== 32 && c0 !== 96 && c0 !== 126) return null;const end = s.charCodeAt(s.length - 1) === 13 ? s.length - 1 : s.length;@@ -171,6 +184,7 @@ class RegionFenceWalk {private subFirst = false;push(line: Line): void {+ bodyScanWork.walks++;if (!line.contentStart) return;const text = this.started ? line.text : line.text.trimStart();this.stepHeld(this.walk, false);@@ -180,6 +194,7 @@ class RegionFenceWalk {}pushSub(sub: SubLine): void {+ bodyScanWork.walks++;this.stepHeld(this.walk, false);this.subFirst = !this.started;this.sub = sub;@@ -188,6 +203,7 @@ class RegionFenceWalk {}clone(): RegionFenceWalk {+ bodyScanWork.walks++;const copy = new RegionFenceWalk();copy.walk = { ...this.walk };copy.started = this.started;@@ -206,6 +222,7 @@ class RegionFenceWalk {/** scanMarkdownCode ends lines at CR too; `last` applies the region's trailing trim. */private stepHeld(walk: RunWalk, last: boolean): void {if (this.text !== null) {+ bodyScanWork.chars += this.text.length;for (const sub of (last ? this.text.trimEnd() : this.text).split('\r')) stepToken(walk, fenceToken(sub));} else if (this.sub) {const sub = this.sub;@@ -290,17 +307,20 @@ class LongLine {if (!this.truncated) this.compress(text);let last = text.length - 1;while (last >= 0 && isWs(text.charCodeAt(last))) last--;+ bodyScanWork.chars += 2 * (text.length - last);if (last >= 0) {const line = this.line;if (!line.contentStart) {let first = 0;while (isWs(text.charCodeAt(first))) first++;+ bodyScanWork.chars += 2 * first;line.contentStart = { byte: line.start + before + utf8(text.slice(0, first)), line: line.index };}this.contentEnd = this.bytes - utf8(text.slice(last + 1));}if (this.quote && this.quote.phase !== QUOTE_NO) this.stepQuote(text);if (this.lastUnit === 13) this.innerCr = true;+ bodyScanWork.chars += 2 * text.length;const cr = text.indexOf('\r');if (cr !== -1 && cr < text.length - 1) this.innerCr = true;this.lastUnit = text.charCodeAt(text.length - 1);@@ -337,7 +357,8 @@ class LongLine {}private compress(text: string): void {- for (let i = 0; i < text.length && !this.truncated; i++) {+ let i = 0;+ for (; i < text.length && !this.truncated; i++) {const c = text.charCodeAt(i);const kind = isWs(c) ? 1 : c === 42 ? 2 : 0;if (kind !== this.runKind) this.endRun();@@ -359,6 +380,7 @@ class LongLine {this.wsLastB = c;}}+ bodyScanWork.chars += i;}private endRun(): void {@@ -382,6 +404,7 @@ class LongLine {const s = this.sub;for (let i = from; i < to; i++) {if (s.phase === SUB_NONE || (s.restBad && s.endBad)) return;+ bodyScanWork.chars++;const c = text.charCodeAt(i);if (s.phase === SUB_LEAD) {if (isWs(c)) {@@ -438,6 +461,7 @@ class LongLine {private stepQuote(text: string): void {const q = this.quote!;for (let i = 0; i < text.length; i++) {+ bodyScanWork.chars++;const c = text.charCodeAt(i);const word = (c >= 97 && c <= 122) || (c >= 65 && c <= 90) || c === 95;if (q.phase === QUOTE_KEY0) {@@ -461,6 +485,7 @@ class LongLine {}private quoteValue(value: string): void {+ bodyScanWork.chars += 2 * value.length;const q = this.quote!;if (/[\r\u2028\u2029]/.test(value)) {q.phase = QUOTE_NO;@@ -500,6 +525,7 @@ class LongLine {}private scanValue(text: string, from: number): void {+ bodyScanWork.chars += text.length - from;for (let i = from; i < text.length && this.valueKind !== null; i++) {const c = text.charCodeAt(i);if (this.valueKind === 'h1') {@@ -522,6 +548,7 @@ const utf8 = (text: string) => Buffer.byteLength(text, 'utf8');function concatBytes(parts: Uint8Array[], total: number): Uint8Array {if (parts.length === 1) return parts[0]!;+ bodyScanWork.carry += total;const out = new Uint8Array(total);let at = 0;for (const part of parts) { out.set(part, at); at += part.length; }@@ -656,6 +683,7 @@ export class BodyScanner {const all = concatBytes(this.headParts, this.totalBytes);this.headParts = [];const headBytes = complete ? all : all.subarray(0, FRONTMATTER_HEAD_MAX_BYTES);+ bodyScanWork.bytes += headBytes.length;let text: string;try {text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(headBytes, { stream: !complete });@@ -667,6 +695,7 @@ export class BodyScanner {const bounded = !complete && (firstContent === -1 || text[firstContent] === '-');const prefix = bounded ? text.slice(0, text.lastIndexOf('\n') + 1) : text;if (bounded && !/\S/.test(prefix)) return this.unbounded('first_line');+ bodyScanWork.bytes += 3 * prefix.length;const head = parseMarkdownHead(prefix, this.opts);this.head = head;this.headEnd = utf8(prefix);@@ -690,11 +719,13 @@ export class BodyScanner {this.bodyFileStart = this.headEnd - utf8(head.body);} else {const literal = Buffer.from(head.body, 'utf8');+ bodyScanWork.carry += literal.length;this.literalBytes = literal.length;for (let k = 0; k < literal.length; k++) if (literal[k] === 10) this.literalNewlines++;this.bodyFileStart = this.headEnd;this.feed(literal);}+ bodyScanWork.bytes += this.bodyFileStart;for (let k = 0; k < this.bodyFileStart; k++) if (all[k] === 10) this.fileNewlinesBeforeBody++;this.feed(all.subarray(this.bodyFileStart));}@@ -711,12 +742,14 @@ export class BodyScanner {while (!this.refusal) {const nl = bytes.indexOf(10, from);const end = nl === -1 ? bytes.length : nl;+ bodyScanWork.bytes += end - from + 1;if (this.long || this.carryBytes + end - from > this.lineBufferBytes) {this.feedLong(bytes.subarray(from, end));if (nl === -1 || this.refusal) return;this.endLong(true);} else if (nl === -1) {if (from < end) {+ bodyScanWork.carry += end - from;this.carry.push(bytes.slice(from));this.carryBytes += end - from;}@@ -768,6 +801,7 @@ export class BodyScanner {private onLine(bytes: Uint8Array, hasNewline: boolean): void {const start = this.pos;const index = this.lineIndex++;+ bodyScanWork.lines++;this.pos = start + bytes.length + (hasNewline ? 1 : 0);let text: string;try {@@ -776,7 +810,9 @@ export class BodyScanner {this.refusal = { kind: 'invalid_utf8', offset: this.fileOffset(start) + firstInvalidUtf8(bytes) };return;}+ bodyScanWork.chars += 2 * bytes.length + 2 * text.length;if (bytes.indexOf(0) !== -1) this.noteNul(start, index);+ if (this.quoteWatched(start)) bodyScanWork.chars += text.length;if (this.quoteWatched(start) && !this.watchQuote(text, hasNewline, quoteAmbiguousFrontmatterLine(text) !== null, text.endsWith('\r'))) return;const lead = text.search(/\S/);let contentStart: Pos | null = null;@@ -795,6 +831,7 @@ export class BodyScanner {private feedLong(bytes: Uint8Array): void {let long = this.long;if (!long) {+ bodyScanWork.lines++;const index = this.lineIndex++;const line: Line = { index, start: this.pos, text: '', hasNewline: false, contentStart: null, contentEnd: null };const e = this.embedded;@@ -817,6 +854,7 @@ export class BodyScanner {at += take;if (long.tail.length > 0) slice = concatBytes([long.tail, slice], long.tail.length + slice.length);const cut = codePointCut(slice);+ bodyScanWork.carry += slice.length - cut;long.tail = slice.slice(cut);this.decodeLong(slice.subarray(0, cut));}@@ -825,6 +863,7 @@ export class BodyScanner {private decodeLong(piece: Uint8Array): void {if (piece.length === 0) return;const long = this.long!;+ bodyScanWork.chars += 2 * piece.length;let text: string;try {text = this.decoder.decode(piece);@@ -848,6 +887,7 @@ export class BodyScanner {private drainLong(long: LongLine): void {if (!long.targets) return;+ bodyScanWork.walks += long.targets.length;for (const sub of long.subs) for (const walk of long.targets) walk.pushSub(sub);long.subs.length = 0;}@@ -896,6 +936,7 @@ export class BodyScanner {*/private lineHead(line: Line): RegionFenceWalk[] {const { text, contentStart } = line;+ bodyScanWork.chars += 4 * text.length;const trimmed = contentStart ? text.trim() : '';const targets: RegionFenceWalk[] = [];@@ -912,6 +953,7 @@ export class BodyScanner {else if (kind === 'dash' && this.firstContent) this.pendingDash = { candidate: this.newCandidate(line), opener, mispaired };}for (const candidate of new Set([this.firstQuoted, this.firstOutside])) {+ bodyScanWork.walks++;if (!candidate || candidate.line.index >= line.index) continue;if (!candidate.timelineFirst && contentStart) candidate.timelineFirst = contentStart;targets.push(candidate.timelineWalk);@@ -929,7 +971,10 @@ export class BodyScanner {/** The rest of the line once it has ended: `fence` is its token for the sentinel walk, `value` its text for the title readers. */private lineEnd(line: Line, fence: Token, value: string | null): void {if (!this.decided) stepToken(this.sentinelWalk, fence);- if (this.titleLine && value !== null) this.bodyTitle = h1TitleLineValue(value);+ if (this.titleLine && value !== null) {+ bodyScanWork.chars += value.length;+ this.bodyTitle = h1TitleLineValue(value);+ }this.stepEmbeddedTitle(line, value);if (line.contentStart) {this.firstContent ??= line;@@ -945,6 +990,7 @@ export class BodyScanner {}const pending = this.bareCandidate;if (pending) {+ bodyScanWork.chars += line.text.length;const kind = bareTimelineSectionLine(line.text, pending.bullets);if (kind === 'end' || kind === 'other') {this.bareCandidate = null;@@ -967,6 +1013,7 @@ export class BodyScanner {/** inferTitleFromEmbeddedFrontmatter, one line at a time. */private stepEmbeddedTitle(line: Line, value: string | null): void {const e = this.embedded;+ if (e.state !== 'done') bodyScanWork.chars += line.text.length + (value?.length ?? 0);if (e.state === 'start') {if (!line.contentStart) return;e.state = line.hasNewline && /^---[ \t]*\r?$/.test(line.text.trimStart()) ? 'block' : 'done';diff --git a/src/core/page-body/region-scan.ts b/src/core/page-body/region-scan.tsindex b71387b75d..fd7b28af1f 100644--- a/src/core/page-body/region-scan.ts+++ b/src/core/page-body/region-scan.ts@@ -27,8 +27,19 @@ import { PROTECTED_PAIRS } from '../remote-body.ts';import { PEM_BEGIN_RE, PEM_BODY_MAX_CHARS, PEM_END_RE, pemBackwardStart, pemForwardEnd } from '../secret-scan.ts';import { SEGMENT_MAX_BYTES } from './limits.ts';+/**+ * @internal Work the scans do, for the linearity tests: UTF-16 units the line+ * split, token search, fence probe, byte counting and inline-code scan read+ * (`chars`); projection units the PEM scan appends, searches, walks back over,+ * claims and copies when it trims its buffer (`pem`); and PEM bookkeeping+ * entries visited (`entries`: pending cuts, claims, fences, read-aheads).+ * Counts, not time, so a busy machine cannot move them.+ */+export const regionScanWork = { chars: 0, pem: 0, entries: 0 };+/** UTF-8 byte length of `s.slice(from, to)` without slicing. */export function utf8Len(s: string, from = 0, to = s.length): number {+ regionScanWork.chars += to - from;if (from === 0 && to === s.length && to > 64) return Buffer.byteLength(s, 'utf8');let n = 0;for (let i = from; i < to; i++) {@@ -75,6 +86,7 @@ export function newLineSplit(pos: number, at: LinePosition): LineSplit {/** Split `chunk` into lines and long-line pieces, in order; `final` flushes the last line. */export function splitLines(split: LineSplit, chunk: string, final: boolean, emit: (e: SplitEvent) => void): void {+ regionScanWork.chars += chunk.length;let i = 0;if (split.cr) {if (chunk.length === 0 && !final) return;@@ -126,6 +138,7 @@ function endLine(split: LineSplit, content: string, term: string, emit: (e: Spliemit({ kind: 'piece', text: content, byteStart: split.pos, first: false, term, at: split.at });split.pos += utf8Len(content) + termBytes;} else {+ regionScanWork.chars += split.pending.length;const text = split.pending + content;const bytes = split.pendingBytes + utf8Len(content);if (bytes + termBytes > SEGMENT_MAX_BYTES) emit({ kind: 'piece', text, byteStart: split.pos, first: true, term, at: split.at });@@ -152,6 +165,7 @@ function endLine(split: LineSplit, content: string, term: string, emit: (e: Spliexport function findTokens(carry: string, text: string, tokens: readonly string[],onToken: (token: number, at: number) => boolean | void): string {const s = carry + text;+ regionScanWork.chars += s.length * tokens.length;let from = 0;const next = tokens.map(t => s.indexOf(t));for (;;) {@@ -202,7 +216,8 @@ function newFenceProbe(): FenceProbe {}function feedFenceProbe(p: FenceProbe, s: string): void {- for (let i = 0; i < s.length && p.phase !== 'none'; i++) {+ let i = 0;+ for (; i < s.length && p.phase !== 'none'; i++) {const c = s.charCodeAt(i);if (p.phase === 'indent') {if (c === 32 && p.indent < 3) { p.indent++; continue; }@@ -219,6 +234,7 @@ function feedFenceProbe(p: FenceProbe, s: string): void {if (c !== 32 && c !== 9) p.ws = false;if (!p.ws && p.sep && (p.tick || p.ch === '~')) p.phase = 'none';}+ regionScanWork.chars += i;}function probeOpens(p: FenceProbe): boolean {@@ -294,6 +310,7 @@ export function scanRegionLine(track: RegionTrack, trusted: boolean, text: strinfeedFenceProbe(probe, text);const inBlock = trusted && (track.walk.fence !== null || probeOpens(probe));let coverFrom = track.open || track.truncatedAt !== null ? 0 : -1;+ if (track.truncatedAt === null) regionScanWork.chars += text.length;if (track.truncatedAt === null && text.includes(MARKER_LEAD)) {let spans: Array<[number, number]> | null = null;let charAt = 0;@@ -301,6 +318,7 @@ export function scanRegionLine(track: RegionTrack, trusted: boolean, text: strinfindTokens('', text, MARKER_TEXTS, (i, at) => {byteAt += utf8Len(text, charAt, at);charAt = at;+ if (!spans) regionScanWork.chars += text.length;const read = !inBlock && !insideSpan(spans ??= inlineCodeSpans(text), at);const step = regionToken(track, i, byteAt, read, out);if (step === 'open') coverFrom = at;@@ -462,11 +480,13 @@ export function initialPemScan(start: PemStart): PemScanState {*/export function feedPemScan(st: PemScanState, text: string, final: boolean, onSpan: (start: number, end: number) => void): void {st.buf += text;+ regionScanWork.pem += text.length;st.final = final;discoverPem(st, 'begin');discoverPem(st, 'end');processPem(st, onSpan);const resolved = pemResolvedTo(st);+ regionScanWork.entries += st.cuts.length;for (const cut of st.cuts) if (!cut.done && cut.at <= resolved) cut.done = pemCutCheck(st, cut.at);trimPem(st);}@@ -487,6 +507,7 @@ export function markPemCut(st: PemScanState, at: number): void {/** The answer for a marked cut (removing it), or null while unresolved. */export function takePemCut(st: PemScanState, at: number): { clean: boolean; start: PemStart } | null {+ regionScanWork.entries += st.cuts.length;const i = st.cuts.findIndex(c => c.at === at && c.done);if (i === -1) return null;return st.cuts.splice(i, 1)[0]!.done!;@@ -494,6 +515,7 @@ export function takePemCut(st: PemScanState, at: number): { clean: boolean; star/** The answer for a marked cut taken before it resolved: never clean; where a resumed scan restarts. */export function forcePemCut(st: PemScanState, at: number): { clean: boolean; start: PemStart } {+ regionScanWork.entries += st.cuts.length;const i = st.cuts.findIndex(c => c.at === at);const done = i === -1 ? undefined : st.cuts.splice(i, 1)[0]!.done;if (done) return done;@@ -521,6 +543,7 @@ export function pemExposedFrom(st: PemScanState): number {for (let i = buf.length, open = true; i > lo; open = false) {let j = i;while (j > lo && buf.charCodeAt(j - 1) !== 10 && !(buf.charCodeAt(j - 1) === 110 && buf.charCodeAt(j - 2) === 92)) j--;+ regionScanWork.pem += i - j + 1;if (!(open ? PEM_LINE_OPEN : PEM_LINE_DONE).test(buf.slice(j, i))) break;start = j;i = buf.charCodeAt(j - 1) === 10 ? j - 1 : j - 2;@@ -537,6 +560,7 @@ function discoverPem(st: PemScanState, kind: 'begin' | 'end'): void {const end = st.base + st.buf.length;const held = st.final ? end : heldFrom(st.buf, prefix, find.from - st.base) + st.base;re.lastIndex = find.from - st.base;+ regionScanWork.pem += st.buf.length - re.lastIndex;for (let m = re.exec(st.buf); m && m.index + st.base < held; m = re.exec(st.buf)) {const fence = { begin: kind === 'begin', start: m.index + st.base, end: m.index + st.base + m[0].length };queue.push(fence);@@ -553,7 +577,9 @@ function heldFrom(buf: string, prefix: string, from: number): number {let i = len;const lim = Math.max(from, len - PEM_FENCE_HOLD_MAX);while (i > lim && isFenceClass(buf.charCodeAt(i - 1))) i--;+ regionScanWork.pem += 2 * (len - i);for (let q = buf.indexOf(prefix, i); q !== -1; q = buf.indexOf(prefix, q + 1)) {+ regionScanWork.pem += len - q;FENCE_REST.lastIndex = q + prefix.length;if (FENCE_REST.test(buf)) return q;}@@ -605,6 +631,7 @@ function processPem(st: PemScanState, onSpan: (start: number, end: number) => vo}function claimPem(st: PemScanState, start: number, end: number, onSpan: (start: number, end: number) => void): void {+ regionScanWork.pem += end - start;st.claims.push({ start, end });onSpan(start, end);}@@ -620,6 +647,7 @@ function pemCutCheck(st: PemScanState, at: number): { clean: boolean; start: Pemconst lineStart = st.buf.charCodeAt(rel - 1) === 10;const start: PemStart = lineStart ? 'line_start' : 'mid_line';const spans = (r: { start: number; end: number }) => r.start < at && at < r.end;+ regionScanWork.entries += st.claims.length + st.fences.length + st.readAhead.length;if (st.claims.some(spans) || st.fences.some(spans) || st.readAhead.some(r => r.start < at && r.until > at)) return { clean: false, start };if (!lineStart) return { clean: !isPemLineChar(st.buf.charCodeAt(rel - 1)), start };return { clean: !(bodyLikeBefore(st.buf, rel - 1) && bodyLikeFrom(st.buf, rel)), start };@@ -637,6 +665,7 @@ export function pemBodyLike(line: string): boolean {function bodyLikeFrom(s: string, from: number): boolean {let any = false;for (let i = from; i < s.length; i++) {+ regionScanWork.pem++;const c = s.charCodeAt(i);if (c === 10 || c === 13) return any;if (i - from >= PEM_LINE_PROBE) return true;@@ -651,6 +680,7 @@ function bodyLikeBefore(s: string, nl: number): boolean {if (s.charCodeAt(i - 1) === 13) i--;let any = false;for (let k = i - 1; k >= 0; k--) {+ regionScanWork.pem++;const c = s.charCodeAt(k);if (c === 10) return any;if (i - k > PEM_LINE_PROBE) return true;@@ -665,8 +695,11 @@ function trimPem(st: PemScanState): void {const f = headFence(st);if (f) keep = Math.min(keep, f.start);keep -= 2 * PEM_CONTEXT_CHARS;+ regionScanWork.entries += st.cuts.length;for (const cut of st.cuts) if (!cut.done) keep = Math.min(keep, cut.at - PEM_LINE_PROBE - 2);if (st.final || keep - st.base < 4 * PEM_CONTEXT_CHARS) return;+ regionScanWork.pem += st.buf.length - (keep - st.base);+ regionScanWork.entries += st.fences.length + st.claims.length + st.readAhead.length;st.buf = st.buf.slice(keep - st.base);st.base = keep;st.fences = st.fences.filter(x => x.end > keep);diff --git a/src/core/page-body/segmenter.ts b/src/core/page-body/segmenter.tsindex 847c207407..82fa4aec08 100644--- a/src/core/page-body/segmenter.ts+++ b/src/core/page-body/segmenter.ts@@ -81,7 +81,22 @@ const GEAR: Uint32Array = (() => {return table;})();+/**+ * @internal Work the segmenter does, for the linearity tests: line and piece+ * events handled (`lines`); UTF-16 units the per-line passes read (`chars`:+ * cut-candidate classifiers and gear hash, cut blockers, line state, the+ * projection, a long piece's fit and remainder); bookkeeping entries visited+ * (`entries`: held segments, removals re-sorted, projection pieces copied,+ * PEM spans and region ends scanned at each emit, kept ranges); and units of+ * each emitted segment's raw and projected text read by its join, byte copy,+ * hash, projection parts, outline, dates and line count (`emitted`). The line+ * split, token search and PEM scan count in `regionScanWork`. Counts, not+ * time, so a busy machine cannot move them.+ */+export const segmenterWork = { lines: 0, chars: 0, entries: 0, emitted: 0 };+function gearHit(line: string): boolean {+ segmenterWork.chars += line.length;let h = 0;for (let i = 0; i < line.length; i++) {const c = line.charCodeAt(i);@@ -246,8 +261,10 @@ export class Segmenter {markPemCut(this.pem, this.proj);this.feedPem(false);this.release();+ segmenterWork.entries += this.closed.length;let held = this.closed.reduce((n, seg) => n + seg.bytes, 0);while (held > HOLD_MAX_BYTES) {+ segmenterWork.entries += this.closed.length;const seg = this.closed.shift()!;held -= seg.bytes;seg.exit.pem = forcePemCut(this.pem, seg.projEnd);@@ -258,6 +275,7 @@ export class Segmenter {}private onEvent(e: SplitEvent): void {+ segmenterWork.lines++;if (e.kind === 'line') {const bytes = utf8Len(e.text) + e.term.length;const kind = this.candidate(e.text, e.at);@@ -278,6 +296,7 @@ export class Segmenter {if (fit.chars > 0) this.piece(text.slice(0, fit.chars), byteStart, e.first && byteStart === e.byteStart, null);byteStart += fit.bytes;text = text.slice(fit.chars);+ segmenterWork.chars += text.length;this.st.at = 'mid';this.close('forced');}@@ -287,6 +306,7 @@ export class Segmenter {private candidate(text: string, at: SplitEvent['at']): SegmentCutKind | null {const size = this.cur.bytes;if (at !== 'lf' || size < SEGMENT_MIN_BYTES) return null;+ segmenterWork.chars += text.length;const st = this.st;let kind: SegmentCutKind | null = null;let rank = 4;@@ -301,6 +321,7 @@ export class Segmenter {}private blocked(text: string): boolean {+ segmenterWork.chars += text.length;const st = this.st;if (st.trusted.walk.fence || st.trusted.open || st.untrusted.open || st.withdrawal.open) return true;if (st.pemMargin.trusted !== null || st.pemMargin.untrusted !== null) return true;@@ -317,6 +338,7 @@ export class Segmenter {scanRegionLine(st.trusted, true, text, byteStart, term, outT);scanRegionLine(st.untrusted, false, text, byteStart, term, outU);const whole = text + term;+ segmenterWork.chars += whole.length;const markers = whole.includes('gbrain:materialized') ? materializedMarkerSpans(whole) : [];this.project(whole, text.length, byteStart, outT, outU, markers);const b = text.lastIndexOf(FACTS_FENCE_BEGIN);@@ -345,6 +367,7 @@ export class Segmenter {scanRegionPiece(st.trusted, true, text, byteStart, first, term, outT);scanRegionPiece(st.untrusted, false, text, byteStart, first, term, outU);const whole = text + (term ?? '');+ segmenterWork.chars += whole.length;this.project(whole, text.length, byteStart, outT, outU, []);let last = -1;st.withdrawal.carry = findTokens(st.withdrawal.carry, text, [FACTS_FENCE_BEGIN, FACTS_FENCE_END], t => { last = t; });@@ -377,6 +400,8 @@ export class Segmenter {const plain = out.covers.length === 0 && markers.length === 0;const keep = plain ? (whole.length ? [[0, whole.length] as [number, number]] : []) : keptRanges(whole, textLen, out, markers);const projected = plain ? whole : keep.map(([a, b]) => whole.slice(a, b)).join('');+ segmenterWork.chars += projected.length;+ segmenterWork.entries += keep.length;const carryKey = isTrusted ? 'carryTrusted' : 'carryUntrusted';const marginKey = isTrusted ? 'trusted' : 'untrusted';let found = -1;@@ -411,8 +436,10 @@ export class Segmenter {else this.cur.removals.push(r);};const covers: Cover[] = out.covers.map(c => ({ ...c, to: c.to === textLen && out.coverTerm ? whole.length : c.to }));+ segmenterWork.entries += covers.length + markers.length * (covers.length + 1);for (const [a, b] of markers) if (!covers.some(c => a < c.to && c.from < b)) add({ start: at(a), end: at(b), kind: 'marker', regionStart: at(a) });for (const c of covers) add({ start: at(c.from), end: at(c.to), kind: c.pair === 0 ? 'facts' : c.pair === 1 ? 'takes' : 'tail', regionStart: c.start });+ segmenterWork.entries += this.cur.removals.length;this.cur.removals.sort((x, y) => x.start - y.start);}@@ -429,7 +456,10 @@ export class Segmenter {const mid = (lo + hi) >> 1;if (pieces[mid]!.proj + pieces[mid]!.text.length < resolved) lo = mid + 1; else hi = mid;}- if (lo > 0) this.projPieces = pieces.slice(lo);+ if (lo > 0) {+ segmenterWork.entries += pieces.length - lo;+ this.projPieces = pieces.slice(lo);+ }}/** Stored byte of projection offset `pos` (`end`: the offset just past a char). */@@ -467,6 +497,8 @@ export class Segmenter {private emit(seg: ClosedSegment, guardFrom: number | null): SegmentOut {const raw = seg.parts.join('');const bytes = Buffer.from(raw, 'utf8');+ segmenterWork.emitted += raw.length + 2 * bytes.length;+ segmenterWork.entries += seg.removals.length + 2 * this.pemSpans.length + this.regionEnds.size;const segEnd = seg.byteStart + seg.bytes;const tailFrom = seg.tailFrom;const regions: StoredRegion[] = [];@@ -494,6 +526,7 @@ export class Segmenter {this.pemSpans = this.pemSpans.filter(s => s.end > segEnd);for (const [start, end] of this.regionEnds) if (end <= segEnd) this.regionEnds.delete(start);regions.sort((a, b) => a.start - b.start || b.end - a.end);+ segmenterWork.entries += regions.length;const parts = segmentProjectionParts(raw, regions, seg.byteStart);let projected = '';let projBytes = 0;@@ -504,6 +537,7 @@ export class Segmenter {...(p.region!.open_end !== undefined ? { open_end: p.region!.open_end } : {}) });if (p.kind === 'text' || p.kind === 'pem') { projected += p.text; projBytes += utf8Len(p.text); }}+ segmenterWork.emitted += 2 * projected.length;const { outline, dateMin, dateMax } = this.outlineOf(projected);seg.exit.outline = { ...this.outline };let projLines = 0;@@ -548,6 +582,7 @@ export class Segmenter {}skip = false;const next = nl === -1 ? text.length : nl + 1;+ segmenterWork.emitted += next - at;byte += utf8Len(text, at, next);at = next;}@@ -579,10 +614,14 @@ function fitChars(text: string, room: number): { chars: number; bytes: number }const d = c >= 0xd800 && c <= 0xdbff ? text.charCodeAt(i + 1) : 0;const pair = d >= 0xdc00 && d <= 0xdfff;const n = c < 0x80 ? 1 : c < 0x800 ? 2 : pair ? 4 : 3;- if (bytes + n > room) return { chars: i, bytes };+ if (bytes + n > room) {+ segmenterWork.chars += i;+ return { chars: i, bytes };+ }bytes += n;if (pair) i++;}+ segmenterWork.chars += text.length;return { chars: text.length, bytes };}@@ -639,11 +678,16 @@ export interface ProjectionPart {*/export function segmentProjectionParts(raw: string, regions: readonly StoredRegion[], byteStart: number): ProjectionPart[] {const sorted = [...regions].sort((a, b) => a.start - b.start || b.end - a.end);+ segmenterWork.entries += sorted.length;const charAt = byteToChar(raw, sorted.flatMap(r => [r.start, r.end]));const parts: ProjectionPart[] = [];let cursor = 0;const text = (to: number) => {- if (to > cursor) parts.push({ kind: 'text', start: cursor, end: to, text: raw.slice(charAt.get(cursor)!, charAt.get(to)!) });+ if (to > cursor) {+ const part = raw.slice(charAt.get(cursor)!, charAt.get(to)!);+ segmenterWork.emitted += part.length;+ parts.push({ kind: 'text', start: cursor, end: to, text: part });+ }};charAt.set(0, 0);for (let i = 0; i < sorted.length; i++) {@@ -662,6 +706,7 @@ export function segmentProjectionParts(raw: string, regions: readonly StoredRegilet newlines = 0;let k = from;for (let j = i + 1; j < sorted.length && sorted[j]!.start < r.end; j++) {+ segmenterWork.entries++;const inner = sorted[j]!;newlines += countNewlines(raw, k, charAt.get(inner.start)!);k = Math.max(k, charAt.get(inner.end)!);@@ -681,6 +726,7 @@ export function segmentProjectionParts(raw: string, regions: readonly StoredRegi}function countNewlines(s: string, from: number, to: number): number {+ segmenterWork.emitted += Math.max(0, to - from);let n = 0;for (let i = s.indexOf('\n', from); i !== -1 && i < to; i = s.indexOf('\n', i + 1)) n++;return n;@@ -703,6 +749,7 @@ function byteToChar(s: string, offsets: readonly number[]): Map<number, number>}out.set(target, i);}+ segmenterWork.emitted += i;return out;}diff --git a/test/helpers/cpu-time.ts b/test/helpers/cpu-time.tsindex 0beda48d13..1492e18c56 100644--- a/test/helpers/cpu-time.ts+++ b/test/helpers/cpu-time.ts@@ -12,52 +12,6 @@ export function cpuMs(fn: () => unknown): number {return (used.user + used.system) / 1000;}-/**- * 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` 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; minWindowMs?: number } = {},-): number {- const rounds = opts.rounds ?? 3;- const runs = opts.runs ?? 3;- const minWindowMs = opts.minWindowMs ?? 200;- small();- large();- 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++) {- 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)]!;-}-/*** cpuMs for an async span: thread CPU from the call until it settles. It counts everything the thread runs in* between (PGLite's WASM engine runs on the calling thread) and nothing the span waits for (I/O on other threads,diff --git a/test/helpers/work-counts.ts b/test/helpers/work-counts.tsnew file mode 100644index 0000000000..8de546d20e--- /dev/null+++ b/test/helpers/work-counts.ts@@ -0,0 +1,76 @@+/**+ * Linearity bounds over deterministic work counters (`@internal` objects of+ * integer counts the code under test increments in its scanning loops), for+ * tests that would otherwise compare CPU time across input sizes. A count does+ * not depend on the machine, so a co-tenant that slows one size cannot move it.+ */++/** Doubling the input must less than this many times each counter (linear 2, quadratic 4). */+export const MAX_DOUBLING_RATIO = 2.1;++/**+ * A counter needs this many counts at the small size before its doubling ratio+ * is checked; its per-byte bound always applies. Below it a counter visits the+ * bookkeeping of a handful of segments or cuts (a 1 MiB fence is one segment,+ * 2 MiB two), so its ratio reads how many segments each size happens to cut+ * (3 entries against 13), not growth per byte.+ */+export const MIN_RATIO_COUNT = 10_000;++export type Counters = Record<string, Record<string, number>>;+export type Work = Record<string, number>;++/** Zero every counter, run `fn`, and return each count as `group.field`. */+export function countWork(counters: Counters, fn: () => unknown): Work {+ for (const group of Object.values(counters)) for (const k of Object.keys(group)) group[k] = 0;+ fn();+ const work: Work = {};+ for (const [name, group] of Object.entries(counters)) for (const [k, v] of Object.entries(group)) work[`${name}.${k}`] = v;+ return work;+}++export interface Sample { bytes: number; work: Work }++/**+ * Every bound a linear run at `small` and twice the input at `large` breaks:+ * a count above `perByte[key]` times its input bytes, or a count at least+ * MIN_RATIO_COUNT at the small size that grows MAX_DOUBLING_RATIO times or more.+ */+export function linearityViolations(small: Sample, large: Sample, perByte: Record<string, number>): string[] {+ const out: string[] = [];+ for (const [key, limit] of Object.entries(perByte)) {+ for (const [side, s] of [['small', small], ['large', large]] as const) {+ const per = s.work[key]! / s.bytes;+ if (!(per <= limit)) out.push(`${key}: ${per.toFixed(3)} per byte at the ${side} size exceeds ${limit}`);+ }+ const ratio = large.work[key]! / small.work[key]!;+ if (small.work[key]! >= MIN_RATIO_COUNT && !(ratio < MAX_DOUBLING_RATIO)) out.push(`${key}: doubling ratio ${ratio.toFixed(3)} reaches ${MAX_DOUBLING_RATIO}`);+ }+ return out;+}++/** `key: count (per byte)` for each counter, and the doubling ratio, for the test log. */+export function describeWork(small: Sample, large: Sample): string {+ return Object.keys(small.work).map(key => {+ const ratio = small.work[key] ? (large.work[key]! / small.work[key]!).toFixed(3) : '-';+ return `${key} ${small.work[key]}/${large.work[key]} (${(small.work[key]! / small.bytes).toFixed(3)}/B, x${ratio})`;+ }).join(', ');+}++/**+ * Run `fn`, then burn `extra` times its thread CPU time on the same thread: a+ * stand-in for a co-tenant on a sibling vCPU that slows one size's run (CI read+ * 1.06-1.65x). Returns the thread CPU of `fn` and of the whole call, in ms.+ */+export function withCpuInflation(fn: () => unknown, extra: number): { workMs: number; totalMs: number } {+ const start = process.threadCpuUsage();+ const ms = () => {+ const used = process.threadCpuUsage(start);+ return (used.user + used.system) / 1000;+ };+ fn();+ const workMs = ms();+ let spin = 0;+ while (ms() < workMs * (1 + extra)) spin = (spin * 31 + 7) >>> 0;+ return { workMs, totalMs: ms() + (spin & 0) };+}diff --git a/test/large-pages/body-scan-linear.test.ts b/test/large-pages/body-scan-linear.test.tsindex 013978ae7d..24d9065725 100644--- a/test/large-pages/body-scan-linear.test.ts+++ b/test/large-pages/body-scan-linear.test.ts@@ -1,25 +1,43 @@/*** Wave B (spec 3.1): pass 1 stays linear in the file size.*- * Protects: the streamed body scan does O(bytes) work: CPU time at 2n bytes is- * under 2.5x the time at n bytes (n = 4 MiB, median of three best-of-three ratios) on a page dense with every state the scan- * carries (quoted sentinels inside fences, `---` lines awaiting a Timeline- * H2, bare-section headings that fail their lookahead, CRLF, astral text).- * Fails when: a step re-reads buffered input per line or per chunk (a- * re-decoded prefix, a re-split carry, a per-candidate rescan); the forced- * probe below runs exactly such a variant and asserts the ratio catches it.+ * Protects: the streamed body scan does O(bytes) work on a page dense with+ * every state the scan carries (quoted sentinels inside fences, `---` lines+ * awaiting a Timeline H2, bare-section headings that fail their lookahead,+ * CRLF, astral text). The scan counts its work in `bodyScanWork`: bytes the+ * line split searches and the head readers read, bytes copied to join a carry+ * or keep a code-point tail, lines read, units the per-line passes read+ * (decode, NUL and content endpoints, line-head classifiers, fence tokens,+ * region walks, long-line and title readers), and region-walk steps. Counts,+ * not CPU time: a co-tenant on a sibling vCPU inflates one size's thread CPU+ * by 1.06-1.65x on CI, which no count sees.+ * Fails when: at n and 2n bytes (n = 4 MiB) a counter exceeds its per-byte+ * bound, or (with at least MIN_RATIO_COUNT counts at n) grows 2.1x or more:+ * a step that re-reads buffered input per line or per chunk (a re-decoded+ * prefix, a re-split carry, a per-candidate rescan). The forced probe re-reads+ * the whole buffered prefix through a fresh BodyScanner before each 32 KiB+ * push and asserts the counts catch it; the inflation probe burns 60% extra+ * thread CPU around the large size and asserts the counts and bounds hold+ * (the old CPU-time ratio read 3.16x there, 1.93x plain, past its 2.5x bound).+ * A new loop over the input or over carried state must count its work too.* Why existing coverage misses it: split-body-linear covers the whole-string* splitBody, not the streaming scanner.- * Seams: none; the quadratic variant wraps the public push API.- * Measured (12 runs, 4 in parallel on a 4-core machine, cpuScalingRatio): the- * scan 1.94-2.04x, the prefix-re-reading probe 3.30-3.65x.+ * Seams: `bodyScanWork` (@internal counters in body-scan.ts).+ * Measured (deterministic; per byte at n, doubling ratio): bytes 1.24 x1.81+ * (the 256 KiB head is read once), carry 0.077 x1.01 (the head join), lines+ * 0.049 x2.00, chars 11.15 x2.00, walks 0.112 x2.00. Prefix-re-reading probe+ * (n = 512 KiB): lines, chars and walks x4.51, bytes x3.28.*/import { describe, expect, test } from 'bun:test';-import { BodyScanner } from '../../src/core/page-body/body-scan.ts';-import { cpuScalingRatio } from '../helpers/cpu-time.ts';+import { BodyScanner, bodyScanWork } from '../../src/core/page-body/body-scan.ts';+import {+ countWork, describeWork, linearityViolations, MAX_DOUBLING_RATIO, withCpuInflation, type Sample,+} from '../helpers/work-counts.ts';const MB = 1024 * 1024;-const RATIO_LIMIT = 2.5;+/** Per input byte, about 2x the measured value or more. */+const PER_BYTE = { 'scan.bytes': 3, 'scan.carry': 0.5, 'scan.lines': 1, 'scan.chars': 24, 'scan.walks': 0.5 };+const PROBE_PUSH = 32 * 1024;function page(bytes: number): Uint8Array {const unit = [@@ -36,33 +54,42 @@ function scan(bytes: Uint8Array): void {expect(scanner.finish().kind).toBe('ok');}-/** The deliberately quadratic variant: re-decodes everything buffered so far before each 1 KiB push. */+/** The deliberately quadratic variant: re-reads everything buffered so far through a fresh scanner before each push. */function quadraticScan(bytes: Uint8Array): void {const scanner = new BodyScanner('notes/linear-example.md', { validate: true });- const decoder = new TextDecoder();- for (let at = 0; at < bytes.length; at += 1024) {- decoder.decode(bytes.subarray(0, at));- scanner.push(bytes.subarray(at, at + 1024));+ for (let at = 0; at < bytes.length; at += PROBE_PUSH) {+ new BodyScanner('notes/linear-example.md', { validate: true }).push(bytes.subarray(0, at));+ scanner.push(bytes.subarray(at, at + PROBE_PUSH));}expect(scanner.finish().kind).toBe('ok');}-function ratio(run: (bytes: Uint8Array) => void, n: number, runs: number): number {- const small = page(n);- const large = page(2 * n);- return cpuScalingRatio(() => run(small), () => run(large), { runs });-}+const sample = (bytes: Uint8Array, run: (bytes: Uint8Array) => void): Sample => ({ bytes: bytes.length, work: countWork({ scan: bodyScanWork }, () => run(bytes)) });-describe('body scan cost', () => {- test(`CPU time at 2n stays under ${RATIO_LIMIT}x the time at n`, () => {- const r = ratio(scan, 4 * MB, 3);- console.log(`[body-scan-linear] scan: ${r.toFixed(2)}x`);- expect(r).toBeLessThan(RATIO_LIMIT);+describe('body scan work', () => {+ test('work per byte is bounded and doubles with the input', () => {+ const a = sample(page(4 * MB), scan);+ const b = sample(page(8 * MB), scan);+ console.log(`[body-scan-linear] scan: ${describeWork(a, b)}`);+ expect(linearityViolations(a, b, PER_BYTE)).toEqual([]);}, 60_000);- test('forced probe: the same ratio fails a scan that re-reads its buffered prefix', () => {- const r = ratio(quadraticScan, MB, 3);- console.log(`[body-scan-linear] prefix-re-reading scan (quadratic probe): ${r.toFixed(2)}x`);- expect(r).toBeGreaterThan(RATIO_LIMIT);+ test('forced probe: the same bounds fail a scan that re-reads its buffered prefix', () => {+ const a = sample(page(MB / 2), quadraticScan);+ const b = sample(page(MB), quadraticScan);+ console.log(`[body-scan-linear] prefix-re-reading scan (quadratic probe): ${describeWork(a, b)}`);+ expect(b.work['scan.chars']! / a.work['scan.chars']!).toBeGreaterThan(MAX_DOUBLING_RATIO);+ expect(b.work['scan.lines']! / a.work['scan.lines']!).toBeGreaterThan(MAX_DOUBLING_RATIO);}, 120_000);++ test('inflation probe: 60% extra CPU on the large size cannot move the counts', () => {+ const a = sample(page(4 * MB), scan);+ const large = page(8 * MB);+ const plain = sample(large, scan);+ let cpu = { workMs: 0, totalMs: 0 };+ const inflated = sample(large, bytes => { cpu = withCpuInflation(() => scan(bytes), 0.6); });+ console.log(`[body-scan-linear] large size under a co-tenant: ${cpu.workMs.toFixed(0)} ms work, ${cpu.totalMs.toFixed(0)} ms thread CPU`);+ expect(inflated.work).toEqual(plain.work);+ expect(linearityViolations(a, inflated, PER_BYTE)).toEqual([]);+ }, 60_000);});diff --git a/test/large-pages/segmenter-linear.slow.test.ts b/test/large-pages/segmenter-linear.slow.test.tsindex 674d59ef91..9d18a1ed95 100644--- a/test/large-pages/segmenter-linear.slow.test.ts+++ b/test/large-pages/segmenter-linear.slow.test.ts@@ -5,95 +5,141 @@* 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: 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 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.+ * 2. Measures work, not time: `segmenterWork` (line and piece events; units the+ * per-line passes read: cut-candidate classifiers and gear hash, blockers,+ * line state, projection, long-piece fit and remainder; bookkeeping entries+ * visited; units each emitted segment's join, copy, hash, projection parts,+ * outline and dates read) and `regionScanWork` (units the line split, token+ * search with its carry, fence probe, byte counts and inline-code scan read;+ * projection units the PEM scan appends, searches, walks, claims and copies+ * on trim; PEM cut, claim and fence entries visited). Thread CPU time grows+ * when a co-tenant on a sibling vCPU slows one size (1.06-1.65x on CI), so a+ * time ratio flakes on linear code; counts are the same on every machine.+ * A new loop over the input or over carried state must count its work too.+ * 3. Fails when: at n and 2n bytes, for prose, short lines, one newline-free+ * line, a giant fence, an unterminated protected region and key-dense text,+ * or for the resuming append, a counter exceeds its per-byte bound or (with+ * at least MIN_RATIO_COUNT counts at n) grows 2.1x or more.+ * 4. Forced probes: a cut search that rescans everything pushed so far (the+ * whole prefix re-pushed into a fresh Segmenter before each 16 KiB push,+ * 256 and 512 KiB of giant fence) and an append path that resegments the+ * whole page per 64 KiB append (256 and 512 KiB) both run through the+ * counted code, and their doubling ratios exceed the bound.+ * 5. Inflation probe: the large size run while a co-tenant burns 60% extra+ * thread CPU gives the same counts and passes the same bounds. The old+ * CPU-time exponent at 4x read 1.34-1.48 there for every shape and the+ * resuming append (0.93-1.04 plain), past its 1.3 bound.+ * 6. Measured (deterministic; per byte at n, doubling ratio x):+ * - mixed page (1 MiB): lines 0.014 x1.99, chars 3.55 x2.01, entries 0.043+ * x1.90, emitted 7.60 x2.01, region chars 11.4 x2.00, pem 3.06 x2.00.+ * - short lines (512 KiB): lines 0.50, chars 3.44 x2.02, entries 1.13,+ * emitted 8.0, region chars 11.0, pem 3.26 (x2.00 where not given).+ * - one newline-free line (4 MiB): chars 4.19 x2.02, emitted 8.0, region+ * chars 19.0, pem 3.11 x2.01; lines 14, entries 41 and region entries 21+ * sit under the ratio floor.+ * - giant fence (1 MiB): lines 0.107, chars 4.67, entries 0.24, emitted+ * 8.0, region chars 11.7, pem 3.23 x2.01.+ * - unterminated protected region (1 MiB): lines 0.136, chars 2.61,+ * entries 0.27, emitted 4.0, region chars 8.64, pem 0.+ * - key-dense text (2 MiB): chars 3.92, entries 0.092 x2.02, emitted 5.69,+ * region chars 10.6, pem 4.38, region entries 0.045 x2.02.+ * - resuming append (2 MiB): lines 0.045 x2.01, chars 11.2, entries 0.126+ * x1.98, emitted 24.6, region chars 37.3, pem 9.78 x1.99 (region+ * entries 1,010, under the floor; at 1 MiB pem read x2.09, so this test+ * runs at 2 MiB, where the last segment's size averages out).+ * - probes: rescanning cut search lines x3.88, chars x4.22, region chars+ * x3.88, pem x3.97; whole-page resegmenting per append chars x3.19,+ * region chars x3.14.*/import { describe, expect, test } from 'bun:test';import { initialEntryState } from '../../src/core/page-body/entry-state.ts';-import { Segmenter, segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';-import { cpuScalingRatio } from '../helpers/cpu-time.ts';+import { regionScanWork } from '../../src/core/page-body/region-scan.ts';+import { Segmenter, segmenterWork, segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';import { mulberry32 } from '../helpers/seeded-random.ts';import { bigPage, PEM_BLOCK, segmentOptions } from '../helpers/segment-bodies.ts';+import {+ countWork, describeWork, linearityViolations, MAX_DOUBLING_RATIO, withCpuInflation, type Sample,+} from '../helpers/work-counts.ts';const MB = 1024 * 1024;-const SCALE = 4;-const MAX_EXPONENT = 1.3;const entry = () => initialEntryState({ region: 'truth' });-/** 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(SCALE * small);- return Math.log(cpuScalingRatio(() => run(a), () => run(b))) / Math.log(SCALE);-}+/** Per input byte, about 1.5-2x the largest measured value of any shape. */+const SEGMENT_PER_BYTE = {+ 'segmenter.lines': 1, 'segmenter.chars': 8, 'segmenter.entries': 2, 'segmenter.emitted': 12,+ 'region.chars': 32, 'region.pem': 8, 'region.entries': 0.1,+};+/** The resuming append re-reads the last segment per 64 KiB append. */+const APPEND_PER_BYTE = {+ 'segmenter.lines': 1, 'segmenter.chars': 16, 'segmenter.entries': 2, 'segmenter.emitted': 40,+ 'region.chars': 64, 'region.pem': 16, 'region.entries': 0.1,+};++const counters = { segmenter: segmenterWork, region: regionScanWork };+const sample = (body: string, run: (body: string) => unknown): Sample => ({ bytes: Buffer.byteLength(body), work: countWork(counters, () => run(body)) });const page = bigPage(mulberry32(7), 4.5 * MB);const prefix = (bytes: number) => page.slice(0, page.indexOf('\n', bytes) + 1);const segmentAll = (body: string) => segmentString(body, entry(), segmentOptions('trusted'));-/** Segment `body` in 256 KiB pushes, keeping only a count (ingest streams segments out; holding them all would time the GC). */-function segmentStreaming(body: string): number {+/** Segment `body` in `push`-char pushes, keeping only a count (ingest streams segments out). */+function segmentStreaming(body: string, push = 256 * 1024): number {const seg = new Segmenter(entry(), segmentOptions('trusted'));let n = 0;- for (let i = 0; i < body.length; i += 256 * 1024) n += seg.push(body.slice(i, i + 256 * 1024)).length;+ for (let i = 0; i < body.length; i += push) n += seg.push(body.slice(i, i + push)).length;return n + seg.finish().length;}+const PROBE_PUSH = 16 * 1024;+/**- * The quadratic cut search: before each 4 KiB push it searches everything pushed so far for the last heading cut- * candidate, as a cut decision that rescans the open input instead of carrying its scan state would.+ * The quadratic cut search: before each 16 KiB push it re-reads everything pushed so far through a fresh+ * Segmenter, as a cut decision that rescans the open input instead of carrying its scan state would.*/function segmentRescanningCuts(body: string): number {- const seg = new Segmenter(entry(), segmentOptions('trusted'));let n = 0;- let candidates = 0;- for (let i = 0; i < body.length; i += 4 * 1024) {- const pushed = body.slice(0, i);- for (const cut = /\n## /g; cut.exec(pushed);) candidates++;- n += seg.push(body.slice(i, i + 4 * 1024)).length;- }- return n + seg.finish().length + (candidates & 0);+ for (let at = PROBE_PUSH; at < body.length + PROBE_PUSH; at += PROBE_PUSH) n = segmentStreaming(body.slice(0, at), PROBE_PUSH);+ return n;}-describe('the segmenter scales linearly', () => {- const shapes: Array<[string, (bytes: number) => string, number]> = [- ['mixed page', prefix, 1 * MB],- ['short lines', bytes => 'a\n'.repeat(bytes / 2), MB / 2],- ['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],- ];+const shapes: Array<[string, (bytes: number) => string, number]> = [+ ['mixed page', prefix, 1 * MB],+ ['short lines', bytes => 'a\n'.repeat(bytes / 2), MB / 2],+ ['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],+];++describe('the segmenter does linear work', () => {for (const [name, make, small] of shapes) {- 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);+ test(`${name}: work per byte is bounded and doubles with the input`, () => {+ const a = sample(make(small), segmentStreaming);+ const b = sample(make(2 * small), segmentStreaming);+ console.log(`[segmenter-linear] ${name}: ${describeWork(a, b)}`);+ expect(linearityViolations(a, b, SEGMENT_PER_BYTE)).toEqual([]);}, 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 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);+ const a = sample(giantFence[1](MB / 4), segmentRescanningCuts);+ const b = sample(giantFence[1](MB / 2), segmentRescanningCuts);+ console.log(`[segmenter-linear] giant fence, rescanning cut search (quadratic probe): ${describeWork(a, b)}`);+ expect(b.work['segmenter.chars']! / a.work['segmenter.chars']!).toBeGreaterThan(MAX_DOUBLING_RATIO);+ expect(b.work['region.chars']! / a.work['region.chars']!).toBeGreaterThan(MAX_DOUBLING_RATIO);+ }, 120_000);++ test('inflation probe: 60% extra CPU on the large size cannot move the counts', () => {+ const small = prefix(1 * MB);+ const large = prefix(2 * MB);+ const a = sample(small, segmentStreaming);+ const plain = sample(large, segmentStreaming);+ let cpu = { workMs: 0, totalMs: 0 };+ const inflated = sample(large, body => { cpu = withCpuInflation(() => segmentStreaming(body), 0.6); });+ console.log(`[segmenter-linear] mixed page, large size under a co-tenant: ${cpu.workMs.toFixed(0)} ms work, ${cpu.totalMs.toFixed(0)} ms thread CPU`);+ expect(inflated.work).toEqual(plain.work);+ expect(linearityViolations(a, inflated, SEGMENT_PER_BYTE)).toEqual([]);}, 120_000);});@@ -127,15 +173,18 @@ 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(`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);+ test('appended text: work per byte is bounded and doubles with the input', () => {+ const a = sample(ascii(2 * MB), appendResuming);+ const b = sample(ascii(4 * MB), appendResuming);+ console.log(`[segmenter-linear] appends resuming: ${describeWork(a, b)}`);+ expect(linearityViolations(a, b, APPEND_PER_BYTE)).toEqual([]);}, 120_000);test('forced probe: resegmenting the whole page per append exceeds the 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);+ const a = sample(ascii(MB / 4), appendResegmenting);+ const b = sample(ascii(MB / 2), appendResegmenting);+ console.log(`[segmenter-linear] appends resegmenting (quadratic probe): ${describeWork(a, b)}`);+ expect(b.work['segmenter.chars']! / a.work['segmenter.chars']!).toBeGreaterThan(MAX_DOUBLING_RATIO);+ expect(b.work['region.chars']! / a.work['region.chars']!).toBeGreaterThan(MAX_DOUBLING_RATIO);}, 120_000);});