Skip to content
Open
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
1 change: 1 addition & 0 deletions changelog.d/fixes/21166-call-log-dir-handles.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **fix(call-logs):** the resumable orphan-artifact scan no longer holds directory descriptors between bounded passes, so the call-log base directory and the active day directory do not stay open in `/proc/<pid>/fd` ([#21166](https://github.com/cheaper-inference/OmniRoute/pull/21166))
4 changes: 4 additions & 0 deletions src/lib/gracefulShutdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,15 @@ async function cleanup(): Promise<void> {
{ closeLogRotation },
{ closeSharedLoggerResource },
{ closeCallLogSaves },
{ closeOrphanScanCursor },
] = await Promise.all([
import("@omniroute/open-sse/mcp-server/audit.ts"),
import("@/lib/db/core"),
import("@/lib/spend/batchWriter"),
import("@/lib/logRotation"),
import("@/shared/utils/loggerResource"),
import("@/lib/usage/callLogs"),
import("@/lib/usage/callLogRotation"),
]);
const flushResult = await flushSpendBatchWriter();
if (flushResult.flushedEntries > 0) {
Expand All @@ -146,6 +148,8 @@ async function cleanup(): Promise<void> {
);
}
await closeCallLogSaves();
// Drop the resumable orphan-scan position so no call-log directory state survives shutdown.
closeOrphanScanCursor();
try {
const { flushPayloadTraffic } = await import("@/lib/db/proxyTraffic");
flushPayloadTraffic();
Expand Down
104 changes: 65 additions & 39 deletions src/lib/usage/callLogRotation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,24 @@ function deleteCallLogRowsByIds(ids: string[]): DeleteResult {
};
}

/**
* Resumable orphan-scan position.
*
* The scan must survive across bounded cleanup passes (a day directory holds thousands of
* files, so one pass never finishes it), but it must NOT keep an `fs.Dir` — a directory file
* descriptor — open between runs: a long-lived cursor left the base directory and the current
* day directory in `/proc/<pid>/fd` until the whole cycle was exhausted. The position is a
* one-shot listing plus an index instead: no descriptor outlives the call that created it,
* and advancing is pure array arithmetic, so resumption stays O(1) per pass.
*/
type OrphanScanCursor = {
baseDir: string;
root: fs.Dir;
day: fs.Dir | null;
rootListed: boolean;
dayNames: string[];
dayIndex: number;
dayName: string | null;
pendingDayName: string | null;
fileNames: string[];
fileIndex: number;
};

type OrphanScanBatch = {
Expand All @@ -111,16 +123,35 @@ type OrphanScanBatch = {

let orphanScanCursor: OrphanScanCursor | null = null;

function closeOrphanScanCursor(): void {
try {
orphanScanCursor?.day?.closeSync();
} catch {}
try {
orphanScanCursor?.root.closeSync();
} catch {}
/**
* Drop the resumable scan position. The cursor holds names only, never a descriptor, so this
* is the single reset point for shutdown paths and for a changed base directory.
*/
export function closeOrphanScanCursor(): void {
orphanScanCursor = null;
}

function listOrphanDayNames(baseDir: string): string[] {
return fs
.readdirSync(baseDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort();
}

function listOrphanDayFiles(dayDir: string): string[] {
try {
return fs
.readdirSync(dayDir, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
.map((entry) => entry.name)
.sort();
} catch {
// Unreadable or vanished day directory: skip it, like a failed opendir did before.
return [];
}
}

function readOrphanCandidates(
baseDir: string,
candidateLimit: number,
Expand All @@ -135,54 +166,49 @@ function readOrphanCandidates(
scannedEntries++;
orphanScanCursor = {
baseDir,
root: fs.opendirSync(baseDir),
day: null,
rootListed: false,
dayNames: [],
dayIndex: 0,
dayName: null,
pendingDayName: null,
fileNames: [],
fileIndex: 0,
};
}
const cursor = orphanScanCursor;

const candidates: string[] = [];
let exhausted = false;
while (candidates.length < candidateLimit && scannedEntries < scanLimit) {
if (!orphanScanCursor.day) {
if (orphanScanCursor.pendingDayName) {
if (cursor.dayName === null) {
if (!cursor.rootListed) {
scannedEntries++;
const dayName = orphanScanCursor.pendingDayName;
orphanScanCursor.pendingDayName = null;
try {
orphanScanCursor.day = fs.opendirSync(path.join(baseDir, dayName));
orphanScanCursor.dayName = dayName;
} catch {
continue;
}
cursor.dayNames = listOrphanDayNames(baseDir);
cursor.rootListed = true;
continue;
}

scannedEntries++;
const dayEntry = orphanScanCursor.root.readSync();
if (!dayEntry) {
if (cursor.dayIndex >= cursor.dayNames.length) {
closeOrphanScanCursor();
exhausted = true;
break;
}
if (!dayEntry.isDirectory()) continue;
orphanScanCursor.pendingDayName = dayEntry.name;
scannedEntries++;
cursor.dayName = cursor.dayNames[cursor.dayIndex];
cursor.fileNames = listOrphanDayFiles(path.join(baseDir, cursor.dayName));
cursor.fileIndex = 0;
continue;
}

scannedEntries++;
const fileEntry = orphanScanCursor.day.readSync();
if (!fileEntry) {
try {
orphanScanCursor.day.closeSync();
} catch {}
orphanScanCursor.day = null;
orphanScanCursor.dayName = null;
if (cursor.fileIndex >= cursor.fileNames.length) {
cursor.dayName = null;
cursor.fileNames = [];
cursor.fileIndex = 0;
cursor.dayIndex++;
continue;
}
if (!fileEntry.isFile() || !fileEntry.name.endsWith(".json")) continue;
candidates.push(path.posix.join(orphanScanCursor.dayName!, fileEntry.name));

scannedEntries++;
candidates.push(path.posix.join(cursor.dayName, cursor.fileNames[cursor.fileIndex]));
cursor.fileIndex++;
}
return { candidates, exhausted, scannedEntries };
}
Expand Down
141 changes: 118 additions & 23 deletions tests/unit/call-log-file-rotation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,25 +218,30 @@ test("rotateCallLogs swallows filesystem errors during cleanup", () => {
assert.ok(CALL_LOGS_DIR, "CALL_LOGS_DIR should resolve for test data dir");
fs.mkdirSync(CALL_LOGS_DIR, { recursive: true });

const originalOpendirSync = fs.opendirSync;
const originalReaddirSync = fs.readdirSync;
const originalConsoleError = console.error;
const consoleCalls = [];

fs.opendirSync = () => {
throw new Error("simulated opendir failure");
};
// The orphan scan lists the call-log tree with readdirSync; failing that listing must be
// swallowed like the opendir failure it replaced.
fs.readdirSync = ((targetPath, options) => {
if (String(targetPath).startsWith(CALL_LOGS_DIR)) {
throw new Error("simulated readdir failure");
}
return originalReaddirSync(targetPath, options);
}) as typeof fs.readdirSync;
console.error = (...args) => {
consoleCalls.push(args.join(" "));
};

try {
assert.doesNotThrow(() => rotateCallLogs());
} finally {
fs.opendirSync = originalOpendirSync;
fs.readdirSync = originalReaddirSync;
console.error = originalConsoleError;
}

assert.ok(consoleCalls.some((line) => /simulated opendir failure/.test(line)));
assert.ok(consoleCalls.some((line) => /simulated readdir failure/.test(line)));
});

test("cleanupOverflowCallLogFiles ignores rmSync failures for old artifacts", () => {
Expand Down Expand Up @@ -614,41 +619,131 @@ test("orphan traversal bounds every directory operation and resumes", () => {
fs.writeFileSync(path.join(dayDir, `${String(i).padStart(4, "0")}.json`), "{}");
}

const originalOpendirSync = fs.opendirSync;
let operations = 0;
fs.opendirSync = ((...args: Parameters<typeof fs.opendirSync>) => {
operations++;
const dir = originalOpendirSync(...args);
const originalReadSync = dir.readSync.bind(dir);
dir.readSync = () => {
operations++;
return originalReadSync();
};
return dir;
}) as typeof fs.opendirSync;
// Directory work is bounded by listings, never by one handle operation per entry: one
// listing of the base directory per scan cycle plus one per day directory entered, and a
// resumed pass still inside a day performs none at all.
const originalReaddirSync = fs.readdirSync;
const listings: string[] = [];
fs.readdirSync = ((...args: Parameters<typeof fs.readdirSync>) => {
const targetPath = String(args[0]);
if (targetPath === baseDir || targetPath === dayDir) listings.push(targetPath);
return originalReaddirSync(...args);
}) as typeof fs.readdirSync;

const passOperations: number[] = [];
let deleted = 0;
try {
for (let pass = 0; pass < 2; pass++) {
operations = 0;
listings.length = 0;
deleted += cleanupOrphanCallLogFiles(baseDir, {
maxCandidates: 100,
maxScanEntries: 100,
minAgeMs: 0,
});
passOperations.push(operations);
passOperations.push(listings.length);
}
} finally {
fs.opendirSync = originalOpendirSync;
fs.readdirSync = originalReaddirSync;
}

assert.equal(passOperations[0], 100);
assert.ok(passOperations[1] > 0 && passOperations[1] <= 100);
assert.ok(passOperations[0] > 0 && passOperations[0] <= 2, `pass 0: ${passOperations[0]}`);
assert.ok(passOperations[1] <= 2, `pass 1: ${passOperations[1]}`);
assert.equal(deleted, 10);
assert.equal(fs.readdirSync(dayDir).filter((entry) => entry.endsWith(".json")).length, 0);
});

test("orphan traversal resumes a large day across bounded passes", () => {
const baseDir = path.join(TEST_DATA_DIR, "big-artifact-day");
const dayDir = path.join(baseDir, "2026-04-11");
fs.mkdirSync(dayDir, { recursive: true });
const old = new Date(Date.now() - 10 * 60_000);
for (let i = 0; i < 250; i++) {
const file = path.join(dayDir, `${String(i).padStart(4, "0")}.json`);
fs.writeFileSync(file, "{}");
fs.utimesSync(file, old, old);
}

const passDeletes: number[] = [];
for (let pass = 0; pass < 10; pass++) {
const deleted = cleanupOrphanCallLogFiles(baseDir, {
maxCandidates: 100,
maxScanEntries: 100,
minAgeMs: 0,
});
passDeletes.push(deleted);
if (deleted === 0) break;
}

// Every bounded pass continues where the previous one stopped, so nothing is skipped and
// nothing is rescanned.
for (const deleted of passDeletes.slice(0, -1)) {
assert.ok(deleted > 0 && deleted <= 100, `bounded pass deleted ${deleted}`);
}
assert.ok(passDeletes.length >= 3, `expected several passes, got ${passDeletes.join(",")}`);
assert.equal(
passDeletes.reduce((sum, deleted) => sum + deleted, 0),
250
);
// Deleting a day's last artifact also removes the now-empty day directory.
assert.equal(fs.existsSync(dayDir) ? fs.readdirSync(dayDir).length : 0, 0);
});

function openDirectoryHandlesUnder(directory: string): string[] {
const real = fs.realpathSync.native(directory);
const prefix = `${real}${path.sep}`;
const handles: string[] = [];
for (const entry of fs.readdirSync("/proc/self/fd")) {
let target: string;
try {
target = fs.readlinkSync(path.join("/proc/self/fd", entry));
} catch {
continue; // the descriptor closed between readdir and readlink
}
if (target === real || target.startsWith(prefix)) handles.push(target);
}
return handles;
}

test(
"orphan cleanup holds no directory handle between bounded passes",
{ skip: process.platform === "linux" ? false : "requires /proc/self/fd (Linux only)" },
() => {
const baseDir = path.join(TEST_DATA_DIR, "fd-release-artifacts");
const dayDir = path.join(baseDir, "2026-04-12");
fs.mkdirSync(dayDir, { recursive: true });
const old = new Date(Date.now() - 10 * 60_000);
for (let i = 0; i < 40; i++) {
const file = path.join(dayDir, `${String(i).padStart(4, "0")}.json`);
fs.writeFileSync(file, "{}");
fs.utimesSync(file, old, old);
}
assert.deepEqual(openDirectoryHandlesUnder(baseDir), []);

// A pass smaller than the day leaves the resumable cursor alive. The old cursor kept the
// base directory and the day directory open here for the rest of the scan cycle.
const deleted = cleanupOrphanCallLogFiles(baseDir, {
maxCandidates: 10,
maxScanEntries: 10,
minAgeMs: 0,
});
assert.ok(deleted > 0 && deleted < 40, `expected a bounded pass, deleted ${deleted}`);
assert.deepEqual(
openDirectoryHandlesUnder(baseDir),
[],
"a bounded orphan pass must not leave the call-log directories open"
);

while (
cleanupOrphanCallLogFiles(baseDir, { maxCandidates: 100, maxScanEntries: 100, minAgeMs: 0 }) >
0
) {
// Drain the cycle: an exhausted scan must not leave handles behind either.
}
assert.deepEqual(openDirectoryHandlesUnder(baseDir), []);
assert.equal(fs.existsSync(dayDir) ? fs.readdirSync(dayDir).length : 0, 0);
}
);

test("hot rotation avoids full artifact listing and bounds stat calls", () => {
assert.ok(CALL_LOGS_DIR);
const dayDir = path.join(CALL_LOGS_DIR, "2026-04-05");
Expand Down
Loading