From 4081106813914a05fd025dfe8c7197215956ae96 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 15:50:59 -0500 Subject: [PATCH 1/3] perf(pipeline): merge step output in place to drop the O(n^2) context copy runSteps rebuilt the whole request context every step with { ...context, ...output }, so an N-step route paid 1+2+...+N = O(N^2) property copies plus N throwaway objects. At 100 chained steps that measured ~250us/req vs ~100us after the fix (2.5x throughput); per-step cost drops from superlinear to a flat ~0.5us/step. Mutate one accumulator in place with Object.assign -- O(N). The returned context is now the same object every step observes. Adds a regression guard that fails if a per-step copy is reintroduced; full suite green (322 tests). Signed-off-by: Diego Resendez --- src/pipeline.ts | 4 ++-- test/pipeline.test.ts | 35 ++++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/pipeline.ts b/src/pipeline.ts index 1003e49..680e25b 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -47,12 +47,12 @@ export function isStreamResult(result: PipelineResult): result is StreamResult { */ export async function runSteps(steps: PipelineStep[], seed: Record, bus: Bus): Promise { // context is intentionally `any`: each step merges arbitrary keys into the accumulator - let context: any = seed; + const context: any = seed; for (const step of steps) { bus.emit('request:step:enter', { name: step.name, scope: step.origin }); const output = await step.run(context); - context = { ...context, ...output }; + Object.assign(context, output); bus.emit('request:step:leave', { name: step.name, scope: step.origin }); } diff --git a/test/pipeline.test.ts b/test/pipeline.test.ts index 24e7168..abeb142 100644 --- a/test/pipeline.test.ts +++ b/test/pipeline.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, test, vi } from 'vitest'; -import { runPipeline, isStreamResult } from '../src/pipeline'; +import { runPipeline, runSteps, isStreamResult } from '../src/pipeline'; import { Bus } from '../src/bus'; import { JsonTransformer } from '../src/transformers'; import { Unauthorized } from '../src/signals'; @@ -100,3 +100,36 @@ describe('runPipeline transport enforcement', () => { expect(isStreamResult(res)).toBe(true); }); }); + +describe('runSteps accumulation', () => { + // A chain where step k reads s{k-1} and provides s{k} = s{k-1} + 1: proves each + // step observes the previous ones' output (the graph's whole point). + const chain = (n: number) => + Array.from({ length: n }, (_, i) => { + const k = i + 1; + return { name: `s${k}`, origin: 'mod', run: (ctx: any) => ({ [`s${k}`]: (ctx[`s${k - 1}`] ?? 0) + 1 }) }; + }); + + it('each step sees prior outputs; the final context holds them all', async () => { + const ctx = await runSteps(chain(50), {}, new Bus()); + expect(ctx.s1).toBe(1); + expect(ctx.s50).toBe(50); // 50 only lands if every step saw the previous + expect(Object.keys(ctx)).toHaveLength(50); + }); + + // Regression guard for the O(n^2) context merge (was `context = { ...context, ...output }`, + // which handed every step a freshly copied object — quadratic in the step count). The fix + // accumulates into ONE object in place, so every step must observe the same instance. + it('accumulates into a single object in place — never a per-step copy', async () => { + const seen: unknown[] = []; + const steps = Array.from({ length: 6 }, (_, i) => ({ + name: `s${i}`, + origin: 'mod', + run: (ctx: any) => { seen.push(ctx); return { [`k${i}`]: i }; }, + })); + const out = await runSteps(steps, { req: {} }, new Bus()); + for (const ctx of seen) expect(ctx).toBe(seen[0]); // a spread would hand each step a new object + expect(out).toBe(seen[0]); // and the returned context is that same accumulator + expect((out as any).k5).toBe(5); + }); +}); From 642ef109b2bda336bae0bc08cc985dda0f1eeecb Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 16:25:31 -0500 Subject: [PATCH 2/3] feat(app): warn at boot when a route's dependency chain is unusually deep A route whose need-closure resolves to more than 20 steps is almost always a modeling smell -- a step doing too much, or work that belongs in a provider. Per-request cost is linear, so this is a design nudge, not a perf guard (and a warning, not an error). Tunable and silenceable via createApp({ warnGraphDepth }): a number sets the threshold, false quiets it. Default 20. Signed-off-by: Diego Resendez --- src/app/index.ts | 29 +++++++++++++++++++++-- test/graph-depth.test.ts | 50 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 test/graph-depth.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 7554943..f265dca 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -104,6 +104,12 @@ export function createApp(opts: { static?: boolean | string; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; + /** + * Warn at boot when a route's dependency chain resolves to more than this many steps (default 20; + * `false` silences). A design nudge, not a perf limit — deep graphs run fine (cost is linear), but + * 20+ steps on one route usually means a step is doing too much. + */ + warnGraphDepth?: number | false; }): App { // mesh is alpha: its API and wire protocol may change. Require an explicit opt-in. if (opts.mesh && !opts.experimental) { @@ -136,7 +142,7 @@ export function createApp(opts: { const meshLinks: Link[] = []; const finalize = (): void => { - ({ orderedProviders, orderedSteps } = finalizeGraph(registry)); + ({ orderedProviders, orderedSteps } = finalizeGraph(registry, opts.warnGraphDepth)); booted = true; }; @@ -437,11 +443,19 @@ function provideBuiltins(registry: Registry): void { registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms } +// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling +// smell (a step doing too much, or work that belongs in a provider), not a real dependency depth. +// Cost is linear so it isn't a perf problem — it's a design one. Generous on purpose. +const DEEP_GRAPH_WARN = 20; + /** * Topo-sorts the graph, slices each route's provider/step closure into its plan, and validates every need. * @returns The app-scope providers and request-scope steps in execution order. */ -function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { +function finalizeGraph( + registry: Registry, + warnDepth: number | false = DEEP_GRAPH_WARN, +): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { const { providerNodes, stepNodes, routePlans } = registry; const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); const orderedProviders = ordered.filter((node) => providerNodes.includes(node)); @@ -454,6 +468,17 @@ function finalizeGraph(registry: Registry): { orderedProviders: GraphNode[]; ord plan.providers = closure.filter((node) => providerNodes.includes(node)); const sliced = new Set([...closure.filter((node) => stepNodes.includes(node)), ...alwaysSteps]); plan.steps = ordered.filter((node) => stepNodes.includes(node) && sliced.has(node)); // topo order, deduped + + // The route's own dependency depth, excluding always-on observer steps (plugins). + const depth = closure.filter((node) => stepNodes.includes(node)).length; + + if (warnDepth !== false && depth > warnDepth) { + console.warn( + `[green-tea] ${plan.method} ${plan.pattern} resolves to ${depth} steps — an unusually deep dependency chain. ` + + `It runs fine (per-request cost is linear), but ${warnDepth}+ steps on one route usually means a step ` + + `is doing too much or the graph wants splitting. If it's intentional, ignore this.`, + ); + } } assertNeedsSatisfiable(routePlans, providerNodes, stepNodes); diff --git a/test/graph-depth.test.ts b/test/graph-depth.test.ts new file mode 100644 index 0000000..7726ab4 --- /dev/null +++ b/test/graph-depth.test.ts @@ -0,0 +1,50 @@ +import 'reflect-metadata'; +import { describe, expect, it, vi } from 'vitest'; +import { createApp, Step, Route, Get, Module, needs } from '../src/index'; + +// Builds a module with an n-deep chain: s1..sn (each needs the previous) + a route that @needs the last. +function deepModule(n: number) { + const steps = Array.from({ length: n }, (_, i) => { + const k = i + 1; + @Step({ provides: `s${k}`, needs: k > 1 ? [`s${k - 1}`] : [] }) + class S { run() { return { [`s${k}`]: k }; } } + return S; + }); + + @Route('/') + class C { @Get('/deep') deep(@needs(`s${n}`) s: number) { return { s }; } } + + @Module({ mountpoint: '/', steps, controllers: [C] }) + class M {} + return M; +} + +describe('deep-graph warning', () => { + it('warns at boot when a route resolves to more than 20 steps', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + createApp({ modules: [deepModule(25)] }); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('25 steps')); + warn.mockRestore(); + }); + + it('stays quiet under the threshold', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + createApp({ modules: [deepModule(10)] }); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('warnGraphDepth: false silences it', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + createApp({ modules: [deepModule(25)], warnGraphDepth: false }); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('warnGraphDepth tunes the threshold', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + createApp({ modules: [deepModule(10)], warnGraphDepth: 5 }); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('10 steps')); + warn.mockRestore(); + }); +}); From 3a4cd5a7ceac8b4cbbd7a872ae8088102b104b24 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 17 Jul 2026 19:05:52 -0500 Subject: [PATCH 3/3] test(bench): reach bench servers cross-host + add scale and Bun/Deno servers Fastify and the Nest adapters bound 127.0.0.1, unreachable from a separate load generator; bind 0.0.0.0 so two-machine benchmarks work. Adds scale-{green-tea,express} (step-vs-middleware depth sweeps that surfaced the O(n^2)) and green-tea-{bun,deno} (the same app served via serveBun/serveDeno, to benchmark across runtimes). Signed-off-by: Diego Resendez --- bench/servers/fastify.ts | 2 +- bench/servers/green-tea-bun.ts | 34 ++++++++++++++++++++++++++++++++ bench/servers/green-tea-deno.ts | 33 +++++++++++++++++++++++++++++++ bench/servers/nestjs-express.ts | 2 +- bench/servers/nestjs-fastify.ts | 2 +- bench/servers/scale-express.ts | 26 ++++++++++++++++++++++++ bench/servers/scale-green-tea.ts | 33 +++++++++++++++++++++++++++++++ 7 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 bench/servers/green-tea-bun.ts create mode 100644 bench/servers/green-tea-deno.ts create mode 100644 bench/servers/scale-express.ts create mode 100644 bench/servers/scale-green-tea.ts diff --git a/bench/servers/fastify.ts b/bench/servers/fastify.ts index 9cd8833..8ea42bf 100644 --- a/bench/servers/fastify.ts +++ b/bench/servers/fastify.ts @@ -12,7 +12,7 @@ app.post('/validate', { if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; } return { email: b.email }; }); -app.listen({ port: 0 }, (err, addr) => { +app.listen({ port: 0, host: '0.0.0.0' }, (err, addr) => { if (err) { console.error(err); process.exit(1); } console.log(`READY ${Number(new URL(addr).port)}`); }); diff --git a/bench/servers/green-tea-bun.ts b/bench/servers/green-tea-bun.ts new file mode 100644 index 0000000..2b5cbfa --- /dev/null +++ b/bench/servers/green-tea-bun.ts @@ -0,0 +1,34 @@ +import 'reflect-metadata'; +import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs'; +import { serveBun } from '../../dist/bun.mjs'; + +// Same BenchModule as green-tea.ts (Node), served via Bun.serve instead of app.listen. +const emailSchema = { + '~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) => + (v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } }, +}; + +function makeStep(n: number) { + @Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] }) + class S { run() { return { [`s${n}`]: n }; } } + return S; +} +const steps = [1, 2, 3, 4, 5].map(makeStep); + +@Route('/') +class Bench { + @Get('/hello') hello() { return { hello: 'world' }; } + @Get('/users/:id') user(@param('id') id: string) { return { id }; } + @Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; } + @Get('/steps/0') steps0() { return { hello: 'world' }; } + @Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; } +} + +@Module({ mountpoint: '/', steps, controllers: [Bench] }) +class BenchModule {} + +const app = createApp({ modules: [BenchModule], security: false }); +const server = serveBun(app, { port: 0, hostname: '0.0.0.0' }); +console.log(`READY ${server.port}`); diff --git a/bench/servers/green-tea-deno.ts b/bench/servers/green-tea-deno.ts new file mode 100644 index 0000000..70b0319 --- /dev/null +++ b/bench/servers/green-tea-deno.ts @@ -0,0 +1,33 @@ +import 'reflect-metadata'; +import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../dist/index.mjs'; +import { serveDeno } from '../../dist/deno.mjs'; + +// Same BenchModule as green-tea.ts (Node), served via Deno.serve instead of app.listen. +const emailSchema = { + '~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) => + (v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } }, +}; + +function makeStep(n: number) { + @Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] }) + class S { run() { return { [`s${n}`]: n }; } } + return S; +} +const steps = [1, 2, 3, 4, 5].map(makeStep); + +@Route('/') +class Bench { + @Get('/hello') hello() { return { hello: 'world' }; } + @Get('/users/:id') user(@param('id') id: string) { return { id }; } + @Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; } + @Get('/steps/0') steps0() { return { hello: 'world' }; } + @Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; } + @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; } +} + +@Module({ mountpoint: '/', steps, controllers: [Bench] }) +class BenchModule {} + +const app = createApp({ modules: [BenchModule], security: false }); +serveDeno(app, { port: 0, hostname: '0.0.0.0', onListen: (a: { port: number }) => console.log(`READY ${a.port}`) }); diff --git a/bench/servers/nestjs-express.ts b/bench/servers/nestjs-express.ts index 7945244..210de81 100644 --- a/bench/servers/nestjs-express.ts +++ b/bench/servers/nestjs-express.ts @@ -9,7 +9,7 @@ async function main() { inst.disable('x-powered-by'); inst.set('etag', false); const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false }); - await app.listen(0, '127.0.0.1'); + await app.listen(0, '0.0.0.0'); const server = app.getHttpServer(); server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen) console.log(`READY ${server.address().port}`); diff --git a/bench/servers/nestjs-fastify.ts b/bench/servers/nestjs-fastify.ts index 4b95565..9556f98 100644 --- a/bench/servers/nestjs-fastify.ts +++ b/bench/servers/nestjs-fastify.ts @@ -6,7 +6,7 @@ import { BenchModule } from './_nest-shared'; async function main() { const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor const app = await NestFactory.create(BenchModule, adapter, { logger: false }); - await app.listen(0, '127.0.0.1'); + await app.listen(0, '0.0.0.0'); const server = app.getHttpServer(); console.log(`READY ${(server.address() as any).port}`); } diff --git a/bench/servers/scale-express.ts b/bench/servers/scale-express.ts new file mode 100644 index 0000000..16c843d --- /dev/null +++ b/bench/servers/scale-express.ts @@ -0,0 +1,26 @@ +import express from 'express'; + +// Express counterpart: /chain/N runs N trivial middlewares before the handler — +// the closest apples-to-apples to green-tea's N chained steps. +const app = express(); +app.disable('x-powered-by'); +app.set('etag', false); + +const mw = (_req: any, _res: any, next: any) => next(); + +function route(path: string, n: number): void { + const chain = Array.from({ length: n }, () => mw); + app.get(path, ...chain, (_req, res) => { res.json({ ok: 1 }); }); +} + +route('/chain/0', 0); +route('/chain/10', 10); +route('/chain/25', 25); +route('/chain/50', 50); +route('/chain/75', 75); +route('/chain/100', 100); + +const server = app.listen(0, () => { + server.keepAliveTimeout = 5000; + console.log(`READY ${(server.address() as any).port}`); +}); diff --git a/bench/servers/scale-green-tea.ts b/bench/servers/scale-green-tea.ts new file mode 100644 index 0000000..e351994 --- /dev/null +++ b/bench/servers/scale-green-tea.ts @@ -0,0 +1,33 @@ +import 'reflect-metadata'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; + +// 100 chained steps: s1..s100, each needs the previous. A route that @needs the Nth +// pulls exactly N steps transitively — so /chain/100 runs the full 100-deep graph slice. +function makeStep(n: number) { + @Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] }) + class S { run() { return { [`s${n}`]: n }; } } + return S; +} +const steps = Array.from({ length: 100 }, (_, i) => makeStep(i + 1)); + +@Route('/chain') +class Chain { + @Get('/0') d0() { return { ok: 1 }; } + @Get('/10') d10(@needs('s10') s: number) { return { s }; } + @Get('/25') d25(@needs('s25') s: number) { return { s }; } + @Get('/50') d50(@needs('s50') s: number) { return { s }; } + @Get('/75') d75(@needs('s75') s: number) { return { s }; } + @Get('/100') d100(@needs('s100') s: number) { return { s }; } +} + +@Module({ mountpoint: '/', steps, controllers: [Chain] }) +class ScaleModule {} + +const app = createApp({ modules: [ScaleModule], security: false }); + +async function main() { + const server = await app.listen(0); + server.keepAliveTimeout = 5000; + console.log(`READY ${(server.address() as any).port}`); +} +main().catch((e) => { console.error(e); process.exit(1); });