xonecas.io
64875
Mc

mini-coder / commit 3fb86f1

perf(api-log): hoist DROP_KEYS to module scope and fix truncation unit mismatch

xonecas2026-03-13 3fb86f12d0ff08b3a81b8b13bfdf5383ad1cf61e parent 166bb23

4 files changed

src/cli/error-log.ts+3−2
@@ -1,4 +1,4 @@
1-import { mkdirSync } from "node:fs";
1+import { mkdirSync, writeFileSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { join } from "node:path";
44
@@ -12,7 +12,8 @@ export function initErrorLog(): void {
1212
1313 mkdirSync(dirPath, { recursive: true });
1414
15- // Truncate on open
15+ // Truncate on open so it doesn't grow forever between sessions
16+ writeFileSync(logPath, "");
1617 writer = Bun.file(logPath).writer();
1718
1819 process.on("uncaughtException", (err) => {
src/index.ts+2−0
@@ -33,6 +33,7 @@ import {
3333 getPreferredShowReasoning,
3434 getPreferredThinkingEffort,
3535 getPreferredToolResultPayloadCapBytes,
36+ pruneOldData,
3637 } from "./session/db/index.ts";
3738 import { getMostRecentSession, printSessionList } from "./session/manager.ts";
3839
@@ -42,6 +43,7 @@ registerTerminalCleanup();
4243 initErrorLog();
4344 initApiLog();
4445 initModelInfoCache();
46+pruneOldData();
4547 void refreshModelInfoInBackground().catch(() => {});
4648
4749 // ─── Main ─────────────────────────────────────────────────────────────────────
src/llm-api/api-log.ts+11−10
@@ -1,4 +1,4 @@
1-import { mkdirSync } from "node:fs";
1+import { mkdirSync, writeFileSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { join } from "node:path";
44
@@ -17,6 +17,7 @@ export function initApiLog(): void {
1717 mkdirSync(dirPath, { recursive: true });
1818
1919 // Truncate on open so it doesn't grow forever between sessions
20+ writeFileSync(logPath, "");
2021 writer = Bun.file(logPath).writer();
2122 }
2223
@@ -30,19 +31,19 @@ function isObject(v: unknown): v is Record<string, unknown> {
3031 * `responseBody` (full HTML error pages) — serializing these can produce
3132 * tens of megabytes per error and block the event loop on flush.
3233 */
34+const LOG_DROP_KEYS = new Set([
35+ "requestBodyValues",
36+ "responseBody",
37+ "responseHeaders",
38+ "stack",
39+]);
40+
3341 function sanitizeForLog(data: unknown): unknown {
3442 if (!isObject(data)) return data;
3543
36- const DROP_KEYS = new Set([
37- "requestBodyValues",
38- "responseBody",
39- "responseHeaders",
40- "stack",
41- ]);
42-
4344 const result: Record<string, unknown> = {};
4445 for (const key in data) {
45- if (DROP_KEYS.has(key)) continue;
46+ if (LOG_DROP_KEYS.has(key)) continue;
4647 const value = data[key];
4748 if (key === "errors" && Array.isArray(value)) {
4849 result[key] = value.map((e) => sanitizeForLog(e));
@@ -65,7 +66,7 @@ export function logApiEvent(event: string, data?: unknown): void {
6566 try {
6667 const safe = sanitizeForLog(data);
6768 let serialized = JSON.stringify(safe, null, 2);
68- if (Buffer.byteLength(serialized, "utf8") > MAX_ENTRY_BYTES) {
69+ if (serialized.length > MAX_ENTRY_BYTES) {
6970 serialized = `${serialized.slice(0, MAX_ENTRY_BYTES)}\n …truncated`;
7071 }
7172 entry += serialized
src/session/db/connection.ts+36−0
@@ -141,3 +141,39 @@ export function getDb(): Database {
141141 }
142142 return _db;
143143 }
144+
145+/** Keep only this many most-recent sessions (messages/snapshots cascade). */
146+const MAX_SESSIONS = 100;
147+/** Keep only this many most-recent prompt_history entries. */
148+const MAX_PROMPT_HISTORY = 500;
149+
150+/**
151+ * Prune old sessions and prompt history, then reclaim space.
152+ * Call once at startup (after getDb()).
153+ */
154+export function pruneOldData(): void {
155+ const db = getDb();
156+
157+ const deletedSessions = db.run(
158+ `DELETE FROM sessions WHERE id NOT IN (
159+ SELECT id FROM sessions ORDER BY updated_at DESC LIMIT ?
160+ )`,
161+ [MAX_SESSIONS],
162+ ).changes;
163+
164+ const deletedHistory = db.run(
165+ `DELETE FROM prompt_history WHERE id NOT IN (
166+ SELECT id FROM prompt_history ORDER BY id DESC LIMIT ?
167+ )`,
168+ [MAX_PROMPT_HISTORY],
169+ ).changes;
170+
171+ // Reclaim pages freed by deletions.
172+ if (deletedSessions > 0 || deletedHistory > 0) {
173+ db.exec("VACUUM;");
174+ }
175+
176+ // Checkpoint WAL (including any pages written by VACUUM) so the WAL file
177+ // shrinks back to near-zero.
178+ db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
179+}