mirror of
https://github.com/morluto/rea.git
synced 2026-11-30 16:18:26 +00:00
* perf(decompile-all): group durable writes per batch of functions The export synced each function file and then the journal, one function at a time, so it spent about as long waiting on the disk as decompiling. Each file's bytes are now synced in staging while later functions are decompiled. A group of up to eight functions then publishes its files in visit order and appends its journal records with one write and one sync. A journal record is still written only after its file's content is synced and published. Cancellation and failures commit the pending group before they are reported. Files, journal records and their order, the index and counts are unchanged. A stopped process or host now leaves up to eight decompiled functions unrecorded instead of one; a resume decompiles them again and adopts files already in place. Addresses #14830 * fix(decompile-all): commit the pending group on a throw and after one second A provider adapter that threw inside a group dropped the functions already decompiled in it: their staged files were removed and no record was written, where each had been committed before the next was requested. The pending group is now committed before the throw propagates. A group is also committed by the first function that settles a second or more after the previous commit, so a slow provider is committed function by function instead of leaving up to eight long decompilations unrecorded. Adds the missing lifecycle regressions: a caller abort during a group's publication and during its journal append, a failed removal of a discarded staged file, and a resume beside staging left by a stopped run. * test(decompile-all): release the export a failed-discard test retains The test left its export's cleanup failing, so the directory lease stayed held by the test process. The lease is keyed by device and inode; where the filesystem reuses the removed directory's inode, the next test's export was refused as already running. The test now gives the export a resource scope, retries the retained cleanup once removal works, and resumes in the same directory, which also covers the cleanup retry. * fix(decompile-all): retain failures the group commit observed after a stop or throw A write failure that stops a group now keeps a later function's provider failure as a secondary failure, with its cleanup still attached. When a provider throws and the commit of earlier functions then fails, that commit failure is returned as primary and the throw is retained with it. The first provider failure before an independent retry now joins the group before the retry runs, so a retry that throws cannot drop it. * refactor(decompile-all): compose every export failure through one owner Group settlement now carries each entry's outcome: the first stop leads, entries after it are abandoned but keep any failure they observed, and a failed journal append leads those. One composeFailures helper retains later failures as secondary and keeps every cleanup they own, and the final publish/index/close composition uses it too, so an index failure that still owns cleanup is no longer dropped behind an earlier failure. A journal write failure also keeps a later invalid record as a secondary failure.
504 lines
19 KiB
TypeScript
504 lines
19 KiB
TypeScript
import { lstat, readFile, stat, writeFile, unlink } from "node:fs/promises";
|
|
import { basename, join } from "node:path";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
|
|
// Host filesystems cannot fail chmod on one new directory on demand; every
|
|
// other creation step runs on the real filesystem.
|
|
const failChmodFor = vi.hoisted(() => ({
|
|
path: undefined as string | undefined,
|
|
journalClose: undefined as string | undefined,
|
|
beforeCleanup: undefined as (() => Promise<void>) | undefined,
|
|
cleanupPath: undefined as string | undefined,
|
|
beforeLeasePath: undefined as string | undefined,
|
|
beforeLease: undefined as (() => Promise<void>) | undefined,
|
|
// Models a macOS virtiofs share: lstat reports a new inode for a directory
|
|
// after chmod changes its mode.
|
|
renumberDirectories: false,
|
|
renumbered: new Set<string>(),
|
|
// mkdir(0o700) cannot gain bits from umask, and the export root's chmod
|
|
// clears an inherited setgid bit before the functions directory is created.
|
|
// Set this to the mode left on that directory so the repair chmod runs.
|
|
functionsCreateMode: undefined as number | undefined,
|
|
// After the functions directory is chmod'd, lstat reports a different device.
|
|
swapFunctionsDevice: false,
|
|
}));
|
|
|
|
vi.mock("node:fs/promises", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
|
return {
|
|
...actual,
|
|
open: async (...args: Parameters<typeof actual.open>) => {
|
|
const handle = await actual.open(...args);
|
|
if (args[0] === failChmodFor.journalClose) {
|
|
failChmodFor.journalClose = undefined;
|
|
const close = handle.close.bind(handle);
|
|
vi.spyOn(handle, "close")
|
|
.mockImplementationOnce(async () => {
|
|
throw new Error("injected close failure");
|
|
})
|
|
.mockImplementation(close);
|
|
}
|
|
return handle;
|
|
},
|
|
rm: async (...args: Parameters<typeof actual.rm>) => {
|
|
if (
|
|
args[0] === failChmodFor.cleanupPath ||
|
|
`${String(args[0])}/decompile-journal.jsonl` ===
|
|
failChmodFor.cleanupPath
|
|
) {
|
|
const hook = failChmodFor.beforeCleanup;
|
|
failChmodFor.beforeCleanup = undefined;
|
|
await hook?.();
|
|
}
|
|
return actual.rm(...args);
|
|
},
|
|
unlink: async (...args: Parameters<typeof actual.unlink>) => {
|
|
if (args[0] === failChmodFor.cleanupPath) {
|
|
const hook = failChmodFor.beforeCleanup;
|
|
failChmodFor.beforeCleanup = undefined;
|
|
await hook?.();
|
|
}
|
|
return actual.unlink(...args);
|
|
},
|
|
lstat: (async (
|
|
path: Parameters<typeof actual.lstat>[0],
|
|
options?: { bigint?: boolean },
|
|
) => {
|
|
const metadata = await actual.lstat(path, options);
|
|
if (metadata.isDirectory() && failChmodFor.renumbered.has(String(path))) {
|
|
metadata.ino =
|
|
typeof metadata.ino === "bigint"
|
|
? metadata.ino + 1n
|
|
: metadata.ino + 1;
|
|
if (
|
|
failChmodFor.swapFunctionsDevice &&
|
|
basename(String(path)) === "functions"
|
|
)
|
|
metadata.dev =
|
|
typeof metadata.dev === "bigint"
|
|
? metadata.dev + 1n
|
|
: metadata.dev + 1;
|
|
}
|
|
return metadata;
|
|
}) as typeof actual.lstat,
|
|
mkdir: async (
|
|
path: Parameters<typeof actual.mkdir>[0],
|
|
options?: Parameters<typeof actual.mkdir>[1],
|
|
) => {
|
|
const created = await actual.mkdir(path, options);
|
|
const mode = failChmodFor.functionsCreateMode;
|
|
// Bypass the chmod mock: this is the mode mkdir left, not a later repair.
|
|
if (mode !== undefined && basename(String(path)) === "functions")
|
|
await actual.chmod(path, mode);
|
|
return created;
|
|
},
|
|
chmod: async (path: Parameters<typeof actual.chmod>[0], mode: number) => {
|
|
if (path === failChmodFor.path)
|
|
throw Object.assign(new Error("denied"), { code: "EPERM" });
|
|
await actual.chmod(path, mode);
|
|
if (
|
|
failChmodFor.renumberDirectories &&
|
|
(await actual.lstat(path)).isDirectory()
|
|
)
|
|
failChmodFor.renumbered.add(String(path));
|
|
if (path === failChmodFor.beforeLeasePath) {
|
|
const hook = failChmodFor.beforeLease;
|
|
failChmodFor.beforeLease = undefined;
|
|
await hook?.();
|
|
}
|
|
},
|
|
};
|
|
});
|
|
|
|
const { DecompileExport } =
|
|
await import("../../../src/application/decompileDirectory/exportTree.js");
|
|
|
|
const { BinarySessionRecords } =
|
|
await import("../../../src/application/binary/BinarySessionRecords.js");
|
|
class SessionResources extends BinarySessionRecords {
|
|
protected activeAnalysisBinding() {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
const { acquireOwnedLease } =
|
|
await import("../../../src/process/OwnedLease.js");
|
|
|
|
const identity = {
|
|
targetSha256: "ab".repeat(32),
|
|
provider: { id: "fixture", name: "Fixture", version: "1" },
|
|
analysisProfileDigest: "cd".repeat(32),
|
|
layout: "address" as const,
|
|
};
|
|
|
|
afterEach(() => {
|
|
failChmodFor.path = undefined;
|
|
failChmodFor.journalClose = undefined;
|
|
failChmodFor.beforeCleanup = undefined;
|
|
failChmodFor.cleanupPath = undefined;
|
|
failChmodFor.beforeLeasePath = undefined;
|
|
failChmodFor.beforeLease = undefined;
|
|
failChmodFor.renumberDirectories = false;
|
|
failChmodFor.renumbered.clear();
|
|
failChmodFor.functionsCreateMode = undefined;
|
|
failChmodFor.swapFunctionsDevice = false;
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
describe("decompile export creation", () => {
|
|
it("removes the output directory it created when it cannot be made private", async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-create-");
|
|
const root = join(parent, "out");
|
|
failChmodFor.path = root;
|
|
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
|
|
expect(opened.ok).toBe(false);
|
|
if (opened.ok) return;
|
|
expect(opened.error.userMessage).toContain("could not be secured");
|
|
// A fresh export can be retried at the same path.
|
|
await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" });
|
|
failChmodFor.path = undefined;
|
|
const retried = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(retried.ok).toBe(true);
|
|
if (retried.ok) expect((await retried.value.close()).ok).toBe(true);
|
|
});
|
|
it("holds the lease while removing a failed initialization with a valid journal", async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-create-");
|
|
const root = join(parent, "out");
|
|
const journal = join(root, "decompile-journal.jsonl");
|
|
failChmodFor.path = journal;
|
|
failChmodFor.cleanupPath = journal;
|
|
let resumedTag: string | undefined;
|
|
failChmodFor.beforeCleanup = async () => {
|
|
// The original header is valid when the competing run tries to resume.
|
|
expect(
|
|
JSON.parse((await readFile(journal, "utf8")).trim()),
|
|
).toMatchObject({ kind: "header" });
|
|
const resumed = await DecompileExport.open({
|
|
placement: { mode: "resume", root },
|
|
identity,
|
|
});
|
|
if (resumed.ok) await resumed.value.close();
|
|
resumedTag = resumed.ok ? "acquired" : resumed.error._tag;
|
|
};
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(opened.ok).toBe(false);
|
|
expect(resumedTag).toBe("AnalysisResourceConstraintError");
|
|
await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it("retains an export after a journal close failure until session cleanup retries it", async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-close-");
|
|
const root = join(parent, "out");
|
|
const resources = new SessionResources();
|
|
failChmodFor.journalClose = join(root, "decompile-journal.jsonl");
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
resourceScope: resources.resourceScope,
|
|
});
|
|
expect(opened.ok).toBe(true);
|
|
if (!opened.ok) return;
|
|
const closed = await opened.value.close();
|
|
expect(closed.ok).toBe(false);
|
|
if (closed.ok) return;
|
|
expect(closed.error.cleanupIncomplete).toBe(true);
|
|
const refused = await DecompileExport.open({
|
|
placement: { mode: "resume", root },
|
|
identity,
|
|
});
|
|
expect(refused.ok).toBe(false);
|
|
if (!refused.ok)
|
|
expect(refused.error._tag).toBe("AnalysisResourceConstraintError");
|
|
expect((await resources.closeFileResources()).ok).toBe(true);
|
|
expect(closed.error.cleanupIncomplete).toBe(false);
|
|
const resumed = await DecompileExport.open({
|
|
placement: { mode: "resume", root },
|
|
identity,
|
|
});
|
|
expect(resumed.ok).toBe(true);
|
|
if (resumed.ok) expect((await resumed.value.close()).ok).toBe(true);
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"removes its functions directory after failed initialization on a mount that renumbers directories on chmod",
|
|
async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-renumber-");
|
|
const root = join(parent, "out");
|
|
failChmodFor.renumberDirectories = true;
|
|
failChmodFor.path = join(root, "decompile-journal.jsonl");
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(opened.ok).toBe(false);
|
|
if (opened.ok) return;
|
|
expect(opened.error.cleanupIncomplete).toBe(false);
|
|
expect(failChmodFor.renumbered).not.toContain(join(root, "functions"));
|
|
await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"removes a functions directory whose mode repair renumbers it",
|
|
async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-renumber-");
|
|
const root = join(parent, "out");
|
|
const functions = join(root, "functions");
|
|
failChmodFor.renumberDirectories = true;
|
|
// setgid plus group read and execute: not the owner-only mode mkdir requested.
|
|
failChmodFor.functionsCreateMode = 0o2750;
|
|
failChmodFor.path = join(root, "decompile-journal.jsonl");
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(opened.ok).toBe(false);
|
|
if (opened.ok) return;
|
|
expect(opened.error.cleanupIncomplete).toBe(false);
|
|
expect(failChmodFor.renumbered).toContain(functions);
|
|
await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"leaves the functions directory owner-only after a mode repair that renumbers it",
|
|
async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-renumber-");
|
|
const root = join(parent, "out");
|
|
const functions = join(root, "functions");
|
|
failChmodFor.renumberDirectories = true;
|
|
failChmodFor.functionsCreateMode = 0o2750;
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(opened.ok).toBe(true);
|
|
if (!opened.ok) return;
|
|
try {
|
|
const metadata = await lstat(functions);
|
|
expect(metadata.isSymbolicLink()).toBe(false);
|
|
expect(metadata.isDirectory()).toBe(true);
|
|
expect(metadata.mode & 0o7777).toBe(0o700);
|
|
expect(failChmodFor.renumbered).toContain(functions);
|
|
} finally {
|
|
expect((await opened.value.close()).ok).toBe(true);
|
|
}
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"does not remove a functions directory whose device changed during mode repair",
|
|
async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-renumber-");
|
|
const root = join(parent, "out");
|
|
const functions = join(root, "functions");
|
|
failChmodFor.renumberDirectories = true;
|
|
failChmodFor.functionsCreateMode = 0o2750;
|
|
failChmodFor.swapFunctionsDevice = true;
|
|
const resources = new SessionResources();
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
resourceScope: resources.resourceScope,
|
|
});
|
|
try {
|
|
expect(opened.ok).toBe(false);
|
|
if (!opened.ok) expect(opened.error.cleanupIncomplete).toBe(true);
|
|
expect((await lstat(functions)).isDirectory()).toBe(true);
|
|
expect((await lstat(root)).isDirectory()).toBe(true);
|
|
} finally {
|
|
// Restore the owned functions directory's identity before retrying cleanup.
|
|
failChmodFor.renumbered.delete(functions);
|
|
if (opened.ok) await opened.value.close();
|
|
expect((await resources.closeFileResources()).ok).toBe(true);
|
|
}
|
|
await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
it("preserves unexpected files and keeps initialization cleanup owned until a retry", async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-cleanup-");
|
|
const root = join(parent, "out");
|
|
const journal = join(root, "decompile-journal.jsonl");
|
|
const resources = new SessionResources();
|
|
failChmodFor.path = journal;
|
|
failChmodFor.cleanupPath = journal;
|
|
failChmodFor.beforeCleanup = () =>
|
|
writeFile(join(root, "caller.txt"), "keep me");
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
resourceScope: resources.resourceScope,
|
|
});
|
|
expect(opened.ok).toBe(false);
|
|
if (opened.ok) return;
|
|
expect(opened.error.cleanupIncomplete).toBe(true);
|
|
expect(await readFile(join(root, "caller.txt"), "utf8")).toBe("keep me");
|
|
expect((await resources.closeFileResources()).ok).toBe(false);
|
|
await unlink(join(root, "caller.txt"));
|
|
expect((await resources.closeFileResources()).ok).toBe(true);
|
|
expect(opened.error.cleanupIncomplete).toBe(false);
|
|
await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
});
|
|
|
|
describe("decompile export lease acquisition", () => {
|
|
it("preserves an empty new root when another run acquires its lease first", async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-lease-race-");
|
|
const root = join(parent, "out");
|
|
let release: (() => Promise<void>) | undefined;
|
|
failChmodFor.beforeLeasePath = root;
|
|
failChmodFor.beforeLease = async () => {
|
|
const stat = await lstat(root, { bigint: true });
|
|
const acquired = await acquireOwnedLease({
|
|
identity: {
|
|
operation: "decompile_all",
|
|
device: stat.dev.toString(),
|
|
inode: stat.ino.toString(),
|
|
},
|
|
runId: "competing-export",
|
|
directory: join("/tmp", `rea-decompile-${process.getuid?.() ?? 0}`),
|
|
failure: () => new Error("competing lease could not be acquired"),
|
|
});
|
|
expect(acquired.acquired).toBe(true);
|
|
if (acquired.acquired) release = acquired.lease.release;
|
|
};
|
|
try {
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(opened.ok).toBe(false);
|
|
expect((await stat(root)).isDirectory()).toBe(true);
|
|
if (!opened.ok) {
|
|
expect(opened.error._tag).toBe("AnalysisResourceConstraintError");
|
|
expect(opened.error.diagnostics).toMatchObject({
|
|
created_output_directory: root,
|
|
});
|
|
}
|
|
} finally {
|
|
await release?.();
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("decompile journal ownership", () => {
|
|
it("keeps the parsed committed record when a caller mutates its input during append", async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-record-");
|
|
const root = join(parent, "out");
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(opened.ok).toBe(true);
|
|
if (!opened.ok) return;
|
|
try {
|
|
const record = {
|
|
address: "0x1000",
|
|
name: "original",
|
|
status: "failed" as const,
|
|
body: { available: false as const, reason: "original body" },
|
|
failure: { code: "fixture", message: "original failure" },
|
|
limitations: ["original caveat"],
|
|
};
|
|
const appended = opened.value.append([record]);
|
|
record.address = "0x2000";
|
|
record.body.reason = "changed body";
|
|
record.failure.message = "changed failure";
|
|
record.limitations[0] = "changed caveat";
|
|
expect((await appended).ok).toBe(true);
|
|
expect(
|
|
(
|
|
await opened.value.writeIndex({
|
|
layoutStatus: "address",
|
|
limitations: [],
|
|
latestRun: {
|
|
resume: false,
|
|
selected: 1,
|
|
excluded: 0,
|
|
selection: {
|
|
name: null,
|
|
namespace: null,
|
|
address_start: null,
|
|
address_end: null,
|
|
limit: null,
|
|
},
|
|
inventoryLimitations: [],
|
|
},
|
|
})
|
|
).ok,
|
|
).toBe(true);
|
|
const index = JSON.parse(
|
|
await readFile(join(root, "decompile-index.json"), "utf8"),
|
|
);
|
|
expect(index.functions).toEqual([
|
|
{
|
|
address: "0x1000",
|
|
name: "original",
|
|
status: "failed",
|
|
body: { available: false, reason: "original body" },
|
|
failure: { code: "fixture", message: "original failure" },
|
|
limitations: ["original caveat"],
|
|
},
|
|
]);
|
|
} finally {
|
|
expect((await opened.value.close()).ok).toBe(true);
|
|
}
|
|
});
|
|
|
|
it("appends the records before an invalid one and reports the invalid record", async () => {
|
|
const parent = await createTestTempDirectory("rea-decompile-batch-");
|
|
const root = join(parent, "out");
|
|
const opened = await DecompileExport.open({
|
|
placement: { mode: "create", root },
|
|
identity,
|
|
});
|
|
expect(opened.ok).toBe(true);
|
|
if (!opened.ok) return;
|
|
try {
|
|
const record = (address: string) => ({
|
|
address,
|
|
name: null,
|
|
status: "failed" as const,
|
|
body: { available: false as const, reason: "fixture" },
|
|
failure: { code: "fixture", message: "fixture" },
|
|
});
|
|
const appended = await opened.value.append([
|
|
record("0x1000"),
|
|
{ ...record("0x2000"), relative_path: "../outside.c" },
|
|
record("0x3000"),
|
|
]);
|
|
expect(appended.ok).toBe(false);
|
|
expect(opened.value.record("0x1000")).toMatchObject({
|
|
address: "0x1000",
|
|
});
|
|
expect(opened.value.record("0x2000")).toBeUndefined();
|
|
expect(opened.value.record("0x3000")).toBeUndefined();
|
|
const lines = (
|
|
await readFile(join(root, "decompile-journal.jsonl"), "utf8")
|
|
)
|
|
.trimEnd()
|
|
.split("\n");
|
|
expect(lines.map((line) => JSON.parse(line).address)).toEqual([
|
|
undefined,
|
|
"0x1000",
|
|
]);
|
|
} finally {
|
|
expect((await opened.value.close()).ok).toBe(true);
|
|
}
|
|
});
|
|
});
|