Skip to content

Event-loop freeze (120–149% CPU) on large chat-completion requests due to synchronous RegExp.split() in token estimator #1

Backlog

Description

@BillyOutlast

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

  1. Small/medium requests (2–158 msgs): Complete normally, though /healthz shows 208ms–1030ms event-loop lag warnings ([HEALTHZ] GET /healthz event-loop lag ... (HTTP 200 is not healthy; busy != ready)).
  2. Large requests (375 msgs | 17 tools | effort=max, in=286317): Immediately after routing/auth or stream completion, CPU jumps to 121%–149% and /healthz, /dashboard, and /mcp time out completely (healthz:000).
  3. Ruled out via isolation:
    • Raising OMNIROUTE_MEMORY_MB from 2048 to 8192 (mem_limit: 12g): freeze still occurred with heapUsed=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 .env and storage.sqlite): freeze still occurred.
    • Increasing LXC/Docker CPU cores: ineffective because Node.js's JS event loop is single-threaded.

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/:

  1. chunks/51473.js: when usage.input.source === "unknown", calls bC(c) (request_body_heuristic).
  2. chunks/12362.js: calls bC(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

  1. Fast-path O(1) length estimation for large payloads: In 659880 (estimateTokens), if the serialized string length exceeds a safe threshold (e.g., > 50_000 chars), 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.
  2. Avoid unconditional bC(b) in chunks/12362.js when upstream usage is already available.

Additional Observations

  • Open call_logs directory handles: Across restarts, /proc/<pid>/fd showed two pairs of open directory handles on /app/data/call_logs and /app/data/call_logs/2026-11-07 (4,608 files in 2026-11-07, 340–358 files in 2026-11-06, 88,241 rows in call_logs SQLite table).
  • Semantic cache embedding dimension (768): When configuring Lemonade with embeddinggemma-2 (768 dimensions), the dashboard/DB (databaseSettings.cache.semanticCacheEmbeddingDimension) could not be set to 768 via the UI and remained 1024 in SQLite even when OMNIROUTE_SEMANTIC_CACHE_EMBEDDING_DIMENSION=768 was set in .env.

Activity

  1. BillyOutlast commented on Nov 24, 2026

    @BillyOutlast
    Author

    Thanks for the --prof capture — 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:

    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 carrying usage{prompt_tokens: 0, completion_tokens: n} — the 3.8.54 trigger:

    3.8.54 path (measured equivalent) 3.8.55
    estimateInputTokens per stream 400 1
    body serializations per stream 800 3
    synchronous loop block 8.2–9.2 s 17–24 ms (single) / 93–128 ms (4 concurrent)
    drain — 46–60 ms (single) / 168–293 ms (4 concurrent)
    same counters at 800 frames — yes

    Warm re-drain (memo populated) peaks at 0.34–0.90 ms.

    Important: diegosouzapw/omniroute:latest and the npm package are still 3.8.54 (published 2026-11-17), which predates cheaper-inference#20086 (2026-11-20). Pulling latest today still reproduces the bug. The :next Docker channel builds from release/v* and already contains the fix.

    Estimator optimization

    PR cheaper-inference#19713 replaces the split/filter estimator 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

    The remainder after cheaper-inference#19713 is a single ~6 ms estimate per large request, not the multi-second freeze.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions