fix(artifacts): recheck failed DMG detaches before reporting cleanup failure (#1155)

* fix(artifacts): recheck failed DMG detaches before reporting cleanup failure

NativeDmgArtifactReader.close() detached each device once and, when a
detach failed, asked `hdiutil info` once whether the device was still
attached. On APFS images, detaching the synthesized container ejects the
image disk too. `hdiutil info` can still list that ejected device
briefly, and a just-read volume can report busy. Either way a real
cleanup succeeded but close() reported "DMG detach or mount-root cleanup
failed" and kept the mount root.

macOS CI hit this intermittently in verify:macos-bundle: `hdiutil
detach /dev/disk23` failed with "No such file or directory" (already
ejected) and the device was still counted as attached. The #1103
review also raised the missing recheck.

After the first pass, recheck the remaining devices up to three times
with 250/500/1000 ms settle delays. Drop any that hdiutil no longer
lists, retry the detach of any still listed, and fail only for devices
that stay attached. The host seam gains an optional delay so tests run
without real waits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(artifacts): share DMG detach fixtures to stay under the duplication gate

The new busy-device and recheck cases copied the fake hdiutil host and
the APFS close sequence from neighbouring tests, which pushed jscpd to
its 2.5% threshold in Static checks. Share one single-device host
between the busy and retained-attachment cases and one APFS close
helper between the ejected-device cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-09 10:01:52 +08:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 089bbf58f3
commit 58a91f03d7
2 changed files with 176 additions and 71 deletions
+47 -14
View File
@@ -15,6 +15,12 @@ import {
import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
const DETACH_TIMEOUT_MS = 120_000;
/**
* Waits before rechecking devices whose detach failed. A related device's
* later detach can eject one, `hdiutil info` can still list an ejected device
* briefly, and a volume can report busy just after it was read.
*/
const DETACH_SETTLE_DELAYS_MS = [250, 500, 1000] as const;
const attachOutputSchema = z.object({
"system-entities": z.array(
z.object({
@@ -43,9 +49,13 @@ export interface NativeDmgHost {
readonly exitCode: number;
readonly cause?: unknown;
}>;
/** Wait between detach rechecks; tests may resolve immediately. */
delay?(milliseconds: number): Promise<void>;
}
const systemHost: NativeDmgHost = {
delay: (milliseconds) =>
new Promise((resolve) => setTimeout(resolve, milliseconds)),
async run(arguments_, signal, options) {
try {
const { stdout, stderr } = await execFileOutput(
@@ -128,23 +138,33 @@ export class NativeDmgArtifactReader implements ArtifactReader {
async close(): Promise<void> {
let detachFailure: unknown;
const remainingDevices: string[] = [];
let remainingDevices: string[] = [];
for (const device of [...this.#devices].reverse()) {
try {
await runChecked(this.host, ["detach", device], undefined, {
timeoutMs: DETACH_TIMEOUT_MS,
});
this.#provenance.push(command(["detach", device], ["mount"]));
} catch (cause: unknown) {
// Detaching a synthesized APFS container also ejects the image that
// backs it, so a later whole disk of the same image may already be
// gone. Only a device that is still attached is a cleanup failure.
if (await this.#isAttached(device)) {
remainingDevices.push(device);
detachFailure ??= cause;
}
const failure = await this.#detach(device);
if (failure !== undefined) {
remainingDevices.push(device);
detachFailure ??= failure;
}
}
// Detaching a synthesized APFS container also ejects the image that backs
// it, so a device whose own detach failed may be gone by the end of the
// pass, and hdiutil can list an ejected device or report busy briefly.
// Only a device that stays attached through every recheck is a failure.
for (const delayMs of DETACH_SETTLE_DELAYS_MS) {
if (remainingDevices.length === 0) break;
await (this.host.delay ?? systemHost.delay)?.(delayMs);
const stillAttached: string[] = [];
for (const device of remainingDevices) {
if (!(await this.#isAttached(device))) continue;
const failure = await this.#detach(device);
if (failure !== undefined) {
stillAttached.push(device);
detachFailure = failure;
}
}
remainingDevices = stillAttached;
}
if (remainingDevices.length === 0) detachFailure = undefined;
this.#devices = remainingDevices.reverse();
if (this.#devices.length === 0 && this.#mountRoot !== undefined)
await rm(this.#mountRoot, { recursive: true, force: true }).then(
@@ -164,6 +184,19 @@ export class NativeDmgArtifactReader implements ArtifactReader {
);
}
/** Detach one device; return the failure only while it remains attached. */
async #detach(device: string): Promise<unknown> {
try {
await runChecked(this.host, ["detach", device], undefined, {
timeoutMs: DETACH_TIMEOUT_MS,
});
this.#provenance.push(command(["detach", device], ["mount"]));
return undefined;
} catch (cause: unknown) {
return (await this.#isAttached(device)) ? cause : undefined;
}
}
/**
* Report whether hdiutil still lists a device; unknown state counts as
* attached. Like detach, this cleanup query runs after the inventory
@@ -83,6 +83,7 @@ describe("native DMG artifact reader", () => {
await rm(mountRoot, { recursive: true, force: true });
});
const host: NativeDmgHost = {
delay: () => Promise.resolve(),
run(arguments_) {
if (arguments_[0] === "detach")
return Promise.reject(new Error("detach failed"));
@@ -396,14 +397,19 @@ it("owns the canonical mount root and detaches each observed whole image once",
// hdiutil reports the image disk and synthesized APFS container separately;
// detaching the container can already eject the image disk.
const apfsHost = (stillListed: readonly string[]) => {
const apfsHost = (
stillListed: readonly string[],
listedInfoReads = Infinity,
) => {
const calls: string[][] = [];
let infoReads = 0;
let mountRoot: string | undefined;
onTestFinished(async () => {
if (mountRoot !== undefined)
await rm(mountRoot, { recursive: true, force: true });
});
const host: NativeDmgHost = {
delay: () => Promise.resolve(),
async run(arguments_) {
calls.push([...arguments_]);
if (arguments_[0] === "detach" && arguments_[1] === "/dev/disk4")
@@ -412,7 +418,7 @@ const apfsHost = (stillListed: readonly string[]) => {
return {
stdout: build({
images:
stillListed.length === 0
stillListed.length === 0 || (infoReads += 1) > listedInfoReads
? []
: [
{
@@ -445,18 +451,91 @@ const apfsHost = (stillListed: readonly string[]) => {
return { calls, host };
};
// One mounted device whose detach reports busy while `busy(attempt)` holds.
const singleDeviceHost = (busy: (attempt: number) => boolean) => {
const state = {
attached: true,
attempts: 0,
mountRoot: undefined as string | undefined,
waits: [] as number[],
};
onTestFinished(async () => {
if (state.mountRoot !== undefined)
await rm(state.mountRoot, { recursive: true, force: true });
});
const host: NativeDmgHost = {
delay: (milliseconds) => {
state.waits.push(milliseconds);
return Promise.resolve();
},
async run(args) {
if (args[0] === "attach") {
state.mountRoot = args[args.indexOf("-mountroot") + 1];
if (state.mountRoot === undefined)
throw new Error("missing mount root");
const mountPoint = join(state.mountRoot, "Fixture");
await mkdir(mountPoint);
await writeFile(join(mountPoint, "hello.txt"), "owned observation");
return {
stdout: build({
"system-entities": [
{ "dev-entry": "/dev/disk7", "mount-point": mountPoint },
],
}),
exitCode: 0,
};
}
if (args[0] === "info")
return {
stdout: build({
images: state.attached
? [{ "system-entities": [{ "dev-entry": "/dev/disk7" }] }]
: [],
}),
exitCode: 0,
};
if (args[0] === "detach") {
state.attempts += 1;
if (busy(state.attempts))
return {
stdout: "",
stderr: "hdiutil: detach failed - Resource busy",
exitCode: 16,
};
state.attached = false;
}
return { stdout: "", exitCode: 0 };
},
};
return { host, state };
};
/** Close an APFS fixture and return the cleanup-phase hdiutil calls. */
const closeApfsFixture = async (
...listing: Parameters<typeof apfsHost>
): Promise<{
readonly reader: NativeDmgArtifactReader;
readonly cleanup: readonly string[][];
}> => {
const { calls, host } = apfsHost(...listing);
const reader = await NativeDmgArtifactReader.create(
"/tmp/image.dmg",
undefined,
host,
);
await reader.close();
return {
reader,
cleanup: calls.filter(
(call) => call[0] !== "verify" && call[0] !== "attach",
),
};
};
describe("APFS disk image detach", () => {
it("accepts an image disk that its container detach already ejected", async () => {
const { calls, host } = apfsHost([]);
const reader = await NativeDmgArtifactReader.create(
"/tmp/image.dmg",
undefined,
host,
);
await reader.close();
expect(
calls.filter((call) => call[0] !== "verify" && call[0] !== "attach"),
).toEqual([
const { reader, cleanup } = await closeApfsFixture([]);
expect(cleanup).toEqual([
["detach", "/dev/disk5"],
["detach", "/dev/disk4"],
["info", "-plist"],
@@ -482,51 +561,8 @@ describe("APFS disk image detach", () => {
});
it("retains a failed attachment and its mount root until a later close detaches it", async () => {
let mountRoot: string | undefined;
let busy = true;
let attached = true;
onTestFinished(async () => {
if (mountRoot !== undefined)
await rm(mountRoot, { recursive: true, force: true });
});
const host: NativeDmgHost = {
async run(args) {
if (args[0] === "attach") {
mountRoot = args[args.indexOf("-mountroot") + 1];
if (mountRoot === undefined) throw new Error("missing mount root");
const mountPoint = join(mountRoot, "Fixture");
await mkdir(mountPoint);
await writeFile(join(mountPoint, "hello.txt"), "owned observation");
return {
stdout: build({
"system-entities": [
{ "dev-entry": "/dev/disk7", "mount-point": mountPoint },
],
}),
exitCode: 0,
};
}
if (args[0] === "info")
return {
stdout: build({
images: attached
? [{ "system-entities": [{ "dev-entry": "/dev/disk7" }] }]
: [],
}),
exitCode: 0,
};
if (args[0] === "detach") {
if (busy)
return {
stdout: "",
stderr: "hdiutil: detach failed - Resource busy",
exitCode: 16,
};
attached = false;
}
return { stdout: "", exitCode: 0 };
},
};
const { host, state } = singleDeviceHost(() => busy);
const reader = await NativeDmgArtifactReader.create(
"/tmp/image.dmg",
undefined,
@@ -535,6 +571,7 @@ describe("APFS disk image detach", () => {
await expect(reader.close()).rejects.toMatchObject({
reason: "unavailable",
});
const { mountRoot } = state;
if (mountRoot === undefined) throw new Error("missing owned mount root");
expect
.soft(
@@ -545,7 +582,7 @@ describe("APFS disk image detach", () => {
.toBe("owned observation");
busy = false;
await reader.close();
expect.soft(attached).toBe(false);
expect.soft(state.attached).toBe(false);
await expect(
readFile(join(mountRoot, "Fixture", "hello.txt")),
).rejects.toMatchObject({
@@ -553,3 +590,38 @@ describe("APFS disk image detach", () => {
});
});
});
describe("DMG detach recheck", () => {
it("accepts an ejected device that hdiutil listed once more after its failed detach", async () => {
const { cleanup } = await closeApfsFixture(
["/dev/disk4", "/dev/disk4s1"],
1,
);
expect(cleanup).toEqual([
["detach", "/dev/disk5"],
["detach", "/dev/disk4"],
["info", "-plist"],
["info", "-plist"],
]);
});
it("detaches a device that was busy on its first attempt within one close", async () => {
const { host, state } = singleDeviceHost((attempt) => attempt === 1);
const reader = await NativeDmgArtifactReader.create(
"/tmp/image.dmg",
undefined,
host,
);
await reader.close();
expect(state).toMatchObject({
attempts: 2,
attached: false,
waits: [250],
});
if (state.mountRoot === undefined)
throw new Error("missing owned mount root");
await expect(
readFile(join(state.mountRoot, "Fixture", "hello.txt")),
).rejects.toMatchObject({ code: "ENOENT" });
});
});