diff --git a/src/kuna/KunaSpecIdentity.ts b/src/kuna/KunaSpecIdentity.ts index 174f4d29af1..33a45f4b1ad 100644 --- a/src/kuna/KunaSpecIdentity.ts +++ b/src/kuna/KunaSpecIdentity.ts @@ -4,7 +4,11 @@ import { lstat, opendir, readlink, realpath, stat } from "node:fs/promises"; import { z } from "zod"; -import { cancelledBy, OwnerCancellation } from "../domain/analysisErrorCore.js"; +import { + cancelledBy, + carriedReason, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { Deadline } from "../domain/deadline.js"; import { equalJsonValues, type JsonValue } from "../domain/jsonValue.js"; @@ -345,8 +349,14 @@ const listDirectory = async ( }; const message = `Could not close specification directory ${directory}: ${errorMessage(cause)}`; // An interrupted listing stays an interruption; the close failure is its - // cleanup, as on the regular-file path. - const interruption = regularFileCancellation(failure); + // cleanup, as on the regular-file path. A close-time abort is an + // interruption only when the listing finished without a failure, so a + // later cancellation does not hide a physical read error. + const interruption = + regularFileCancellation(failure) ?? + (failure === undefined && options.signal?.aborted === true + ? { reason: options.signal.reason } + : undefined); throw interruption === undefined ? new ArtifactReaderFailure("unavailable", message, cleanupFacts) : new ArtifactReaderFailure("cancelled", message, { @@ -638,6 +648,14 @@ const identifySpecTree = async ( }; }; +/** The cancellation recorded by an interrupted spec read, file or directory. */ +const scanInterruption = ( + cause: unknown, +): { readonly reason: unknown } | undefined => + cause instanceof ArtifactReaderFailure + ? cause.cancellation + : regularFileCancellation(cause); + /** * An interrupted spec read whose file or directory close then failed: the * cleanup it still owes and the lease that retries it. @@ -684,11 +702,6 @@ const withCleanup = ( return error; }; -const specScanCancelled = (cause: unknown): boolean => - cause instanceof RegularFileCancelled || - cause instanceof RegularFileOperationCancelled || - regularFileCancellation(cause) !== undefined; - const readKunaExternalSpecs = async ( specs: readonly KunaSelectedSpec[], options: KunaSpecIdentityOptions, @@ -739,34 +752,31 @@ export const identifyKunaExternalSpecs = async ( if (options.budget.expired()) throw specTreeTimeout(options); return records; } catch (cause: unknown) { + // What stopped the read is the recorded interruption, not whichever + // signal is aborted by the time cleanup has settled. + const stopped = scanInterruption(cause); + if (stopped === undefined) throw cause; const interrupted = interruptedCleanup(cause); - if (options.signal?.aborted === true) { - // A file close failure already reports its cancellation downstream; a - // directory's envelope keeps the caller's cancellation here. - if ( - !(cause instanceof ArtifactReaderFailure) || - interrupted === undefined - ) - throw cause; - throw withCleanup( - cancelledBy(options.operation, options.signal, { - cleanup: interrupted.cleanup, - }), - interrupted.leases, - ); - } - if (!(controller.signal.aborted || options.budget.expired())) throw cause; - // Only a read the deadline stopped is a timeout. An earlier physical - // failure keeps its own cause beside any cleanup it left. - if (interrupted === undefined && !specScanCancelled(cause)) throw cause; - // A handle whose close failed while the deadline stopped the read stays - // with the timeout, bound to its retained lease. - throw interrupted === undefined - ? specTreeTimeout(options) - : withCleanup( - specTreeTimeout(options, interrupted.cleanup), - interrupted.leases, - ); + if ( + controller.signal.aborted && + stopped.reason === controller.signal.reason + ) + throw interrupted === undefined + ? specTreeTimeout(options) + : withCleanup( + specTreeTimeout(options, interrupted.cleanup), + interrupted.leases, + ); + // A file close failure reports its cancellation downstream; a directory's + // envelope keeps the caller's cancellation here. + if (!(cause instanceof ArtifactReaderFailure) || interrupted === undefined) + throw cause; + throw withCleanup( + cancelledBy(options.operation, carriedReason(stopped.reason), { + cleanup: interrupted.cleanup, + }), + interrupted.leases, + ); } finally { clearTimeout(timer); } diff --git a/tests/boundary/providers/kuna/kunaSpecIdentity.test.ts b/tests/boundary/providers/kuna/kunaSpecIdentity.test.ts index 67b07124db7..bf0a1de2955 100644 --- a/tests/boundary/providers/kuna/kunaSpecIdentity.test.ts +++ b/tests/boundary/providers/kuna/kunaSpecIdentity.test.ts @@ -989,11 +989,12 @@ it("keeps a launch's spec-directory close failure on the command scope", async ( }); /** Fail the next directory close after really closing it, so a retry succeeds. */ -const failNextDirectoryClose = () => { +const failNextDirectoryClose = (duringClose?: () => void) => { const close = vi .spyOn(OwnedDirectoryHandle.prototype, "close") .mockImplementationOnce(async function (this: OwnedDirectoryHandle) { close.mockRestore(); + duringClose?.(); await this.close(); throw new Error("spec directory close failed"); }); @@ -1095,6 +1096,200 @@ it("reports a deadline-stopped directory listing as a timeout beside its failed expect(thrown).toMatchObject({ cleanupIncomplete: false }); }); +it("keeps a cancellation that arrives while a finished listing closes", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-dir-close-cancel-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const caller = new AbortController(); + // Enumeration finished; the caller cancels while the close is pending. + const close = failNextDirectoryClose(() => caller.abort()); + const retained: AnalysisCleanupLease[] = []; + let thrown: unknown; + try { + await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: specs }], + specRead({ + platform: "linux", + signal: caller.signal, + retainFailedClose: (owner, resource) => { + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + retained.push(lease); + return lease; + }, + }), + ); + } catch (cause: unknown) { + thrown = cause; + } finally { + close.mockRestore(); + } + expect(thrown).toMatchObject({ + _tag: "AnalysisCancelledError", + cleanupIncomplete: true, + cleanupResources: [specs], + }); + await retained[0]?.release(); + expect(thrown).toMatchObject({ cleanupIncomplete: false }); +}); + +it("keeps the deadline that stopped a listing when the caller cancels during its close", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-dir-late-cancel-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const caller = new AbortController(); + const originalRead = Dir.prototype.read as (this: Dir) => Promise; + // The 50 ms scan deadline stops the listing first. + const read = vi + .spyOn(Dir.prototype, "read") + .mockImplementationOnce(async function (this: Dir) { + await new Promise((resolve) => setTimeout(resolve, 150)); + return originalRead.call(this); + } as unknown as typeof Dir.prototype.read); + // The caller's later cancellation must not replace that timeout. + const close = failNextDirectoryClose(() => caller.abort()); + const deadline = { + setting: "REA_KUNA_TIMEOUT_MS" as const, + ms: 50, + source: "runtime" as const, + }; + let thrown: unknown; + try { + await identifyKunaExternalSpecs([{ variable: "KUNA_SPECS", path: specs }], { + operation: "kuna:spec-identity", + deadline, + budget: Deadline.after(deadline.ms), + platform: "linux", + signal: caller.signal, + retainFailedClose: (owner, resource) => + AnalysisCleanupLease.forCloseOwner(owner, resource), + }); + } catch (cause: unknown) { + thrown = cause; + } finally { + read.mockRestore(); + close.mockRestore(); + } + expect(thrown).toMatchObject({ + _tag: "AnalysisTimeoutError", + cleanupIncomplete: true, + limit: { setting: "kuna.function_timeout_ms", effective_value: 50 }, + }); +}); + +it("keeps a listing read failure when cancellation arrives during its close", async () => { + const root = await createTestTempDirectory( + "rea-kuna-spec-dir-read-fail-cancel-", + ); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const caller = new AbortController(); + const listingFailed = Object.assign(new Error("spec directory read failed"), { + code: "EIO", + }); + const read = vi + .spyOn(Dir.prototype, "read") + .mockImplementationOnce(async () => { + throw listingFailed; + }); + // The caller cancels while the failed close settles; that must not replace + // the physical listing failure. + const close = failNextDirectoryClose(() => caller.abort()); + const retained: AnalysisCleanupLease[] = []; + let thrown: unknown; + try { + await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: specs }], + specRead({ + platform: "linux", + signal: caller.signal, + retainFailedClose: (owner, resource) => { + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + retained.push(lease); + return lease; + }, + }), + ); + } catch (cause: unknown) { + thrown = cause; + } finally { + read.mockRestore(); + close.mockRestore(); + } + expect(thrown).toMatchObject({ + name: "ArtifactReaderFailure", + reason: "unavailable", + cause: listingFailed, + cleanup: { resources: [specs] }, + cleanupLeases: [retained[0]], + }); + expect(thrown).not.toHaveProperty("_tag", "AnalysisCancelledError"); + await retained[0]?.release(); +}); + +it("keeps a listing read failure when the deadline arrives during its close", async () => { + const root = await createTestTempDirectory( + "rea-kuna-spec-dir-read-fail-timeout-", + ); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const listingFailed = Object.assign(new Error("spec directory read failed"), { + code: "EIO", + }); + const read = vi + .spyOn(Dir.prototype, "read") + .mockImplementationOnce(async () => { + throw listingFailed; + }); + // The 50 ms scan deadline fires while close is pending. It did not stop + // the read, so the close failure must keep the listing error. + const close = vi + .spyOn(OwnedDirectoryHandle.prototype, "close") + .mockImplementationOnce(async function (this: OwnedDirectoryHandle) { + close.mockRestore(); + await new Promise((resolve) => setTimeout(resolve, 150)); + await this.close(); + throw new Error("spec directory close failed"); + }); + const retained: AnalysisCleanupLease[] = []; + const deadline = { + setting: "REA_KUNA_TIMEOUT_MS" as const, + ms: 50, + source: "runtime" as const, + }; + let thrown: unknown; + try { + await identifyKunaExternalSpecs([{ variable: "KUNA_SPECS", path: specs }], { + operation: "kuna:spec-identity", + deadline, + budget: Deadline.after(deadline.ms), + platform: "linux", + retainFailedClose: (owner, resource) => { + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + retained.push(lease); + return lease; + }, + }); + } catch (cause: unknown) { + thrown = cause; + } finally { + read.mockRestore(); + close.mockRestore(); + } + expect(thrown).toMatchObject({ + name: "ArtifactReaderFailure", + reason: "unavailable", + cause: listingFailed, + cleanup: { resources: [specs] }, + cleanupLeases: [retained[0]], + }); + expect(thrown).not.toHaveProperty("_tag", "AnalysisTimeoutError"); + await retained[0]?.release(); +}); + it("binds a specification file close to the lease the hook returned", async () => { const root = await createTestTempDirectory("rea-kuna-spec-file-close-"); const specs = join(root, "specs");