perf(javascript): reuse the source-analysis worker within a process (#5819)

* perf(javascript): reuse the source-analysis worker within a process

Each analyze-javascript-application call started a new Node worker.
That startup, not fixture IO or the shared CLI session, dominated the
slow loader-review and factory-completion files.

Park one healthy worker on the artifact resource scope and on the CLI
process. Stop it when the scope, session, or one-shot process ends.
Do not reuse after failure, cancellation, or a different heap or timeout.

Co-authored-by: morluto <[email protected]>

* fix(cli): close the JavaScript worker when dispatch throws

Minimal dispatcher runtimes now export a no-op closeCliJavaScriptResources,
and CLI dispatch plus output rendering always await that cleanup. A dispatch
failure and a cleanup failure are both reported.

Co-authored-by: morluto <[email protected]>

* fix(artifacts): report close-hook failures with retained cleanup

When retained cleanup and the scope close hook both fail, the close error
keeps both causes and both resource labels. The pending owners and the hook
stay registered so the next close retries each path.

Co-authored-by: morluto <[email protected]>

* fix(javascript): stop a replaced analysis worker before the next one starts

A heap or timeout change now closes the parked worker before constructing
its replacement. The scope retains that process only when the close fails.

Co-authored-by: morluto <[email protected]>

* style: format worker-reuse close and launch helpers

Co-authored-by: morluto <[email protected]>

* fix(cli): report a failed JavaScript worker shutdown before exit

Share one in-flight close and drop the CLI scope only after it succeeds,
so a later caller retries a worker that is still owned. The one-shot
exit callback writes that failure and exits non-zero, while a closed
stdout pipe still exits 141.

Co-authored-by: morluto <[email protected]>

* fix(javascript): keep a worker parked during an overlapping limit change

Claim the scope slot only when it is still empty after the replaced
worker closes. A concurrent analysis that parked another healthy worker
keeps that process, and the extra worker is closed through its own port.

Co-authored-by: morluto <[email protected]>

* fix(artifacts): run later close hooks when an earlier hook fails

Run every registered close hook on each close. One failure is returned
unchanged, and several failures are aggregated so a later hook is not
skipped.

Co-authored-by: morluto <[email protected]>

* fix(javascript): fail a limit change when the previous worker stays alive

A failed close used to be retained and then ignored, so MCP could return
a successful analysis while the old process and its replacement were
both owned. The request now fails before the replacement is constructed,
and the still-live worker stays owned for a later close.

Co-authored-by: morluto <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: morluto <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-21 19:01:20 +08:00
1 parent c76edbebbe
commit 647717c050
15 files changed
+925 -77

No files matched your search

@@ -158,7 +158,7 @@ export const reconstructJavaScriptArtifact = async (
? {}
: { fileNodes: input.max_semantic_nodes_per_file }),
});
const worker = createJavaScriptSourceAnalysis(
const worker = await createJavaScriptSourceAnalysis(
{
heapMb:
input.max_heap_mb ?? JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS.heapMb,
@@ -169,6 +169,7 @@ export const reconstructJavaScriptArtifact = async (
files.files.filter(
(file) => file.kind === "javascript" && file.text.included,
).length,
{ scope },
);
let outcome;
let cleanupFailure: AnalysisError | undefined;
@@ -55,6 +55,89 @@ it("waits for admitted operations and shares concurrent close", async () => {
expect(closed).toBe(true);
});
it("stops a close hook even when retained cleanup is still failing", async () => {
const scope = new ArtifactResourceScope();
let releases = 0;
const owner = {
kind: "lease" as const,
resource: "stuck lease",
lease: {
async release() {
releases += 1;
if (releases < 3) throw new Error("still owned");
},
},
};
expect(await scope.release(owner)).toMatchObject({ kind: "failed" });
let hookRuns = 0;
scope.addCloseHook(async () => {
hookRuns += 1;
if (hookRuns === 1) throw new Error("hook still stopping");
});
const closeFailure = await scope.close().then(
() => {
throw new Error("close succeeded while cleanup and the hook failed");
},
(cause: unknown) => cause,
);
expect(closeFailure).toMatchObject({
message: "Artifact cleanup remains incomplete: stuck lease, close hook",
failedOwners: [owner],
cleanup: {
reason: "still owned; hook still stopping",
resources: ["stuck lease", "close hook"],
},
});
expect(closeFailure).toBeInstanceOf(ArtifactResourceRetryFailure);
const causes = (closeFailure as ArtifactResourceRetryFailure).cause;
expect(causes).toBeInstanceOf(AggregateError);
expect(
(causes as AggregateError).errors.map((error) =>
error instanceof Error ? error.message : String(error),
),
).toEqual([
"Artifact cleanup remains incomplete: stuck lease",
"hook still stopping",
]);
expect(releases).toBe(2);
expect(hookRuns).toBe(1);
await scope.close();
expect(releases).toBe(3);
expect(hookRuns).toBe(2);
});
it("runs later close hooks when an earlier hook fails", async () => {
const scope = new ArtifactResourceScope();
const order: string[] = [];
scope.addCloseHook(async () => {
order.push("first");
throw new Error("first hook failed");
});
scope.addCloseHook(async () => {
order.push("second");
throw new Error("second hook failed");
});
const failure = await scope.close().then(
() => {
throw new Error("close succeeded while hooks failed");
},
(cause: unknown) => cause,
);
expect(order).toEqual(["first", "second"]);
expect(failure).toBeInstanceOf(AggregateError);
expect(
(failure as AggregateError).errors.map((error) =>
error instanceof Error ? error.message : String(error),
),
).toEqual(["first hook failed", "second hook failed"]);
order.length = 0;
await expect(scope.close()).rejects.toBeInstanceOf(AggregateError);
expect(order).toEqual(["first", "second"]);
});
it("retains the same failed reader owner in a retry failure and retries before admitting work", async () => {
const scope = new ArtifactResourceScope();
let closeAttempts = 0;
+95 -1
View File
@@ -95,6 +95,8 @@ export class ArtifactResourceScope {
>();
readonly #active = new Set<Promise<unknown>>();
#draining: Promise<void> | undefined;
#closeInFlight: Promise<void> | undefined;
readonly #closeHooks: Array<() => Promise<void>> = [];
#closed = false;
get hasPending(): boolean {
@@ -203,10 +205,102 @@ export class ArtifactResourceScope {
return this.#draining;
}
/**
* Run after retained owners are released. Hooks stay registered so a later
* close retries them, and a failing hook does not skip the ones after it.
* Concurrent closes share one in-flight attempt.
*/
addCloseHook(hook: () => Promise<void>): void {
this.#closeHooks.push(hook);
}
/** Stop admission, wait for active operations, and retry every retained owner. */
close(): Promise<void> {
this.#closed = true;
return this.retryCleanup();
if (this.#closeInFlight !== undefined) return this.#closeInFlight;
const attempt = this.#finishClose();
let published: Promise<void>;
published = attempt.finally(() => {
if (this.#closeInFlight === published) this.#closeInFlight = undefined;
});
this.#closeInFlight = published;
return published;
}
/** Every registered hook runs. One failure is returned unchanged; several are aggregated. */
async #runCloseHooks(): Promise<unknown> {
const failures: unknown[] = [];
for (const hook of this.#closeHooks) {
try {
await hook();
} catch (cause: unknown) {
failures.push(cause);
}
}
if (failures.length === 0) return undefined;
if (failures.length === 1) return failures[0];
return new AggregateError(
failures,
failures
.map((cause) =>
cause instanceof Error ? cause.message : String(cause),
)
.join("; "),
);
}
async #finishClose(): Promise<void> {
// A parked analyzer is not a pending owner. Stop it even when another
// retained cleanup is still failing. A later close retries both.
const cleanup = await this.retryCleanup().then(
() => undefined,
(cause: unknown) => cause,
);
const hookFailure = await this.#runCloseHooks();
if (cleanup !== undefined && hookFailure !== undefined)
throw this.#composeCloseFailures(cleanup, hookFailure);
if (hookFailure !== undefined) throw hookFailure;
if (cleanup !== undefined) throw cleanup;
}
/**
* Report both outstanding owners. The pending set and the close hook stay
* registered, so the next close retries each failed path.
*/
#composeCloseFailures(
cleanup: unknown,
hookFailure: unknown,
): ArtifactReaderFailure {
const retained = ArtifactReaderFailure.cleanupObservation(
cleanup,
"retained artifact cleanup",
);
const hook = ArtifactReaderFailure.cleanupObservation(
hookFailure,
"close hook",
);
const resources = [...new Set([...retained.resources, ...hook.resources])];
const options = {
cause: new AggregateError(
[cleanup, hookFailure],
"Retained cleanup and a close hook both failed",
),
cleanup: {
reason: `${retained.reason}; ${hook.reason}`,
resources,
},
};
const message = `Artifact cleanup remains incomplete: ${resources.join(", ")}`;
if (cleanup instanceof ArtifactResourceRetryFailure)
return new ArtifactResourceRetryFailure(
cleanup.failedOwners.map((owner) => ({
owner,
lease: this.#lease(owner),
})),
message,
options,
);
return new ArtifactReaderFailure("unavailable", message, options);
}
async #drainAndRetry(): Promise<void> {
@@ -3,10 +3,153 @@ import type {
JavaScriptSourceAnalysisPort,
} from "../../domain/javascript/javascriptSourceAnalysis.js";
import { JavaScriptAnalysisWorker } from "../../javascript/analysis/JavaScriptAnalysisWorker.js";
import type { spawnOwnedProviderProcess } from "../../process/ProviderProcess.js";
import { ArtifactResourceScope } from "../ArtifactResourceScope.js";
interface RetainedJavaScriptSourceAnalysis {
readonly worker: JavaScriptAnalysisWorker;
readonly limits: JavaScriptSourceAnalysisLimits;
busy: boolean;
}
const retained = new WeakMap<
ArtifactResourceScope,
RetainedJavaScriptSourceAnalysis
>();
const closeHookRegistered = new WeakSet<ArtifactResourceScope>();
export interface JavaScriptSourceAnalysisAcquisition {
/** Keep a healthy worker until this scope closes. */
readonly scope?: ArtifactResourceScope;
/** Test seam. Reuse keeps the process already launched for the scope. */
readonly launcher?: typeof spawnOwnedProviderProcess;
}
/** Construct the inert artifact analyzer; resources are acquired on the first source. */
export const createJavaScriptSourceAnalysis = (
limits: JavaScriptSourceAnalysisLimits,
sourceCount: number,
): JavaScriptSourceAnalysisPort =>
new JavaScriptAnalysisWorker(limits, undefined, sourceCount);
acquisition: JavaScriptSourceAnalysisAcquisition = {},
): Promise<JavaScriptSourceAnalysisPort> => {
if (acquisition.scope === undefined)
return Promise.resolve(
new JavaScriptAnalysisWorker(limits, acquisition.launcher, sourceCount),
);
return checkoutJavaScriptSourceAnalysis(
acquisition.scope,
limits,
sourceCount,
acquisition.launcher,
);
};
const checkoutJavaScriptSourceAnalysis = async (
scope: ArtifactResourceScope,
limits: JavaScriptSourceAnalysisLimits,
sourceCount: number,
launcher: typeof spawnOwnedProviderProcess | undefined,
): Promise<JavaScriptSourceAnalysisPort> => {
registerJavaScriptSourceAnalysisClose(scope);
const current = retained.get(scope);
if (current !== undefined && !current.busy) {
if (
sameLimits(current.limits, limits) &&
current.worker.prepareForAnotherAnalysis(sourceCount)
) {
current.busy = true;
return new ScopeJavaScriptSourceAnalysis(scope, current.worker);
}
retained.delete(scope);
try {
await current.worker.close();
} catch (cause) {
// The old process is still alive. Keep it owned and fail this request
// before another worker is constructed, including on MCP where the
// analysis result is returned without a later cleanup retry.
if (retained.get(scope) === undefined) {
retained.set(scope, {
worker: current.worker,
limits: current.limits,
busy: false,
});
} else {
scope.retain({
kind: "lease",
resource: "replaced JavaScript source analyzer",
lease: { release: () => current.worker.close() },
});
}
throw cause;
}
}
const worker = new JavaScriptAnalysisWorker(limits, launcher, sourceCount);
// A concurrent analysis may have parked another healthy worker while the
// replaced process was closing. Claim the slot only when it is still empty.
// This extra process is closed through the port returned below.
if (retained.get(scope) === undefined)
retained.set(scope, { worker, limits, busy: true });
return new ScopeJavaScriptSourceAnalysis(scope, worker);
};
const registerJavaScriptSourceAnalysisClose = (
scope: ArtifactResourceScope,
): void => {
if (closeHookRegistered.has(scope)) return;
closeHookRegistered.add(scope);
scope.addCloseHook(async () => {
const current = retained.get(scope);
if (current === undefined) return;
await current.worker.close();
if (retained.get(scope) === current) retained.delete(scope);
});
};
const sameLimits = (
left: JavaScriptSourceAnalysisLimits,
right: JavaScriptSourceAnalysisLimits,
): boolean =>
left.heapMb === right.heapMb && left.timeoutMs === right.timeoutMs;
/**
* Park a healthy worker on its scope. The next checkout with the same limits
* reuses that process; scope close is what actually stops it.
*/
class ScopeJavaScriptSourceAnalysis implements JavaScriptSourceAnalysisPort {
#failed = false;
#closed = false;
constructor(
private readonly scope: ArtifactResourceScope,
private readonly worker: JavaScriptAnalysisWorker,
) {}
analyze(
...args: Parameters<JavaScriptSourceAnalysisPort["analyze"]>
): ReturnType<JavaScriptSourceAnalysisPort["analyze"]> {
return this.worker.analyze(...args).then((result) => {
if (!result.ok) this.#failed = true;
return result;
});
}
async close(): Promise<void> {
if (this.#closed) return;
this.#closed = true;
try {
const current = retained.get(this.scope);
if (
current?.worker === this.worker &&
!this.#failed &&
this.worker.canReuse()
) {
current.busy = false;
return;
}
if (current?.worker === this.worker) retained.delete(this.scope);
await this.worker.close();
} catch (cause) {
this.#closed = false;
throw cause;
}
}
}
+2
View File
@@ -58,6 +58,8 @@ import {
import { registerReverseEngineeringCommands } from "./cli/reverseEngineeringCommands.js";
import { registerCutterCommands } from "./cli/cutterCommands.js";
export { closeCliJavaScriptResources } from "./cli/javascriptApplicationAnalysis.js";
/**
* Describe CLI settings that are invalid before any command runs, as MCP does.
* Keep this aligned with PROCESS_START_CONFIGURATION_SETTINGS.
+40 -3
View File
@@ -7,7 +7,43 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
/** Execute the shared one-shot CLI boundary for static JavaScript analysis. */
/**
* One scope for every JavaScript analysis in this process. A healthy worker
* stays parked between commands; {@link closeCliJavaScriptResources} stops it.
* Pending cleanup is still retried before each command returns.
*/
let retainedScope: ArtifactResourceScope | undefined;
/** One shutdown shared by the exit callback and the dispatch `finally`. */
let closing: Promise<void> | undefined;
const cliAnalysisScope = (): ArtifactResourceScope => {
retainedScope ??= new ArtifactResourceScope();
return retainedScope;
};
/**
* Stop the process-owned JavaScript worker. Callers that overlap share the
* attempt in flight. The scope stays owned when shutdown fails, so the next
* call retries instead of treating the worker as already released.
*/
export const closeCliJavaScriptResources = (): Promise<void> => {
if (closing !== undefined) return closing;
const scope = retainedScope;
if (scope === undefined) return Promise.resolve();
let published: Promise<void>;
published = scope
.close()
.then(() => {
if (retainedScope === scope) retainedScope = undefined;
})
.finally(() => {
if (closing === published) closing = undefined;
});
closing = published;
return published;
};
/** Execute the shared CLI boundary for static JavaScript analysis. */
export const runCliJavaScriptApplicationAnalysis = async (
input: unknown,
signal?: AbortSignal,
@@ -20,13 +56,14 @@ export const runCliJavaScriptApplicationAnalysis = async (
},
{ minimumIntervalMs: 0 },
);
const resources = new ArtifactResourceScope();
const resources = cliAnalysisScope();
const result = await analyzeJavaScriptApplication(input, resources, {
progress,
...(signal === undefined ? {} : { signal }),
});
try {
await resources.close();
// Retry failed owners without stopping a healthy parked worker.
await resources.retryCleanup();
} catch (cause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cause,
@@ -105,7 +105,7 @@ export class JavaScriptAnalysisWorker {
#parentCapacityExhausted = false;
#sourcesRemaining: number | undefined;
#deadline: ProviderStartupDeadline | undefined;
readonly #resultBudgetBytes: number;
#resultBudgetBytes = 0;
/** Null when the runtime enforces the V8 heap flags instead. */
readonly #processMemoryLimitBytes: number | null;
readonly #onStdout = (chunk: Buffer | string): void => {
@@ -179,8 +179,50 @@ export class JavaScriptAnalysisWorker {
this.#processMemoryLimitBytes = javaScriptWorkerMemoryLimitBytes(
limits.heapMb,
);
// Reserve host-side control, schema/Evidence work and a maximum record's
// transient copies. Admission also accounts for retained earlier files.
this.#refreshResultBudget();
}
/**
* Whether this idle process can analyze another application. A failed,
* cancelled, or still-open job must not be reused.
*/
canReuse(): boolean {
return (
this.#ready &&
this.#activeJobId === undefined &&
this.#primaryFailure === undefined &&
this.#lastFailure === undefined &&
this.#frames.length === 0 &&
this.#pending === "" &&
this.#runtime.inputFailure === undefined &&
!this.#runtime.hasPendingCleanup &&
this.#runtime.supervisor !== undefined
);
}
/**
* Reset per-analysis admission for one idle process. The worker heap limit
* stays the one selected at launch; callers must not reuse across limits.
*/
prepareForAnotherAnalysis(sourceCount: number): boolean {
if (!this.canReuse()) return false;
if (!Number.isSafeInteger(sourceCount) || sourceCount < 0)
throw new RangeError(
"JavaScript worker source count must be a nonnegative safe integer",
);
this.#sourcesRemaining = sourceCount;
this.#estimatedRetainedBytes = 0;
this.#parentCapacityExhausted = false;
this.#applicationProjectionFailure = undefined;
this.#refreshResultBudget();
return true;
}
/**
* Reserve host-side control, schema/Evidence work, and a maximum record's
* transient copies. Admission also accounts for retained earlier files.
*/
#refreshResultBudget(): void {
this.#resultBudgetBytes = Math.max(
0,
Math.floor(