Files
PaperClipAI/server
Dotta b85e189408 perf(runner,native-runtime): silence AJV format warnings, cache validators, and retain released catalogs (#23812)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server and Runner validate assigned MCP tool input schemas with
AJV and project shared frozen tool catalogs into native sessions
> - Today, AJV runs with `validateFormats: true` and no registered
formats, so every tool schema with `format` keywords (such as `uuid` or
`date-time`) emits two synchronous `console.warn` lines per property
while still ignoring those formats
> - Each call to `admitToolInputSchema` also recompiles identical
schemas from scratch, `resolveAssignedCatalog` evicts a shared catalog
as soon as its last active session closes (so back-to-back runs rebuild
the catalog every time), and `createAssignedMcpTools` logs the
over-budget and uncompilable schema warnings on every run even on a
cache hit
> - Together these issues produce heavy synchronous stderr/log churn and
repeat CPU and allocation work on sequential runs
> - This pull request disables AJV format lookup in
`tool-input-schema.ts`, adds a bounded compiled-validator LRU cache with
isolated error state, retains explicitly closed assigned catalogs in a
bounded short-TTL warm LRU, and deduplicates catalog schema warnings per
`(gatewayPublicId, catalogKey)`
> - The benefit is zero `unknown format` stderr warnings, up to ~27x
faster repeat schema admission, sequential catalog cache reuse across
back-to-back runs, and one warning per distinct gateway and catalog
instead of per-run log floods

## Linked Issues or Issue Description

Refs #21274, #21482. No separate public GitHub issue exists; the bug is
described below using the bug report template.

**What happened?**

During native agent runs that use assigned MCP tools with JSON Schema
`format` annotations (such as `"format": "uuid"` and `"format":
"date-time"`) or tool catalogs over the 768 KiB compile budget:
1. `admitToolInputSchema` in
`packages/paperclip-runner/src/drivers/tool-input-schema.ts` creates
`Ajv`, `Ajv2019`, and `Ajv2020` with `{ allErrors: true, strict: false,
addUsedSchema: false }`, leaving `validateFormats` at its default
(`true`) without registering any formats. AJV still ignores unknown
formats because `strict: false`, but writes two synchronous `unknown
format "..." ignored in schema at path "..."` `console.warn` lines per
property on every compilation.
2. Repeated calls to `admitToolInputSchema` for identical schemas re-run
AJV compilation (`new Function`) each time.
3. `resolveAssignedCatalog` in
`server/src/services/native-runtime/assigned-mcp-tools.ts` evicts the
shared catalog immediately when `holder.holders === 0`, so sequential
runs for the same company and unchanged tool listing never reuse the
frozen catalog.
4. `createAssignedMcpTools` logs `assigned MCP tools whose input schema
is over the compile budget are offered only through assigned-tool
search` and `assigned MCP tools whose input schema the Runner cannot
validate are not offered` unconditionally on every call, including cache
hits.

**Expected behavior**

1. `admitToolInputSchema` preserves exact validation behavior (ignoring
unregistered format annotations while still rejecting invalid non-string
`format` values via meta-schema validation) with zero `unknown format`
warnings.
2. Identical schemas reuse cached compiled validators in a bounded LRU
without sharing mutable `.errors` state or allowing mutation of the
cached schema.
3. Explicitly closed assigned tool catalogs stay warm in a bounded
short-TTL LRU so sequential runs reuse the frozen catalog when the fresh
gateway listing is unchanged, while expired or changed catalogs rebuild
cleanly and idle processes hold no background polling timers.
4. Catalog schema warnings log once per distinct `(gatewayPublicId,
catalogKey)` within a bounded deduplication window instead of flooding
logs on every run.

**Steps to reproduce**

1. Call `admitToolInputSchema` on 50 schemas containing `format:
"uuid"`, `format: "date-time"`, and `format: "email"` across 20
iterations (1,000 admissions) and count `console.warn` lines matching
`unknown format`.
2. Call `createAssignedMcpTools` 20 times sequentially (`close()` after
each call) for the same `companyId` and `gatewayPublicId` with an
unchanged listing over the 768 KiB compile budget and with an
under-budget listing, counting `logger.warn` lines and schema object
reuse across runs.

**Paperclip version or commit**

Reproduced on `master` at `306437a2a5`.

**Deployment mode**

Self-hosted server / Local dev (`pnpm dev`).

## What Changed

- `packages/paperclip-runner/src/drivers/tool-input-schema.ts`:
- Pass `validateFormats: false` to `Ajv`, `Ajv2019`, and `Ajv2020`
compilers.
- Add a bounded compiled-validator LRU cache
(`TOOL_INPUT_SCHEMA_CACHE_MAX_ENTRIES = 512`,
`TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES = 16 MiB` serialized schema bytes)
keyed by canonical dialect and SHA-256 of the normalized schema JSON,
including caching `uncompilable` outcomes and skipping `$async` schemas.
- Deep-freeze cached compiled schemas after `forgetCompiledSchema` and
wrap cached `ValidateFunction` instances in `isolatedValidator` so each
caller has independent `.errors` state and cached validators retain no
prior error arrays.
- Export `toolInputSchemaCacheStats`,
`TOOL_INPUT_SCHEMA_CACHE_MAX_ENTRIES`, and
`TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES` for verification.
- `packages/paperclip-runner/src/drivers/tool-input-schema.test.ts`:
- Add tests covering zero `unknown format` warnings across all three
dialects while preserving validation and rejecting invalid non-string
`format` values.
- Add tests covering validator cache reuse (including `$schema` fragment
normalization, `uncompilable` caching, and uncached `$async` schemas),
isolated `.errors` state, frozen `validate.schema`, independent
`admission.schema`, and cache bounds.
- Give each `reserved $id` iteration a unique `title` so every iteration
still compiles fresh on the compiler.
- `server/src/services/native-runtime/assigned-mcp-tools.ts`:
- Retain explicitly closed shared catalogs in a bounded warm LRU
(`ASSIGNED_CATALOG_RETAIN_ENTRIES = 64`, `ASSIGNED_CATALOG_RETAIN_BYTES
= 32 MiB`, `ASSIGNED_CATALOG_RETAIN_TTL_MS = 60_000`) promoted back to
active `sharedCatalogs` on sequential hits and invalidated automatically
whenever the fresh gateway listing changes `identity`.
- Unregister the `collectedCatalogs` `FinalizationRegistry` token
(`catalog`) in `forgetSharedCatalog` and before re-registering in
`shareAssignedCatalog` so repeated sequential warm reuses never
accumulate live registrations.
- Keep `FinalizationRegistry` GC drop callbacks (`drop` from
`createSessionRelease`) in a separate lexical scope with no reference to
`assigned` or `catalog`, releasing holds without retaining abandoned
sessions.
- Manage warm TTL expiry with lazy pruning on lookup/insert plus one
per-entry `.unref()` `setTimeout` cleared in `forgetRetainedCatalog` on
hit, eviction, or expiry. Keep `assignedRetainedCatalogCacheStats()`
read-only.
- Deduplicate `unavailable` and `unchecked` `logger.warn` emissions per
`(gatewayPublicId, catalogKey)` in a bounded LRU
(`ASSIGNED_CATALOG_WARNING_CACHE_ENTRIES = 512`,
`ASSIGNED_CATALOG_WARNING_DEDUP_MS = 10 * 60_000`).
- `server/src/services/native-runtime/assigned-mcp-tools.test.ts` and
`server/src/services/native-runtime/assigned-mcp-tools-cache.test.ts`:
- Split `describe("shared assigned tool catalogs")` into
`assigned-mcp-tools-cache.test.ts` (353 lines), reducing
`assigned-mcp-tools.test.ts` from 980 to 808 lines.
- Add fake-timer tests verifying timer-driven and lazy warm catalog TTL
expiration, invalidation on listing changes, bounded
`FinalizationRegistry` registrations across 50 sequential warm reuses,
and per-`(gatewayPublicId, catalogKey)` warning deduplication and window
expiry.

## Verification

### Local Before vs After Benchmark

Measured in the worktree against `306437a2a5` (before) and `2b3757ad58`
(after):

| Workload | Metric | Before | After |
| --- | --- | ---: | ---: |
| `admitToolInputSchema` (50 schemas w/ 4 format fields × 20 calls) |
`unknown format` warnings (cold 50 / total 1,000) | 400 / 8,000 | **0 /
0** |
| `admitToolInputSchema` (950 repeat admissions) | Total wall time |
144.44 ms | **5.28 ms** (27.4× faster) |
| `createAssignedMcpTools` over-budget (120 tools × ~6.7 KiB, 20
sequential runs) | `unknown format` warnings | 672 | **0** |
| `createAssignedMcpTools` over-budget (20 sequential runs) |
Compile-budget `logger.warn` count | 20 | **1** |
| `createAssignedMcpTools` over-budget (runs 2–20) | Median / total time
| 1.35 ms / 29.07 ms | **1.18 ms / 23.52 ms** |
| `createAssignedMcpTools` under-budget (50 tools × ~1 KiB, 20
sequential runs) | Sequential catalog cache hits | 0 / 19 | **19 / 19**
|
| `createAssignedMcpTools` under-budget (runs 2–20) | Median / total
time | 0.34 ms / 6.81 ms | **0.29 ms / 5.66 ms** |

Memory benchmark (`NODE_OPTIONS="--expose-gc" npx tsx
scripts/benchmark-assigned-mcp-tools-memory.ts --tools 80 --schema-bytes
2048 --sessions 50 --turns 10`):
- `sharedAcrossTurns: true`, `retainedBytesPerSession: 10052`,
`bytesStillHeldAfterRelease: 321248` (unclosed sessions released on GC
without entering warm retention).

### Automated Tests & Checks (on head `687fe283be`)

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/tool-input-schema.test.ts
src/drivers/runner-tool-bridge.schemas.test.ts`: 2 files, 26 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/assigned-mcp-tools.test.ts
src/services/native-runtime/assigned-mcp-tools-cache.test.ts`: 2 files,
80 passed.
- `pnpm --filter @paperclipai/paperclip-runner run
typecheck:typescript`: passed.
- `pnpm --filter @paperclipai/server exec tsc --noEmit`: passed.
- `pnpm check:module-boundaries`: passed.
- `node scripts/check-test-budget.mjs --base origin/master`: passed (`2
test file(s) checked`).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs "$(git rev-parse
HEAD)" --check`: passed (`changed: false`).

### Operational Assumptions & Sleep Safety

- **Format validation parity:** `tool-input-schema.ts` never registered
`ajv-formats` and ran with `strict: false`, so format keywords were
never enforced before this change. Verified with real `Ajv`, `Ajv2019`,
and `Ajv2020` instances across all shared fixtures plus explicit format
tests.
- **Warm retention lifecycle (`sleep-aware-background-work`):** Trigger
is explicit `assigned.close()` releasing the last active holder
(`holders === 0`). Source of truth for tool grants remains the fresh
gateway listing on every `createAssignedMcpTools` call. Pending-work
predicate is `retainedCatalogs.size > 0`, with one `.unref()`
`setTimeout` per retained entry (at most 64 entries, 60s TTL), cleared
immediately in `forgetRetainedCatalog` on hit, eviction, or expiry. When
all retained entries expire or are promoted back to active, zero timers,
SQL queries, or network requests remain.
- **Remaining coverage:** Full repository test suites and build gates
run in CI on this revision.

## Risks

- **Frozen `validate.schema` in `tool-input-schema.ts`:** Cached
compiled schemas are deep-frozen before reuse so callers cannot corrupt
shared cache entries. All in-repo consumers (`admitToolInput`,
`toolInputError`, `RepeatedToolInputRejectionGuard`) only read
`validate.schema`, and `admission.schema` remains a fresh unfrozen
clone. Any future consumer attempting to mutate `validate.schema` will
get a `TypeError` instead of silent cross-caller corruption.
- **Validator cache byte accounting:**
`TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES` (16 MiB) accounts for serialized
schema JSON bytes rather than V8 compiled closure heap, and is paired
with a 512-entry cap so total validator memory stays bounded.
- **Warm catalog memory bound:** Released catalogs are held strongly for
up to 60 seconds, capped strictly at 64 entries and 32 MiB accounted
bytes, and cleared by per-entry `.unref()` expiry timers. Abandoned
sessions dropped without `close()` are never retained, and
`collectedCatalogs` unregisters tokens on release and re-share.
- **Warning deduplication window:** Repeated warnings for an unchanged
`(gatewayPublicId, catalogKey)` are suppressed for 10 minutes (bounded
at 512 entries). Changes to the tool listing or gateway ID log
immediately, and unchanged warnings re-log after the 10-minute window.
- **No database schema changes or migrations.**

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Gemini 4 Neon (Google DeepMind, XHigh reasoning, with tool use and
code execution)

## Checklist

- [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 (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
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
2026-12-04 20:05:03 -06:00
..