Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,10 +307,13 @@ export {
export { qualifyVideoLayer } from "./services/videoLayerPassthrough.js";
export { isSelfOrAncestorHidden } from "./services/mediaHidden.js";
export {
createCacheLease,
directorySizeBytes,
gcExtractionCache,
privateCacheRoot,
type CacheLease,
} from "./services/extractionCache.js";
export { ownerRecordState, processOwnerRecord, type OwnerRecord } from "./utils/processOwner.js";

export {
resolveReferencedStart,
Expand Down
105 changes: 105 additions & 0 deletions packages/engine/src/services/extractionCache.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import {
chmodSync,
Expand All @@ -22,6 +23,7 @@ import {
SCHEMA_PREFIX,
cacheEntryDirName,
computeCacheKey,
createCacheLease,
ensureCacheEntryDir,
gcExtractionCache,
lookupCacheEntry,
Expand All @@ -37,6 +39,7 @@ import {
type CacheKeyInput,
} from "./extractionCache.js";
import { defaultExtractCacheDir } from "../config.js";
import { processOwnerRecord } from "../utils/processOwner.js";

const keyFor = (videoPath: string, overrides: Partial<CacheKeyInput> = {}): CacheKeyInput => {
const stat = readKeyStat(videoPath);
Expand Down Expand Up @@ -615,6 +618,108 @@ describe("gcExtractionCache", () => {
});
});

describe("cache lease", () => {
const HOUR = 60 * 60 * 1000;
const sweepAll = () => gcExtractionCache(tmpRoot, { maxBytes: 0, minAgeMs: HOUR });
let tmpRoot: string;

beforeEach(() => {
tmpRoot = mkdtempSync(join(tmpdir(), "hf-extract-cache-lease-test-"));
});

afterEach(() => {
rmSync(tmpRoot, { recursive: true, force: true });
});

function agedEntry(name: string): string {
const dir = join(tmpRoot, `${SCHEMA_PREFIX}${name}`);
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "frame_00001.jpg"), "frame", "utf-8");
markCacheEntryComplete({ dir, keyHash: name.padEnd(64, "0") });
const old = new Date(Date.now() - 2 * HOUR);
utimesSync(join(dir, COMPLETE_SENTINEL), old, old);
utimesSync(dir, old, old);
return dir;
}

it("keeps an entry a running render holds, however long ago it was last touched", () => {
const held = agedEntry("held");
const free = agedEntry("free");
const lease = createCacheLease();
lease.hold(held);

sweepAll();
expect(existsSync(join(held, "frame_00001.jpg"))).toBe(true);
expect(existsSync(free)).toBe(false);

lease.release();
expect(readdirSync(tmpRoot).some((name) => name.includes(".hold-"))).toBe(false);
sweepAll();
expect(existsSync(held)).toBe(false);
});

it("keeps a held partial directory past the aged-partial sweep", () => {
const partial = join(tmpRoot, `${SCHEMA_PREFIX}abc.partial-${process.pid}-deadbeef`);
mkdirSync(partial);
const old = new Date(Date.now() - 2 * HOUR);
utimesSync(partial, old, old);
const lease = createCacheLease();
lease.hold(partial);

sweepAll();
expect(existsSync(partial)).toBe(true);
lease.release();
});

it("keeps the hold while another render in the same process still holds the entry", () => {
const shared = agedEntry("shared");
const first = createCacheLease();
const second = createCacheLease();
first.hold(shared);
second.hold(shared);

first.release();
sweepAll();
expect(existsSync(shared)).toBe(true);

second.release();
sweepAll();
expect(existsSync(shared)).toBe(false);
});

it("takes no hold after the render released its lease", () => {
const late = agedEntry("late");
const lease = createCacheLease();
lease.release();
lease.hold(late);

expect(readdirSync(tmpRoot).some((name) => name.includes(".hold-"))).toBe(false);
sweepAll();
expect(existsSync(late)).toBe(false);
});

it("drops the hold of a process that has exited, and the entry with it", () => {
const orphaned = agedEntry("orphaned");
const exited = spawnSync(process.execPath, ["-e", ""]).pid;
const holdFile = `${orphaned}.hold-${exited}`;
writeFileSync(holdFile, JSON.stringify({ ...processOwnerRecord(), pid: exited }));

sweepAll();
expect(existsSync(orphaned)).toBe(false);
expect(existsSync(holdFile)).toBe(false);
});

it("leaves a hold it cannot read to the age guard alone", () => {
const unreadable = agedEntry("unreadable");
const holdFile = `${unreadable}.hold-1`;
writeFileSync(holdFile, "not json");

sweepAll();
expect(existsSync(unreadable)).toBe(false);
expect(existsSync(holdFile)).toBe(true);
});
});

describe.skipIf(process.getuid === undefined)("privateCacheRoot", () => {
const savedTmpdir = process.env.TMPDIR;
let sharedTmp: string;
Expand Down
104 changes: 94 additions & 10 deletions packages/engine/src/services/extractionCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,28 @@
import { createHash } from "node:crypto";
import {
chmodSync,
closeSync,
constants,
createReadStream,
existsSync,
lstatSync,
mkdirSync,
openSync,
readFileSync,
readdirSync,
rmSync,
statSync,
utimesSync,
writeFileSync,
type Dirent,
} from "node:fs";
import { createStagingDir } from "@hyperframes/core/atomic-file";
import { renameWithRetry } from "@hyperframes/core/rename-retry";
import { basename, dirname, join } from "node:path";
import { defaultExtractCacheDir } from "../config.js";
import type { VideoMetadata } from "../utils/ffprobe.js";
import { FRAME_FILENAME_PREFIX, framePathsFromDirectory } from "./extractedFrameIndex.js";
import { ownerRecordState, processOwnerRecord } from "../utils/processOwner.js";

/** Filename prefix for extracted frames. Shared with the extractor. */
export { FRAME_FILENAME_PREFIX } from "./extractedFrameIndex.js";
Expand Down Expand Up @@ -366,6 +372,85 @@ export function markCacheEntryComplete(entry: CacheEntry): void {
writeFileSync(join(entry.dir, COMPLETE_SENTINEL), "", "utf-8");
}

/** `<entry>.hold-<pid>` beside an entry: a running process still reads it, so no sweep removes it. */
const HOLD_SUFFIX = ".hold-";
/** Leases in this process holding each entry; its hold file goes when the last one releases. */
const leasesByDir = new Map<string, number>();
const HOLD_FLAGS =
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0);

const holdFile = (dir: string) => `${dir}${HOLD_SUFFIX}${process.pid}`;

/** The cache entries one render reads, held from when it finds them until `release`. */
export interface CacheLease {
hold(dir: string): void;
release(): void;
}

export function createCacheLease(): CacheLease {
const dirs = new Set<string>();
let released = false;
return {
hold(dir) {
// A late find from an aborted extraction must not outlive the render it belonged to.
if (released || dirs.has(dir)) return;
dirs.add(dir);
const leases = leasesByDir.get(dir) ?? 0;
leasesByDir.set(dir, leases + 1);
if (leases > 0) return;
try {
const fd = openSync(holdFile(dir), HOLD_FLAGS, 0o600);
try {
writeFileSync(fd, JSON.stringify(processOwnerRecord()));
} finally {
closeSync(fd);
}
} catch {
// An unwritable hold leaves the entry to the age guard alone.
}
},
release() {
released = true;
for (const dir of dirs) {
const leases = (leasesByDir.get(dir) ?? 1) - 1;
if (leases > 0) {
leasesByDir.set(dir, leases);
continue;
}
leasesByDir.delete(dir);
// A hold left behind names this pid; the next sweep drops it once the process has exited.
removeDir(holdFile(dir));
}
dirs.clear();
},
};
}

function holdState(path: string): "gone" | "live" | "unknown" {
try {
return ownerRecordState(JSON.parse(readFileSync(path, "utf-8")));
} catch {
return "unknown";
}
}

/** Names of the entries a live process holds; holds of exited processes are removed on the way. */
function liveHolds(
rootDir: string,
children: Dirent[],
remove: (path: string) => void,
): Set<string> {
const held = new Set<string>();
for (const child of children) {
const at = child.name.lastIndexOf(HOLD_SUFFIX);
if (!child.isFile() || at <= 0) continue;
const state = holdState(join(rootDir, child.name));
if (state === "live") held.add(child.name.slice(0, at));
else if (state === "gone") remove(join(rootDir, child.name));
}
return held;
}

/** Any generation of this cache's entries ("hfcache-v*"), current or superseded. */
const CACHE_GENERATION_PREFIX = "hfcache-v";

Expand Down Expand Up @@ -471,13 +556,6 @@ export interface GcStats {
agedPartialsRemoved: number;
}

/**
* Opportunistic size-capped LRU cleanup for extracted video frames.
*
* Scans only direct cache-looking children and never throws. The age guard is
* a liveness heuristic, not a lock. Returns counts so the caller can surface
* eviction pressure in render observability.
*/
/**
* Whether the staleness fallback should force a sweep: true when no sweep
* marker exists or the last sweep is older than `maxAgeMs`. Lets 100%-warm
Expand All @@ -499,6 +577,10 @@ function markGcSweep(rootDir: string): void {
}
}

/**
* Size-capped LRU cleanup of direct cache-looking children; never throws. An entry a live process holds
* (`createCacheLease`) is never removed. Returns counts for render observability.
*/
export function gcExtractionCache(
rootDir: string,
opts: { maxBytes: number; minAgeMs: number; dryRun?: boolean },
Expand All @@ -509,8 +591,10 @@ export function gcExtractionCache(
try {
const now = Date.now();
const entries: GcEntry[] = [];
for (const child of readdirSync(rootDir, { withFileTypes: true })) {
if (!child.isDirectory() || !isCacheLikeChild(child.name)) continue;
const children = readdirSync(rootDir, { withFileTypes: true });
const held = liveHolds(rootDir, children, remove);
for (const child of children) {
if (!child.isDirectory() || !isCacheLikeChild(child.name) || held.has(child.name)) continue;
const entry = collectGcEntry(
join(rootDir, child.name),
child.name,
Expand All @@ -527,7 +611,7 @@ export function gcExtractionCache(

entries.sort((a, b) => a.lastUseMs - b.lastUseMs);
for (const entry of entries) {
// ponytail: age-based liveness guard, not a lock; a render longer than minAge with a full cache could lose entries mid-read - acceptable, next render re-extracts.
// Unheld entries keep the age guard: a render on another host, or one whose hold failed, is not seen here.
if (entry.ageMs < opts.minAgeMs) continue;
remove(entry.dir);
stats.evictedEntries += 1;
Expand Down
5 changes: 5 additions & 0 deletions packages/engine/src/services/videoFrameExtractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ import {
privateCacheRoot,
rehydrateCacheEntry,
touchCacheEntry,
type CacheLease,
type CacheEntry,
type CacheFrameFormat,
} from "./extractionCache.js";
Expand Down Expand Up @@ -326,6 +327,7 @@ export interface ExtractionOptions {
assetRoots?: readonly string[];
shownBox?: { width: number; height: number };
shownBoxes?: ReadonlyMap<string, { width: number; height: number }>;
cacheLease?: CacheLease;
}

const DOWNLOAD_SUBDIR = "_downloads";
Expand Down Expand Up @@ -2675,6 +2677,7 @@ export async function extractAllVideoFrames(
}

function rehydratePublishedCache(work: PreparedExtraction, target: CacheMissTarget) {
options.cacheLease?.hold(target.entry.dir);
const rehydrated = rehydrateCacheEntry(target.entry, {
videoId: work.video.id,
srcPath: target.srcPath,
Expand Down Expand Up @@ -2798,6 +2801,7 @@ export async function extractAllVideoFrames(
const published = publishCacheEntry(cacheTarget.entry, partialDir, result.totalFrames);
if (!published.published) {
breakdown.cachePublishFailures += 1;
options.cacheLease?.hold(partialDir);
return { ...result, ownedByLookup: false };
}
return rehydratePublishedCache(work, cacheTarget);
Expand Down Expand Up @@ -2924,6 +2928,7 @@ export async function extractAllVideoFrames(
const published = publishCacheEntry(cacheTarget.entry, partialDir, sliced.totalFrames);
if (!published.published) {
breakdown.cachePublishFailures += 1;
options.cacheLease?.hold(partialDir);
return { ...sliced, ownedByLookup: false };
}
return rehydratePublishedCache(work, cacheTarget);
Expand Down
Loading
Loading