diff --git a/server/src/__tests__/logger-pretty-transport-reuse.test.ts b/server/src/__tests__/logger-pretty-transport-reuse.test.ts new file mode 100644 index 00000000000..42e6c7fd5d1 --- /dev/null +++ b/server/src/__tests__/logger-pretty-transport-reuse.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +/** + * `middleware/logger.ts` builds its non-production pino instance on top of a + * `pino.transport` pretty-printer, which spawns a worker thread. Nothing hands + * this module a handle to close that worker, so a module-registry reset that + * re-evaluates the module leaks one worker — thread, MessagePort and V8 + * isolate — per evaluation, for the life of the process. + * + * That is not hypothetical: 46 files under `server/src/__tests__` call + * `vi.resetModules()` in `beforeEach` and then re-import a module that reaches + * this one, so a 50-test suite re-evaluates it 50 times. This test pins the + * transport to one per process, and fails if the cache is ever removed. + */ + +/** + * Count the live `pino.transport` workers, one MessagePort each. Reading active + * resources is portable; reading /proc/self/task would pin this test to Linux. + */ +function messagePortCount() { + return process.getActiveResourcesInfo().filter((resource) => resource === "MessagePort").length; +} + +describe("pretty-print transport reuse across module-registry resets", () => { + beforeEach(() => { + vi.resetModules(); + }); + + it("spawns no additional worker when the logger module is re-evaluated", async () => { + // Evaluate once first so the baseline already includes this process's one + // transport; the assertion is then purely about what the *extra* + // evaluations cost. + await vi.importActual("../middleware/logger.js"); + const baseline = messagePortCount(); + + for (let evaluation = 0; evaluation < 10; evaluation += 1) { + vi.resetModules(); + await vi.importActual("../middleware/logger.js"); + } + + // Before the fix this grew by exactly one per evaluation (10 here, 50 in a + // full route suite). An exact-equality assertion would be hostage to any + // unrelated MessagePort the runner happens to open mid-test, so allow a + // small constant — anything proportional to the loop count still fails. + expect(messagePortCount() - baseline).toBeLessThanOrEqual(2); + }); + + it("hands every re-evaluated module instance the same transport object", async () => { + const first = await vi.importActual("../middleware/logger.js"); + const firstTransport = (globalThis as Record).__paperclipPinoPrettyTransport; + expect(firstTransport).toBeDefined(); + + vi.resetModules(); + const second = await vi.importActual("../middleware/logger.js"); + + // Distinct module instances — the registry really was reset … + expect(second.logger).not.toBe(first.logger); + // … sharing the one cached transport, which is what keeps the worker count + // flat. Identity, not mere presence: a per-evaluation transport would also + // leave something defined here. + expect((globalThis as Record).__paperclipPinoPrettyTransport).toBe(firstTransport); + }); +}); diff --git a/server/src/middleware/logger.ts b/server/src/middleware/logger.ts index d874058c4a6..0e1aa4a2bbb 100644 --- a/server/src/middleware/logger.ts +++ b/server/src/middleware/logger.ts @@ -25,6 +25,49 @@ const sharedOpts = { }; const isProduction = process.env.NODE_ENV === "production"; + +// One pretty-print transport per process, even when this module is evaluated +// more than once. +// +// `pino.transport` spawns a worker thread (thread-stream) and hands back no +// handle this module could close, so every extra evaluation leaks one worker +// thread, one MessagePort and that worker's whole V8 isolate for the life of +// the process. A server process evaluates this module once, so the cache is +// inert in production. The server test suites do not: 46 files under +// `server/src/__tests__` call `vi.resetModules()` in `beforeEach` and then +// re-import a module that reaches this one, so the module is evaluated once +// per test and a 50-test suite ends holding 50 live worker threads. +// +// Measured cost of the leak: 400 transports in one process reach 407 threads +// and 1.68 GB RSS, so a 50-test suite carries roughly 280 MB of dead workers. +// `server/vitest.config.ts` pins `maxWorkers: 1`, so those suites run one at a +// time on one runner and each pays the whole cost. +// +// The cache lives on `globalThis` on purpose: a module-scoped variable is +// discarded by the very module-registry reset this guards against. +const PRETTY_TRANSPORT_KEY = "__paperclipPinoPrettyTransport"; +type PrettyTransportCache = { + [PRETTY_TRANSPORT_KEY]?: ReturnType; +}; + +/** + * The process's one pretty-print transport, created on first use. See the note + * above for why it is cached rather than built per module evaluation. + */ +function prettyTransport() { + const cache = globalThis as typeof globalThis & PrettyTransportCache; + cache[PRETTY_TRANSPORT_KEY] ??= pino.transport({ + target: "pino-pretty", + options: { + ...sharedOpts, + ignore: "pid,hostname,req,res,responseTime", + colorize: true, + destination: 1, + }, + }); + return cache[PRETTY_TRANSPORT_KEY]; +} + export const logger = isProduction ? pino({ level: process.env.PAPERCLIP_LOG_LEVEL?.trim() || "info", @@ -35,15 +78,7 @@ export const logger = isProduction level: process.env.PAPERCLIP_LOG_LEVEL?.trim() || "debug", redact: [...HTTP_LOG_REDACT_PATHS], }, - pino.transport({ - target: "pino-pretty", - options: { - ...sharedOpts, - ignore: "pid,hostname,req,res,responseTime", - colorize: true, - destination: 1, - }, - }), + prettyTransport(), ); function requestClassificationUrl(req: {