diff --git a/src/captures/TsharkCaptureProvider.ts b/src/captures/TsharkCaptureProvider.ts index d22515929..23496aac4 100644 --- a/src/captures/TsharkCaptureProvider.ts +++ b/src/captures/TsharkCaptureProvider.ts @@ -175,7 +175,7 @@ export class TsharkCaptureProvider implements PacketCapturePort { ]; phase = "workspace"; root = await this.createRuntime(); - this.#resources.retain(root, undefined, operation); + this.#resources.retain(root, undefined); const snapshotPath = join(root.path, "capture"); const configurationPath = join(root.path, "configuration"); await mkdir(configurationPath, { mode: 0o700 }); @@ -406,7 +406,7 @@ export class TsharkCaptureProvider implements PacketCapturePort { cause instanceof OwnedCommandFailure && cause.cleanupOwner !== undefined ) - this.#resources.retain(root, cause.cleanupOwner, operation); + this.#resources.retain(root, cause.cleanupOwner); result = err( this.#failure( cause, diff --git a/src/process/ArtifactAnalysisResources.ts b/src/process/ArtifactAnalysisResources.ts index b0083e05b..ae3d9f803 100644 --- a/src/process/ArtifactAnalysisResources.ts +++ b/src/process/ArtifactAnalysisResources.ts @@ -33,7 +33,10 @@ export type ArtifactAnalysisRuntime = Pick< /** Own admission, artifact descriptors, producer cleanup and private workspaces together. */ export class ArtifactAnalysisResources { - readonly #artifacts = new ArtifactResourceScope(); + readonly #artifacts: { + readonly scope: ArtifactResourceScope; + operation: string; + }; readonly #pending = new Map< ArtifactAnalysisRuntime, { @@ -54,7 +57,9 @@ export class ArtifactAnalysisResources { readonly message: string; readonly details: Readonly>; }, - ) {} + ) { + this.#artifacts = { scope: new ArtifactResourceScope(), operation }; + } run( work: () => Promise>, @@ -76,8 +81,15 @@ export class ArtifactAnalysisResources { ); this.#busy = true; const running = this.#tail - .then(() => this.#artifacts.run(work)) - .catch((cause: unknown) => err(this.#artifactFailure(cause, operation))) + .then(() => + this.#artifacts.scope.run(() => { + // Failed descriptor cleanup still belongs to the preceding request until + // this scope has drained it and admits acquisition for the new request. + this.#artifacts.operation = operation; + return work(); + }), + ) + .catch((cause: unknown) => err(this.#artifactFailure(cause))) .finally(() => { this.#busy = false; }); @@ -94,20 +106,23 @@ export class ArtifactAnalysisResources { maximumBytes, signal, undefined, - this.#artifacts, + this.#artifacts.scope, ); } readLimits(limits: LinuxResourceLimits): Promise { - return this.readKernelLimits(limits, this.#artifacts); + return this.readKernelLimits(limits, this.#artifacts.scope); } retain( root: ArtifactAnalysisRuntime, owner?: ProviderProcessSupervisor, - operation = this.operation, ): void { - this.#pending.set(root, { owner, operation }); + this.#pending.set(root, { + owner, + operation: + this.#pending.get(root)?.operation ?? this.#artifacts.operation, + }); } get pendingPaths(): readonly string[] { @@ -251,7 +266,7 @@ export class ArtifactAnalysisResources { async #closeResources(): Promise { let descriptorFailure: AnalysisError | undefined; try { - await this.#artifacts.close(); + await this.#artifacts.scope.close(); } catch (cause: unknown) { descriptorFailure = this.#artifactFailure(cause); } @@ -262,14 +277,17 @@ export class ArtifactAnalysisResources { throw analysisErrorWithCleanupFailure( descriptorFailure, cause, - this.operation, + this.#artifacts.operation, ); throw cause; } if (descriptorFailure !== undefined) throw descriptorFailure; } - #artifactFailure(cause: unknown, operation = this.operation): AnalysisError { + #artifactFailure( + cause: unknown, + operation = this.#artifacts.operation, + ): AnalysisError { if (cause instanceof AnalysisError) return cause; if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined) return this.cleanupFailure(cause.cleanup, cause, undefined, operation); diff --git a/tests/boundary/captures/captureDescriptorCleanup.test.ts b/tests/boundary/captures/captureDescriptorCleanup.test.ts index a1ef5efc1..c200144c4 100644 --- a/tests/boundary/captures/captureDescriptorCleanup.test.ts +++ b/tests/boundary/captures/captureDescriptorCleanup.test.ts @@ -35,7 +35,15 @@ vi.mock("node:fs/promises", async (importOriginal) => { it .runIf(process.platform === "linux") - .each(["capture", "tool", "limiter", "kernel"])( + .each([ + "capture", + "tool", + "limiter", + "kernel", + "field-tool", + "field-limiter", + "field-kernel", + ])( "retains failed %s descriptors and retries them before further acquisition and shutdown", async (member) => { const directory = await createTestTempDirectory("rea-capture-descriptor-"); @@ -67,12 +75,17 @@ it }, () => PrivateRuntimeRoot.create({ parent: directory }), ); + const discovery = member.startsWith("field-"); + const resource = discovery ? member.slice(6) : member; + const operation = discovery + ? "inspect_packet_fields" + : "inspect_packet_capture"; cleanup.path = - member === "capture" + resource === "capture" ? path - : member === "tool" + : resource === "tool" ? command - : member === "limiter" + : resource === "limiter" ? limiter : "/proc/self/limits"; cleanup.denied = true; @@ -84,21 +97,31 @@ it cleanup.path = ""; }); const service = new PacketCaptureService(provider); - const first = await service.inspect({ path, fields: ["frame.number"] }); + const first = discovery + ? await service.inspectFields({ query: "usb" }) + : await service.inspect({ path, fields: ["frame.number"] }); expect(first).toMatchObject({ ok: false, - error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] }, + error: { + cleanupIncomplete: true, + cleanupResources: [cleanup.path], + operation, + }, }); expect(cleanup.handles).toHaveLength(1); expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0); const launchCount = launches; expect( await service.inspect({ path, fields: ["frame.number"] }), - ).toMatchObject({ ok: false, error: { cleanupIncomplete: true } }); + ).toMatchObject({ + ok: false, + error: { cleanupIncomplete: true, operation }, + }); expect(cleanup.handles).toHaveLength(1); expect(launches).toBe(launchCount); await expect(provider.close()).rejects.toMatchObject({ cleanupIncomplete: true, + operation, }); cleanup.denied = false; await provider.close(); diff --git a/tests/boundary/captures/captureProvider.test.ts b/tests/boundary/captures/captureProvider.test.ts index 2428b39d4..881b43e63 100644 --- a/tests/boundary/captures/captureProvider.test.ts +++ b/tests/boundary/captures/captureProvider.test.ts @@ -11,6 +11,9 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { createDeferred } from "../../fixtures/binarySession.js"; +import { Cli } from "incur"; +import { registerCaptureCommands } from "../../../src/cli/captureCommands.js"; +import { silentLogger } from "../../../src/logger.js"; // A command-boundary simulator: real process ownership/filesystem, not real TShark coverage. const fixture = async (mode = "ok", failCleanup = false) => { @@ -625,3 +628,34 @@ it("retains completed discovery on late cancellation and cleanup failure", async await f.service.close(); } }); + +it("preserves discovery resource ownership through CLI shutdown retries", async () => { + const f = await fixture("cleanup", true); + const cli = Cli.create("discovery-cleanup", { sync: false }); + registerCaptureCommands(cli, silentLogger, {}, f.service); + let stdout = ""; + try { + await cli.serve( + ["inspect-packet-fields", "--query", "usb", "--format", "json"], + { + stdout: (text) => { + stdout += text; + }, + exit: () => {}, + }, + ); + expect(JSON.parse(stdout)).toMatchObject({ + code: "cleanup_incomplete", + details: { + diagnostics: { + cleanup_error: { + details: { operation: "inspect_packet_fields" }, + }, + }, + }, + }); + } finally { + f.allowCleanup(); + await f.service.close(); + } +});