fix(media-use): remove only the temp folders media-use made, and never fail on cleanup (#8267)

* fix(media-use): remove only the temp folders media-use made, and never fail on cleanup

discardPrivateOutput now removes a folder only if privateOutputPath made it in this
run, instead of matching names against the raw temp setting, and a removal error no
longer turns a finished or failed generation into a cleanup error. The hosted video
and favicon providers use the same helper, so resolve removes their folders too.
Provider tests remove the folders they create; the resolve test also redirects
TEMP and TMP, so it checks the cleanup on Windows as well.

* test(media-use): prove resolve can remove the hosted video and favicon folders

* test(media-use): name the folder this run did not make plainly
This commit is contained in:
Ular Kimsanov
2026-11-20 06:26:07 +00:00
committed by GitHub
parent 026bff07d6
commit e16c681dc0
9 changed files with 109 additions and 34 deletions
@@ -1,9 +1,7 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { refuseUnderLimit } from "./credit-limit.mjs";
import { freezeUrl } from "./freeze.mjs";
import { discardPrivateOutput, privateOutputPath } from "./private-output.mjs";
import {
classifyHeygenErrorCode,
HEYGEN_AUTH_COMMAND,
@@ -110,20 +108,12 @@ export async function heygenVideoGenerate(intent, ctx) {
return null;
}
let tmpDir;
let tmpPath;
try {
tmpDir = mkdtempSync(join(tmpdir(), "media-use-heygen-video-"));
tmpPath = join(tmpDir, "video.mp4");
tmpPath = privateOutputPath("heygen-video", ".mp4");
await freezeUrl(videoUrl, tmpPath);
} catch (err) {
if (tmpDir) {
try {
rmSync(tmpDir, { recursive: true, force: true });
} catch {
// Preserve the download failure if temporary-directory cleanup fails.
}
}
if (tmpPath) discardPrivateOutput(tmpPath);
console.error(terminalText(`media-use: heygen video download failed: ${err.message}`));
return null;
}
@@ -1,6 +1,7 @@
import { strict as assert } from "node:assert";
import {
chmodSync,
existsSync,
mkdtempSync,
readFileSync,
rmSync,
@@ -15,10 +16,11 @@ import { basename, dirname, join } from "node:path";
import { test } from "node:test";
import { HEYGEN_NOT_AUTHENTICATED_MESSAGE } from "./heygen-cli.mjs";
import { AVATAR_VIDEO_SIGNIN_MESSAGE } from "./heygen-video-provider.mjs";
import { discardPrivateOutput } from "./private-output.mjs";
function cleanupDownload(localPath) {
if (
basename(localPath) === "video.mp4" &&
basename(localPath) === "output.mp4" &&
basename(dirname(localPath)).startsWith("media-use-heygen-video-")
) {
rmSync(dirname(localPath), { recursive: true, force: true });
@@ -178,7 +180,7 @@ test("downloads a generated avatar video and returns the generated MP4 result",
});
assert.ok(result);
assert.equal(join(tmpdir(), result.localPath.slice(tmpdir().length + 1)), result.localPath);
assert.match(result.localPath, /media-use-heygen-video-[^/\\]+[/\\]video\.mp4$/);
assert.match(result.localPath, /media-use-heygen-video-[^/\\]+[/\\]output\.mp4$/);
if (process.platform !== "win32") {
assert.equal(statSync(dirname(result.localPath)).mode & 0o777, 0o700);
}
@@ -193,6 +195,8 @@ test("downloads a generated avatar video and returns the generated MP4 result",
},
});
assert.deepEqual(readFileSync(result.localPath), VIDEO_FIXTURE);
discardPrivateOutput(result.localPath);
assert.equal(existsSync(dirname(result.localPath)), false);
},
);
} finally {
@@ -12,9 +12,8 @@ import { fetchMedia, readCappedBody } from "./media-fetch.mjs";
// falls through to resolve's normal failure path (`no provider could resolve
// logo`, exit 1).
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { writeFileSync } from "node:fs";
import { privateOutputPath } from "./private-output.mjs";
// Bump by pointing at a newer glincker/thesvg commit; the manifest and every
// icon URL resolve against the same pin, so a resolve is reproducible.
@@ -234,7 +233,7 @@ export async function faviconSearch(intent, ctx = {}) {
// instead of re-downloading, so the size check is authoritative over what
// gets frozen and the favicon tier costs one network round-trip, not two.
const bytes = body.byteLength;
const tmp = join(mkdtempSync(join(tmpdir(), "media-use-logo-")), `${domain}.ico`);
const tmp = privateOutputPath("logo", ".ico");
writeFileSync(tmp, body);
return {
localPath: tmp,
@@ -1,6 +1,8 @@
import test from "node:test";
import assert from "node:assert";
import { readFileSync } from "node:fs";
import { existsSync, readFileSync, rmSync } from "node:fs";
import { discardPrivateOutput } from "./private-output.mjs";
import { dirname } from "node:path";
import {
entityFrom,
titleMatches,
@@ -232,9 +234,13 @@ test("faviconSearch hands verified bytes over as a local file — one fetch, no
const fetchMock = t.mock.method(globalThis, "fetch", async () => bin(600));
const res = await faviconSearch("someco logo", {});
assert.ok(res.localPath, "returns a localPath, not a url");
t.after(() => rmSync(dirname(res.localPath), { recursive: true, force: true }));
assert.match(res.localPath, /media-use-logo-[^/\\]+[/\\]output\.ico$/);
assert.equal(readFileSync(res.localPath).byteLength, 600, "frozen bytes are the verified bytes");
assert.equal(fetchMock.mock.callCount(), 1, "single network round-trip");
assert.equal(res.metadata.provenance.low_res, true);
discardPrivateOutput(res.localPath);
assert.equal(existsSync(dirname(res.localPath)), false, "resolve can remove its folder");
});
test("githubAvatarSearch never touches the network for an unmapped entity", async (t) => {
@@ -267,6 +273,7 @@ test("the real logo cascade falls through tier by tier to the first hit", async
entity: "zzzbrand",
});
assert.ok(res, "cascade must land on the favicon tier");
t.after(() => rmSync(dirname(res.localPath), { recursive: true, force: true }));
assert.equal(res.metadata.provider, "favicon.ddg");
});
@@ -1,10 +1,14 @@
import { test } from "node:test";
import { after, test } from "node:test";
import assert from "node:assert/strict";
import { existsSync } from "node:fs";
import { dirname } from "node:path";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { homedir, tmpdir } from "node:os";
import { ltxVideoGenerate } from "./ltx-video-provider.mjs";
const scratch = mkdtempSync(join(tmpdir(), "ltx-provider-test-"));
process.env.TMPDIR = process.env.TEMP = process.env.TMP = scratch;
after(() => rmSync(scratch, { recursive: true, force: true }));
const fittingSpecs = { availableRamMB: 20000, gpu: { present: true } };
test("no fitting local model: falls through without checking for a binary", async (t) => {
@@ -1,7 +1,14 @@
import { test } from "node:test";
import { after, test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { mfluxImageGenerate } from "./mflux-provider.mjs";
const scratch = mkdtempSync(join(tmpdir(), "mflux-provider-test-"));
process.env.TMPDIR = process.env.TEMP = process.env.TMP = scratch;
after(() => rmSync(scratch, { recursive: true, force: true }));
// 40GB clears the 32GB klein tier and the 8GB schnell tier below it; the 64GB
// qwen tier stays out of reach. Two rungs is what makes demotion observable.
const bothTiersSpecs = { availableRamMB: 40000, gpu: { present: true } };
@@ -1,21 +1,26 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { dirname, join } from "node:path";
// Where a local generator writes its file: inside a fresh folder that only this account can
// open (mkdtemp: an unguessable name, created exclusively, mode 0700). A guessable name in the
// shared temp folder, which is /tmp on Linux, could be created first by another account and
// then taken as the generated file.
// then taken as the generated file. `made` holds the folders this run created.
const made = new Set();
export function privateOutputPath(provider, ext) {
return join(mkdtempSync(join(tmpdir(), `media-use-${provider}-`)), `output${ext}`);
const dir = mkdtempSync(join(tmpdir(), `media-use-${provider}-`));
made.add(dir);
return join(dir, `output${ext}`);
}
// Remove the folder privateOutputPath made for `path`, once its file is copied into the project.
// Any other path is left alone: providers also return files they do not own, such as a sound in
// the bundled SFX library.
// Any other path is left alone, and a folder that will not go stays behind, still owner-only.
export function discardPrivateOutput(path) {
const dir = dirname(path);
if (dirname(dir) !== tmpdir() || !/^media-use-[a-z]+-[A-Za-z0-9]{6}$/.test(basename(dir))) return;
if (!/^output\.[a-z0-9]+$/.test(basename(path))) return;
rmSync(dir, { recursive: true, force: true });
if (!made.delete(dir)) return;
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// never turn a finished or failed generation into a cleanup error
}
}
@@ -1,6 +1,14 @@
import test from "node:test";
import assert from "node:assert";
import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { discardPrivateOutput, privateOutputPath } from "./private-output.mjs";
@@ -54,3 +62,46 @@ test("discarding leaves any file a generator does not own", (t) => {
assert.equal(existsSync(lookalike), true);
assert.equal(existsSync(otherTool), true);
});
test("discarding leaves a folder named like a generator's that this run did not make", (t) => {
const notOurs = join(
removeAfter(t, mkdtempSync(join(tmpdir(), "media-use-codex-"))),
"output.png",
);
writeFileSync(notOurs, "x");
discardPrivateOutput(notOurs);
assert.equal(existsSync(notOurs), true);
});
test(
"a temp setting that ends in extra slashes still gets its folder removed",
{ skip: process.platform === "win32" },
(t) => {
const base = removeAfter(t, mkdtempSync(join(tmpdir(), "slashed-temp-")));
const previous = process.env.TMPDIR;
t.after(() => {
if (previous === undefined) delete process.env.TMPDIR;
else process.env.TMPDIR = previous;
});
process.env.TMPDIR = `${base}//`;
const out = privateOutputPath("ltx", ".mp4");
writeFileSync(out, "video");
discardPrivateOutput(out);
assert.equal(existsSync(dirname(out)), false);
},
);
test(
"a folder that cannot be removed does not make discarding throw",
{ skip: process.platform === "win32" || process.getuid?.() === 0 },
(t) => {
const out = privateOutputPath("mflux", ".png");
t.after(() => {
chmodSync(dirname(out), 0o700);
rmSync(dirname(out), { recursive: true, force: true });
});
writeFileSync(out, "image");
chmodSync(dirname(out), 0o500);
assert.doesNotThrow(() => discardPrivateOutput(out));
},
);
+9 -1
View File
@@ -1802,7 +1802,15 @@ test("a local generator's private output folder is gone once the file is in the
"kokoro.local",
"--json",
],
{ env: { HOME: tmp, TMPDIR: privateTmp, HYPERFRAMES_CLI_ENTRY: entry } },
{
env: {
HOME: tmp,
TMPDIR: privateTmp,
TEMP: privateTmp,
TMP: privateTmp,
HYPERFRAMES_CLI_ENTRY: entry,
},
},
);
assert.equal(result.status, 0, result.stderr);
const parsed = JSON.parse(result.stdout);