perf(process): transfer chunked string buffers into RegexMatcher worker (#13428)

* perf(process): transfer chunked string buffers into RegexMatcher worker

* test(process): verify 1M RegexMatcher inventory in isolated 16 MiB subprocess
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 14:08:26 +00:00
1 parent 0f771abed0
commit 48d4b6145a
3 files changed
+224 -15

No files matched your search

+73
View File
@@ -566,3 +566,76 @@ it("validates patterns even when the worker has no candidate values", async () =
});
expect(empty).toEqual({ ok: true, value: [] });
});
it("preserves Unicode, supplementary emoji, lone surrogates, and empty strings via packed buffer", async () => {
const values = [
"",
"ascii_only",
"Δelta",
"😀_emoji",
"\uD800",
"middle",
"",
"😀_end",
];
expect(
await matchRegexValues({
operation: "search_strings",
pattern: "^(😀_|\\u{1F600}_|δ)",
caseSensitive: false,
values,
}),
).toEqual({ ok: true, value: [2, 3, 7] });
expect(
await matchRegexValues({
operation: "search_strings",
pattern: "^$",
caseSensitive: true,
values,
}),
).toEqual({ ok: true, value: [0, 6] });
expect(
await matchRegexValues({
operation: "search_strings",
pattern: "[\\uD800]",
caseSensitive: true,
values,
}),
).toEqual({ ok: true, value: [4] });
});
it("matches across mixed ASCII, Unicode, and oversized single-item chunk boundaries", async () => {
const hugeString = `${"a".repeat(300_000)}NEEDLE_${"b".repeat(100)}`;
const values = Array.from({ length: 5_000 }, (_, i) => `item_${i}`);
values[12] = "Δ_chunk0";
values[4095] = "edge_chunk0_NEEDLE";
values[4096] = "start_chunk1_ascii";
values[4500] = hugeString;
values[4501] = "😀_post_huge_NEEDLE";
values[4999] = "\uD800_tail_NEEDLE";
expect(
await matchRegexValues({
operation: "search_strings",
pattern: "NEEDLE|Δ_chunk0",
caseSensitive: true,
values,
}),
).toEqual({ ok: true, value: [12, 4095, 4500, 4501, 4999] });
const allEmpty = Array.from({ length: 4_200 }, () => "");
allEmpty[4097] = "";
expect(
await matchRegexValues({
operation: "search_strings",
pattern: "^$",
caseSensitive: true,
values: allEmpty,
}),
).toEqual({
ok: true,
value: Array.from({ length: 4_200 }, (_, i) => i),
});
});
+106 -9
View File
@@ -601,7 +601,77 @@ const parseWorkerReply = (
return { kind: "matched", indices: indices as number[] };
};
// Code is constant; caller patterns and target strings cross only workerData.
const REGEX_PACK_CHUNK_ITEMS = 4096;
const REGEX_PACK_CHUNK_CHARS = 262_144;
interface PackedRegexChunk {
readonly buffer: ArrayBuffer;
readonly encoding: "latin1" | "utf16le";
readonly startIndex: number;
readonly count: number;
}
interface PackedRegexValues {
readonly lengthsBuffer: ArrayBuffer;
readonly chunks: readonly PackedRegexChunk[];
}
interface PackedRegexTransfer {
readonly packed: PackedRegexValues;
readonly transferList: ArrayBuffer[];
}
const packRegexValues = (
values: readonly string[],
): PackedRegexTransfer | undefined => {
const count = values.length;
if (count === 0) return undefined;
const lengths = new Uint32Array(count);
const chunks: PackedRegexChunk[] = [];
const transferList: ArrayBuffer[] = [lengths.buffer];
let index = 0;
while (index < count) {
const startIndex = index;
const parts: string[] = [];
let chars = 0;
const itemLimit = Math.min(count, startIndex + REGEX_PACK_CHUNK_ITEMS);
while (index < itemLimit) {
const value = values[index]!;
const len = value.length;
if (parts.length > 0 && chars + len > REGEX_PACK_CHUNK_CHARS) break;
lengths[index] = len;
parts.push(value);
chars += len;
index += 1;
}
const joined = parts.join("");
const isAscii = Buffer.byteLength(joined, "utf8") === joined.length;
const encoding: "latin1" | "utf16le" = isAscii ? "latin1" : "utf16le";
const byteLength = isAscii ? joined.length : joined.length * 2;
const buffer = new ArrayBuffer(byteLength);
if (byteLength > 0) {
Buffer.from(buffer).write(joined, encoding);
}
chunks.push({
buffer,
encoding,
startIndex,
count: index - startIndex,
});
transferList.push(buffer);
}
return {
packed: {
lengthsBuffer: lengths.buffer,
chunks,
},
transferList,
};
};
// Code is constant; patterns cross workerData and candidate strings are
// transferred in chunked off-heap ArrayBuffers so structured cloning neither
// allocates millions of V8 heap strings upfront nor stalls on per-item bridges.
// process.getBuiltinModule loads synchronously in both CJS and ESM workers
// without async import overhead or ESM customization hook startup.
const WORKER_SOURCE = String.raw`
@@ -613,10 +683,26 @@ try {
parentPort.postMessage({ status: "invalid_pattern", reason: cause instanceof Error ? cause.message : String(cause) });
}
if (expression !== undefined) {
const { values } = workerData;
const indices = [];
for (let index = 0, length = values.length; index < length; index += 1)
if (expression.test(values[index])) indices.push(index);
if (workerData.packed !== undefined) {
const lengths = new Uint32Array(workerData.packed.lengthsBuffer);
const { chunks } = workerData.packed;
for (let c = 0; c < chunks.length; c += 1) {
const chunk = chunks[c];
const block = Buffer.from(chunk.buffer).toString(chunk.encoding);
let offset = 0;
for (let index = chunk.startIndex, end = index + chunk.count; index < end; index += 1) {
const len = lengths[index];
if (expression.test(block.slice(offset, offset + len)))
indices.push(index);
offset += len;
}
}
} else {
const { values } = workerData;
for (let index = 0, length = values.length; index < length; index += 1)
if (expression.test(values[index])) indices.push(index);
}
parentPort.postMessage({ status: "matched", indices });
}
`;
@@ -662,15 +748,26 @@ export const matchRegexValues = async (input: {
);
if (!admitted.ok) return admitted;
const { deadline, heapRequest } = admitted.value;
const transfer = packRegexValues(input.values);
let worker: Worker;
try {
worker = new Worker(WORKER_SOURCE, {
eval: true,
workerData: {
pattern: input.pattern,
caseSensitive: input.caseSensitive,
values: input.values,
},
workerData:
transfer === undefined
? {
pattern: input.pattern,
caseSensitive: input.caseSensitive,
values: input.values,
}
: {
pattern: input.pattern,
caseSensitive: input.caseSensitive,
packed: transfer.packed,
},
...(transfer === undefined
? {}
: { transferList: transfer.transferList }),
resourceLimits: { maxOldGenerationSizeMb: heapRequest.heapMiB },
});
} catch (cause: unknown) {
+45 -6
View File
@@ -466,8 +466,17 @@ it("stops a slow match at the configured deadline and names the setting", async
});
});
it("matches a trivial pattern in a real worker at the heap floor", async () => {
const directory = await createTestTempDirectory("rea-regex-heap-floor-");
const runIsolatedRegexProbe = async (
prefix: string,
buildValuesExpression: string,
pattern: string,
heapMiB: number,
): Promise<{
readonly ok: boolean;
readonly indices?: readonly number[];
readonly message?: string;
}> => {
const directory = await createTestTempDirectory(prefix);
const probe = join(directory, "probe.mjs");
const repository = fileURLToPath(new URL("../../../", import.meta.url));
const tsxApi = pathToFileURL(
@@ -482,13 +491,14 @@ it("matches a trivial pattern in a real worker at the heap floor", async () => {
probe,
`import { tsImport } from ${JSON.stringify(tsxApi)};
const { matchRegexValues } = await tsImport(${JSON.stringify(matcher)}, import.meta.url);
const values = ${buildValuesExpression};
const result = await matchRegexValues({
operation: "search_procedures",
pattern: "^a",
pattern: ${JSON.stringify(pattern)},
caseSensitive: true,
values: ["a"],
values,
heapRequest: {
heapMiB: ${String(MINIMUM_REGEX_WORKER_HEAP_REQUEST_MIB)},
heapMiB: ${String(heapMiB)},
source: "setting",
},
});
@@ -506,7 +516,21 @@ if (!result.ok) process.exitCode = 1;
timeout: 30_000,
});
expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
expect(JSON.parse(result.stdout)).toEqual({ ok: true, indices: [0] });
return JSON.parse(result.stdout) as {
readonly ok: boolean;
readonly indices?: readonly number[];
readonly message?: string;
};
};
it("matches a trivial pattern in a real worker at the heap floor", async () => {
const outcome = await runIsolatedRegexProbe(
"rea-regex-heap-floor-",
'["a"]',
"^a",
MINIMUM_REGEX_WORKER_HEAP_REQUEST_MIB,
);
expect(outcome).toEqual({ ok: true, indices: [0] });
});
it("preserves Unicode matching order and refuses a pre-cancelled match", async () => {
@@ -644,3 +668,18 @@ it("returns ordered matching indices across large batches in the supervised work
expect(matched.value[1]).toBe(2);
expect(matched.value.at(-1)).toBe(2498);
});
it("matches a 1M inventory inside a constrained 16 MiB worker heap without structured-clone OOM", async () => {
const outcome = await runIsolatedRegexProbe(
"rea-regex-1m-16mib-",
`(() => {
const list = new Array(1_000_000);
for (let i = 0; i < list.length; i += 1)
list[i] = i === 987_654 ? "sym_needle_hit_value" : \`sym_padding_entry_\${i}\`;
return list;
})()`,
"^sym_needle_",
16,
);
expect(outcome).toEqual({ ok: true, indices: [987_654] });
});