Skip to content

Commit f759357

Browse files
committed
test(parsers): measure prefix work without wall-clock limits
1 parent 3798ec5 commit f759357

2 files changed

Lines changed: 62 additions & 36 deletions

File tree

‎packages/ai/src/utils/reasoning-tag-text-partitioner.test.ts‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Reasoning tag partitioner tests cover splitting reasoning and visible text segments.
2-
import { describe, expect, it } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
3+
import * as reasoningTagParser from "../../../markdown-core/src/reasoning-tag-parser.js";
34
import {
45
createReasoningTagTextPartitioner,
56
type ReasoningTagTextDelta,
@@ -215,16 +216,35 @@ describe("createReasoningTagTextPartitioner", () => {
215216

216217
it("recovers a byte-streamed 110KB malformed quoted tag without reparsing prefixes", () => {
217218
const input = `<think data-x="${"x".repeat(110_000)}<think>hidden</think>After`;
218-
const startedAt = Date.now();
219-
const result = collectVisibleMode(
220-
input,
221-
Array.from({ length: input.length }, (_value, index) => index + 1),
222-
);
223-
224-
expect(result.text).not.toContain("hidden");
225-
expect(result.text.endsWith("After")).toBe(true);
226-
expect(result.thinking).toBe("hidden");
227-
expect(Date.now() - startedAt).toBeLessThan(30_000);
219+
let parsedCharacters = 0;
220+
const parserSpies = (
221+
["parseReasoningTagAt", "scanReasoningTags", "parseMarkdownOwnership"] as const
222+
).map((name) => {
223+
const original = reasoningTagParser[name];
224+
return vi
225+
.spyOn(reasoningTagParser, name)
226+
.mockImplementation((text: string, ...args: unknown[]) => {
227+
// Bound reparsed input independently of runner speed, and fail before quadratic work.
228+
parsedCharacters += text.length;
229+
expect(parsedCharacters).toBeLessThanOrEqual(input.length * 4);
230+
return Reflect.apply(original, undefined, [text, ...args]);
231+
});
232+
});
233+
234+
try {
235+
const result = collectVisibleMode(
236+
input,
237+
Array.from({ length: input.length }, (_value, index) => index + 1),
238+
);
239+
240+
expect(result.text).not.toContain("hidden");
241+
expect(result.text.endsWith("After")).toBe(true);
242+
expect(result.thinking).toBe("hidden");
243+
} finally {
244+
for (const spy of parserSpies) {
245+
spy.mockRestore();
246+
}
247+
}
228248
});
229249

230250
it("keeps newline-heavy malformed-tag recovery linear", () => {

‎packages/tool-call-repair/src/stream-normalizer.test.ts‎

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, expect, it } from "vitest";
1+
import { describe, expect, it, vi } from "vitest";
22
import { parseStandalonePlainTextToolCallBlocks } from "./payload.js";
33
import {
44
normalizePlainTextToolCallStreamEvents,
@@ -1068,15 +1068,7 @@ describe("normalizePlainTextToolCallStreamEvents over-cap XML", () => {
10681068
});
10691069

10701070
it("keeps a large preceding block's prefix check bounded across many later candidates (#122513)", async () => {
1071-
// codex review: hasUntrackedPrecedingContext's deep (same-length) check materialized
1072-
// the tracked prefix via materializeProtectionPrefix, which joins EVERY chunk ever
1073-
// pushed -- including the current, still-growing block's own chunks -- before
1074-
// slicing. Doing that once per candidate made a large preceding block followed by a
1075-
// bracket-dense later block Theta(precedingBlockSize x candidateCount) again. This
1076-
// must stay bounded: derive it once per block (cached) using a prefix-bounded
1077-
// accumulator, not a full join, on every one of the many candidates that follow.
1078-
// Keep the prefix exactly 200,000 characters while ending its line so the next
1079-
// block's delimiter is a real CommonMark fence, not a mid-line backtick run.
1071+
// End the preceding line so the next block opens a CommonMark fence.
10801072
const precedingBlock = `${"x".repeat(199_999)}\n`;
10811073
const fenced = [
10821074
"```toml",
@@ -1099,23 +1091,37 @@ describe("normalizePlainTextToolCallStreamEvents over-cap XML", () => {
10991091
];
11001092

11011093
let resolverCalls = 0;
1102-
const start = performance.now();
1103-
const normalized = await collectNormalizedEvents(events, {
1104-
matcher,
1105-
createPromotedToolCallEvents: () => [],
1106-
normalizeTerminalMessage: () => undefined,
1107-
protectedRangesFenceCompatible: true,
1108-
resolveProtectedRanges: (text) => {
1109-
resolverCalls += 1;
1110-
return resolveTestFenceRanges(text);
1111-
},
1112-
});
1113-
const elapsedMs = performance.now() - start;
1094+
let precedingPrefixSlices = 0;
1095+
// oxlint-disable-next-line typescript/unbound-method -- called below with the intercepted string receiver.
1096+
const originalSlice = String.prototype.slice;
1097+
const sliceSpy = vi
1098+
.spyOn(String.prototype, "slice")
1099+
.mockImplementation(function (this: string, start, end) {
1100+
if (start === 0 && end === precedingBlock.length && this.length >= end) {
1101+
precedingPrefixSlices += 1;
1102+
}
1103+
return originalSlice.call(this, start, end);
1104+
});
1105+
let normalized: Record<string, unknown>[];
1106+
try {
1107+
normalized = await collectNormalizedEvents(events, {
1108+
matcher,
1109+
createPromotedToolCallEvents: () => [],
1110+
normalizeTerminalMessage: () => undefined,
1111+
protectedRangesFenceCompatible: true,
1112+
resolveProtectedRanges: (text) => {
1113+
resolverCalls += 1;
1114+
return resolveTestFenceRanges(text);
1115+
},
1116+
});
1117+
} finally {
1118+
sliceSpy.mockRestore();
1119+
}
11141120

11151121
expect(resolverCalls).toBeLessThanOrEqual(3);
1116-
// A large preceding block re-materialized per candidate would push this into the
1117-
// hundreds of milliseconds; bounded (cached) prefix validation stays well under it.
1118-
expect(elapsedMs).toBeLessThan(200);
1122+
// Rechecking the entire preceding block for every candidate makes work quadratic.
1123+
// Count full-prefix operations so this bound does not depend on runner speed.
1124+
expect(precedingPrefixSlices).toBeLessThanOrEqual(4);
11191125
expect(textDeltas(normalized).join("")).toBe(precedingBlock + fenced);
11201126
});
11211127

0 commit comments

Comments
 (0)