7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(logs): stop the stdio EPIPE -> server_logs feedback loop (#1345)
Chong Jia Zhencbbe3778419b
diff --git a/server/src/__tests__/fixtures/stdio-epipe-child.ts b/server/src/__tests__/fixtures/stdio-epipe-child.tsnew file mode 100644index 00000000..73338610--- /dev/null+++ b/server/src/__tests__/fixtures/stdio-epipe-child.ts@@ -0,0 +1,14 @@+// Child process for lib/stdio-epipe-loop.test.ts. Boots the same three pieces+// index.ts installs before anything else logs (console redaction + its+// server_logs tap, the process safety net, the DB), then logs a warn on a+// timer the way the health checker does. The parent closes our stdout/stderr+// after "child ready", so every later console write hits a dead pipe.+import { installLogRedaction } from '../../lib/log-redaction.js';+import { installProcessSafetyNet } from '../../lib/process-safety-net.js';+import { initDb } from '../../db/index.js';++installLogRedaction();+installProcessSafetyNet();+initDb(process.argv[2]);+console.log('child ready');+setInterval(() => console.warn('[fixture] periodic warn'), 500);diff --git a/server/src/__tests__/lib/process-safety-net.test.ts b/server/src/__tests__/lib/process-safety-net.test.tsindex f35d2b34..988a82f9 100644--- a/server/src/__tests__/lib/process-safety-net.test.ts+++ b/server/src/__tests__/lib/process-safety-net.test.ts@@ -3,7 +3,10 @@ import {isTransportError,classifyProcessError,handleProcessError,+ isBrokenPipeWrite,+ guardStdio,} from '../../lib/process-safety-net.js';+import { EventEmitter } from 'node:events';import type { SafetyNetHooks } from '../../lib/process-safety-net.js';describe('isTransportError', () => {@@ -79,3 +82,30 @@ describe('handleProcessError', () => {expect(exit).toHaveBeenCalledExactlyOnceWith(1);});});++describe('dead stdio', () => {+ const epipeWrite = () => Object.assign(new Error('write EPIPE'), { code: 'EPIPE', syscall: 'write' });++ it('swallows a broken-pipe write without logging it (logging would write to the same dead pipe)', () => {+ const log = vi.fn();+ const exit = vi.fn();+ expect(isBrokenPipeWrite(epipeWrite())).toBe(true);+ expect(handleProcessError('uncaughtException', epipeWrite(), { log, exit })).toBe('swallow');+ expect(log).not.toHaveBeenCalled();+ expect(exit).not.toHaveBeenCalled();+ });++ it('still logs other swallowed transport errors', () => {+ const log = vi.fn();+ handleProcessError('uncaughtException', Object.assign(new Error('x'), { code: 'EPIPE', syscall: 'read' }), { log, exit: vi.fn() });+ expect(log).toHaveBeenCalledTimes(1);+ });++ it('guardStdio drops dead-pipe stream errors and rethrows anything else', () => {+ const stream = new EventEmitter();+ guardStdio([stream]);+ expect(() => stream.emit('error', epipeWrite())).not.toThrow();+ expect(() => stream.emit('error', Object.assign(new Error('gone'), { code: 'ERR_STREAM_DESTROYED' }))).not.toThrow();+ expect(() => stream.emit('error', Object.assign(new Error('odd'), { code: 'EACCES' }))).toThrow('odd');+ });+});diff --git a/server/src/__tests__/lib/server-logs-rate-cap.test.ts b/server/src/__tests__/lib/server-logs-rate-cap.test.tsnew file mode 100644index 00000000..60fde7c7--- /dev/null+++ b/server/src/__tests__/lib/server-logs-rate-cap.test.ts@@ -0,0 +1,55 @@+import { describe, it, expect, beforeAll, beforeEach } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import {+ PERSIST_MAX_PER_SECOND,+ initServerLogs,+ recordLogEntry,+ resetServerLogsForTest,+ ringSnapshot,+} from '../../lib/server-logs.js';++function rows(): Array<{ id: number; message: string }> {+ return getDb().prepare('SELECT id, message FROM server_logs ORDER BY id').all() as Array<{ id: number; message: string }>;+}++describe('server_logs persist rate cap', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ beforeEach(() => {+ getDb().prepare('DELETE FROM server_logs').run();+ resetServerLogsForTest();+ initServerLogs();+ });++ it('persists at most PERSIST_MAX_PER_SECOND rows per second, then one summary row', () => {+ const t0 = 1_700_000_000_000;+ for (let i = 0; i < 200; i++) recordLogEntry({ level: 'error', message: `storm ${i}`, tsMs: t0 + i });+ expect(rows()).toHaveLength(PERSIST_MAX_PER_SECOND);+ // Every line still reached the live view.+ expect(ringSnapshot().filter(e => e.message.startsWith('storm'))).toHaveLength(200);++ recordLogEntry({ level: 'warn', message: 'after the storm', tsMs: t0 + 1500 });+ const all = rows();+ expect(all).toHaveLength(PERSIST_MAX_PER_SECOND + 2);+ expect(all[all.length - 2]!.message).toContain(`${200 - PERSIST_MAX_PER_SECOND} warn/error lines not persisted`);+ expect(all[all.length - 1]!.message).toBe('after the storm');++ // Ids in the ring stay strictly increasing (the dashboard's sinceId cursor relies on it).+ const ids = ringSnapshot().map(e => e.id);+ expect([...ids].sort((a, b) => a - b)).toEqual(ids);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('does not cap a normal rate, and info lines never count', () => {+ const t0 = 1_700_000_000_000;+ for (let i = 0; i < 1000; i++) recordLogEntry({ level: 'info', message: `info ${i}`, tsMs: t0 });+ for (let s = 0; s < 5; s++) {+ for (let i = 0; i < 10; i++) recordLogEntry({ level: 'warn', message: `w ${s}.${i}`, tsMs: t0 + s * 1000 + i });+ }+ expect(rows()).toHaveLength(50);+ expect(rows().some(r => r.message.includes('not persisted'))).toBe(false);+ });+});diff --git a/server/src/__tests__/lib/stdio-epipe-loop.test.ts b/server/src/__tests__/lib/stdio-epipe-loop.test.tsnew file mode 100644index 00000000..ef2b9f8b--- /dev/null+++ b/server/src/__tests__/lib/stdio-epipe-loop.test.ts@@ -0,0 +1,77 @@+import { describe, it, expect, afterEach } from 'vitest';+import { spawn, type ChildProcess } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import Database from 'better-sqlite3';++// Regression: a server started with stdout/stderr piped to a process that then+// goes away (a shell tool that returned, a closed terminal) must not turn every+// console write into an EPIPE -> safety-net console.error -> server_logs row ->+// EPIPE loop. Observed in the wild at ~3-6k rows/s with zero traffic.++const here = path.dirname(fileURLToPath(import.meta.url));+const childScript = path.join(here, '..', 'fixtures', 'stdio-epipe-child.ts');++let child: ChildProcess | null = null;+let dir: string | null = null;++afterEach(async () => {+ const proc = child;+ child = null;+ if (proc && proc.exitCode === null) {+ const exited = new Promise((r) => proc.once('exit', r));+ proc.kill();+ await exited;+ }+ // The child held the DB open; Windows refuses to unlink until it is gone.+ if (dir) rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });+ dir = null;+});++function countRows(dbPath: string): number {+ const db = new Database(dbPath, { readonly: true });+ try {+ return (db.prepare('SELECT COUNT(*) AS n FROM server_logs').get() as { n: number }).n;+ } finally {+ db.close();+ }+}++describe('dead stdio pipe', () => {+ it('does not feed an EPIPE loop into server_logs, and the process survives', async () => {+ dir = mkdtempSync(path.join(tmpdir(), 'freellmapi-epipe-'));+ const dbPath = path.join(dir, 'epipe.db');++ const proc = spawn(process.execPath, ['--import', 'tsx', childScript, dbPath], {+ stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, ENCRYPTION_KEY: 'a'.repeat(64) },+ });+ child = proc;++ await new Promise<void>((resolve, reject) => {+ let buf = '';+ const timer = setTimeout(() => reject(new Error(`child never became ready: ${buf}`)), 20_000);+ proc.stdout!.on('data', (d) => {+ buf += d;+ if (buf.includes('child ready')) {+ clearTimeout(timer);+ resolve();+ }+ });+ proc.stderr!.on('data', (d) => { buf += d; });+ proc.once('exit', (code) => reject(new Error(`child exited early (${code}): ${buf}`)));+ });++ const before = countRows(dbPath);+ proc.stdout!.destroy();+ proc.stderr!.destroy();+ await new Promise((r) => setTimeout(r, 2500));++ const grown = countRows(dbPath) - before;+ // ~5 legitimate periodic warns in the window; the loop writes thousands.+ expect(grown).toBeLessThan(50);+ expect(proc.exitCode).toBeNull();+ }, 40_000);+});diff --git a/server/src/lib/process-safety-net.ts b/server/src/lib/process-safety-net.tsindex cd3d682d..c679964a 100644--- a/server/src/lib/process-safety-net.ts+++ b/server/src/lib/process-safety-net.ts@@ -87,6 +87,11 @@ export function handleProcessError(): ProcessErrorDecision {const log = hooks.log ?? console.error;const decision = classifyProcessError(err);+ // A write that hit a closed pipe is swallowed WITHOUT logging: when the pipe+ // is our own stdout/stderr, logging it writes to that same dead pipe, which+ // raises the next EPIPE — and every one of those lines is also persisted to+ // server_logs. That loop ran at thousands of rows a second.+ if (decision === 'swallow' && isBrokenPipeWrite(err)) return 'swallow';if (decision === 'swallow') {log(`[safety-net] swallowed transient ${kind}: ${describeError(err)}`);return 'swallow';@@ -96,6 +101,31 @@ export function handleProcessError(return 'fatal';}+/** Pure: true for a write that failed because the reading end of the pipe is gone. */+export function isBrokenPipeWrite(err: unknown): boolean {+ const e = err as { code?: unknown; syscall?: unknown } | null;+ return !!e && typeof e === 'object' && e.code === 'EPIPE' && e.syscall === 'write';+}++// Codes a stdio stream emits once whatever was reading it has gone away.+const DEAD_STDIO_CODES = new Set(['EPIPE', 'EOF', 'ERR_STREAM_DESTROYED']);++/**+ * Give stdout/stderr an 'error' listener. Without one, a stream error — the+ * terminal closed, or the process that started us with piped output exited —+ * is escalated to an uncaughtException on every later console write. A dead+ * console is not a reason to crash or to log, so those codes are dropped and+ * anything else is rethrown to keep the fail-fast contract.+ */+export function guardStdio(streams: NodeJS.EventEmitter[] = [process.stdout, process.stderr]): void {+ for (const stream of streams) {+ stream.on('error', (err: { code?: string }) => {+ if (err && typeof err.code === 'string' && DEAD_STDIO_CODES.has(err.code)) return;+ throw err;+ });+ }+}+let installed = false;/** Install the global handlers once. Idempotent. Call as early as possible at@@ -105,6 +135,7 @@ export function installProcessSafetyNet(hooks: SafetyNetHooks = {}): void {if (installed) return;installed = true;if (hooks.hasProcessHooks === false) return;+ guardStdio();process.on('uncaughtException', (err) => handleProcessError('uncaughtException', err, hooks));process.on('unhandledRejection', (reason) => handleProcessError('unhandledRejection', reason, hooks));}diff --git a/server/src/lib/server-logs.ts b/server/src/lib/server-logs.tsindex e5f7736d..dd3dc6e3 100644--- a/server/src/lib/server-logs.ts+++ b/server/src/lib/server-logs.ts@@ -53,6 +53,17 @@ export const MAX_MESSAGE_LENGTH = 6000;const TRUNCATION_SUFFIX = '… [truncated]';+/**+ * Ceiling on warn/error rows written per second. The table is pruned only on+ * the request path, so an idle server has no retention at all; a log storm (a+ * dead stdout feeding the safety net, a provider erroring in a tight loop) must+ * not be able to grow it without bound. Lines over the cap still reach the live+ * ring — only the row is skipped — and the next line after the window rolls+ * writes one summary row saying how many were dropped.+ */+export const PERSIST_MAX_PER_SECOND = 50;+const PERSIST_WINDOW_MS = 1000;+/*** The viewer polls GET /api/logs every couple of seconds. If the deployment in* front of us emits access-log lines, those polls would be the loudest thing in@@ -109,6 +120,11 @@ let persisting = false;/** Reentrancy guard for the boot seed, for the same reason as `persisting`. */let seeding = false;+/** Persist rate-cap window (see PERSIST_MAX_PER_SECOND). */+let persistWindowStartMs = 0;+let persistWindowCount = 0;+let persistSuppressed = 0;+// ── Formatting ───────────────────────────────────────────────────────────────/** One console argument, rendered the way it reaches stdout: strings verbatim,@@ -193,10 +209,41 @@ export function recordLogEntry(options: RecordLogOptions): ServerLogEntry | nullif (requestId) entry.requestId = requestId;push(entry);- if (PERSISTED_LEVELS.has(entry.level)) persist(entry);+ if (PERSISTED_LEVELS.has(entry.level)) persistCapped(entry);return entry;}+function persistCapped(entry: ServerLogEntry): void {+ if (entry.tsMs - persistWindowStartMs >= PERSIST_WINDOW_MS || entry.tsMs < persistWindowStartMs) {+ const dropped = persistSuppressed;+ persistWindowStartMs = entry.tsMs;+ persistWindowCount = 0;+ persistSuppressed = 0;+ if (dropped > 0) {+ const summary: ServerLogEntry = {+ id: ++lastId,+ tsMs: entry.tsMs,+ level: 'warn',+ source: 'server-logs',+ message: `[server-logs] ${dropped} warn/error lines not persisted (over ${PERSIST_MAX_PER_SECOND}/s); they reached the live view only`,+ };+ // Keep ids increasing in arrival order: the summary takes the next id and+ // the line that rolled the window is re-stamped after it.+ entry.id = ++lastId;+ ring.splice(ring.length - 1, 0, summary);+ if (ring.length > RING_CAPACITY) ring.shift();+ persist(summary);+ persistWindowCount++;+ }+ }+ if (persistWindowCount >= PERSIST_MAX_PER_SECOND) {+ persistSuppressed++;+ return;+ }+ persistWindowCount++;+ persist(entry);+}+function push(entry: ServerLogEntry): void {ring.push(entry);if (ring.length > RING_CAPACITY) ring.splice(0, ring.length - RING_CAPACITY);@@ -493,6 +540,9 @@ export function resetServerLogsForTest(): void {seeding = false;mirroring = false;persisting = false;+ persistWindowStartMs = 0;+ persistWindowCount = 0;+ persistSuppressed = 0;}/** Test/introspection seam: the ring exactly as stored. */