From 9b8cafd5f8e5b0c2c9fb7d0ae979372638fbdc12 Mon Sep 17 00:00:00 2001 From: Sachin Sharma Date: Thu, 26 Nov 2026 00:20:45 +0530 Subject: [PATCH] chore(benchmarks): add SDK overhead benchmarks against a local mock provider Measures what NeuroLink itself costs apart from the model call: import time and memory, CPU per generate() and stream() call, the module count one import loads, and the CPU-bound helpers (chunking, tokenize, BM25, cosine). Every call goes to a fake OpenAI-compatible server in the parent process, and the measured child gets only PATH, HOME and the mock's settings, so no real provider key is read and no paid API is called. Not wired into CI. --- benchmarks/sdk-overhead/README.md | 43 ++++++++ benchmarks/sdk-overhead/call-bench.mjs | 116 +++++++++++++++++++++ benchmarks/sdk-overhead/cpu-helpers.mjs | 84 +++++++++++++++ benchmarks/sdk-overhead/import-modules.mjs | 48 +++++++++ benchmarks/sdk-overhead/mock-server.mjs | 76 ++++++++++++++ benchmarks/sdk-overhead/run.mjs | 64 ++++++++++++ 6 files changed, 431 insertions(+) create mode 100644 benchmarks/sdk-overhead/README.md create mode 100644 benchmarks/sdk-overhead/call-bench.mjs create mode 100644 benchmarks/sdk-overhead/cpu-helpers.mjs create mode 100644 benchmarks/sdk-overhead/import-modules.mjs create mode 100644 benchmarks/sdk-overhead/mock-server.mjs create mode 100644 benchmarks/sdk-overhead/run.mjs diff --git a/benchmarks/sdk-overhead/README.md b/benchmarks/sdk-overhead/README.md new file mode 100644 index 0000000000..2bbf051df0 --- /dev/null +++ b/benchmarks/sdk-overhead/README.md @@ -0,0 +1,43 @@ +# SDK overhead benchmarks + +These scripts measure what NeuroLink itself costs, apart from the model call: +import time, memory, CPU per `generate()` and `stream()` call, and the +CPU-bound helpers. They were written to answer whether a Rust core would pay +off, and they are kept so the numbers can be rerun after a change such as +lazy loading. + +Every call goes to a local fake OpenAI-compatible server +(`mock-server.mjs`) that returns a fixed 300-word reply. The benchmark +processes get only `PATH`, `HOME` and the mock server's settings, so no real +provider key is read and no paid API is called. + +## Run + +```bash +pnpm run build +node benchmarks/sdk-overhead/run.mjs # 3 runs of 200 calls each +node benchmarks/sdk-overhead/run.mjs --calls 3000 --runs 1 +``` + +`--dist ` points at another build, for a before/after comparison. The +build can live anywhere: its own folder, not a folder named `dist`, decides +which loaded modules count as NeuroLink's. + +## What each script measures + +| Script | Measures | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `call-bench.mjs` | In one fresh process: import time, CPU and memory, then `new NeuroLink()` timed on its own; the first call; CPU per call, p50 and p95 latency and calls per second over sequential calls; then 50 calls at once; memory and heap at the end | +| `import-modules.mjs` | How many modules one import loads, and which packages they come from | +| `cpu-helpers.mjs` | Median time to chunk and tokenize 1 MB of text with each strategy, BM25 indexing and search over 10,000 documents, and 10,000 cosine similarities at 1,536 dimensions | +| `mock-server.mjs` | The fake server. It also runs alone: `node benchmarks/sdk-overhead/mock-server.mjs 18765` | + +## Reading the numbers + +Import time varies a lot between runs (1.7 to 6.0 s was seen on one +machine), because it is mostly file reads and compiling. Compare medians over +several runs, on the same machine, with nothing else heavy running. The fake +server runs in the parent process, so its CPU is never counted in the child's +figures. + +These are not part of CI, and nothing in `test/` depends on them. diff --git a/benchmarks/sdk-overhead/call-bench.mjs b/benchmarks/sdk-overhead/call-bench.mjs new file mode 100644 index 0000000000..f3699e8ba2 --- /dev/null +++ b/benchmarks/sdk-overhead/call-bench.mjs @@ -0,0 +1,116 @@ +// Times one fresh process: importing dist/index.js, then generate() or +// stream() against the mock server. Run it through run.mjs, which starts the +// mock server and sets OPENAI_COMPATIBLE_* for this process. +// node --expose-gc call-bench.mjs +import path from "node:path"; +import { performance } from "node:perf_hooks"; +import { pathToFileURL } from "node:url"; + +const [distArg, callsArg = "200", mode = "generate"] = process.argv.slice(2); +const distUrl = distArg.startsWith("file:") + ? distArg + : pathToFileURL(path.resolve(distArg)).href; +const calls = Number(callsArg); +const CONCURRENT = 50; +const WARMUP = 20; + +const cpuMs = (since) => { + const u = process.cpuUsage(since); + return (u.user + u.system) / 1000; +}; +const rssMB = () => process.memoryUsage().rss / 1048576; + +const importCpu = process.cpuUsage(); +const importStart = performance.now(); +const { NeuroLink } = await import(distUrl); +const importResult = { + ms: performance.now() - importStart, + cpuMs: cpuMs(importCpu), + rssMB: rssMB(), +}; + +const constructCpu = process.cpuUsage(); +const constructStart = performance.now(); +const neurolink = new NeuroLink(); +const constructResult = { + ms: performance.now() - constructStart, + cpuMs: cpuMs(constructCpu), + rssMB: rssMB(), +}; + +async function one() { + const options = { + input: { text: "hello" }, + provider: "openai-compatible", + model: "mock-model", + disableTools: true, + }; + if (mode === "stream") { + const result = await neurolink.stream(options); + for await (const _ of result.stream) { + // Drain every chunk, as a caller would. + } + return; + } + await neurolink.generate(options); +} + +const firstCpu = process.cpuUsage(); +const firstStart = performance.now(); +await one(); +const firstCall = { + ms: performance.now() - firstStart, + cpuMs: cpuMs(firstCpu), +}; + +for (let i = 0; i < WARMUP; i++) { + await one(); +} +global.gc?.(); +const rssWarmMB = rssMB(); + +const latencies = []; +const seqCpu = process.cpuUsage(); +const seqStart = performance.now(); +for (let i = 0; i < calls; i++) { + const start = performance.now(); + await one(); + latencies.push(performance.now() - start); +} +const seqWall = performance.now() - seqStart; +const seqCpuMs = cpuMs(seqCpu); +latencies.sort((a, b) => a - b); + +const concCpu = process.cpuUsage(); +const concStart = performance.now(); +await Promise.all(Array.from({ length: CONCURRENT }, one)); +const concurrent = { + calls: CONCURRENT, + wallMs: performance.now() - concStart, + cpuMs: cpuMs(concCpu), + rssMB: rssMB(), +}; + +global.gc?.(); +console.log( + JSON.stringify({ + mode, + calls, + import: importResult, + construct: constructResult, + firstCall, + rssWarmMB, + perCall: { + cpuMs: seqCpuMs / calls, + p50Ms: latencies[calls >> 1], + p95Ms: latencies[Math.floor(calls * 0.95)], + callsPerSecond: calls / (seqWall / 1000), + }, + concurrent, + end: { + rssMB: rssMB(), + heapMB: process.memoryUsage().heapUsed / 1048576, + }, + }), +); +process.exit(0); diff --git a/benchmarks/sdk-overhead/cpu-helpers.mjs b/benchmarks/sdk-overhead/cpu-helpers.mjs new file mode 100644 index 0000000000..377ff7b48d --- /dev/null +++ b/benchmarks/sdk-overhead/cpu-helpers.mjs @@ -0,0 +1,84 @@ +// Times the CPU-bound public helpers on realistic inputs: chunking and +// tokenizing 1 MB of text, BM25 over 10,000 documents, and 10,000 cosine +// similarities at 1,536 dimensions. +// node cpu-helpers.mjs +import path from "node:path"; +import { performance } from "node:perf_hooks"; +import { pathToFileURL } from "node:url"; + +const distArg = process.argv[2]; +const neurolink = await import( + distArg.startsWith("file:") + ? distArg + : pathToFileURL(path.resolve(distArg)).href +); + +const PARAGRAPH = + "Juspay processes payments for merchants across India. The orchestration layer routes each transaction to the best gateway. "; +const TEXT_1MB = PARAGRAPH.repeat(Math.ceil(1_048_576 / PARAGRAPH.length)); +const results = []; + +async function time(name, fn, reps = 5) { + try { + await fn(); + const samples = []; + for (let i = 0; i < reps; i++) { + const start = performance.now(); + await fn(); + samples.push(performance.now() - start); + } + samples.sort((a, b) => a - b); + results.push({ name, medianMs: samples[samples.length >> 1] }); + } catch (error) { + results.push({ name, error: error.message }); + } +} + +for (const strategy of [ + "character", + "recursive", + "sentence", + "token", + "markdown", +]) { + await time( + `chunk 1 MB (${strategy})`, + async () => { + const chunker = await neurolink.createChunker(strategy); + return chunker.chunk(TEXT_1MB, { maxSize: 1000, overlap: 100 }); + }, + 3, + ); +} +await time("tokenize 1 MB", () => neurolink.tokenize(TEXT_1MB), 3); + +const DOCS = Array.from({ length: 10_000 }, (_, i) => ({ + id: `d${i}`, + text: `${PARAGRAPH} document ${i}`, +})); +await time( + "BM25 index 10,000 docs", + async () => { + const index = new neurolink.InMemoryBM25Index(); + await index.addDocuments(DOCS); + }, + 3, +); +const bm25 = new neurolink.InMemoryBM25Index(); +await bm25.addDocuments(DOCS); +await time("BM25 search 10,000 docs", () => + bm25.search("payment gateway routing", 10), +); + +const a = Array.from({ length: 1536 }, Math.random); +const b = Array.from({ length: 1536 }, Math.random); +await time("cosine 1536-dim x 10,000", () => { + let sum = 0; + for (let i = 0; i < 10_000; i++) { + sum += neurolink.cosineSimilarity(a, b); + } + return sum; +}); + +console.log(JSON.stringify({ helpers: results })); +process.exit(0); diff --git a/benchmarks/sdk-overhead/import-modules.mjs b/benchmarks/sdk-overhead/import-modules.mjs new file mode 100644 index 0000000000..26de0082cf --- /dev/null +++ b/benchmarks/sdk-overhead/import-modules.mjs @@ -0,0 +1,48 @@ +// Counts the modules one import of dist/index.js loads, grouped by package. +// node import-modules.mjs +import { registerHooks } from "node:module"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const distArg = process.argv[2]; +const distUrl = distArg.startsWith("file:") + ? distArg + : pathToFileURL(path.resolve(distArg)).href; +// The selected build's own folder, wherever it lives (dist/ or a copy). +const buildRoot = new URL(".", distUrl).href; +const loaded = new Set(); +registerHooks({ + load(url, context, next) { + loaded.add(url); + return next(url, context); + }, +}); + +await import(distUrl); + +const byPackage = {}; +let ownFiles = 0; +for (const url of loaded) { + const match = url.match( + /node_modules\/\.pnpm\/[^/]+\/node_modules\/((?:@[^/]+\/)?[^/]+)/, + ); + if (match) { + byPackage[match[1]] = (byPackage[match[1]] || 0) + 1; + } else if (url.startsWith(buildRoot) && !url.includes("/node_modules/")) { + ownFiles++; + } +} +const top = Object.entries(byPackage) + .sort((a, b) => b[1] - a[1]) + .slice(0, 15) + .map(([name, files]) => ({ name, files })); + +console.log( + JSON.stringify({ + totalModules: loaded.size, + neurolinkFiles: ownFiles, + thirdPartyPackages: Object.keys(byPackage).length, + topPackages: top, + }), +); +process.exit(0); diff --git a/benchmarks/sdk-overhead/mock-server.mjs b/benchmarks/sdk-overhead/mock-server.mjs new file mode 100644 index 0000000000..03d9bf5c36 --- /dev/null +++ b/benchmarks/sdk-overhead/mock-server.mjs @@ -0,0 +1,76 @@ +// A fake OpenAI-compatible server with a fixed 300-word reply, so the +// benchmarks time NeuroLink's own work and never the network or a model. +import http from "node:http"; + +const WORDS = Array.from({ length: 300 }, (_, i) => `word${i}`); +const USAGE = { prompt_tokens: 50, completion_tokens: 300, total_tokens: 350 }; + +function chunk(delta, finishReason, extra = {}) { + return `data: ${JSON.stringify({ + id: "bench", + object: "chat.completion.chunk", + created: 1, + model: "mock-model", + choices: [{ index: 0, delta, finish_reason: finishReason }], + ...extra, + })}\n\n`; +} + +export function startMockServer(port = 0) { + const server = http.createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + if (req.url.endsWith("/models")) { + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + object: "list", + data: [{ id: "mock-model", object: "model" }], + }), + ); + return; + } + let request = {}; + try { + request = JSON.parse(body || "{}"); + } catch { + // A malformed body still gets the plain reply. + } + if (request.stream) { + res.writeHead(200, { "content-type": "text/event-stream" }); + for (const word of WORDS) { + res.write(chunk({ content: `${word} ` }, null)); + } + res.write(chunk({}, "stop", { usage: USAGE })); + res.end("data: [DONE]\n\n"); + return; + } + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + id: "bench", + object: "chat.completion", + created: 1, + model: "mock-model", + choices: [ + { + index: 0, + message: { role: "assistant", content: WORDS.join(" ") }, + finish_reason: "stop", + }, + ], + usage: USAGE, + }), + ); + }); + }); + return new Promise((resolve) => { + server.listen(port, "127.0.0.1", () => resolve(server)); + }); +} + +if (import.meta.main) { + const server = await startMockServer(Number(process.argv[2] || 0)); + console.log(`mock server on http://127.0.0.1:${server.address().port}/v1`); +} diff --git a/benchmarks/sdk-overhead/run.mjs b/benchmarks/sdk-overhead/run.mjs new file mode 100644 index 0000000000..5be1eb445f --- /dev/null +++ b/benchmarks/sdk-overhead/run.mjs @@ -0,0 +1,64 @@ +// Runs every SDK-overhead benchmark, each in a fresh Node process, and prints +// one JSON report. Needs a build first (`pnpm run build`). +// node benchmarks/sdk-overhead/run.mjs [--calls 200] [--runs 3] [--dist ] +import { execFile } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "node:path"; +import { promisify } from "node:util"; +import { startMockServer } from "./mock-server.mjs"; + +const run = promisify(execFile); +const here = path.dirname(fileURLToPath(import.meta.url)); + +function flag(name, fallback) { + const i = process.argv.indexOf(`--${name}`); + return i === -1 ? fallback : process.argv[i + 1]; +} +const calls = flag("calls", "200"); +const runs = Number(flag("runs", "3")); +// A file URL, not a path: import() takes URLs, and a Windows path or a path +// with "#" would not resolve as one. +const dist = pathToFileURL( + path.resolve(flag("dist", path.join(here, "..", "..", "dist", "index.js"))), +).href; + +const server = await startMockServer(); +// Only what the benchmark needs: no real provider keys reach the child, so +// nothing can fall through to a paid API. +const env = { + PATH: process.env.PATH, + HOME: process.env.HOME, + OPENAI_COMPATIBLE_BASE_URL: `http://127.0.0.1:${server.address().port}/v1`, + OPENAI_COMPATIBLE_API_KEY: "mock", + OPENAI_COMPATIBLE_MODEL: "mock-model", +}; + +async function child(script, args, nodeFlags = []) { + const { stdout } = await run( + process.execPath, + [...nodeFlags, path.join(here, script), dist, ...args], + { env, maxBuffer: 16 * 1024 * 1024 }, + ); + const lastLine = stdout.trim().split("\n").at(-1); + return JSON.parse(lastLine); +} + +const report = { + node: process.version, + platform: `${process.platform}-${process.arch}`, + generate: [], + stream: [], +}; +for (let i = 0; i < runs; i++) { + report.generate.push( + await child("call-bench.mjs", [calls, "generate"], ["--expose-gc"]), + ); + report.stream.push( + await child("call-bench.mjs", [calls, "stream"], ["--expose-gc"]), + ); +} +report.modules = await child("import-modules.mjs", []); +report.cpuHelpers = await child("cpu-helpers.mjs", []); + +server.close(); +console.log(JSON.stringify(report, null, 2));