fix(workflows): retain staged output ownership and cancellation semantics

Give atomic Evidence and snapshot writes an explicit resource owner, preserve primary failures and completed publication receipts, and retry retained staging cleanup at the owning lifecycle. Verify inode identity before publishing or deleting; unknown path disappearance remains a cleanup failure. Keep snapshot admission reusable when a session closes and reopens.

Consolidate JavaScript source-scope classification so cancellation cannot fabricate failures for unselected files. Classify configuration failures as invalid input. Remove stale assertions and reuse shared test cleanup ownership.

Validation: 266 focused tests before final ownership tightening, 108 affected tests afterward, static and documentation checks, actual invalid-configuration CLI behavior, and isolated test temporary-directory hygiene.

Refs #1968
This commit is contained in:
morluto
2026-10-12 06:29:27 +08:00
parent 8bd5ba2d23
commit 7285e15839
26 changed files with 988 additions and 126 deletions
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
@@ -76,11 +77,14 @@ describe("analysis snapshots: persistence", () => {
const directory = await createTestTempDirectory("rea-snapshot-");
const path = join(directory, "analysis.json");
const snapshot = snapshotFixture();
const written = await writeAnalysisSnapshot(snapshot, path, false);
expect(written.ok).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(snapshot, path, false, resources),
);
if (!written.ok) throw written.error;
expect((await readFile(path, "utf8")).endsWith("\n")).toBe(true);
expect((await stat(path)).mode & 0o777).toBe(0o600);
expect((await readAnalysisSnapshot(path)).ok).toBe(true);
const roundTrip = await readAnalysisSnapshot(path);
if (!roundTrip.ok) throw roundTrip.error;
const altered: unknown = JSON.parse(await readFile(path, "utf8"));
if (
@@ -102,8 +106,9 @@ describe("analysis snapshots: persistence", () => {
Reflect.set(first.parameters, "address", "0x2000");
await writeFile(path, JSON.stringify(altered));
const loaded = await readAnalysisSnapshot(path);
expect(loaded.ok).toBe(false);
if (!loaded.ok) expect(loaded.error._tag).toBe("EvidenceIntegrityError");
if (loaded.ok)
throw new Error("Expected changed snapshot identity rejection");
expect(loaded.error._tag).toBe("EvidenceIntegrityError");
expect(() => parseAnalysisSnapshot(altered)).toThrow(/identifier/u);
});
});
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { writeAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
@@ -84,9 +85,10 @@ describe("direct analysis snapshot files", () => {
workflow_entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
};
expect(
(await writeAnalysisSnapshot(snapshot, snapshotPath, false)).ok,
).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(snapshot, snapshotPath, false, resources),
);
if (!written.ok) throw written.error;
vi.stubEnv("HOPPER_LAUNCHER_PATH", launcherPath);
await expect(
@@ -2,7 +2,7 @@ import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
@@ -33,11 +33,13 @@ import {
createAnalysisSnapshotWorkflowEntry,
type AnalysisSnapshot,
} from "../../../src/domain/analysisSnapshot.js";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import {
createTestBinarySession,
createTestProviderRouter,
} from "../../fixtures/binarySession.js";
import { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
CAPABILITIES as GHIDRA_CAPABILITIES,
@@ -342,6 +344,58 @@ const withEarlierHistoricalEvidence = (
};
};
describe("snapshot output cleanup lifecycle", () => {
it("returns completed analysis after retrying cleanup of a published snapshot", async () => {
const fixture = await createSnapshotReplayFixture(
"rea-snapshot-cleanup-retry-",
);
const cleanup = vi
.spyOn(OwnedStagedOutput.prototype, "close")
.mockRejectedValueOnce(new Error("transient staging cleanup failure"));
try {
const output = await runDirectAnalysis(
fixture.dependencies(fixture.createProvider()),
fixture.path,
"binary_overview",
{},
{ snapshotPath: fixture.snapshotPath },
);
expect(parseEvidence(output).operation).toBe("binary_overview");
const saved = await readAnalysisSnapshot(fixture.snapshotPath);
if (!saved.ok) throw saved.error;
expect(saved.value.workflow_entries).toHaveLength(1);
expect(cleanup).toHaveBeenCalledTimes(2);
} finally {
cleanup.mockRestore();
}
});
it("saves snapshots after closing and reopening the same session", async () => {
const fixture = await createSnapshotReplayFixture("rea-snapshot-reopen-");
const session = createTestBinarySession(fixture.createProvider());
try {
for (const index of [1, 2]) {
const opened = await session.open(fixture.path);
if (!opened.ok) throw opened.error;
const analyzed = await session.execute("list_segments", {});
if (!analyzed.ok) throw analyzed.error;
const path = join(
dirname(fixture.snapshotPath),
`snapshot-${index}.json`,
);
const saved = await session.closeWithSnapshot(path, false);
if (!saved.ok) throw saved.error;
const loaded = await readAnalysisSnapshot(path);
if (!loaded.ok) throw loaded.error;
expect(loaded.value.target.sha256).toBe(opened.value.sha256);
}
} finally {
const closed = await session.close();
if (!closed.ok) throw closed.error;
}
});
});
describe("direct analysis composed snapshot replay", () => {
it.each([
{
@@ -530,15 +584,15 @@ describe("binary overview snapshot replay", () => {
);
if (current === undefined)
throw new Error("composed Evidence was not saved");
expect(
(
await writeAnalysisSnapshot(
withEarlierHistoricalEvidence(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
)
).ok,
).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(
withEarlierHistoricalEvidence(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
resources,
),
);
if (!written.ok) throw written.error;
const second = await runDirectAnalysis(
dependencies,
@@ -735,15 +789,15 @@ describe("workflow snapshot profile and cancellation binding", () => {
);
if (current === undefined)
throw new Error("composed Evidence was not saved");
expect(
(
await writeAnalysisSnapshot(
withAlternateWorkflowProfile(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
)
).ok,
).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(
withAlternateWorkflowProfile(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
resources,
),
);
if (!written.ok) throw written.error;
const refreshed = await runDirectAnalysis(
dependencies,
@@ -11,6 +11,7 @@ import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import {
readEvidenceBundle,
@@ -99,15 +100,10 @@ describe("evidence bundle export cancellation", () => {
yield "unused";
}
expect(
await writeTextParts(
parts(),
join(root, "missing", "bundle.json"),
false,
{
signal: controller.signal,
operation: "export_evidence_bundle",
},
),
await writeParts(parts(), join(root, "missing", "bundle.json"), false, {
signal: controller.signal,
operation: "export_evidence_bundle",
}),
).toMatchObject({
ok: false,
error: {
@@ -118,7 +114,7 @@ describe("evidence bundle export cancellation", () => {
expect(advanced).toBe(false);
expect(await readdir(root)).toEqual([]);
expect(
await writeEvidenceBundle(
await writeBundle(
bundle(),
join(root, "bundle.json"),
false,
@@ -149,7 +145,7 @@ describe("evidence bundle export cancellation", () => {
}
}
expect(
await writeTextParts(parts(), path, overwrite, {
await writeParts(parts(), path, overwrite, {
signal: controller.signal,
operation: "export_evidence_bundle",
}),
@@ -164,9 +160,9 @@ describe("evidence bundle export cancellation", () => {
expect(continued).toBe(false);
expect(await readdir(root)).toEqual(overwrite ? ["bundle.json"] : []);
if (overwrite) expect(await readFile(path, "utf8")).toBe("original");
expect(
await writeEvidenceBundle(bundle(), path, overwrite),
).toMatchObject({ ok: true });
expect(await writeBundle(bundle(), path, overwrite)).toMatchObject({
ok: true,
});
expect(await readEvidenceBundle(path)).toEqual({
ok: true,
value: bundle(),
@@ -184,7 +180,7 @@ describe("evidence bundle export cancellation", () => {
controller.abort();
}
expect(
await writeTextParts(parts(), path, true, {
await writeParts(parts(), path, true, {
signal: controller.signal,
operation: "export_evidence_bundle",
}),
@@ -194,6 +190,29 @@ describe("evidence bundle export cancellation", () => {
});
});
const writeBundle = (
value: ReturnType<typeof bundle>,
path: string,
overwrite: boolean,
signal?: AbortSignal,
) =>
withArtifactResourceScope((resources) =>
writeEvidenceBundle(value, path, overwrite, resources, signal),
);
const writeParts = (
parts: Iterable<string>,
path: string,
overwrite: boolean,
cancellation?: {
readonly signal: AbortSignal;
readonly operation: string;
},
) =>
withArtifactResourceScope((resources) =>
writeTextParts(parts, path, overwrite, resources, cancellation),
);
describe("evidence bundle publication", () => {
it.each([false, true])(
"never publishes a partial streamed file (overwrite: %s)",
@@ -205,9 +224,7 @@ describe("evidence bundle publication", () => {
yield "partial";
throw new Error("Source stream failed");
}
expect(
await writeTextParts(brokenParts(), path, overwrite),
).toMatchObject({
expect(await writeParts(brokenParts(), path, overwrite)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "io" },
});
@@ -220,7 +237,7 @@ describe("evidence bundle publication", () => {
const root = await createTestTempDirectory("rea-stream-bytes-");
const path = join(root, "bundle.json");
const parts = ["雪", "😀", "\n"];
expect(await writeTextParts(parts, path, false)).toEqual({
expect(await writeParts(parts, path, false)).toEqual({
ok: true,
value: { path, bytes: Buffer.byteLength(parts.join("")) },
});
@@ -233,7 +250,7 @@ describe("evidence bundle publication", () => {
const path = join(root, "bundle.json");
const candidates = [bundle(), bundle(false)];
const results = await Promise.all(
candidates.map((value) => writeEvidenceBundle(value, path, false)),
candidates.map((value) => writeBundle(value, path, false)),
);
expect(results.filter(({ ok }) => ok)).toHaveLength(1);
expect(results.filter(({ ok }) => !ok)).toMatchObject([
@@ -253,7 +270,7 @@ describe("evidence bundle publication", () => {
await mkdir(directory);
const path = join(directory, "bundle.json");
const value = bundle();
expect(await writeEvidenceBundle(value, path, false)).toMatchObject({
expect(await writeBundle(value, path, false)).toMatchObject({
ok: true,
});
expect(await readEvidenceBundle(path)).toEqual({
@@ -308,7 +325,7 @@ describe("evidence bundle filesystem adapter", () => {
const directory = await createTestTempDirectory("rea-evidence-");
const path = join(directory, "bundle.json");
const evidenceBundle = bundle();
const first = await writeEvidenceBundle(evidenceBundle, path, false);
const first = await writeBundle(evidenceBundle, path, false);
expect(first).toMatchObject({ ok: true, value: { path } });
expect(await readFile(path, "utf8")).toBe(
serializeEvidenceBundle(evidenceBundle),
@@ -329,15 +346,13 @@ describe("evidence bundle filesystem adapter", () => {
summary: { records_unchanged: 1 },
},
});
expect(
await writeEvidenceBundle(evidenceBundle, path, false),
).toMatchObject({
expect(await writeBundle(evidenceBundle, path, false)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "exists" },
});
expect(await writeEvidenceBundle(evidenceBundle, path, true)).toMatchObject(
{ ok: true },
);
expect(await writeBundle(evidenceBundle, path, true)).toMatchObject({
ok: true,
});
});
it("reads the caller-selected symlink target and refuses to replace a symlink", async () => {
@@ -352,7 +367,7 @@ describe("evidence bundle filesystem adapter", () => {
ok: true,
value: bundle(),
});
expect(await writeEvidenceBundle(bundle(), link, true)).toMatchObject({
expect(await writeBundle(bundle(), link, true)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "not-file" },
});
@@ -373,7 +388,7 @@ describe("evidence bundle filesystem adapter", () => {
});
const orphan = join(directory, "absent", "bundle.json");
const written = await writeEvidenceBundle(bundle(), orphan, false);
const written = await writeBundle(bundle(), orphan, false);
expect(written).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "missing", path: orphan },
@@ -11,7 +11,78 @@ import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.
import { scanCanonicalArtifactInventory } from "../../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
import {
analyzeJavaScriptApplication,
readJavaScriptArtifactFiles,
} from "../../../support/javascriptApplicationScope.js";
import { createJavaScriptArtifactReader } from "../../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
import { createJavaScriptSourceAnalysis } from "../../../../src/artifacts/javascript/JavaScriptSourceAnalysis.js";
import { analyzeAndAdoptJavaScriptArtifactFiles } from "../../../../src/application/javascript/JavaScriptArtifactAnalysis.js";
import { createJavaScriptSemanticGraphProjection } from "../../../../src/application/javascript/JavaScriptSemanticGraphBuilder.js";
describe("JavaScript source selection cancellation boundary", () => {
it("keeps unselected files outside scope when the real worker cancels after the last selected file", async () => {
const root = await createTestTempDirectory(
"rea-js-selected-last-cancellation-",
);
await writeJavaScriptSourceSelectionFixture(root);
const snapshot = await scanCanonicalArtifactInventory(root, {});
const reader = createJavaScriptArtifactReader(root, "directory");
const controller = new AbortController();
const sourcePaths = ["main.mjs"];
try {
const files = await readJavaScriptArtifactFiles(
reader,
snapshot,
controller.signal,
sourcePaths,
);
const worker = createJavaScriptSourceAnalysis(
{ heapMb: 512, timeoutMs: 30_000 },
1,
);
let outcome: Awaited<
ReturnType<typeof analyzeAndAdoptJavaScriptArtifactFiles>
>;
try {
const realWorker = worker.analyze.bind(worker);
outcome = await analyzeAndAdoptJavaScriptArtifactFiles(
files,
{
analyze: async (...args) => {
const result = await realWorker(...args);
controller.abort();
return result;
},
},
createJavaScriptSemanticGraphProjection(),
async () => {},
controller.signal,
);
} finally {
await worker.close();
}
expect(outcome.interruption).toBeInstanceOf(AnalysisCancelledError);
const unselected = outcome.analysis.files.filter(
({ file }) =>
!file.text.included && file.text.reason === "outside-analysis-scope",
);
expect(unselected).toHaveLength(5);
expect(
unselected.every(
({ analysis_failure }) => analysis_failure === undefined,
),
).toBe(true);
expect(
outcome.analysis.files.find(({ file }) => file.path === "main.mjs")
?.javascript,
).toMatchObject({ parse_status: "complete" });
} finally {
await reader.close();
}
});
});
describe("Selected JavaScript source failure diagnostics", () => {
it("analyzes selected files in first-request order and reports only selected progress", async () => {
@@ -0,0 +1,273 @@
import { readdirSync, renameSync, writeFileSync } from "node:fs";
import { mkdir, open, rm } from "node:fs/promises";
import * as fs from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { EvidenceFileError } from "../../../src/domain/evidenceErrors.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { writeTextParts } from "../../../src/application/JsonFiles.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("reports committed output when post-publication staging cleanup remains owned", async () => {
const root = await createTestTempDirectory("rea-json-write-");
const resources = new ArtifactResourceScope();
try {
const result = await writeTextParts(
stagingPollutingParts(root),
join(root, "bundle.json"),
false,
resources,
);
if (result.ok) throw new Error("Expected staged cleanup failure");
const cleanupResource = result.error.cleanup?.resources[0];
if (cleanupResource === undefined)
throw new Error("Expected retained staging resource");
expect(result.error).toBeInstanceOf(EvidenceFileError);
expect(result.error.published).toMatchObject({
path: join(root, "bundle.json"),
bytes: 16,
});
expect(cleanupResource).toContain(".rea-write-");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cleanup_incomplete",
details: { published: true, published_path: join(root, "bundle.json") },
});
expect(await fs.readFile(join(root, "bundle.json"), "utf8")).toBe(
"canonical output",
);
await fs.rm(join(cleanupResource, "unexpected"));
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("preserves cancellation when staging cleanup also fails", async () => {
const root = await createTestTempDirectory("rea-json-cancel-");
const resources = new ArtifactResourceScope();
const controller = new AbortController();
try {
function* cancelledParts(): Generator<string> {
const directories = requireStages(root);
if (directories.length !== 1)
throw new Error("Expected one staging directory");
writeFileSync(join(root, directories[0]!, "unexpected"), "retain this");
controller.abort();
yield "must not publish";
}
const result = await writeTextParts(
cancelledParts(),
join(root, "cancelled.json"),
false,
resources,
{ signal: controller.signal, operation: "export_evidence_bundle" },
);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cause).toMatchObject({
cause: expect.any(AnalysisCancelledError),
owner: { directory: expect.stringContaining(".rea-write-") },
});
await expect(fs.access(join(root, "cancelled.json"))).rejects.toThrow();
const stage = requireStages(root)[0];
if (stage !== undefined) await fs.rm(join(root, stage, "unexpected"));
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("refuses to publish a staged path replaced after its descriptor opened", async () => {
const root = await createTestTempDirectory("rea-staged-swap-");
const resources = new ArtifactResourceScope();
const destination = join(root, "swapped.json");
try {
const result = await writeTextParts(
replacingStagedParts(root),
destination,
false,
resources,
);
if (result.ok) throw new Error("Expected staged identity rejection");
expect(
await fs.readFile(join(root, requireStages(root)[0]!, "content"), "utf8"),
).toBe("foreign bytes");
await expect(fs.access(destination)).rejects.toThrow();
const stage = requireStages(root)[0];
if (stage !== undefined) {
const directory = join(root, stage);
await fs.rm(join(directory, "content"));
await fs.rename(join(directory, "original"), join(directory, "content"));
}
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("does not invent a staged owner when the supplied scope is closed", async () => {
const root = await createTestTempDirectory("rea-closed-output-scope-");
const resources = new ArtifactResourceScope();
await resources.close();
const destination = join(root, "closed.json");
const result = await writeTextParts(
["unused"],
destination,
false,
resources,
);
if (result.ok) throw new Error("Expected closed-scope admission failure");
expect(result.error).toBeInstanceOf(EvidenceFileError);
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupResources).toEqual([]);
expect(await fs.readdir(root)).toEqual([]);
});
function stagingPollutingParts(root: string): Iterable<string> {
return {
*[Symbol.iterator](): Generator<string> {
const directories = readdirSync(root);
const stage = directories.find((entry) =>
entry.startsWith(".rea-write-"),
);
if (stage === undefined) throw new Error("Expected staging directory");
writeFileSync(join(root, stage, "unexpected"), "retain this");
yield "canonical output";
},
};
}
function replacingStagedParts(root: string): Iterable<string> {
return {
*[Symbol.iterator](): Generator<string> {
const stage = requireStages(root)[0];
if (stage === undefined) throw new Error("Expected staging directory");
const content = join(root, stage, "content");
renameSync(content, join(root, stage, "original"));
writeFileSync(content, "foreign bytes");
yield "owned bytes";
},
};
}
const requireStages = (root: string): string[] =>
readdirSync(root).filter((entry) => entry.startsWith(".rea-write-"));
it("retains a failed file close owner and retries before removing its stage", async () => {
const root = await createTestTempDirectory("rea-staged-close-");
const directory = join(root, ".rea-write-owned");
await mkdir(directory);
const path = join(directory, "content");
const handle = await open(path, "wx", 0o600);
const owner = await OwnedStagedOutput.create(directory);
let closeAttempts = 0;
const actualClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeAttempts += 1;
if (closeAttempts === 1) throw new Error("injected close failure");
await actualClose();
});
await owner.setFile(new OwnedFileHandle(handle));
const resources = new ArtifactResourceScope();
const stagedOwner = {
kind: "staged-output" as const,
resource: directory,
output: owner,
};
try {
expect(await resources.release(stagedOwner)).toMatchObject({
kind: "failed",
});
await resources.close();
expect(closeAttempts).toBe(2);
await expect(fs.access(directory)).rejects.toThrow();
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("refuses to remove unexpected files from an owned staging directory", async () => {
const root = await createTestTempDirectory("rea-staged-replaced-");
const directory = join(root, ".rea-write-owned");
await mkdir(directory);
const owner = await OwnedStagedOutput.create(directory);
const unexpected = join(directory, "unexpected");
writeFileSync(unexpected, "unowned");
try {
await expect(owner.close()).rejects.toThrow(/Unexpected staging entries/u);
expect(await fs.readFile(unexpected, "utf8")).toBe("unowned");
} finally {
await fs.rm(unexpected, { force: true });
await owner.close();
await rm(root, { recursive: true, force: true });
}
});
it("retains cleanup when its staging directory was renamed", async () => {
const root = await createTestTempDirectory("rea-staged-renamed-dir-");
const directory = join(root, ".rea-write-owned");
const moved = join(root, ".rea-write-moved");
await mkdir(directory);
const path = join(directory, "content");
const handle = await open(path, "wx", 0o600);
const owner = await OwnedStagedOutput.create(directory);
await owner.setFile(new OwnedFileHandle(handle));
const resources = new ArtifactResourceScope();
const stagedOwner = {
kind: "staged-output" as const,
resource: directory,
output: owner,
};
try {
writeFileSync(join(directory, "unexpected"), "retain this");
expect(await resources.release(stagedOwner)).toMatchObject({
kind: "failed",
});
await fs.rename(directory, moved);
await expect(resources.close()).rejects.toThrow();
await fs.rename(moved, directory);
await rm(join(directory, "unexpected"));
await expect(resources.close()).resolves.toBeUndefined();
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("retains cleanup when owned staged content was renamed", async () => {
const root = await createTestTempDirectory("rea-staged-renamed-file-");
const directory = join(root, ".rea-write-owned");
const content = join(directory, "content");
const moved = join(directory, "moved-content");
await mkdir(directory);
const handle = await open(content, "wx", 0o600);
const owner = await OwnedStagedOutput.create(directory);
await owner.setFile(new OwnedFileHandle(handle));
const resources = new ArtifactResourceScope();
const stagedOwner = {
kind: "staged-output" as const,
resource: directory,
output: owner,
};
try {
await fs.rename(content, moved);
expect(await resources.release(stagedOwner)).toMatchObject({
kind: "failed",
});
await expect(resources.close()).rejects.toThrow(
/cleanup remains incomplete/u,
);
await fs.rename(moved, content);
await expect(resources.close()).resolves.toBeUndefined();
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
+2 -1
View File
@@ -12,9 +12,10 @@ export const readJavaScriptArtifactFiles = (
reader: ArtifactReader,
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
sourcePaths?: readonly string[],
) =>
withArtifactResourceScope((scope) =>
readOwned(reader, snapshot, scope, signal),
readOwned(reader, snapshot, scope, signal, sourcePaths),
);
/** Run a JavaScript analysis with an awaited, test-owned artifact scope. */