Deep graphs: O(n²) → O(n), plus a boot warning when they're suspiciously deep #2

Merged
chrnx merged 3 commits from fix/pipeline-context-on2 into develop 2026-07-18 00:35:29 +00:00
11 changed files with 242 additions and 8 deletions

No files matched your search

+1 -1
View File
@@ -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)}`);
});
+34
View File
@@ -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}`);
+33
View File
@@ -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}`) });
+1 -1
View File
@@ -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}`);
+1 -1
View File
@@ -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<NestFastifyApplication>(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}`);
}
+26
View File
@@ -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}`);
});
+33
View File
@@ -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); });
+27 -2
View File
@@ -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<GraphNode>([...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);
+2 -2
View File
@@ -47,12 +47,12 @@ export function isStreamResult(result: PipelineResult): result is StreamResult {
*/
export async function runSteps(steps: PipelineStep[], seed: Record<string, unknown>, bus: Bus): Promise<any> {
// 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 });
}
+50
View File
@@ -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();
});
});
+34 -1
View File
@@ -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);
});
});