Files
PaperClipAI/server
30dc924dc9 fix(server): reuse one pino-pretty transport per process (#12987)
## 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 <noreply@anthropic.com>
Co-authored-by: kronik187 <david@teasoftware.io>
2026-11-23 19:30:40 -06:00
..