From 319e035d2e43bfc1c216cc799586540a0054e51a Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Wed, 12 Aug 2026 01:37:49 +0800 Subject: [PATCH] fix: reap decompress temp files (bounded retention, no /tmp leak) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit resolveDecompress writes a /tmp/acp-decompress--.txt for every large (>10000 bytes) decompress and never cleaned up — long sessions leaked unbounded files. Add bounded retention: track generated paths, unlink oldest past BILI_DECOMPRESS_TMP_CAP (default 50), best-effort clean on beforeExit. --- node_modules | 1 + src/decompress-shared.ts | 37 +++++++++++++- tests/fix-decompress-reaper.test.ts | 76 +++++++++++++++++++++++++++++ 3 files changed, 113 insertions(+), 1 deletion(-) create mode 120000 node_modules create mode 100644 tests/fix-decompress-reaper.test.ts diff --git a/node_modules b/node_modules new file mode 120000 index 0000000000..8ce1922339 --- /dev/null +++ b/node_modules @@ -0,0 +1 @@ +/home/dog/projects/billion-context-fix-stream/node_modules \ No newline at end of file diff --git a/src/decompress-shared.ts b/src/decompress-shared.ts index 37618bdf8a..cf6e176fed 100644 --- a/src/decompress-shared.ts +++ b/src/decompress-shared.ts @@ -5,11 +5,44 @@ import { type Config, type CoreMessage, } from "acp-kernel"; -import { mkdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import type { Session } from "./session.js"; +/** Bounded retention for large-decompress temp files. Each decompress with + * body > 10000 writes one file under tmpdir(); the reaper unlinks oldest past + * BILI_DECOMPRESS_TMP_CAP (default 50) and beforeExit cleans all. */ +type TrackedTempFile = { path: string; mtimeMs: number }; +const trackedTempFiles: TrackedTempFile[] = []; + +function getDecompressTmpCap(): number { + const raw = process.env.BILI_DECOMPRESS_TMP_CAP; + const parsed = raw ? Number.parseInt(raw, 10) : NaN; + return Number.isFinite(parsed) && parsed > 0 ? parsed : 50; +} + +function reapTempFiles(): void { + const cap = getDecompressTmpCap(); + while (trackedTempFiles.length > cap) { + trackedTempFiles.sort((a, b) => a.mtimeMs - b.mtimeMs); + const oldest = trackedTempFiles.shift(); + if (!oldest) break; + try { + unlinkSync(oldest.path); + } catch {} + } +} + +process.on("beforeExit", () => { + for (const f of trackedTempFiles) { + try { + unlinkSync(f.path); + } catch {} + } + trackedTempFiles.length = 0; +}); + /** Shared ctx shape used by both the chat and responses compress loops. */ export type ProxyToolCtx = { core: CompressionCore; @@ -73,6 +106,8 @@ export function resolveDecompress( try { mkdirSync(dirname(outPath), { recursive: true }); writeFileSync(outPath, body, "utf8"); + trackedTempFiles.push({ path: outPath, mtimeMs: Date.now() }); + reapTempFiles(); return `${header}\nContent (${body.length} chars) written to: ${outPath}\nUse the read tool to access it.`; } catch (e) { return `${header}\n[Failed to write to ${outPath}: ${String(e)}]\n${body.slice(0, 4000)}...`; diff --git a/tests/fix-decompress-reaper.test.ts b/tests/fix-decompress-reaper.test.ts new file mode 100644 index 0000000000..84eb1b83d9 --- /dev/null +++ b/tests/fix-decompress-reaper.test.ts @@ -0,0 +1,76 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createCore, defaultConfig, type Config, type CoreMessage } from "acp-kernel"; +import { resolveDecompress } from "../src/decompress-shared.ts"; +import { applyRanges } from "../src/stream.ts"; +import { parseCompressInput } from "../src/compress-tool.ts"; +import { getSession } from "../src/session.ts"; + +function makeCtx(tag: string) { + const core = createCore(); + const config = defaultConfig(200000) as Config; + const session = getSession(`fix-${tag}-${Math.random().toString(36).slice(2)}`); + return { core, config, session }; +} + +function buildLargeBlock(tag: string, bodySize: number) { + const { core, config, session } = makeCtx(tag); + const msgs: CoreMessage[] = []; + for (let i = 0; i < 12; i++) { + msgs.push({ + id: `h_${tag}_${i}`, + role: i % 2 === 0 ? "user" : "assistant", + contentType: "text", + text: `\x3cacp tokens="2K" type="text"\x3em${String(i + 1).padStart(5, "0")}\x3c/acp\x3e\nHistorical detail ${i}. ${"x".repeat(2000)}`, + }); + } + const turn = core.processTurn({ messages: msgs, state: session.state, config, tokenCount: 9999, renderTags: "text-only" }); + session.state = turn.state; + const ctx = { core, config, messages: turn.messages, session, log: () => {} }; + applyRanges(parseCompressInput({ content: [{ startId: "m00001", endId: "m00007", summary: `Compressed range for ${tag}: initial setup and baseline testing.` }] }), ctx as never); + const blockId = [...session.state.blocks].slice(-1)[0]?.blockId; + assert.ok(blockId, "block created"); + const big = "x".repeat(bodySize); + session.blockContents.set(blockId!, { one: { text: big, count: 1 }, full: { text: big, count: 1 } }); + return { ctx, blockId: blockId! }; +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +test("resolveDecompress reaper: caps tracked temp files, unlinks oldest", async () => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "bili-reap-")); + const prevTmpdir = process.env.TMPDIR; + const prevCap = process.env.BILI_DECOMPRESS_TMP_CAP; + process.env.TMPDIR = scratch; + process.env.BILI_DECOMPRESS_TMP_CAP = "3"; + try { + const written: string[] = []; + for (let i = 0; i < 5; i++) { + const { ctx, blockId } = buildLargeBlock(`r${i}`, 11000); + const out = resolveDecompress({ blockId }, ctx); + const m = out.match(/written to: (.+)$/m); + assert.ok(m, `iteration ${i} should spill to temp file`); + written.push(m![1]); + await sleep(2); + } + const remaining = fs.readdirSync(scratch).filter((f) => f.startsWith("acp-decompress-")); + assert.ok(remaining.length <= 3, `reaper should keep <= cap(3) files, got ${remaining.length}`); + assert.ok(!fs.existsSync(written[0]), "oldest temp file should be reaped"); + assert.ok(!fs.existsSync(written[1]), "2nd oldest temp file should be reaped"); + assert.ok(fs.existsSync(written[2]), "3rd file should survive"); + assert.ok(fs.existsSync(written[3]), "4th file should survive"); + assert.ok(fs.existsSync(written[4]), "5th file should survive"); + } finally { + if (prevTmpdir === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = prevTmpdir; + if (prevCap === undefined) delete process.env.BILI_DECOMPRESS_TMP_CAP; + else process.env.BILI_DECOMPRESS_TMP_CAP = prevCap; + try { + for (const f of fs.readdirSync(scratch)) fs.unlinkSync(path.join(scratch, f)); + fs.rmdirSync(scratch); + } catch {} + } +});