Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(gfs-controller): destroy reopened legacy stream on copy staging error

Alfredo Lopez2d1e78382750
diff --git a/gfs-controller/src/db/copyBlobStaging.test.ts b/gfs-controller/src/db/copyBlobStaging.test.ts
index 881070936..9b0c77256 100644
--- a/gfs-controller/src/db/copyBlobStaging.test.ts
+++ b/gfs-controller/src/db/copyBlobStaging.test.ts
@@ -3,7 +3,7 @@ import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Readable } from "node:stream";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BlobStore, BlobVerificationError, BlobWriteCleanupError } from "../storage/blobStore";
import { resolveBlobKeyPath } from "../storage/paths";
import { PgBlobStagingStore, type ManifestQueryable, type PublishedTreeRef } from "./blobStaging";
@@ -190,6 +190,70 @@ describe("recursive copy blob staging", () => {
}
);
+ it("destroys a reopened legacy stream when writeImmutable throws before consuming it", async () => {
+ // reopen() succeeds (opens an fd), then writeImmutable throws BEFORE its
+ // pipeline() consumes the input — models its parent/symlink/O_EXCL guards or
+ // a deadline firing first. Without explicit cleanup the reopened legacy fd
+ // leaks (the generation path is owned by copyPublication, the legacy stream
+ // is owned here). The stage path must destroy it on error.
+ const db = new FakeDb();
+ const bytes = Buffer.from("legacy");
+ const reopened = Readable.from(bytes);
+ const destroySpy = vi.spyOn(reopened, "destroy");
+ const boom = Object.assign(new Error("destination exists"), { code: "EEXIST" });
+ const blobs = {
+ writeImmutable: async () => {
+ throw boom;
+ },
+ verify: async () => undefined,
+ deleteByKey: async () => undefined,
+ deleteLegacyFlat: async () => undefined,
+ };
+ await expect(
+ stageCopiedBlob(new PgBlobStagingStore(db), blobs, {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "legacy_flat", reopen: async () => reopened },
+ expectedBytes: bytes.length,
+ expectedSha256: digest(bytes),
+ deadlineAtMs: Date.now() + 10_000,
+ })
+ ).rejects.toMatchObject({ code: "EEXIST" });
+ expect(destroySpy).toHaveBeenCalled();
+ });
+
+ it("does not destroy a generation stream the caller owns", async () => {
+ // Generation streams are owned by copyPublication (destroyed in its own
+ // catch). stageCopiedBlob must NOT double-manage them: it only owns the
+ // legacy stream it reopens itself.
+ const db = new FakeDb();
+ const bytes = Buffer.from("gen");
+ const callerStream = Readable.from(bytes);
+ const destroySpy = vi.spyOn(callerStream, "destroy");
+ const boom = Object.assign(new Error("destination exists"), { code: "EEXIST" });
+ const blobs = {
+ writeImmutable: async () => {
+ throw boom;
+ },
+ verify: async () => undefined,
+ deleteByKey: async () => undefined,
+ deleteLegacyFlat: async () => undefined,
+ };
+ await expect(
+ stageCopiedBlob(new PgBlobStagingStore(db), blobs, {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "generation", stream: callerStream },
+ expectedBytes: bytes.length,
+ expectedSha256: digest(bytes),
+ deadlineAtMs: Date.now() + 10_000,
+ })
+ ).rejects.toMatchObject({ code: "EEXIST" });
+ expect(destroySpy).not.toHaveBeenCalled();
+ });
+
it.each([false, true])(
"durably handles an owned recursive copy candidate when cleanup failure is %s",
async cleanupFails => {
diff --git a/gfs-controller/src/db/copyBlobStaging.ts b/gfs-controller/src/db/copyBlobStaging.ts
index 3425c2689..ff1e12abc 100644
--- a/gfs-controller/src/db/copyBlobStaging.ts
+++ b/gfs-controller/src/db/copyBlobStaging.ts
@@ -54,11 +54,25 @@ export async function stageCopiedBlob(
bytes: input.expectedBytes,
}, budget);
let physicalCandidateOwned = false;
+ // For a legacy_flat source we own the reopened stream. writeImmutable's
+ // pipeline() destroys its input once reached, but a throw BEFORE pipeline —
+ // the checkDeadline() below, or writeImmutable's own parent/symlink/O_EXCL
+ // guards and deadline checks firing before it pipes — would otherwise leak the
+ // reopened file descriptor. Generation streams stay owned by the caller
+ // (copyPublication destroys them), so only the reopened legacy stream is
+ // tracked here for destruction on error. destroy() is idempotent.
+ let ownedLegacyStream: Readable | undefined;
try {
checkDeadline();
// Legacy rows have no committed digest. Their preflight must hash and close
// one stream, then provide this explicit reopen callback for the copy pass.
- const stream = input.source.kind === "generation" ? input.source.stream : await input.source.reopen();
+ let stream: Readable;
+ if (input.source.kind === "generation") {
+ stream = input.source.stream;
+ } else {
+ stream = await input.source.reopen();
+ ownedLegacyStream = stream;
+ }
checkDeadline();
const options = { signal: input.signal, checkDeadline };
const written = await blobs.writeImmutable(input.destinationResourceId, input.generation, stream, options);
@@ -73,6 +87,9 @@ export async function stageCopiedBlob(
await blobs.verify(blobKey, input.expectedBytes, input.expectedSha256, options);
return written;
} catch (err) {
+ // Destroy the reopened legacy stream if writeImmutable threw before its
+ // pipeline() consumed it; otherwise the reopened fd leaks. No-op once piped.
+ ownedLegacyStream?.destroy();
// Reopen and write failures occur before ownership is established. Keep
// the staged manifest for reconciliation rather than deleting a key that
// may already belong to a committed request.
diff --git a/gfs-controller/src/db/renamePublication.ts b/gfs-controller/src/db/renamePublication.ts
index aa70bb390..3954e4ffa 100644
--- a/gfs-controller/src/db/renamePublication.ts
+++ b/gfs-controller/src/db/renamePublication.ts
@@ -207,6 +207,14 @@ export async function publishRename(tx: Transactor, input: RenameInput): Promise
let expectedRoot: GfsResource | undefined;
try {
return await tx.transaction(async client => {
+ // Asymmetry with publishCopy (intentional): rename does NOT re-check the
+ // caller's permission epoch inside this transaction. publishCopy must,
+ // because it stages blob bytes asynchronously OUTSIDE its commit txn, so a
+ // revocation can land during that gap. Rename has no such gap — it
+ // authorizes, then runs only this single short structure transaction; the
+ // sole window is the txn itself (few ms under advisory lock + FOR UPDATE).
+ // If rename ever grows an async pre-commit phase, add the same epoch
+ // revalidate that publishCopy performs before its INSERT.
await client.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`, [input.drive]);
const observed = await loadTree(client, input.drive, dbId(input.resourceId), loadLimit(input));
assertWithinLimit(observed, input);