Repository navigation
Description
Summary
Large POST /v1/chat/completions requests (e.g., 375 msgs | 17 tools | effort=max, ~286k input tokens) cause the Node.js event loop to freeze at 121%–149% CPU, timing out /healthz, /dashboard, and /mcp (HTTP 000 after 2–5s).
V8 --prof profiling pinpointed the bottleneck to the synchronous request-body token-estimation heuristic (module 659880 / bC in /app/.build/next/server/chunks/51473.js, also called from chunks/12362.js), which runs .split(/(\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))/).filter(...) over JSON.stringify(body) on the main thread.
Environment
- Image:
diegosouzapw/omniroute:latest(Next.js 16.4.2,Node.js v26.12.1) - Host / Resources: Proxmox LXC (8 CPU cores, 128 GiB RAM,
OMNIROUTE_MEMORY_MB=8192,mem_limit: 12g, no CPU limit) - Sidecar:
redis:8.6.5-alpine - SQLite Driver:
better-sqlite3(storage.sqlite~405 MB)
Observed Symptoms & Isolation
- Small/medium requests (
2–158 msgs): Complete normally, though/healthzshows208ms–1030msevent-loop lag warnings ([HEALTHZ] GET /healthz event-loop lag ... (HTTP 200 is not healthy; busy != ready)). - Large requests (
375 msgs | 17 tools | effort=max,in=286317): Immediately after routing/auth or stream completion, CPU jumps to121%–149%and/healthz,/dashboard, and/mcptime out completely (healthz:000). - Ruled out via isolation:
- Raising
OMNIROUTE_MEMORY_MBfrom2048to8192(mem_limit: 12g): freeze still occurred withheapUsed=581MB–964MB,rss=1.52GB–1.74GB(not OOM/heap-limit GC thrashing). - Disabling
compression.cavemanConfig(enabled: false): freeze still occurred. - Disabling
compression.mcpAccessibility(enabled: false): freeze still occurred. - Disabling
OMNIROUTE_SEMANTIC_CACHE_ENABLED=false(both.envandstorage.sqlite): freeze still occurred. - Increasing LXC/Docker CPU cores: ineffective because Node.js's JS event loop is single-threaded.
- Raising
V8 --prof Evidence
Capturing V8 CPU ticks (node --prof server-ws.mjs) during a freeze produced:
[JavaScript]:
ticks total nonlib name
4293 17.8% 30.7% RegExp: (\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))
2401 9.9% 17.2% Builtin: RegExpSplit
1328 5.5% 9.5% Builtin: ArrayFilter
1105 4.6% 7.9% Builtin: RecordWriteSaveFP
1084 4.5% 7.7% Builtin: StringPrototypeTrim
796 3.3% 5.7% JS: *<anonymous> /app/.build/next/server/chunks/51473.js:15:7328
765 3.2% 5.5% RegExp: [\u3000-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}]
736 3.0% 5.3% Builtin: SubString
355 1.5% 2.5% RegExp: [\u3000-\u9fff\uf900-\ufaff]
Over 70% of non-lib JS CPU time is spent in this single regex-split tokenization path (strace also showed 92% of syscall time in munmap/mmap/madvise from massive temporary string/array allocations).
Root Cause
In /app/.build/next/server/chunks/51473.js (module 659880, exported as bC via 88530):
function d(a) {
if (!a || "string" != typeof a) return 0;
let b = a.match(/[\u3000-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}]/gu);
return (b ? b.length : 0) + Math.ceil(1.3 * a.replace(/[\u3000-\u9fff\uf900-\ufaff]/g, " ").split(/(\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))/).filter(a => a && a.trim().length > 0).length);
}
function e(a) {
if (!a || "object" != typeof a) return 0;
try {
let b = 0, c = 0;
if (a.tools && Array.isArray(a.tools)) {
let e = JSON.stringify(a.tools);
b = Math.ceil(e.length / 6);
let { tools: f, ...g } = a;
c = d(JSON.stringify(g));
} else c = d(JSON.stringify(a));
return c + b;
} catch { return 0; }
}Call sites observed in .build/next/server/:
chunks/51473.js: whenusage.input.source === "unknown", callsbC(c)(request_body_heuristic).chunks/12362.js: callsbC(b)unconditionally during usage calculation.
On a >1 MB JSON.stringify(body) payload, .split(/(\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))/) allocates hundreds of thousands of substrings into an array and iterates them synchronously with .filter(), blocking the event loop.
Suggested Fix
- Fast-path O(1) length estimation for large payloads: In
659880(estimateTokens), if the serialized string length exceeds a safe threshold (e.g.,> 50_000chars), fall back to the O(1) char-length estimator (oT:Math.ceil(len / 3.5)) already defined in the same module, or iterate with a streaming/regex-free counter without.split()array allocation. - Avoid unconditional
bC(b)inchunks/12362.jswhen upstreamusageis already available.
Additional Observations
- Open
call_logsdirectory handles: Across restarts,/proc/<pid>/fdshowed two pairs of open directory handles on/app/data/call_logsand/app/data/call_logs/2026-11-07(4,608files in2026-11-07,340–358files in2026-11-06,88,241rows incall_logsSQLite table). - Semantic cache embedding dimension (
768): When configuring Lemonade withembeddinggemma-2(768dimensions), the dashboard/DB (databaseSettings.cache.semanticCacheEmbeddingDimension) could not be set to768via the UI and remained1024in SQLite even whenOMNIROUTE_SEMANTIC_CACHE_EMBEDDING_DIMENSION=768was set in.env.
Activity
BillyOutlast commentedon Nov 24, 2026
Thanks for the
--profcapture — it pointed straight at the right function.Status on 3.8.55
The freeze mechanism is fixed on
release/v3.8.55. The estimator is still the same heuristic, but it no longer runs per chunk:estimateInputTokensis memoized per request body (fix(backend): usage sanitizer re-tokenizes the whole request body on every streamed chunk that reports 0 input tokens, saturating the event loop cheaper-inference/OmniRoute#20086).RequestUsageBasisper request and passes it to every parsed SSE payload, sobodyBytes()/inputEstimate()are computed once.finalizeStreamingUsageonly estimates whenusage_evidence.input.source === "unknown", which covers the second call site in your report.Measured on a local build of
release/v3.8.55, with a 1.1 MB body (375 messages, 17 tools) and 400 delta frames each carryingusage{prompt_tokens: 0, completion_tokens: n}— the 3.8.54 trigger:estimateInputTokensper streamWarm re-drain (memo populated) peaks at 0.34–0.90 ms.
Important:
diegosouzapw/omniroute:latestand the npm package are still 3.8.54 (published 2026-11-17), which predates cheaper-inference#20086 (2026-11-20). Pullinglatesttoday still reproduces the bug. The:nextDocker channel builds fromrelease/v*and already contains the fix.Estimator optimization
PR cheaper-inference#19713 replaces the
split/filterestimator with a single-pass counter: 1.1 MB goes from 15.6 ms to 6.1 ms and peak heap from 18.9 MiB to 1.1 MiB, with exact parity over 1.26M cases. It is green and mergeable; I posted the evidence there.The two side observations
call_logsdirectory handles — the resumable orphan-scan cursor held twofs.Dirhandles (base dir + current day) between bounded passes. It now uses a one-shot listing plus indexes, so no descriptor outlives a pass. PR fix(call-logs): release orphan scan directory handles cheaper-inference/OmniRoute#21166.env | db | default), and a probe mismatch is surfaced. PR fix(cache): make semantic embedding dimension settable and effective cheaper-inference/OmniRoute#21167.The remainder after cheaper-inference#19713 is a single ~6 ms estimate per large request, not the multi-second freeze.