mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 09:56:23 +00:00
perf(process): pool regex workers across match calls (#14114)
* perf(process): pool regex workers across match calls matchRegexValues spawned a fresh worker_threads Worker per call (~10.5 ms measured, vs ~0.9 ms pooled for a trivial match on 1-5k candidates). Workers are now pooled by heap class (max 4, 10 s idle reap, unref'd while idle): the worker protocol is message-driven, a worker is reused only after a clean matched/invalid-pattern reply, and deadline, abort, error, exit or malformed replies retire it so a stuck pattern can never poison the pool. Queueing for a busy pool counts toward the caller's deadline. Results, heap and deadline errors, and cancellation semantics are unchanged. Closes #14110. Verified: RegexMatcher + RegexMatcherReply + boundary regexMatcher + HopperRegexSearch + IdaOperationRunner tests (91+15), check:fast, and a 15-call benchmark (10.5 ms -> 0.9 ms per call). * test(process): use the admitted deadline source spelling in the pool test * fix(process): enforce queue deadlines, reclaim idle regex workers, and await retirement Address pooled-worker review findings: the matching deadline now starts before pool acquisition (queue waiters expire and expired jobs are never posted), idle workers of another heap class are reclaimed instead of blocking a changed heap setting, queued worker startup failures reject into the normal Cannot-start path, and non-clean outcomes await worker termination before returning so close() cannot finish while matching work lives. Add RegexMatcherPool.test.ts with a construction-counting fake worker proving reuse across clean calls and termination-before-return plus replacement after a deadline. * fix(process): allocate regex workers through one capacity path Acquisition retired an idle worker and spawned directly, bypassing waiter order: retirement served an older waiter into the freed slot and acquisition then spawned a fifth worker. Acquisition now only takes an idle match or enqueues, and serveRegexWaiters owns every spawn/reclaim decision in waiter order. Add a mock-pool regression proving a fifth queued search deadlines at four constructions. * fix(process): reclaim incompatible regex workers on one path Keep a stopping worker counted until terminate settles, and let release ask the shared allocator so a different heap does not wait out the idle reap. A failed stop stays owned and is recorded beside the match error. * fix(process): mark background regex-worker stops and release test gates Typed lint rejects an unmarked beginStopRegexWorker promise, so the allocator's fire-and-forget stops are explicit. Pool tests release held workers in finally, including when an assertion fails first. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
This commit is contained in:
4 files changed
+864
-36
No files matched your search
@@ -547,6 +547,48 @@ it.each([
|
||||
},
|
||||
);
|
||||
|
||||
it("returns the structured deadline when a real worker pattern does not finish, then matches again", async () => {
|
||||
const first = await matchRegexValues({
|
||||
operation: "search_strings",
|
||||
pattern: "storage",
|
||||
caseSensitive: true,
|
||||
values: ["storage/read", "other"],
|
||||
});
|
||||
expect(first).toEqual({ ok: true, value: [0] });
|
||||
const stuck = await matchRegexValues({
|
||||
operation: "search_strings",
|
||||
pattern: "^(a+)+$",
|
||||
caseSensitive: true,
|
||||
values: [`${"a".repeat(40)}b`],
|
||||
deadline: { deadlineMs: 50, source: "runtime" },
|
||||
});
|
||||
if (stuck.ok) throw new Error("expected the real worker to hit its deadline");
|
||||
expect(projectAnalysisError(stuck.error)).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
operation: "search_strings",
|
||||
resource: "cpu",
|
||||
reported_limits: {
|
||||
matching_deadline_ms: 50,
|
||||
matching_deadline_source: "runtime",
|
||||
},
|
||||
limit: {
|
||||
setting: "regex.matching_deadline_ms",
|
||||
effective_value: 50,
|
||||
source: "runtime",
|
||||
unit: "ms",
|
||||
},
|
||||
},
|
||||
});
|
||||
const after = await matchRegexValues({
|
||||
operation: "search_strings",
|
||||
pattern: "storage",
|
||||
caseSensitive: true,
|
||||
values: ["storage/read"],
|
||||
});
|
||||
expect(after).toEqual({ ok: true, value: [0] });
|
||||
});
|
||||
|
||||
it("validates patterns even when the worker has no candidate values", async () => {
|
||||
const invalid = await matchRegexValues({
|
||||
operation: "search_procedures",
|
||||
|
||||
+402
-34
@@ -675,16 +675,17 @@ const packRegexValues = (values: readonly string[]): PackedRegexTransfer => {
|
||||
// process.getBuiltinModule loads synchronously in both CJS and ESM workers
|
||||
// without async import overhead or ESM customization hook startup.
|
||||
const WORKER_SOURCE = String.raw`
|
||||
const { parentPort, workerData } = process.getBuiltinModule("node:worker_threads");
|
||||
let expression;
|
||||
try {
|
||||
expression = new RegExp(workerData.pattern, workerData.caseSensitive ? "u" : "iu");
|
||||
} catch (cause) {
|
||||
parentPort.postMessage({ status: "invalid_pattern", reason: cause instanceof Error ? cause.message : String(cause) });
|
||||
}
|
||||
if (expression !== undefined) {
|
||||
const { parentPort } = process.getBuiltinModule("node:worker_threads");
|
||||
parentPort.on("message", (job) => {
|
||||
let expression;
|
||||
try {
|
||||
expression = new RegExp(job.pattern, job.caseSensitive ? "u" : "iu");
|
||||
} catch (cause) {
|
||||
parentPort.postMessage({ status: "invalid_pattern", reason: cause instanceof Error ? cause.message : String(cause) });
|
||||
return;
|
||||
}
|
||||
const indices = [];
|
||||
const { lengthsBuffer, chunks } = workerData.packed;
|
||||
const { lengthsBuffer, chunks } = job.packed;
|
||||
const lengths = new Uint32Array(lengthsBuffer);
|
||||
for (let c = 0; c < chunks.length; c += 1) {
|
||||
const chunk = chunks[c];
|
||||
@@ -698,9 +699,314 @@ if (expression !== undefined) {
|
||||
}
|
||||
}
|
||||
parentPort.postMessage({ status: "matched", indices });
|
||||
}
|
||||
});
|
||||
`;
|
||||
|
||||
// Workers are pooled by heap class: spawning one costs ~10 ms, which dominates
|
||||
// small searches. A worker is reused only after a clean reply. A deadline,
|
||||
// abort, error, or exit stops that worker. It stays in the pool, and counts
|
||||
// toward the cap, until its thread exits. A failed stop keeps the slot and is
|
||||
// retried; the caller's match error keeps its identity and records the stop
|
||||
// failure beside it.
|
||||
const MAX_POOLED_REGEX_WORKERS = 4;
|
||||
const REGEX_WORKER_IDLE_MS = 10_000;
|
||||
const REGEX_WORKER_RESOURCE = "regex-worker";
|
||||
|
||||
interface PooledRegexWorker {
|
||||
readonly worker: Worker;
|
||||
readonly heapMiB: number;
|
||||
busy: boolean;
|
||||
/** The thread has exited and the entry has left the pool. */
|
||||
exited: boolean;
|
||||
/** `terminate()` is in flight and has not failed. */
|
||||
stopping: boolean;
|
||||
/** Last `terminate()` rejection. The entry stays counted until a later stop exits. */
|
||||
stopFailure?: unknown;
|
||||
idleTimer?: NodeJS.Timeout | undefined;
|
||||
stopPromise?: Promise<void> | undefined;
|
||||
resolveStop?: (() => void) | undefined;
|
||||
rejectStop?: ((cause: unknown) => void) | undefined;
|
||||
onMessage?: ((message: unknown) => void) | undefined;
|
||||
onError?: ((cause: Error & { code?: string }) => void) | undefined;
|
||||
onExit?: ((code: number) => void) | undefined;
|
||||
}
|
||||
|
||||
interface RegexWorkerWaiter {
|
||||
readonly heapMiB: number;
|
||||
readonly grant: (entry: PooledRegexWorker) => void;
|
||||
readonly fail: (cause: unknown) => void;
|
||||
}
|
||||
|
||||
const regexWorkerPool: PooledRegexWorker[] = [];
|
||||
const regexWorkerWaiters: RegexWorkerWaiter[] = [];
|
||||
|
||||
const isIdleRegexWorker = (entry: PooledRegexWorker): boolean =>
|
||||
!entry.busy && !entry.stopping && entry.stopFailure === undefined;
|
||||
|
||||
const clearRegexWorkerHandlers = (entry: PooledRegexWorker): void => {
|
||||
entry.onMessage = undefined;
|
||||
entry.onError = undefined;
|
||||
entry.onExit = undefined;
|
||||
};
|
||||
|
||||
const regexWorkerStopFailure = (
|
||||
operation: string,
|
||||
entry: PooledRegexWorker,
|
||||
cause: unknown,
|
||||
): AnalysisOutputError =>
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Regex worker did not stop after its match ended",
|
||||
{
|
||||
cause,
|
||||
diagnostics: { worker_heap_mib: entry.heapMiB },
|
||||
cleanup: {
|
||||
reason: "Regex worker termination failed",
|
||||
resources: [REGEX_WORKER_RESOURCE],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const forgetRegexWorkerStop = (entry: PooledRegexWorker): void => {
|
||||
entry.resolveStop = undefined;
|
||||
entry.rejectStop = undefined;
|
||||
};
|
||||
|
||||
/** Drop the worker only after its thread exits, then let the allocator use the slot. */
|
||||
const settleRegexWorkerExit = (entry: PooledRegexWorker): void => {
|
||||
if (entry.exited) return;
|
||||
entry.exited = true;
|
||||
entry.stopping = false;
|
||||
entry.busy = false;
|
||||
entry.stopFailure = undefined;
|
||||
if (entry.idleTimer !== undefined) {
|
||||
clearTimeout(entry.idleTimer);
|
||||
entry.idleTimer = undefined;
|
||||
}
|
||||
const index = regexWorkerPool.indexOf(entry);
|
||||
if (index !== -1) regexWorkerPool.splice(index, 1);
|
||||
const resolve = entry.resolveStop;
|
||||
forgetRegexWorkerStop(entry);
|
||||
resolve?.();
|
||||
serveRegexWaiters();
|
||||
};
|
||||
|
||||
/**
|
||||
* Stop `entry` and keep it counted until exit. A rejection leaves it owned
|
||||
* with `stopFailure` set so a later allocation can retry. The returned
|
||||
* promise rejects only for that failure; exit fulfills it.
|
||||
*/
|
||||
const beginStopRegexWorker = (entry: PooledRegexWorker): Promise<void> => {
|
||||
if (entry.exited) return Promise.resolve();
|
||||
if (entry.stopPromise !== undefined && entry.stopFailure === undefined)
|
||||
return entry.stopPromise;
|
||||
entry.stopFailure = undefined;
|
||||
entry.stopping = true;
|
||||
entry.busy = false;
|
||||
if (entry.idleTimer !== undefined) {
|
||||
clearTimeout(entry.idleTimer);
|
||||
entry.idleTimer = undefined;
|
||||
}
|
||||
entry.worker.ref();
|
||||
let resolveStop!: () => void;
|
||||
let rejectStop!: (cause: unknown) => void;
|
||||
const promise = new Promise<void>((resolve, reject) => {
|
||||
resolveStop = resolve;
|
||||
rejectStop = reject;
|
||||
});
|
||||
entry.resolveStop = resolveStop;
|
||||
entry.rejectStop = rejectStop;
|
||||
entry.stopPromise = promise;
|
||||
void promise.catch(() => undefined);
|
||||
// `terminate()` fulfills with the exit code once the thread has stopped.
|
||||
// The exit listener settles the same way when the thread dies on its own.
|
||||
void entry.worker.terminate().then(
|
||||
() => {
|
||||
settleRegexWorkerExit(entry);
|
||||
},
|
||||
(cause: unknown) => {
|
||||
if (entry.exited || entry.rejectStop !== rejectStop) return;
|
||||
entry.stopping = false;
|
||||
entry.stopFailure = cause;
|
||||
entry.stopPromise = undefined;
|
||||
forgetRegexWorkerStop(entry);
|
||||
entry.worker.unref();
|
||||
rejectStop(cause);
|
||||
},
|
||||
);
|
||||
return promise;
|
||||
};
|
||||
|
||||
const grantIdleRegexWorker = (
|
||||
entry: PooledRegexWorker,
|
||||
waiter: RegexWorkerWaiter,
|
||||
): void => {
|
||||
entry.busy = true;
|
||||
if (entry.idleTimer !== undefined) {
|
||||
clearTimeout(entry.idleTimer);
|
||||
entry.idleTimer = undefined;
|
||||
}
|
||||
entry.worker.ref();
|
||||
waiter.grant(entry);
|
||||
};
|
||||
|
||||
let servingRegexWaiters = false;
|
||||
let regexWaitersNeedService = false;
|
||||
|
||||
const serveRegexWaiters = (): void => {
|
||||
if (servingRegexWaiters) {
|
||||
regexWaitersNeedService = true;
|
||||
return;
|
||||
}
|
||||
servingRegexWaiters = true;
|
||||
try {
|
||||
do {
|
||||
regexWaitersNeedService = false;
|
||||
serveRegexWaitersNow();
|
||||
} while (regexWaitersNeedService);
|
||||
} finally {
|
||||
servingRegexWaiters = false;
|
||||
}
|
||||
};
|
||||
|
||||
const serveRegexWaitersNow = (): void => {
|
||||
for (const entry of regexWorkerPool) {
|
||||
if (entry.stopFailure !== undefined && !entry.stopping)
|
||||
void beginStopRegexWorker(entry);
|
||||
}
|
||||
for (let i = 0; i < regexWorkerWaiters.length;) {
|
||||
const waiter = regexWorkerWaiters[i]!;
|
||||
const idle = regexWorkerPool.find(
|
||||
(entry) => isIdleRegexWorker(entry) && entry.heapMiB === waiter.heapMiB,
|
||||
);
|
||||
if (idle === undefined) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
regexWorkerWaiters.splice(i, 1);
|
||||
grantIdleRegexWorker(idle, waiter);
|
||||
}
|
||||
for (let i = 0; i < regexWorkerWaiters.length;) {
|
||||
if (regexWorkerPool.length < MAX_POOLED_REGEX_WORKERS) {
|
||||
const waiter = regexWorkerWaiters[i]!;
|
||||
regexWorkerWaiters.splice(i, 1);
|
||||
try {
|
||||
waiter.grant(spawnRegexWorker(waiter.heapMiB));
|
||||
} catch (cause: unknown) {
|
||||
waiter.fail(cause);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// One incompatible idle worker fills one queued heap. Stopping every
|
||||
// idle worker here would discard workers the caller did not need.
|
||||
const reclaimable = regexWorkerPool.find((entry) =>
|
||||
isIdleRegexWorker(entry),
|
||||
);
|
||||
if (reclaimable !== undefined) void beginStopRegexWorker(reclaimable);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const spawnRegexWorker = (heapMiB: number): PooledRegexWorker => {
|
||||
const worker = new Worker(WORKER_SOURCE, {
|
||||
eval: true,
|
||||
resourceLimits: { maxOldGenerationSizeMb: heapMiB },
|
||||
});
|
||||
const entry: PooledRegexWorker = {
|
||||
worker,
|
||||
heapMiB,
|
||||
busy: true,
|
||||
exited: false,
|
||||
stopping: false,
|
||||
};
|
||||
worker.on("message", (message: unknown) => entry.onMessage?.(message));
|
||||
worker.on("error", (cause: Error & { code?: string }) => {
|
||||
const settle = entry.onError;
|
||||
settle?.(cause);
|
||||
void beginStopRegexWorker(entry);
|
||||
});
|
||||
worker.on("exit", (code: number) => {
|
||||
const settle = entry.onExit;
|
||||
settleRegexWorkerExit(entry);
|
||||
settle?.(code);
|
||||
});
|
||||
regexWorkerPool.push(entry);
|
||||
return entry;
|
||||
};
|
||||
|
||||
const acquireRegexWorker = async (
|
||||
heapMiB: number,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<PooledRegexWorker | undefined> => {
|
||||
const idle = regexWorkerPool.find(
|
||||
(entry) => isIdleRegexWorker(entry) && entry.heapMiB === heapMiB,
|
||||
);
|
||||
if (idle !== undefined) {
|
||||
idle.busy = true;
|
||||
if (idle.idleTimer !== undefined) clearTimeout(idle.idleTimer);
|
||||
idle.idleTimer = undefined;
|
||||
idle.worker.ref();
|
||||
return idle;
|
||||
}
|
||||
// Spawning and reclaiming go through serveRegexWaiters so one path owns
|
||||
// the cap. An idle match above only borrows a worker already counted.
|
||||
return new Promise<PooledRegexWorker | undefined>((resolve, reject) => {
|
||||
const waiter: RegexWorkerWaiter = {
|
||||
heapMiB,
|
||||
grant: (entry: PooledRegexWorker) => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve(entry);
|
||||
},
|
||||
fail: (cause: unknown) => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(
|
||||
cause instanceof Error ? cause : new Error("Regex worker failed"),
|
||||
);
|
||||
},
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
const index = regexWorkerWaiters.indexOf(waiter);
|
||||
if (index !== -1) regexWorkerWaiters.splice(index, 1);
|
||||
resolve(undefined);
|
||||
};
|
||||
regexWorkerWaiters.push(waiter);
|
||||
if (signal?.aborted) onAbort();
|
||||
else signal?.addEventListener("abort", onAbort, { once: true });
|
||||
serveRegexWaiters();
|
||||
});
|
||||
};
|
||||
|
||||
const armRegexWorkerIdleTimer = (entry: PooledRegexWorker): void => {
|
||||
entry.idleTimer = setTimeout(() => {
|
||||
entry.idleTimer = undefined;
|
||||
if (isIdleRegexWorker(entry)) void beginStopRegexWorker(entry);
|
||||
}, REGEX_WORKER_IDLE_MS);
|
||||
entry.idleTimer.unref();
|
||||
};
|
||||
|
||||
const releaseRegexWorker = (entry: PooledRegexWorker): void => {
|
||||
entry.busy = false;
|
||||
clearRegexWorkerHandlers(entry);
|
||||
entry.worker.unref();
|
||||
// The shared allocator matches this worker or reclaims it for another heap.
|
||||
// A same-heap-only grant here left that waiter waiting out the idle reap.
|
||||
serveRegexWaiters();
|
||||
if (isIdleRegexWorker(entry)) armRegexWorkerIdleTimer(entry);
|
||||
};
|
||||
|
||||
const ensureRegexWorkerStopped = async (
|
||||
operation: string,
|
||||
entry: PooledRegexWorker,
|
||||
): Promise<AnalysisOutputError | undefined> => {
|
||||
if (entry.exited && entry.stopFailure === undefined) return undefined;
|
||||
try {
|
||||
await beginStopRegexWorker(entry);
|
||||
return undefined;
|
||||
} catch (cause: unknown) {
|
||||
return regexWorkerStopFailure(operation, entry, cause);
|
||||
}
|
||||
};
|
||||
|
||||
export interface RegexConfigurationSnapshot {
|
||||
readonly deadline: RegexMatchingDeadline;
|
||||
readonly heapRequest: RegexWorkerHeapRequest;
|
||||
@@ -722,7 +1028,7 @@ export const snapshotRegexConfiguration = (
|
||||
},
|
||||
}));
|
||||
|
||||
/** Match an inventory off the service thread, and prove worker exit before returning. */
|
||||
/** Match an inventory off the service thread; clean workers return to the pool, stuck ones are retired. */
|
||||
export const matchRegexValues = async (input: {
|
||||
readonly operation: string;
|
||||
readonly pattern: string;
|
||||
@@ -753,18 +1059,17 @@ export const matchRegexValues = async (input: {
|
||||
}
|
||||
const { deadline, heapRequest } = admitted.value;
|
||||
const transfer = packRegexValues(input.values);
|
||||
let worker: Worker;
|
||||
const startedAt = performance.now();
|
||||
const queueSignal =
|
||||
input.signal === undefined
|
||||
? AbortSignal.timeout(deadline.deadlineMs)
|
||||
: AbortSignal.any([
|
||||
input.signal,
|
||||
AbortSignal.timeout(deadline.deadlineMs),
|
||||
]);
|
||||
let entry: PooledRegexWorker | undefined;
|
||||
try {
|
||||
worker = new Worker(WORKER_SOURCE, {
|
||||
eval: true,
|
||||
workerData: {
|
||||
pattern: input.pattern,
|
||||
caseSensitive: input.caseSensitive,
|
||||
packed: transfer.packed,
|
||||
},
|
||||
transferList: transfer.transferList,
|
||||
resourceLimits: { maxOldGenerationSizeMb: heapRequest.heapMiB },
|
||||
});
|
||||
entry = await acquireRegexWorker(heapRequest.heapMiB, queueSignal);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new AnalysisOutputError(input.operation, "Cannot start regex worker", {
|
||||
@@ -772,8 +1077,17 @@ export const matchRegexValues = async (input: {
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (entry === undefined)
|
||||
return err(
|
||||
input.signal?.aborted
|
||||
? cancelledBy(input.operation, carriedReason(input.signal.reason))
|
||||
: regexMatchingDeadlineError(input.operation, deadline),
|
||||
);
|
||||
const pooled = entry;
|
||||
let reusable = false;
|
||||
let outcome: Result<readonly number[], AnalysisError>;
|
||||
try {
|
||||
return await new Promise((resolve) => {
|
||||
outcome = await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (result: Result<readonly number[], AnalysisError>) => {
|
||||
if (settled) return;
|
||||
@@ -788,14 +1102,15 @@ export const matchRegexValues = async (input: {
|
||||
cancelledBy(input.operation, carriedReason(input.signal?.reason)),
|
||||
),
|
||||
);
|
||||
// Queueing for a pooled worker counts toward the caller's deadline.
|
||||
const timer = setTimeout(
|
||||
() =>
|
||||
finish(err(regexMatchingDeadlineError(input.operation, deadline))),
|
||||
deadline.deadlineMs,
|
||||
Math.max(0, deadline.deadlineMs - (performance.now() - startedAt)),
|
||||
);
|
||||
input.signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (input.signal?.aborted) onAbort();
|
||||
worker.once("message", (message: unknown) => {
|
||||
pooled.onMessage = (message: unknown) => {
|
||||
const reply = parseWorkerReply(message, input.values.length);
|
||||
switch (reply.kind) {
|
||||
case "malformed":
|
||||
@@ -808,6 +1123,7 @@ export const matchRegexValues = async (input: {
|
||||
),
|
||||
);
|
||||
case "invalid_pattern":
|
||||
reusable = true;
|
||||
return finish(
|
||||
err(invalidRegexPatternError(input.operation, reply.reason)),
|
||||
);
|
||||
@@ -821,10 +1137,11 @@ export const matchRegexValues = async (input: {
|
||||
),
|
||||
);
|
||||
case "matched":
|
||||
reusable = true;
|
||||
return finish(ok(reply.indices));
|
||||
}
|
||||
});
|
||||
worker.once("error", (cause: Error & { code?: string }) =>
|
||||
};
|
||||
pooled.onError = (cause: Error & { code?: string }) =>
|
||||
finish(
|
||||
err(
|
||||
cause.code === "ERR_WORKER_OUT_OF_MEMORY"
|
||||
@@ -840,9 +1157,8 @@ export const matchRegexValues = async (input: {
|
||||
{ cause },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
worker.once("exit", (code) =>
|
||||
);
|
||||
pooled.onExit = (code: number) =>
|
||||
finish(
|
||||
err(
|
||||
new AnalysisOutputError(
|
||||
@@ -850,10 +1166,62 @@ export const matchRegexValues = async (input: {
|
||||
`Regex worker exited without a result (${String(code)})`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
// A worker that failed or is stopping must not run this call's job.
|
||||
// A job whose deadline already expired while queueing is not sent either.
|
||||
if (
|
||||
pooled.exited ||
|
||||
pooled.stopping ||
|
||||
pooled.stopFailure !== undefined
|
||||
) {
|
||||
finish(
|
||||
err(
|
||||
new AnalysisOutputError(
|
||||
input.operation,
|
||||
"Regex worker failed before its match started",
|
||||
{
|
||||
diagnostics: { worker_heap_mib: pooled.heapMiB },
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
} else if (performance.now() - startedAt >= deadline.deadlineMs) {
|
||||
reusable = true;
|
||||
finish(err(regexMatchingDeadlineError(input.operation, deadline)));
|
||||
} else {
|
||||
pooled.worker.postMessage(
|
||||
{
|
||||
pattern: input.pattern,
|
||||
caseSensitive: input.caseSensitive,
|
||||
packed: transfer.packed,
|
||||
},
|
||||
transfer.transferList,
|
||||
);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
await worker.terminate();
|
||||
} catch (cause: unknown) {
|
||||
outcome = err(
|
||||
new AnalysisOutputError(input.operation, "Regex worker failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Clean replies return the worker to the pool. Every other outcome stops
|
||||
// that worker and waits until it exits, so close() awaiting this promise
|
||||
// does not return while the match is still running. A failed stop keeps
|
||||
// the worker counted and leaves the match error as the primary result.
|
||||
const canReuse =
|
||||
reusable &&
|
||||
!pooled.exited &&
|
||||
!pooled.stopping &&
|
||||
pooled.stopFailure === undefined;
|
||||
if (canReuse) {
|
||||
releaseRegexWorker(pooled);
|
||||
return outcome;
|
||||
}
|
||||
clearRegexWorkerHandlers(pooled);
|
||||
const stopFailure = await ensureRegexWorkerStopped(input.operation, pooled);
|
||||
if (stopFailure !== undefined && !outcome.ok)
|
||||
outcome.error.retainSecondaryFailure(stopFailure);
|
||||
return outcome;
|
||||
};
|
||||
@@ -0,0 +1,416 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { waitFor } from "../../tests/support/testWait.js";
|
||||
|
||||
const { fakeWorkers } = vi.hoisted(() => ({
|
||||
fakeWorkers: {
|
||||
generation: 0,
|
||||
constructed: 0,
|
||||
alive: 0,
|
||||
maxAlive: 0,
|
||||
failNextTerminate: false,
|
||||
instances: [] as {
|
||||
exited: boolean;
|
||||
terminated: boolean;
|
||||
terminateCalls: number;
|
||||
patterns: string[];
|
||||
releaseReply: (() => void) | undefined;
|
||||
releaseTerminate: (() => void) | undefined;
|
||||
}[],
|
||||
reset(): void {
|
||||
this.generation += 1;
|
||||
this.constructed = 0;
|
||||
this.alive = 0;
|
||||
this.maxAlive = 0;
|
||||
this.failNextTerminate = false;
|
||||
this.instances = [];
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("node:worker_threads", () => ({
|
||||
Worker: class extends EventEmitter {
|
||||
readonly generation: number;
|
||||
exited = false;
|
||||
terminated = false;
|
||||
terminateCalls = 0;
|
||||
readonly patterns: string[] = [];
|
||||
releaseReply: (() => void) | undefined;
|
||||
releaseTerminate: (() => void) | undefined;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.generation = fakeWorkers.generation;
|
||||
fakeWorkers.constructed += 1;
|
||||
fakeWorkers.alive += 1;
|
||||
fakeWorkers.maxAlive = Math.max(fakeWorkers.maxAlive, fakeWorkers.alive);
|
||||
fakeWorkers.instances.push(this);
|
||||
}
|
||||
|
||||
postMessage(job: {
|
||||
pattern: string;
|
||||
caseSensitive: boolean;
|
||||
packed: {
|
||||
lengthsBuffer: ArrayBuffer;
|
||||
chunks: readonly {
|
||||
buffer: ArrayBuffer;
|
||||
encoding: "latin1" | "utf16le";
|
||||
startIndex: number;
|
||||
count: number;
|
||||
}[];
|
||||
};
|
||||
}): void {
|
||||
this.patterns.push(job.pattern);
|
||||
if (job.pattern.includes("(a+)+")) return;
|
||||
const deliver = (): void => {
|
||||
const expression = new RegExp(
|
||||
job.pattern,
|
||||
job.caseSensitive ? "u" : "iu",
|
||||
);
|
||||
const lengths = new Uint32Array(job.packed.lengthsBuffer);
|
||||
const indices: number[] = [];
|
||||
for (const chunk of job.packed.chunks) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
this.emit("message", { status: "matched", indices });
|
||||
};
|
||||
if (job.pattern.startsWith("HOLD")) {
|
||||
this.releaseReply = deliver;
|
||||
return;
|
||||
}
|
||||
queueMicrotask(deliver);
|
||||
}
|
||||
|
||||
ref(): void {}
|
||||
unref(): void {}
|
||||
|
||||
private markExited(code: number): void {
|
||||
if (this.exited) return;
|
||||
this.exited = true;
|
||||
if (this.generation === fakeWorkers.generation) fakeWorkers.alive -= 1;
|
||||
this.emit("exit", code);
|
||||
}
|
||||
|
||||
terminate(): Promise<number> {
|
||||
this.terminated = true;
|
||||
this.terminateCalls += 1;
|
||||
if (fakeWorkers.failNextTerminate) {
|
||||
fakeWorkers.failNextTerminate = false;
|
||||
return Promise.reject(new Error("terminate refused"));
|
||||
}
|
||||
if (this.releaseTerminate !== undefined) {
|
||||
return new Promise((resolve) => {
|
||||
this.releaseTerminate = () => {
|
||||
queueMicrotask(() => {
|
||||
this.markExited(1);
|
||||
resolve(1);
|
||||
});
|
||||
};
|
||||
});
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
queueMicrotask(() => {
|
||||
this.markExited(0);
|
||||
resolve(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
let matchRegexValues: typeof import("./RegexMatcher.js").matchRegexValues;
|
||||
let projectAnalysisError: typeof import("../domain/analysisErrorProjection.js").projectAnalysisError;
|
||||
|
||||
const deadline = (deadlineMs: number) =>
|
||||
({ deadlineMs, source: "runtime" }) as const;
|
||||
const heap = (heapMiB: number) => ({ heapMiB, source: "runtime" }) as const;
|
||||
|
||||
const search = (
|
||||
pattern: string,
|
||||
values: readonly string[],
|
||||
options: {
|
||||
readonly deadlineMs?: number;
|
||||
readonly heapMiB?: number;
|
||||
readonly signal?: AbortSignal;
|
||||
} = {},
|
||||
) =>
|
||||
matchRegexValues({
|
||||
operation: "search_strings",
|
||||
pattern,
|
||||
caseSensitive: true,
|
||||
values,
|
||||
...(options.deadlineMs === undefined
|
||||
? {}
|
||||
: { deadline: deadline(options.deadlineMs) }),
|
||||
...(options.heapMiB === undefined
|
||||
? {}
|
||||
: { heapRequest: heap(options.heapMiB) }),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
fakeWorkers.reset();
|
||||
vi.resetModules();
|
||||
({ matchRegexValues } = await import("./RegexMatcher.js"));
|
||||
({ projectAnalysisError } =
|
||||
await import("../domain/analysisErrorProjection.js"));
|
||||
});
|
||||
|
||||
const releaseHeldWorkers = (): void => {
|
||||
for (const worker of fakeWorkers.instances) {
|
||||
const reply = worker.releaseReply;
|
||||
const stop = worker.releaseTerminate;
|
||||
worker.releaseReply = undefined;
|
||||
worker.releaseTerminate = undefined;
|
||||
reply?.();
|
||||
stop?.();
|
||||
}
|
||||
};
|
||||
|
||||
it("reclaims the incompatible idle worker instead of starting a fifth", async () => {
|
||||
const held = [0, 1, 2, 3].map((index) =>
|
||||
search(`HOLD-${String(index)}`, [`HOLD-${String(index)}`], {
|
||||
heapMiB: 128,
|
||||
deadlineMs: 2_000,
|
||||
}),
|
||||
);
|
||||
const queued = search("storage", ["storage"], {
|
||||
heapMiB: 64,
|
||||
deadlineMs: 2_000,
|
||||
});
|
||||
try {
|
||||
await waitFor(() => {
|
||||
expect(fakeWorkers.constructed).toBe(4);
|
||||
expect(
|
||||
fakeWorkers.instances.every(
|
||||
(worker) => worker.releaseReply !== undefined,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(fakeWorkers.constructed).toBe(4);
|
||||
const finished = fakeWorkers.instances[0];
|
||||
const release = finished?.releaseReply;
|
||||
if (finished === undefined || release === undefined)
|
||||
throw new Error("expected the first worker to be holding its reply");
|
||||
finished.releaseReply = undefined;
|
||||
release();
|
||||
expect(await held[0]).toEqual({ ok: true, value: [0] });
|
||||
const second = await search("other", ["other"], {
|
||||
heapMiB: 64,
|
||||
deadlineMs: 500,
|
||||
});
|
||||
expect(second).toEqual({ ok: true, value: [0] });
|
||||
expect(await queued).toEqual({ ok: true, value: [0] });
|
||||
const exited = fakeWorkers.instances.filter((worker) => worker.exited);
|
||||
const replacements = fakeWorkers.instances.filter((worker) =>
|
||||
worker.patterns.includes("storage"),
|
||||
);
|
||||
// Four original workers plus the one replacement. A second spawn is a fifth live worker.
|
||||
expect(fakeWorkers.constructed).toBe(5);
|
||||
expect(fakeWorkers.maxAlive).toBeLessThanOrEqual(4);
|
||||
expect(exited).toEqual([finished]);
|
||||
expect(finished.patterns).toEqual(["HOLD-0"]);
|
||||
expect(replacements).toHaveLength(1);
|
||||
expect(replacements[0]?.patterns).toEqual(["storage", "other"]);
|
||||
} finally {
|
||||
releaseHeldWorkers();
|
||||
await Promise.allSettled([...held, queued]);
|
||||
}
|
||||
});
|
||||
|
||||
it("reclaims idle workers of another heap before the idle timeout", async () => {
|
||||
await Promise.all(
|
||||
[0, 1, 2, 3].map(() => search("storage", ["storage"], { heapMiB: 128 })),
|
||||
);
|
||||
expect(fakeWorkers.constructed).toBe(4);
|
||||
expect(fakeWorkers.alive).toBe(4);
|
||||
const started = performance.now();
|
||||
const changed = await search("storage", ["storage"], {
|
||||
heapMiB: 64,
|
||||
deadlineMs: 500,
|
||||
});
|
||||
expect(performance.now() - started).toBeLessThan(500);
|
||||
expect(changed).toEqual({ ok: true, value: [0] });
|
||||
expect(fakeWorkers.maxAlive).toBeLessThanOrEqual(4);
|
||||
expect(fakeWorkers.alive).toBe(4);
|
||||
expect(fakeWorkers.constructed).toBe(5);
|
||||
expect(fakeWorkers.instances.filter((worker) => worker.exited)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it("shares one worker across clean calls and replaces only the timed-out worker", async () => {
|
||||
expect(await search("alpha", ["alpha", "beta"])).toEqual({
|
||||
ok: true,
|
||||
value: [0],
|
||||
});
|
||||
expect(await search("beta", ["alpha", "beta"])).toEqual({
|
||||
ok: true,
|
||||
value: [1],
|
||||
});
|
||||
expect(fakeWorkers.constructed).toBe(1);
|
||||
expect(fakeWorkers.instances[0]?.patterns).toEqual(["alpha", "beta"]);
|
||||
|
||||
const held = search("HOLD", ["HOLD"], { deadlineMs: 2_000 });
|
||||
try {
|
||||
await waitFor(() => {
|
||||
expect(fakeWorkers.instances[0]?.patterns).toContain("HOLD");
|
||||
});
|
||||
const stuck = await search(
|
||||
"^(a+)+$",
|
||||
["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b"],
|
||||
{ deadlineMs: 25 },
|
||||
);
|
||||
if (stuck.ok)
|
||||
throw new Error("expected the stuck pattern to miss its deadline");
|
||||
expect(projectAnalysisError(stuck.error)).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
operation: "search_strings",
|
||||
resource: "cpu",
|
||||
reported_limits: {
|
||||
matching_deadline_ms: 25,
|
||||
matching_deadline_source: "runtime",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(fakeWorkers.instances[0]?.terminated).toBe(false);
|
||||
expect(fakeWorkers.instances[1]?.terminated).toBe(true);
|
||||
expect(fakeWorkers.instances[1]?.exited).toBe(true);
|
||||
expect(fakeWorkers.constructed).toBe(2);
|
||||
const release = fakeWorkers.instances[0]?.releaseReply;
|
||||
if (release === undefined)
|
||||
throw new Error("expected the held worker to stay in use");
|
||||
fakeWorkers.instances[0]!.releaseReply = undefined;
|
||||
release();
|
||||
expect(await held).toEqual({ ok: true, value: [0] });
|
||||
expect(fakeWorkers.instances[0]?.terminated).toBe(false);
|
||||
expect(fakeWorkers.maxAlive).toBeLessThanOrEqual(2);
|
||||
|
||||
const after = await search("storage", ["storage/read"]);
|
||||
expect(after).toEqual({ ok: true, value: [0] });
|
||||
expect(fakeWorkers.instances[0]?.patterns).toContain("storage");
|
||||
expect(fakeWorkers.instances[1]?.patterns).not.toContain("storage");
|
||||
expect(fakeWorkers.constructed).toBe(2);
|
||||
} finally {
|
||||
releaseHeldWorkers();
|
||||
await Promise.allSettled([held]);
|
||||
}
|
||||
});
|
||||
|
||||
it("waits for worker exit when the caller aborts during termination", async () => {
|
||||
const controller = new AbortController();
|
||||
const reason = { request: "stop search" };
|
||||
let exitedBeforeReturn = false;
|
||||
const pending = search("HOLD", ["HOLD"], {
|
||||
deadlineMs: 5_000,
|
||||
signal: controller.signal,
|
||||
}).then((result) => {
|
||||
exitedBeforeReturn = fakeWorkers.instances[0]?.exited === true;
|
||||
return result;
|
||||
});
|
||||
try {
|
||||
await waitFor(() => {
|
||||
expect(fakeWorkers.instances[0]?.releaseReply).toBeTypeOf("function");
|
||||
});
|
||||
const worker = fakeWorkers.instances[0];
|
||||
if (worker === undefined) throw new Error("expected a worker");
|
||||
worker.releaseTerminate = () => undefined;
|
||||
controller.abort(reason);
|
||||
await waitFor(() => {
|
||||
expect(worker.terminated).toBe(true);
|
||||
});
|
||||
let settled = false;
|
||||
void pending.then(
|
||||
() => {
|
||||
settled = true;
|
||||
},
|
||||
() => {
|
||||
settled = true;
|
||||
},
|
||||
);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
const release = worker.releaseTerminate;
|
||||
if (release === undefined)
|
||||
throw new Error("expected termination to be held");
|
||||
worker.releaseTerminate = undefined;
|
||||
release();
|
||||
const result = await pending;
|
||||
expect(exitedBeforeReturn).toBe(true);
|
||||
if (result.ok) throw new Error("expected cancellation");
|
||||
expect(result.error.cause).toBe(reason);
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "cancelled",
|
||||
details: {
|
||||
operation: "search_strings",
|
||||
cleanup: "complete",
|
||||
},
|
||||
});
|
||||
expect(result.error.secondaryFailures).toEqual([]);
|
||||
} finally {
|
||||
releaseHeldWorkers();
|
||||
await pending;
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the deadline when termination fails and retries the owned worker", async () => {
|
||||
fakeWorkers.failNextTerminate = true;
|
||||
const stuck = await search(
|
||||
"^(a+)+$",
|
||||
["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b"],
|
||||
{ deadlineMs: 25 },
|
||||
);
|
||||
const worker = fakeWorkers.instances[0];
|
||||
if (worker === undefined) throw new Error("expected a worker");
|
||||
if (stuck.ok)
|
||||
throw new Error("expected the stuck pattern to miss its deadline");
|
||||
expect(worker.exited).toBe(false);
|
||||
expect(fakeWorkers.alive).toBe(1);
|
||||
expect(worker.terminateCalls).toBe(1);
|
||||
expect(projectAnalysisError(stuck.error)).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
operation: "search_strings",
|
||||
resource: "cpu",
|
||||
reported_limits: {
|
||||
matching_deadline_ms: 25,
|
||||
matching_deadline_source: "runtime",
|
||||
},
|
||||
secondary_failures: [
|
||||
{
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
operation: "search_strings",
|
||||
reason: "Regex worker did not stop after its match ended",
|
||||
diagnostics: { worker_heap_mib: 128 },
|
||||
cleanup: "incomplete",
|
||||
resources: ["regex-worker"],
|
||||
cleanup_reason: "Regex worker termination failed",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(await search("storage", ["storage"], { deadlineMs: 500 })).toEqual({
|
||||
ok: true,
|
||||
value: [0],
|
||||
});
|
||||
expect(worker.terminateCalls).toBe(2);
|
||||
expect(worker.exited).toBe(true);
|
||||
expect(fakeWorkers.constructed).toBe(2);
|
||||
expect(fakeWorkers.maxAlive).toBeLessThanOrEqual(4);
|
||||
});
|
||||
@@ -7,11 +7,13 @@ const { reply } = vi.hoisted(() => ({
|
||||
}));
|
||||
vi.mock("node:worker_threads", () => ({
|
||||
Worker: class extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
postMessage(): void {
|
||||
queueMicrotask(() => this.emit("message", reply.value));
|
||||
}
|
||||
|
||||
ref(): void {}
|
||||
unref(): void {}
|
||||
|
||||
terminate(): Promise<number> {
|
||||
return Promise.resolve(0);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user