From 9e3a2bbc09872eba06fc4bd09b0547762d385e06 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:53:46 -0500 Subject: [PATCH] fix(domain): keep worker, SQLite, and sealing invariants owned (#14770) * fix(domain): keep worker, SQLite, and sealing invariants owned - Retain a late caller cancellation when SQLite keeps an unresolved worker owner instead of finalizing through runOwned. - Key retained JavaScript static checkpoints by source identity so a discovered preload read with another package type releases its entry instead of leaking it across parked-worker reuse. - Keep a parked JavaScript worker owned by its scope until its close succeeds. - Borrow only sealed JSON members that sealing visited, and seal a shared subtree once instead of once per path. - Refuse borrowed Evidence declarations whose resolution depends on the union branch their own frame parse selected. * test(domain): bound shared JSON sealing inspections A synchronous seal cannot be interrupted by the test timeout, so a lost visited set would expand every shared path on the worker. Stop descriptor reads after one per owned edge of this call and assert that count. Co-authored-by: morluto --------- Co-authored-by: Cursor Agent Co-authored-by: morluto --- .../evidenceInputConformance.test.ts | 26 +++++++ src/domain/evidenceInputContract.ts | 19 +++++ src/domain/immutableJson.test.ts | 67 ++++++++++++++++++ src/domain/immutableJson.ts | 25 ++++++- .../JavaScriptAnalysisWorkerServer.ts | 69 +++++++++++++------ .../analysis/JavaScriptSourceAnalysis.ts | 8 ++- .../JavaScriptStaticCheckpointReuse.test.ts | 24 ++++++- src/sqlite/SqliteDatabaseProvider.ts | 17 ++++- .../sqlite/sqliteDatabaseCleanup.test.ts | 47 +++++++++++++ 9 files changed, 274 insertions(+), 28 deletions(-) diff --git a/src/contracts/evidenceInputConformance.test.ts b/src/contracts/evidenceInputConformance.test.ts index a88d5288f5..8ff987aa42 100644 --- a/src/contracts/evidenceInputConformance.test.ts +++ b/src/contracts/evidenceInputConformance.test.ts @@ -5,6 +5,7 @@ import { analysisViewSourceSchema } from "../domain/analysisView/analysisViewReq import { evidenceSchema } from "../domain/evidence.js"; import { evidenceBundleSchema } from "../domain/evidenceBundle.js"; import { + declareBorrowedEvidenceInput, getEvidenceInputContract, isDeclaredEvidenceInput, isEvidenceReferenceAlternative, @@ -248,4 +249,29 @@ describe("public Evidence input declarations", () => { ]); expect(declarationIssues(choice.prefault(fallback))).toEqual([]); }); + + it("refuses to borrow a declaration that resolves by its parsed union branch", () => { + const choice = z.union([ + z.strictObject({ + kind: z.literal("source"), + source: evidenceInputSchema, + }), + z.strictObject({ kind: z.literal("none") }), + ]); + // The borrowing parser never runs the union's branch capture, so its + // Evidence would pass through unvisited. + expect(() => + getEvidenceInputContract( + declareBorrowedEvidenceInput(z.unknown().nonoptional(), choice), + ), + ).toThrow("cannot select union branches"); + expect( + getEvidenceInputContract( + declareBorrowedEvidenceInput( + z.unknown().nonoptional(), + z.array(evidenceInputSchema), + ), + ).hasEvidence, + ).toBe(true); + }); }); diff --git a/src/domain/evidenceInputContract.ts b/src/domain/evidenceInputContract.ts index 89e44ffac9..6c730f705c 100644 --- a/src/domain/evidenceInputContract.ts +++ b/src/domain/evidenceInputContract.ts @@ -118,6 +118,11 @@ export interface EvidenceInputContract { readonly hasEvidence: boolean; /** A declared field can replace inline Evidence with a retained reference. */ readonly hasEvidenceReferenceAlternative: boolean; + /** + * Resolution depends on the union branch this contract's own frame parse + * selected, so the frame cannot be replaced by another parser. + */ + readonly selectsParsedBranch: boolean; resolve( input: unknown, visit: Visitor, @@ -133,6 +138,7 @@ const identity = ( frameSchema: schema, hasEvidence: false, hasEvidenceReferenceAlternative, + selectsParsedBranch: false, resolve: (input) => ok(input), }); @@ -164,6 +170,7 @@ const compile = (schema: z.ZodType): EvidenceInputContract => { frameSchema: z.unknown().nonoptional(), hasEvidence: true, hasEvidenceReferenceAlternative: true, + selectsParsedBranch: false, resolve: (input, visit, path = []) => visit(input, path), }; if (declared?.kind === "borrowed") { @@ -171,6 +178,12 @@ const compile = (schema: z.ZodType): EvidenceInputContract => { if (declaration === undefined) throw new TypeError("Borrowed Evidence schema has no owning declaration"); const source = getEvidenceInputContract(declaration); + // The borrowing parser replaces the frame, so a source that resolves by + // the branch its own frame selected would never visit its Evidence. + if (source.selectsParsedBranch) + throw new TypeError( + "Borrowed Evidence declarations cannot select union branches by parsing", + ); return { ...source, frameSchema: schema }; } if (schema instanceof z.ZodObject) return objectContract(schema); @@ -191,6 +204,7 @@ const compile = (schema: z.ZodType): EvidenceInputContract => { return { hasEvidence: true, hasEvidenceReferenceAlternative: child.hasEvidenceReferenceAlternative, + selectsParsedBranch: child.selectsParsedBranch, frameSchema: replaceWrappedSchema(schema, child.frameSchema), resolve: (input, visit, path = []) => input === undefined || @@ -225,6 +239,9 @@ const objectContract = (schema: z.ZodObject): EvidenceInputContract => { return { hasEvidence: true, hasEvidenceReferenceAlternative, + selectsParsedBranch: selected.some( + ([, child]) => child.selectsParsedBranch, + ), frameSchema: schema.clone( { ...schema.def, @@ -257,6 +274,7 @@ const arrayContract = (schema: z.ZodArray): EvidenceInputContract => { return { hasEvidence: true, hasEvidenceReferenceAlternative: child.hasEvidenceReferenceAlternative, + selectsParsedBranch: child.selectsParsedBranch, frameSchema: schema.clone( { ...schema.def, element: child.frameSchema }, { parent: true }, @@ -301,6 +319,7 @@ const unionContract = (schema: z.ZodUnion): EvidenceInputContract => { return { hasEvidence: true, hasEvidenceReferenceAlternative, + selectsParsedBranch: true, frameSchema: frame.clone({ ...frame.def, ...(schema.def.error === undefined ? {} : { error: schema.def.error }), diff --git a/src/domain/immutableJson.test.ts b/src/domain/immutableJson.test.ts index 49caf837b0..c81a3590f9 100644 --- a/src/domain/immutableJson.test.ts +++ b/src/domain/immutableJson.test.ts @@ -3,12 +3,79 @@ import { describe, expect, it, vi } from "vitest"; import type { JsonValue } from "./jsonValue.js"; import { freezeJsonSnapshot, + freezeOwnedJsonTreeSnapshot, canBorrowParsedJsonSnapshot, immutableJsonSnapshotMember, isImmutableJsonSnapshot, } from "./immutableJson.js"; describe("owned immutable JSON snapshots", () => { + it("never borrows a member that sealing did not visit", () => { + const hidden = { mutable: true }; + const named = { mutable: true }; + const items: JsonValue[] = [1]; + Object.defineProperty(items, "named", { value: named, enumerable: true }); + const record: Record = { items }; + Object.defineProperty(record, "hidden", { value: hidden }); + const sealed = freezeOwnedJsonTreeSnapshot(record); + expect(immutableJsonSnapshotMember(sealed, "hidden")).toBeUndefined(); + const borrowed = immutableJsonSnapshotMember(sealed, "items"); + expect(borrowed).toBe(items); + expect(immutableJsonSnapshotMember(borrowed, "named")).toBeUndefined(); + expect(immutableJsonSnapshotMember(borrowed, "0")).toBe(1); + expect(isImmutableJsonSnapshot(hidden)).toBe(false); + expect(isImmutableJsonSnapshot(named)).toBe(false); + expect(Object.isFrozen(named)).toBe(false); + }); + + it("seals a shared subtree once rather than once per path", () => { + // Each level references the next twice: 2^60 paths and 61 objects. The + // seal is synchronous, so a lost visited set would expand those paths on + // this worker before Vitest can time the test out. The budget is one + // descriptor per owned edge of this call. + const sharingDepth = 60; + let level: JsonValue = { leaf: true }; + for (let depth = 0; depth < sharingDepth; depth += 1) + level = [level, level]; + const inspectionBudget = sharingDepth * 2 + 1; + const describeProperty = Object.getOwnPropertyDescriptor; + let inspections = 0; + const observed = vi + .spyOn(Object, "getOwnPropertyDescriptor") + .mockImplementation((target, property) => { + inspections += 1; + if (inspections > inspectionBudget) + throw Object.assign( + new Error("Shared JSON sealing exceeded its inspection budget"), + { + code: "inspection_budget_exceeded" as const, + inspections, + budget: inspectionBudget, + }, + ); + return describeProperty(target, property); + }); + let sealed: JsonValue; + try { + sealed = freezeOwnedJsonTreeSnapshot(level); + } finally { + observed.mockRestore(); + } + expect(inspections).toBe(inspectionBudget); + expect(isImmutableJsonSnapshot(sealed)).toBe(true); + let cursor: JsonValue = sealed; + for (let depth = 0; depth < sharingDepth; depth += 1) { + expect(Array.isArray(cursor)).toBe(true); + const pair = cursor as readonly JsonValue[]; + expect(pair).toHaveLength(2); + expect(pair[0]).toBe(pair[1]); + expect(Object.isFrozen(pair)).toBe(true); + cursor = pair[0] as JsonValue; + } + expect(cursor).toEqual({ leaf: true }); + expect(Object.isFrozen(cursor)).toBe(true); + }); + it("borrows only the selected own child of a completed sealed root", () => { const value = freezeJsonSnapshot({ selected: { values: [1, 2] }, diff --git a/src/domain/immutableJson.ts b/src/domain/immutableJson.ts index 7ee4f36ed6..a9f3b7bf52 100644 --- a/src/domain/immutableJson.ts +++ b/src/domain/immutableJson.ts @@ -16,6 +16,16 @@ export const isImmutableJsonSnapshot = (value: unknown): value is JsonValue => (typeof value === "number" && Number.isFinite(value)) || (typeof value === "object" && immutableSnapshots.has(value)); +const isArrayIndex = (key: string, length: number): boolean => { + const index = Number(key); + return ( + Number.isInteger(index) && + index >= 0 && + index < length && + String(index) === key + ); +}; + /** Borrow one own member of a completed snapshot, carrying its sealing proof. */ export const immutableJsonSnapshotMember = ( snapshot: unknown, @@ -30,6 +40,13 @@ export const immutableJsonSnapshotMember = ( const descriptor = Object.getOwnPropertyDescriptor(snapshot, key); if (descriptor === undefined || !Object.hasOwn(descriptor, "value")) return undefined; + // Sealing visits only JSON members: enumerable object keys and array + // indices. Any other own property was never checked or frozen beneath it. + if ( + !descriptor.enumerable || + (Array.isArray(snapshot) && !isArrayIndex(key, snapshot.length)) + ) + return undefined; // Completed sealing checked and froze every reachable member. Register only // the selected child; do not traverse it again or add per-node weak entries. const member = descriptor.value as JsonValue; @@ -151,7 +168,8 @@ type OwnedTreeFrame = /** * Seal a freshly parsed, exclusively owned JSON tree. Its parser has removed * aliases, accessors and hidden properties; existing sealed subtrees may be shared. - * Keep only the active ancestry rather than retaining every completed object. + * Completed objects are remembered only for this call, so a subtree shared + * along several paths is sealed once instead of once per path. * Unlike general graph sealing, failure can leave this provisional tree frozen. */ export const freezeOwnedJsonTreeSnapshot = ( @@ -159,8 +177,11 @@ export const freezeOwnedJsonTreeSnapshot = ( ): T => { const frames: OwnedTreeFrame[] = []; const ancestors = new Set(); + const completed = new Set(); const enter = (item: unknown): void => { if (isImmutableJsonSnapshot(item)) return; + if (typeof item === "object" && item !== null && completed.has(item)) + return; if (typeof item !== "object" || item === null) throw new TypeError("Immutable JSON snapshots require JSON values"); if (isProxy(item)) @@ -199,6 +220,7 @@ export const freezeOwnedJsonTreeSnapshot = ( } else { Object.freeze(frame.value); ancestors.delete(frame.value); + completed.add(frame.value); frames.pop(); } } else if (frame.index < frame.keys.length) { @@ -213,6 +235,7 @@ export const freezeOwnedJsonTreeSnapshot = ( } else { Object.freeze(frame.value); ancestors.delete(frame.value); + completed.add(frame.value); frames.pop(); } } diff --git a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts index 54ea0ca18b..92d912fb4f 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts @@ -90,36 +90,59 @@ export interface RetainedStaticCheckpoint extends ReusedJavaScriptStatic { * the key, so a reused checkpoint is byte-identical to a recomputed one. The * store keeps at most one eighth of the V8 heap limit and stays empty where * the runtime does not report one; a miss recomputes. + * + * Entries are keyed by source identity. The normal pass analyzes each source + * once and always removes its entry; it reuses the checkpoint only when the + * package type also matches. A discovered preload script is read as CommonJS + * after discovery read its package as ESM, and that entry must not outlive + * the pass that can no longer use it. */ -const retainedStatics = new Map(); +interface RetainedStaticEntry { + readonly packageType: string; + readonly checkpoint: RetainedStaticCheckpoint; +} +const retainedStatics = new Map(); let retainedStaticBytes = 0; +/** Which source a checkpoint describes, and the package type it was read as. */ +export interface JavaScriptStaticReuseKey { + readonly source: string; + readonly packageType: string; +} + export const javaScriptStaticReuseKey = ( request: ReturnType, -): string => - JSON.stringify([ +): JavaScriptStaticReuseKey => ({ + source: JSON.stringify([ request.file.container_sha256, request.file.path, request.text_sha256, - request.package_type, request.semantic_precision ?? null, request.member_mutation_allowance, - ]); + ]), + packageType: request.package_type, +}); const staticReuseCapacityBytes = (): number => javaScriptRuntime(process.versions).id === "node" ? Math.floor(getHeapStatistics().heap_size_limit / 8) : 0; +const releaseRetainedStatic = ( + source: string, +): RetainedStaticEntry | undefined => { + const previous = retainedStatics.get(source); + if (previous === undefined) return undefined; + retainedStatics.delete(source); + retainedStaticBytes -= previous.checkpoint.retainedBytes; + return previous; +}; + export const retainJavaScriptStaticCheckpoint = ( - key: string, + key: JavaScriptStaticReuseKey, facts: JavaScriptStaticAnalysis, ): void => { - const previous = retainedStatics.get(key); - if (previous !== undefined) { - retainedStatics.delete(key); - retainedStaticBytes -= previous.retainedBytes; - } + releaseRetainedStatic(key.source); // Skip encoding where reuse is disabled or no capacity remains. const capacity = staticReuseCapacityBytes(); if (retainedStaticBytes >= capacity) return; @@ -137,23 +160,25 @@ export const retainJavaScriptStaticCheckpoint = ( return; } if (retainedStaticBytes + retainedBytes > capacity) return; - retainedStatics.set(key, { - text, - retainedBytes, - parse_status: facts.parse_status, - call_paths: facts.electron.call_paths, + retainedStatics.set(key.source, { + packageType: key.packageType, + checkpoint: { + text, + retainedBytes, + parse_status: facts.parse_status, + call_paths: facts.electron.call_paths, + }, }); retainedStaticBytes += retainedBytes; }; export const takeJavaScriptStaticCheckpoint = ( - key: string, + key: JavaScriptStaticReuseKey, ): RetainedStaticCheckpoint | undefined => { - const retained = retainedStatics.get(key); - if (retained === undefined) return undefined; - retainedStatics.delete(key); - retainedStaticBytes -= retained.retainedBytes; - return retained; + const retained = releaseRetainedStatic(key.source); + return retained?.packageType === key.packageType + ? retained.checkpoint + : undefined; }; /** Validate, fit and bound static facts as the checkpoint the parent reads. */ diff --git a/src/javascript/analysis/JavaScriptSourceAnalysis.ts b/src/javascript/analysis/JavaScriptSourceAnalysis.ts index 83a4e5740a..96b44bb287 100644 --- a/src/javascript/analysis/JavaScriptSourceAnalysis.ts +++ b/src/javascript/analysis/JavaScriptSourceAnalysis.ts @@ -207,8 +207,14 @@ class ScopeJavaScriptSourceAnalysis implements JavaScriptSourceAnalysisPort { current.busy = false; return; } - if (current?.worker === this.worker) retained.delete(this.scope); + // Release the scope's ownership only after the process stopped; a + // failed close stays owned by the scope's close hook. await this.worker.close(); + if ( + current?.worker === this.worker && + retained.get(this.scope) === current + ) + retained.delete(this.scope); } catch (cause) { this.#closed = false; throw cause; diff --git a/src/javascript/analysis/JavaScriptStaticCheckpointReuse.test.ts b/src/javascript/analysis/JavaScriptStaticCheckpointReuse.test.ts index ef1951088c..900a00dd77 100644 --- a/src/javascript/analysis/JavaScriptStaticCheckpointReuse.test.ts +++ b/src/javascript/analysis/JavaScriptStaticCheckpointReuse.test.ts @@ -66,7 +66,6 @@ it("retains a discovery checkpoint once for the exact request, including sources const base = request(randomUUID(), plain, "analysis"); retainJavaScriptStaticCheckpoint(javaScriptStaticReuseKey(base), facts); for (const other of [ - request(randomUUID(), plain, "analysis", { package_type: "module" }), request(randomUUID(), plain, "analysis", { path: "other.js" }), request(randomUUID(), `${plain}\n`, "analysis"), ]) @@ -80,6 +79,29 @@ it("retains a discovery checkpoint once for the exact request, including sources ).toBe(encodeJavaScriptStaticCheckpoint(facts)); }); +it("drops a checkpoint the normal pass reads with another package type", () => { + // Discovery reads an ESM package's preload as a module; the normal pass + // reads the discovered preload as CommonJS and cannot reuse that checkpoint. + const preload = "export const ready = true;"; + const facts = analyzeJavaScriptStaticSource(preload); + const discovered = request(randomUUID(), preload, "preload-discovery", { + path: "preload.js", + package_type: "module", + }); + const normal = request(randomUUID(), preload, "analysis", { + path: "preload.js", + package_type: "commonjs", + }); + retainJavaScriptStaticCheckpoint(javaScriptStaticReuseKey(discovered), facts); + expect( + takeJavaScriptStaticCheckpoint(javaScriptStaticReuseKey(normal)), + ).toBeUndefined(); + // The mismatched take released the entry rather than parking it forever. + expect( + takeJavaScriptStaticCheckpoint(javaScriptStaticReuseKey(discovered)), + ).toBeUndefined(); +}); + /** Start the production worker entrypoint in its own private root. */ const startWorker = async () => { const root = await createTestTempDirectory("rea-js-static-reuse-"); diff --git a/src/sqlite/SqliteDatabaseProvider.ts b/src/sqlite/SqliteDatabaseProvider.ts index 9b5c72d3ed..cd71f051f2 100644 --- a/src/sqlite/SqliteDatabaseProvider.ts +++ b/src/sqlite/SqliteDatabaseProvider.ts @@ -17,6 +17,7 @@ import type { AnalysisError, } from "../domain/analysisErrorBase.js"; import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; +import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { AnalysisOutputError, AnalysisResourceConstraintError, @@ -358,6 +359,16 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { result = err(failure); } if (root !== undefined && processOwner !== undefined) { + // This branch keeps the worker instead of finalizing through runOwned; + // retain a late caller cancellation as runOwned would. + const signal = options?.signal; + const withLateCancellation = (failure: AnalysisError): AnalysisError => + signal?.aborted === true + ? analysisErrorWithCancellation( + failure, + cancelledBy(operation, signal), + ) + : failure; const ownership = processOwner.launch.ownership; const rootRelease = new AnalysisCleanupRelease(); const rootFailure = rootRelease.bind(sqliteRootFailure(root)); @@ -413,11 +424,11 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { }, ); failure.bindCleanupDependencies([processFailure, rootFailure]); - return err(failure); + return err(withLateCancellation(failure)); } if (!result.ok) { result.error.bindCleanupDependencies([processFailure, rootFailure]); - return result; + return err(withLateCancellation(result.error)); } const failure = sqliteCleanupFailure( [ @@ -432,7 +443,7 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { retainedOutput, ); failure.bindCleanupDependencies([processFailure, rootFailure]); - return err(failure); + return err(withLateCancellation(failure)); } const finalized = await runOwned(async () => result, { providerId: SQLITE_PROVIDER_IDENTITY.id, diff --git a/tests/boundary/sqlite/sqliteDatabaseCleanup.test.ts b/tests/boundary/sqlite/sqliteDatabaseCleanup.test.ts index 64d7916a2c..b47bc97dab 100644 --- a/tests/boundary/sqlite/sqliteDatabaseCleanup.test.ts +++ b/tests/boundary/sqlite/sqliteDatabaseCleanup.test.ts @@ -2,6 +2,7 @@ import { access } from "node:fs/promises"; import { expect, it, onTestFinished } from "vitest"; import { SqliteDatabaseProvider } from "../../../src/sqlite/SqliteDatabaseProvider.js"; import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; +import { primaryAnalysisError } from "../../../src/domain/analysisErrorBase.js"; import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js"; import { @@ -524,3 +525,49 @@ it("keeps a retained worker owner when the worker fails and its cleanup is unres mayClean = true; await provider.close(); }); + +it("keeps a late caller cancellation beside a retained worker cleanup failure", async () => { + const workspace = await createTestWorkspace("rea-sqlite-late-cancel-"); + const database = createSqliteDatabaseFixture(workspace.root); + database.close(); + const controller = new AbortController(); + const reason = new Error("caller stopped waiting"); + let mayClean = false; + // The real worker completes; the caller cancels while its cleanup is + // unresolved, after the work itself could still observe the signal. + const provider = new SqliteDatabaseProvider({}, async (spawn) => { + const launched = await spawnOwnedProviderProcess(spawn); + const cleanupOwned = + launched.cleanup ?? (() => cleanupOwnedProcessGroup(launched.ownership)); + return { + ...launched, + cleanup: async () => { + const cleaned = await cleanupOwned(); + if (mayClean) return cleaned; + controller.abort(reason); + throw new Error("injected retained cleanup failure"); + }, + }; + }); + onTestFinished(async () => { + mayClean = true; + await provider.close(); + await removeTestWorkspace(workspace.root); + }); + const result = await provider.inspect( + { path: database.path }, + { signal: controller.signal }, + ); + if (result.ok) throw new Error("Expected retained worker cleanup"); + expect(controller.signal.aborted).toBe(true); + expect(result.error.cleanupIncomplete).toBe(true); + const primary = primaryAnalysisError(result.error); + expect( + primary.cause === reason || + primary.secondaryFailures.some( + (secondary) => + secondary._tag === "AnalysisCancelledError" && + secondary.cause === reason, + ), + ).toBe(true); +});