From 5a01812b4da503b42bd1310a53a49c9d9bd33c32 Mon Sep 17 00:00:00 2001 From: John Smith Date: Tue, 24 Nov 2026 16:59:29 -0500 Subject: [PATCH 1/2] fix(call-logs): release orphan scan directory handles The resumable orphan-artifact scan kept an `fs.Dir` for the call-log base directory and another for the day being scanned, and only closed them when the root scan was exhausted or the base directory changed. A production day directory holds thousands of files while each cleanup pass is bounded (maxCandidates/maxScanEntries, 100 in rotateCallLogs), so the cursor survived across passes and left two directory descriptors per base dir in /proc//fd until the whole cycle finished. Replace the long-lived handles with a one-shot listing plus an index cursor: readdirSync captures the day names once per cycle and a day's .json names once when the day is entered, and the scan advances by index. No descriptor outlives the pass that created it, ordering is deterministic (sorted), and resumption stays O(1) per pass instead of re-walking the directory. closeOrphanScanCursor() becomes the single reset point and now runs on the graceful-shutdown path too. Tests: the two opendir/readSync-instrumented expectations were tied to the removed mechanism and now count directory listings (one per directory per cycle, none for a resumed pass) while asserting the same bounded-resumption outcome; a 250-file day resumes across passes, and a /proc/self/fd check proves a bounded pass leaves no handle on the base or day directory (fails on the old implementation with exactly those two paths). --- src/lib/gracefulShutdown.ts | 4 + src/lib/usage/callLogRotation.ts | 104 ++++++++++------ tests/unit/call-log-file-rotation.test.ts | 141 ++++++++++++++++++---- 3 files changed, 187 insertions(+), 62 deletions(-) diff --git a/src/lib/gracefulShutdown.ts b/src/lib/gracefulShutdown.ts index 61e31d47a73c..273fb21ad5b6 100644 --- a/src/lib/gracefulShutdown.ts +++ b/src/lib/gracefulShutdown.ts @@ -131,6 +131,7 @@ async function cleanup(): Promise { { closeLogRotation }, { closeSharedLoggerResource }, { closeCallLogSaves }, + { closeOrphanScanCursor }, ] = await Promise.all([ import("@omniroute/open-sse/mcp-server/audit.ts"), import("@/lib/db/core"), @@ -138,6 +139,7 @@ async function cleanup(): Promise { import("@/lib/logRotation"), import("@/shared/utils/loggerResource"), import("@/lib/usage/callLogs"), + import("@/lib/usage/callLogRotation"), ]); const flushResult = await flushSpendBatchWriter(); if (flushResult.flushedEntries > 0) { @@ -146,6 +148,8 @@ async function cleanup(): Promise { ); } 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(); diff --git a/src/lib/usage/callLogRotation.ts b/src/lib/usage/callLogRotation.ts index cc65c271a888..bfeb7dcc0ab9 100644 --- a/src/lib/usage/callLogRotation.ts +++ b/src/lib/usage/callLogRotation.ts @@ -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//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 = { @@ -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, @@ -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 }; } diff --git a/tests/unit/call-log-file-rotation.test.ts b/tests/unit/call-log-file-rotation.test.ts index 786f8bfcf9f1..882d3132c5af 100644 --- a/tests/unit/call-log-file-rotation.test.ts +++ b/tests/unit/call-log-file-rotation.test.ts @@ -218,13 +218,18 @@ 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(" ")); }; @@ -232,11 +237,11 @@ test("rotateCallLogs swallows filesystem errors during cleanup", () => { 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", () => { @@ -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) => { - 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) => { + 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"); From 8ebae5e265c06a66e3ace8c1ebd433a2b1d555ec Mon Sep 17 00:00:00 2001 From: John Smith Date: Tue, 24 Nov 2026 17:07:32 -0500 Subject: [PATCH 2/2] docs(changelog): add fragment for #21166 --- changelog.d/fixes/21166-call-log-dir-handles.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/fixes/21166-call-log-dir-handles.md diff --git a/changelog.d/fixes/21166-call-log-dir-handles.md b/changelog.d/fixes/21166-call-log-dir-handles.md new file mode 100644 index 000000000000..b51ac374ce4b --- /dev/null +++ b/changelog.d/fixes/21166-call-log-dir-handles.md @@ -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//fd` ([#21166](https://github.com/cheaper-inference/OmniRoute/pull/21166))