From 30dc924dc9e8c9aa81af20cbd894c9797dd02a8c Mon Sep 17 00:00:00 2001 From: kronik187 <48065092+kronik187@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:30:40 -0500 Subject: [PATCH] fix(server): reuse one pino-pretty transport per process (#12987) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server logs through pino, and outside production it writes through a `pino.transport` pretty-printer > - `pino.transport` starts a worker thread and returns no handle the caller can close > - `server/src/middleware/logger.ts` calls it at module scope, so each extra evaluation of that module leaks one worker thread for the life of the process > - A server evaluates the module once, but 46 server test files reset the module registry in `beforeEach`, so those suites evaluate it once per test > - This pull request keeps one transport per process, in a cache that a module-registry reset cannot discard > - The benefit is that a 50-test server suite stops holding 50 dead worker threads and about 280 MB of unused memory ## Linked Issues or Issue Description No existing issue covers this. The problem, in the bug-report shape: **What happened?** `server/src/middleware/logger.ts` calls `pino.transport` at module scope: ```ts export const logger = isProduction ? pino({ ... }) : pino({ ... }, pino.transport({ target: "pino-pretty", ... })); ``` `pino.transport` starts a thread-stream worker. The module keeps no handle to it, so nothing can close it. Each evaluation of the module starts one more. A server process evaluates the module once. The tests do not. 46 files under `server/src/__tests__` call `vi.resetModules()` in `beforeEach` and then re-import a module that reaches the logger, usually to rebuild an express app against fresh mocks. Those suites evaluate the module once per test, so each test adds one worker thread, one MessagePort and one V8 isolate that live until the process exits. **Expected behavior** One pretty-print transport per process. Re-evaluating the module must not start another worker. **Steps to reproduce** Add this to any server test file on `master` and run it: ```ts const ports = () => process.getActiveResourcesInfo().filter((r) => r === "MessagePort").length; it("leaks a worker per evaluation", async () => { await vi.importActual("../middleware/logger.js"); const before = ports(); for (let i = 0; i < 10; i += 1) { vi.resetModules(); await vi.importActual("../middleware/logger.js"); } console.log(ports() - before); // 10 on master, 0 with this PR }); ``` The count rises by exactly one per evaluation. The test this PR adds is that check, written as an assertion. **Measurements** | Transports in one process | Threads | RSS | | --- | --- | --- | | 0 (baseline) | 8 | 60 MB | | 100 | 108 | 276 MB | | 200 | 208 | 1.38 GB | | 400 | 407 | 1.68 GB | A 50-test suite therefore carries roughly 280 MB of dead workers. `server/vitest.config.ts` pins `maxWorkers: 1`, so these suites run one at a time on one runner and each pays the whole cost. **Paperclip version or commit** Reproduces on `master` at `856813ba3`. **Deployment mode** Test and CI only. A running server evaluates the module once, so it never had more than one transport. **Related pull requests** - #10865 (closed) — a different bug in the same file. It fixed unbounded thread-stream *send buffer* growth from prettifying `req`/`res` on the file target. This PR is about the *number of workers*, not the size of one worker's buffer. That PR was closed because the `targets` array it patched no longer exists on `master`; the call this PR changes does still exist. - #8323 (open, last updated 2026-06-19) — makes the log format configurable and edits the same lines. It looks unmaintained. If it is revived, the cache here moves into whichever branch builds the transport. ## What Changed - `server/src/middleware/logger.ts`: `pino.transport` now runs behind `prettyTransport()`, which caches the stream on `globalThis`. The cache is on `globalThis` on purpose — a module-scoped variable is discarded by the very module-registry reset this guards against. Production behaviour does not change: a server evaluates the module once, so it built one transport before and builds one now. - `server/src/__tests__/logger-pretty-transport-reuse.test.ts` is new. It asserts that 10 re-evaluations add no MessagePorts, and that every module instance shares one transport object. ## Verification ```bash pnpm --filter @paperclipai/server exec vitest run src/__tests__/logger-pretty-transport-reuse.test.ts ``` - With the cache: 2 passed. - With the cache defeated (`??=` changed to `=`), both tests fail: `AssertionError: expected 10 to be less than or equal to 2`, and the identity check fails on two different transport objects. Nothing else changes behaviour, so the surrounding suites are the regression check: ```bash pnpm --filter @paperclipai/server exec vitest run \ src/__tests__/instance-settings-routes.test.ts \ src/__tests__/http-log-redaction.test.ts \ src/__tests__/health.test.ts node --test scripts/__tests__/run-vitest-stable-shard.test.mjs ``` 69 passed and 13 passed. `tsc --noEmit` reports no error in either changed file. The new suite joins the general-server group and needs no duration-manifest entry: the staleness check requires 50% coverage and one new file does not cross it. ## Risks Low. - A server process evaluates the module once, so the cache never engages there. The only behaviour it changes is that several module instances in one process now share one pretty-print stream, which is what a single instance already did. - The `globalThis` key is namespaced (`__paperclipPinoPrettyTransport`) and read only by this module and its test. - Merge risk sits with #8323, which edits the same lines. See the note above. ## Model Used Claude Opus 5 (`claude-opus-5`), via Claude Code, with extended thinking, tool use and code execution. ## Checklist Verified on `8391a138b` (2026-09-08): 31 checks pass, 1 skipped (`Storybook visual regression`, not exercised by this diff), merge state `CLEAN`. Greptile scored 5/5 — "safe to merge" — with no inline comments and no open findings. - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 Co-authored-by: kronik187 --- .../logger-pretty-transport-reuse.test.ts | 63 +++++++++++++++++++ server/src/middleware/logger.ts | 53 +++++++++++++--- 2 files changed, 107 insertions(+), 9 deletions(-) create mode 100644 server/src/__tests__/logger-pretty-transport-reuse.test.ts 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: {