From 815f76116f3c025f3c9e3e13938958a4456888d2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 11 Oct 2026 12:33:07 -0500 Subject: [PATCH 1/7] perf(router): index HTTP routes in a radix tree Replace the linear, specificity-sorted scan behind matchRoute, resolveRoute and allowedMethods with a segment trie per HTTP method, built once per route array from the compiled segments compilePattern already produces. Ranking stays global: every terminal carries its position in the old sorted bucket (moreSpecific, declaration order on ties), and the walk keeps the lowest rank it can reach, pruning subtrees that cannot beat it. The tree decides which routes can match; the rank alone decides which one does. A static branch that dead-ends deeper backtracks into its param, constrained and catch-all siblings. All-static routes are also kept by exact path per method. A hit there is provably the tree's best match, so a static request is answered without splitting the path; a miss falls through to the walk. Mesh-spliced remote routes go in a second tree, per the owner's design decision. Both trees answer, the more specific match wins and an equal one goes to the earlier declaration, so local still beats remote on a tie. Allow, 405 and implicit HEAD run over the union. An app without remote routes does one lookup. allowedMethods walks the index instead of recompiling every route on a miss, and an implicit HEAD no longer builds a fresh index from a filtered array on every request. The frozen parity corpus passes unchanged. The frozen mutant script cannot run against the new layout by design, so test/router-index-mutants.ts re-targets its twelve bug classes at the new code and runs the same untouched suite. Refs #109 Signed-off-by: Diego Resendez --- package.json | 1 + src/app/index.ts | 41 ++-- src/http/router.ts | 354 +++++++++++++++++++++++++++++------ test/router-index-mutants.ts | 299 +++++++++++++++++++++++++++++ test/router-index.test.ts | 108 +++++++++++ 5 files changed, 731 insertions(+), 72 deletions(-) create mode 100644 test/router-index-mutants.ts create mode 100644 test/router-index.test.ts diff --git a/package.json b/package.json index 15aba06..2d8a1b2 100644 --- a/package.json +++ b/package.json @@ -105,6 +105,7 @@ "bench:compare": "tsx bench/compare.ts", "bench:lookup": "tsx bench/lookup.ts", "parity:mutants": "tsx test/router-parity/mutants.ts", + "parity:mutants:index": "tsx test/router-index-mutants.ts", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build", "prepare": "git config core.hooksPath .githooks || true" }, diff --git a/src/app/index.ts b/src/app/index.ts index 20c5fd2..8466f5c 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -49,7 +49,7 @@ import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; import { inspectRoute, buildGraphView, explainRoute } from './introspect'; -import { compilePattern, normalizeRequestPath } from '../http/router'; +import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router'; export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types'; @@ -952,24 +952,27 @@ async function spliceRemoteScopes( ); } - remoteRoutes.push({ - method: route.method, - pattern: route.pattern, - transport: 'buffer', - // Built explicitly rather than cast from the handler argument. The cast put the whole - // internal request on the wire — `ip` and `protocol` included — and sent fields the - // protocol never declared, so a teapot could come to rely on something we never promised. - handler: async (req) => - route.handler({ - method: req.method, - params: req.params, - query: req.query, - body: req.body, - headers: req.headers, - url: req.url, - correlation: { requestId: req.requestId, traceId: req.traceId }, - }), - }); + // Marked so the router files it in the remote tree; precedence is unchanged by the split. + remoteRoutes.push( + markRemoteRoute({ + method: route.method, + pattern: route.pattern, + transport: 'buffer', + // Built explicitly rather than cast from the handler argument. The cast put the whole + // internal request on the wire — `ip` and `protocol` included — and sent fields the + // protocol never declared, so a teapot could come to rely on something we never promised. + handler: async (req) => + route.handler({ + method: req.method, + params: req.params, + query: req.query, + body: req.body, + headers: req.headers, + url: req.url, + correlation: { requestId: req.requestId, traceId: req.traceId }, + }), + }), + ); } } } catch (err) { diff --git a/src/http/router.ts b/src/http/router.ts index 4588140..66944ab 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -325,65 +325,305 @@ function moreSpecific(a: CompiledPattern, b: CompiledPattern): number { return 0; } -/** One route with its pattern already compiled. Built once per table, ordered within its method. */ -interface IndexedRoute { +/** + * One route at a terminal of the index. + * + * `rank` is the route's place in its method's specificity order — exactly the order the linear + * matcher sorted its bucket into: `moreSpecific` first, declaration order on ties. Lower wins. The + * tree only decides which routes *can* match; this number alone decides which one *does*, so the + * shape of the tree can never override the global ranking (two overlapping constraints, a catch-all + * at one depth against a param at another, an equal-rank tie). + */ +interface Terminal { def: RouteDef; compiled: CompiledPattern; + rank: number; + /** Position in the route array the index was built from. Breaks a tie between the two trees. */ + order: number; + /** Every segment static: the route has no params to collect. */ + allStatic: boolean; +} + +/** A `:param` edge. Plain params share one edge; constrained ones share an edge per constraint source. */ +interface ParamEdge { + constraintSource: string | undefined; + constraint: RegExp | undefined; + node: RadixNode; +} + +// ponytail: a segment trie — one edge per whole path segment, no compression of single-child static +// chains. Lookup cost already follows path depth, not route count; compressing would save a few map +// hops on long static prefixes and costs a split/merge routine nobody has measured a need for. +interface RadixNode { + statics: Map; + params: ParamEdge[]; + /** Routes whose last segment ends at this node, by rank. */ + exact: Terminal[]; + /** Catch-all routes whose fixed prefix ends at this node, by rank. They match zero or more segments. */ + catchAll: Terminal[]; + /** Lowest rank anywhere below this node: a branch that cannot beat the best match so far is skipped. */ + min: number; +} + +/** One method's routes: the tree, plus its all-static routes by exact path. */ +interface MethodTree { + root: RadixNode; + /** + * All-static routes keyed by their normalized pattern, by rank. A hit here is the tree's best + * match for that path: any other non-catch-all route matching it has as many segments, none of + * them more specific than static, and every catch-all ranks below every exact route. So a static + * request is answered without splitting the path. A miss proves nothing and falls through to the + * walk, as does a path spelled differently from its pattern (`/a/`, `/a//b` on a direct call). + */ + exactPaths: Map; } /** - * Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array - * they were built from. + * The lookup index for one route array: a tree per HTTP method, local and remote kept apart. + * + * Mesh-spliced remote routes get their own trees so they can later be rebuilt alone when peers come + * and go. Precedence stays the single list's: both trees answer, the more specific match wins, and + * a tie goes to the earlier declaration — a local one, since local routes come first. + */ +interface RouteIndex { + /** Length of the array at build time; a cached index for an array that has since grown or shrunk is rebuilt. */ + size: number; + local: Map; + /** Absent for an app without mesh routes, which then does a single lookup. */ + remote: Map | undefined; + /** Every method with at least one route, in either tree. */ + methods: string[]; +} + +/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */ +const remoteRouteDefs = new WeakSet(); + +/** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */ +export function markRemoteRoute(def: T): T { + remoteRouteDefs.add(def); + return def; +} + +/** + * Route indexes keyed by the identity of the array they were built from. * * A server hands the same array to every request, so this is built once and collected with the - * table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a - * different array and gets its own index, so nothing has to remember to invalidate anything. + * table it describes. Both callers (`buildAppFetch` and `listen()`) assemble that array after boot, + * from local, remote and dev routes, and never touch it again. A table assembled fresh is a + * different array and gets its own index. */ -const routeIndexCache = new WeakMap>(); +const routeIndexCache = new WeakMap(); -function routeIndex(routes: RouteDef[]): Map { - const cached = routeIndexCache.get(routes); - if (cached) return cached; +function newNode(): RadixNode { + return { statics: new Map(), params: [], exact: [], catchAll: [], min: Infinity }; +} - const byMethod = new Map(); - - for (const def of routes) { - const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) }; - const bucket = byMethod.get(def.method); - if (bucket) bucket.push(entry); - else byMethod.set(def.method, [entry]); +function childFor(node: RadixNode, segment: Exclude): RadixNode { + if (segment.kind === 'static') { + let next = node.statics.get(segment.value); + if (!next) node.statics.set(segment.value, (next = newNode())); + return next; } - // Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns - // keep registration order — which is exactly what the old scan did by refusing to replace its - // best on a tie. - for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled)); + let edge = node.params.find((candidate) => candidate.constraintSource === segment.constraintSource); - routeIndexCache.set(routes, byMethod); - return byMethod; + if (!edge) { + edge = { constraintSource: segment.constraintSource, constraint: segment.constraint, node: newNode() }; + node.params.push(edge); + } + + return edge.node; } +/** Files one terminal. Insertion runs in rank order, so every list stays sorted and `min` is set once. */ +function insert(tree: MethodTree, terminal: Terminal): void { + let node = tree.root; + if (node.min === Infinity) node.min = terminal.rank; + + for (const segment of terminal.compiled.segments) { + if (segment.kind === 'catchAll') { + node.catchAll.push(terminal); + return; + } + + node = childFor(node, segment); + if (node.min === Infinity) node.min = terminal.rank; + } + + node.exact.push(terminal); + + if (terminal.allStatic) { + const key = terminal.compiled.normalized; + const same = tree.exactPaths.get(key); + if (same) same.push(terminal); + else tree.exactPaths.set(key, [terminal]); + } +} + +/** Builds one tree per method from `(route, array position)` pairs, ranked as the linear matcher sorted them. */ +function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map { + const byMethod = new Map(); + + for (const { def, order } of entries) { + const compiled = compilePattern(def.pattern); + const allStatic = compiled.segments.every((segment) => segment.kind === 'static'); + const terminal: Terminal = { def, compiled, rank: 0, order, allStatic }; + const bucket = byMethod.get(def.method); + if (bucket) bucket.push(terminal); + else byMethod.set(def.method, [terminal]); + } + + const trees = new Map(); + + for (const [method, bucket] of byMethod) { + // `sort` is stable, so equal patterns keep registration order. + bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled)); + const tree: MethodTree = { root: newNode(), exactPaths: new Map() }; + bucket.forEach((terminal, rank) => insert(tree, Object.assign(terminal, { rank }))); + trees.set(method, tree); + } + + return trees; +} + +function routeIndex(routes: RouteDef[]): RouteIndex { + const cached = routeIndexCache.get(routes); + if (cached?.size === routes.length) return cached; + + const local: Array<{ def: RouteDef; order: number }> = []; + const remote: Array<{ def: RouteDef; order: number }> = []; + routes.forEach((def, order) => (remoteRouteDefs.has(def) ? remote : local).push({ def, order })); + + const index: RouteIndex = { + size: routes.length, + local: buildTrees(local), + remote: remote.length ? buildTrees(remote) : undefined, + methods: [...new Set(routes.map((route) => route.method))], + }; + routeIndexCache.set(routes, index); + return index; +} + +/** + * One request's lookup state, shared by every tree it searches: the path, its segments (split only + * if a walk needs them), decoded values memoized by position, and the current search's filter and + * best terminal. One object per call rather than one per tree keeps the small-table cost down. + */ +interface Search { + path: string; + segs: string[] | undefined; + decoded: Array; + accept: ((def: RouteDef) => boolean) | undefined; + best: Terminal | undefined; +} + +/** Placeholder until a walk splits the path; nothing reads or writes it before then. */ +const NO_DECODED: Array = []; + +function newSearch(path: string): Search { + return { path, segs: undefined, decoded: NO_DECODED, accept: undefined, best: undefined }; +} + +function segmentsOf(search: Search): string[] { + if (search.segs) return search.segs; + const segs = splitPath(search.path); + search.segs = segs; + search.decoded = new Array(segs.length); + return segs; +} + +/** Takes the best-ranked acceptable terminal of a rank-ordered list, if it beats the best so far. */ +function offer(search: Search, terminals: Terminal[]): void { + for (let i = 0; i < terminals.length; i++) { + const terminal = terminals[i]; + if (search.best && terminal.rank >= search.best.rank) return; + if (search.accept && !search.accept(terminal.def)) continue; + search.best = terminal; + return; + } +} + +/** + * Depth-first walk with backtracking: a static branch that dead-ends deeper falls back to its param, + * constrained and catch-all siblings. Params are decoded after splitting, so `%2F` stays inside one + * segment. Every branch that could still hold a better rank is visited; `min` prunes the rest. + * + * The indexed loops and the empty-collection guards are measured, not style: at 10 routes the old + * linear scan is a handful of string compares, and these keep the walk within D4 of it (FPRD-001). + */ +function walk(node: RadixNode, search: Search, segs: string[], depth: number): void { + if (search.best && node.min >= search.best.rank) return; + + if (depth === segs.length) { + if (node.exact.length) offer(search, node.exact); + } else { + const segment = segs[depth]; + const next = node.statics.size ? node.statics.get(segment) : undefined; + if (next) walk(next, search, segs, depth + 1); + + const params = node.params; + + for (let i = 0; i < params.length; i++) { + const edge = params[i]; + const value = (search.decoded[depth] ??= decodeSegment(segment)); + if (edge.constraint && !edge.constraint.test(value)) continue; + walk(edge.node, search, segs, depth + 1); + } + } + + if (node.catchAll.length) offer(search, node.catchAll); +} + +function searchTree( + tree: MethodTree | undefined, + search: Search, + accept: ((def: RouteDef) => boolean) | undefined, +): Terminal | undefined { + if (!tree) return undefined; + search.accept = accept; + search.best = undefined; + + const exact = tree.exactPaths.get(search.path); + if (exact) offer(search, exact); + if (!search.best) walk(tree.root, search, segmentsOf(search), 0); + return search.best; +} + +/** Looks a method up in both trees. The more specific match wins; an equal one goes to the earlier declaration. */ +function findRoute( + index: RouteIndex, + method: string, + search: Search, + accept?: (def: RouteDef) => boolean, +): Terminal | undefined { + const local = searchTree(index.local.get(method), search, accept); + if (!index.remote) return local; + + const remote = searchTree(index.remote.get(method), search, accept); + if (!local || !remote) return local ?? remote; + + const order = moreSpecific(local.compiled, remote.compiled); + if (order !== 0) return order > 0 ? local : remote; + return local.order < remote.order ? local : remote; +} + +/** Collects the winning route's own param names and values. The walk already proved it matches. */ +function paramsOf(terminal: Terminal, search: Search): Record { + return terminal.allStatic ? {} : matchCompiled(terminal.compiled, segmentsOf(search), search.decoded)!; +} + +const isBuffered = (def: RouteDef): boolean => def.transport === 'buffer'; + /** * Finds the most specific route matching both method and path; ties keep registration order. * - * The ranking is settled when the table is built, not per request: the answer cannot change between - * requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific` - * call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route - * table. What is left here is a walk that stops at the first match. + * The ranking is settled when the index is built, not per request. What is left here is a walk down + * the method's tree that visits only the branches the path can follow. */ export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { - const candidates = routeIndex(routes).get(method); - if (!candidates) return undefined; - - const pathSegs = splitPath(path); - const decoded: Array = new Array(pathSegs.length); - - for (const { def, compiled } of candidates) { - const params = matchCompiled(compiled, pathSegs, decoded); - if (params) return { params, def }; - } - - return undefined; + const search = newSearch(path); + const hit = findRoute(routeIndex(routes), method, search); + return hit && { params: paramsOf(hit, search), def: hit.def }; } /** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */ @@ -392,29 +632,37 @@ export interface ResolvedRoute extends MatchedRoute { } export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined { - const explicit = matchRoute(routes, method, path); - if (explicit) return { ...explicit, implicitHead: false }; + const index = routeIndex(routes); + const search = newSearch(path); + + const explicit = findRoute(index, method, search); + if (explicit) return { params: paramsOf(explicit, search), def: explicit.def, implicitHead: false }; if (method !== 'HEAD') return undefined; - const fallback = matchRoute( - routes.filter((route) => route.transport === 'buffer'), - 'GET', - path, - ); - return fallback ? { ...fallback, implicitHead: true } : undefined; + // Only a buffered GET can answer HEAD. The filter applies inside the ranking, so a higher-ranked + // streaming GET is passed over for a lower-ranked buffered one rather than ending the search. + const fallback = findRoute(index, 'GET', search, isBuffered); + return fallback ? { params: paramsOf(fallback, search), def: fallback.def, implicitHead: true } : undefined; } const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']; -/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */ +/** + * Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. + * + * One lookup per registered method over the union of both trees. Nothing is recompiled or rescanned + * on a miss. + */ export function allowedMethods(routes: RouteDef[], path: string): string[] { - const pathSegs = splitPath(path); + const index = routeIndex(routes); + const search = newSearch(path); const methods = new Set(); - for (const route of routes) { - if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue; - methods.add(route.method); - if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD'); + for (const method of index.methods) { + // A buffered GET answers both GET and HEAD, so it is looked for first; only a GET path served + // by streaming routes alone needs the second lookup. + if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('GET').add('HEAD'); + else if (findRoute(index, method, search)) methods.add(method); } if (methods.size) methods.add('OPTIONS'); diff --git a/test/router-index-mutants.ts b/test/router-index-mutants.ts new file mode 100644 index 0000000..6f6bcc9 --- /dev/null +++ b/test/router-index-mutants.ts @@ -0,0 +1,299 @@ +/** + * Mutation check for the radix index (CARD-07, #109): the twelve bug classes of the frozen + * `test/router-parity/mutants.ts`, re-targeted at the code that replaced the linear matcher. + * + * npm run parity:mutants:index + * + * The frozen script cannot run against this router: its search texts are lines of the old linear + * scan, and it refuses to start when one is missing — which is what it was written to do ("mutants + * against the new code belong to CARD-07"). This one keeps everything else identical: the same + * suite (`vitest run test/router-parity`, untouched), the same temporary copy of `src/`, the same + * exactly-once rule for every search text, the same unmutated control run, and the same final + * `git diff --exit-code src`. Ids and the bug each one models are unchanged; six mutants apply + * verbatim, six are re-targeted. A mutant may need more than one edit when the new code holds the + * same rule in two places (the walk filters, then `matchCompiled` collects params); every edit + * models the same bug. + * + * Not part of `npm test`: it runs the suite once per mutant. + */ +import { spawnSync, execFileSync } from 'child_process'; +import { cpSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'fs'; +import os from 'os'; +import { join, resolve } from 'path'; + +const ROOT = resolve(__dirname, '..'); +const ROUTER = 'src/http/router.ts'; + +interface Edit { + file: string; + from: string; + to: string; +} + +interface Mutant { + id: string; + models: string; + /** `verbatim`: the frozen mutant's own edit. `retargeted`: the same bug, written against the index. */ + origin: 'verbatim' | 'retargeted'; + edits: Edit[]; +} + +export const MUTANTS: Mutant[] = [ + { + id: 'no-backtrack', + models: 'no backtracking to a param branch once a static first segment was entered', + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` if (next) walk(next, search, segs, depth + 1);`, + to: ` if (next && depth === 0) return walk(next, search, segs, depth + 1); + if (next) walk(next, search, segs, depth + 1);`, + }, + ], + }, + { + id: 'precedence-swapped', + models: 'static and plain-param precedence swapped', + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: `.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),`, + to: `.map((segment) => (segment.kind === 'static' ? 1 : segment.constraint ? 2 : 3)),`, + }, + ], + }, + { + id: 'tie-last-registered', + models: 'equal-rank tie broken by the last-registered declaration', + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));`, + to: ` bucket.reverse().sort((a, b) => moreSpecific(b.compiled, a.compiled));`, + }, + ], + }, + { + id: 'constraint-ignored', + models: 'param constraint not tested during lookup', + origin: 'retargeted', + edits: [ + { file: ROUTER, from: ` if (edge.constraint && !edge.constraint.test(value)) continue;\n`, to: `` }, + // the frozen mutant's own edit: without it the walk would pick a route whose params then fail to collect + { + file: ROUTER, + from: ` if (segment.constraint && !segment.constraint.test(value)) return undefined;\n`, + to: ``, + }, + ], + }, + { + id: 'decode-before-split', + models: 'path decoded before splitting, so %2F becomes a separator', + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: ` return path.split('/').filter(Boolean);`, + to: ` return decodeURIComponent(path).split('/').filter(Boolean);`, + }, + ], + }, + { + id: 'catch-all-needs-segment', + models: 'catch-all does not match zero segments', + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` if (node.catchAll.length) offer(search, node.catchAll);`, + to: ` if (node.catchAll.length && depth < segs.length) offer(search, node.catchAll);`, + }, + ], + }, + { + id: 'implicit-head-from-stream', + models: 'implicit HEAD served by a streaming GET', + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` const fallback = findRoute(index, 'GET', search, isBuffered);`, + to: ` const fallback = findRoute(index, 'GET', search);`, + }, + ], + }, + { + id: 'allow-one-pattern', + models: 'Allow built from the first matching pattern only', + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('GET').add('HEAD'); + else if (findRoute(index, method, search)) methods.add(method);`, + to: ` const hit = findRoute(index, method, search); + if (!hit) continue; + onlyPattern ??= hit.def.pattern; + if (hit.def.pattern !== onlyPattern) continue; + methods.add(method); + if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('HEAD');`, + }, + { + file: ROUTER, + from: ` const methods = new Set();\n\n for (const method of index.methods) {`, + to: ` const methods = new Set();\n let onlyPattern: string | undefined;\n\n for (const method of index.methods) {`, + }, + ], + }, + { + id: 'allow-order', + models: 'Allow in discovery order instead of canonical order', + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: ` return [...methods].sort((a, b) => {`, + to: ` return [...methods]; + [...methods].sort((a, b) => {`, + }, + ], + }, + { + id: 'trailing-slash-kept', + models: 'trailing slash not normalized', + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: ` const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;`, + to: ` const normalized = resolved;`, + }, + ], + }, + { + id: 'ws-ranked-like-http', + models: 'WS upgrades ranked by specificity like HTTP instead of first registered', + origin: 'verbatim', + edits: [ + { + file: 'src/http/ws-core.ts', + from: ` .find((entry) => entry.params);`, + to: ` .filter((entry) => entry.params) + .sort((a, b) => a.def.pattern.split(':').length - b.def.pattern.split(':').length)[0];`, + }, + ], + }, + { + id: 'case-insensitive-static', + models: 'static segments compared case-insensitively', + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` const next = node.statics.size ? node.statics.get(segment) : undefined;`, + to: ` const next = [...node.statics].find(([key]) => key.toLowerCase() === segment.toLowerCase())?.[1];`, + }, + // the frozen mutant's own edit, so the chosen route also collects its params + { + file: ROUTER, + from: ` if (segment.value !== pathSegs[index]) return undefined;`, + to: ` if (segment.value.toLowerCase() !== pathSegs[index].toLowerCase()) return undefined;`, + }, + ], + }, +]; + +function runSuite(dir: string): { passed: boolean; failed: number } { + const out = join(dir, 'vitest.json'); + const res = spawnSync( + process.execPath, + [ + join(ROOT, 'node_modules/vitest/vitest.mjs'), + 'run', + 'test/router-parity', + '--reporter=json', + `--outputFile=${out}`, + ], + { cwd: dir, env: { ...process.env, ROUTER_PARITY_CAPTURE: '' }, encoding: 'utf8', stdio: 'pipe' }, + ); + let failed = 0; + try { + failed = (JSON.parse(readFileSync(out, 'utf8')) as { numFailedTests: number }).numFailedTests; + } catch { + failed = -1; // the suite did not even report, which also kills the mutant + } + return { passed: res.status === 0, failed }; +} + +function copyTree(): string { + const dir = mkdtempSync(join(os.tmpdir(), 'router-index-mutants-')); + for (const entry of ['src', 'test']) cpSync(join(ROOT, entry), join(dir, entry), { recursive: true }); + for (const file of ['package.json', 'tsconfig.json', 'vitest.config.ts']) cpSync(join(ROOT, file), join(dir, file)); + symlinkSync(join(ROOT, 'node_modules'), join(dir, 'node_modules'), 'dir'); + return dir; +} + +/** Applies every edit of one mutant, each of which must find its search text exactly once. */ +function applyMutant(dir: string, mutant: Mutant): Map { + const originals = new Map(); + + for (const edit of mutant.edits) { + const path = join(dir, edit.file); + if (!originals.has(path)) originals.set(path, readFileSync(path, 'utf8')); + const current = readFileSync(path, 'utf8'); + const hits = current.split(edit.from).length - 1; + if (hits !== 1) throw new Error(`${mutant.id}: search text found ${hits} times in ${edit.file}`); + writeFileSync(path, current.replace(edit.from, edit.to)); + } + + return originals; +} + +function main(): void { + const only = process.env.MUTANTS_ONLY?.split(','); + const mutants = only ? MUTANTS.filter((m) => only.includes(m.id)) : MUTANTS; + const dir = copyTree(); + const rows: Array<{ id: string; origin: string; models: string; result: string; failedTests: number }> = []; + + try { + const control = runSuite(dir); + if (!control.passed) + throw new Error('the unmutated copy fails the parity suite; no mutant result would mean anything'); + + for (const mutant of mutants) { + const originals = applyMutant(dir, mutant); + try { + const { passed, failed } = runSuite(dir); + rows.push({ + id: mutant.id, + origin: mutant.origin, + models: mutant.models, + result: passed ? 'SURVIVED' : 'killed', + failedTests: failed, + }); + process.stderr.write(`[mutants] ${mutant.id}: ${passed ? 'SURVIVED' : `killed (${failed} failing)`}\n`); + } finally { + for (const [path, original] of originals) writeFileSync(path, original); + } + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + + console.log('| mutant | edit | models | result | failing tests |'); + console.log('| --- | --- | --- | --- | --- |'); + for (const row of rows) + console.log(`| ${row.id} | ${row.origin} | ${row.models} | ${row.result} | ${row.failedTests} |`); + const killed = rows.filter((row) => row.result === 'killed').length; + console.log(`\n${killed}/${rows.length} killed`); + + // The guarantee this script makes: the real src/ was never touched. + execFileSync('git', ['diff', '--exit-code', '--', 'src'], { cwd: ROOT, stdio: 'inherit' }); + if (killed !== rows.length) process.exitCode = 1; +} + +main(); diff --git a/test/router-index.test.ts b/test/router-index.test.ts new file mode 100644 index 0000000..e67d2b5 --- /dev/null +++ b/test/router-index.test.ts @@ -0,0 +1,108 @@ +/** + * The radix index's own seams, which the frozen parity corpus (test/router-parity/) cannot reach: + * + * - The local/remote split. The corpus drives the matcher with flat arrays, so every scenario lands + * in the local tree; only the app-level mesh captures reach the remote one. Here every frozen + * scenario is replayed with its declarations spread across both trees, and must still answer + * exactly as the oracle does on the same flat array. + * - Index lifetime: an array that changes length after its index was built is never served stale. + */ +import { describe, it, expect } from 'vitest'; +import * as live from '../src/http/router'; +import type { RouteDef } from '../src/http/types'; +import * as oracle from './router-parity/oracle'; +import { runScenario, type MatcherImpl, type Scenario } from './router-parity/matcher'; +import { HAND_SCENARIOS, OWNER_SCENARIOS } from './router-parity/cases'; +import { generateScenarios, generateScenariosV2 } from './router-parity/generator'; + +const SCENARIOS: Scenario[] = [...HAND_SCENARIOS, ...OWNER_SCENARIOS, ...generateScenarios(), ...generateScenariosV2()]; + +/** Which positions of the declaration array go to the remote tree. */ +const SPLITS: Record boolean> = { + 'all remote': () => true, + 'second half remote': (index, length) => index >= length / 2, + 'odd positions remote': (index) => index % 2 === 1, + // Not a shape mesh produces (remote routes are spliced after local ones), but the tie rule is + // array order either way, so the answer must not depend on it. + 'first half remote': (index, length) => index < length / 2, +}; + +/** The live router, with some declarations marked remote before the first lookup builds the index. */ +function splitImpl(isRemote: (index: number, length: number) => boolean): MatcherImpl { + const mark = (routes: RouteDef[]): RouteDef[] => { + routes.forEach((route, index) => isRemote(index, routes.length) && live.markRemoteRoute(route)); + return routes; + }; + return { + normalizeRequestPath: live.normalizeRequestPath, + matchRoute: (routes, method, path) => live.matchRoute(mark(routes), method, path), + resolveRoute: (routes, method, path) => live.resolveRoute(mark(routes), method, path), + allowedMethods: (routes, path) => live.allowedMethods(mark(routes), path), + }; +} + +function route(method: string, pattern: string, transport: RouteDef['transport'] = 'buffer'): RouteDef { + return { method, pattern, transport, handler: async () => ({ status: 200, headers: {}, body: pattern }) }; +} + +describe('radix index: local and remote trees', () => { + for (const [name, isRemote] of Object.entries(SPLITS)) { + it(`answers every frozen scenario like the flat oracle — ${name}`, () => { + const impl = splitImpl(isRemote); + for (const scenario of SCENARIOS) { + expect(runScenario(impl, scenario), scenario.id).toEqual(runScenario(oracle, scenario)); + } + }); + } + + it('lets a remote static route outrank a local param route, and a local twin win a tie', () => { + const localParam = route('GET', '/items/:id'); + const localTwin = route('GET', '/items/special'); + const remoteStatic = live.markRemoteRoute(route('GET', '/items/special')); + const remoteOnly = live.markRemoteRoute(route('GET', '/items/other')); + + expect(live.matchRoute([localParam, remoteStatic, remoteOnly], 'GET', '/items/other')?.def).toBe(remoteOnly); + expect(live.matchRoute([localParam, remoteStatic], 'GET', '/items/special')?.def).toBe(remoteStatic); + expect(live.matchRoute([localParam, localTwin, remoteStatic], 'GET', '/items/special')?.def).toBe(localTwin); + }); + + it('breaks a cross-tree tie by array position, so a later dev route never shadows a remote one', () => { + const remote = live.markRemoteRoute(route('GET', '/__dev')); + const dev = route('GET', '/__dev'); + expect(live.matchRoute([remote, dev], 'GET', '/__dev')?.def).toBe(remote); + }); + + it('builds Allow and implicit HEAD over the union of both trees', () => { + const local = route('POST', '/a/:id'); + const remoteGet = live.markRemoteRoute(route('GET', '/a/:id')); + const routes = [local, remoteGet]; + + expect(live.allowedMethods(routes, '/a/1')).toEqual(['GET', 'HEAD', 'POST', 'OPTIONS']); + expect(live.resolveRoute(routes, 'HEAD', '/a/1')).toMatchObject({ def: remoteGet, implicitHead: true }); + }); + + it('passes over a higher-ranked streaming GET in one tree for a buffered GET in the other', () => { + const stream = route('GET', '/s/live', 'sse'); + const buffered = live.markRemoteRoute(route('GET', '/s/:name')); + expect(live.resolveRoute([stream, buffered], 'HEAD', '/s/live')).toMatchObject({ + def: buffered, + params: { name: 'live' }, + implicitHead: true, + }); + }); +}); + +describe('radix index: lifetime', () => { + it('rebuilds when the array it was built from changes length', () => { + const routes = [route('GET', '/a')]; + expect(live.matchRoute(routes, 'GET', '/b')).toBeUndefined(); + + const added = route('GET', '/b'); + routes.push(added); + expect(live.matchRoute(routes, 'GET', '/b')?.def).toBe(added); + expect(live.allowedMethods(routes, '/b')).toEqual(['GET', 'HEAD', 'OPTIONS']); + + routes.pop(); + expect(live.matchRoute(routes, 'GET', '/b')).toBeUndefined(); + }); +}); -- 2.54.1 From d76afd7f25cc067c7a117dff348e41d6ded0058a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 11 Oct 2026 12:58:26 -0500 Subject: [PATCH 2/7] docs(changelog): note the radix route index An internal change with no behaviour difference, recorded under Changed with the lookup numbers from the jarvis run. Refs #109 Signed-off-by: Diego Resendez --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbafe32..d07f8cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,18 @@ npm treats versions as semver and semver forbids leading zeros. about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and Bun have no connection cap, so set one at the platform or proxy there. +### Changed + +- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted + list per method, and on every 404 and 405 it recompiled and matched every route to build `Allow`. + It now walks a tree per method, built once from the route table, with mesh routes from teapots + in a tree of their own. This is internal and changes no behaviour: the same route wins, with the + same params, `Allow`, implicit `HEAD` and 404/405, checked against the frozen parity corpus. + `graph()`, `explain()` and `openapi()` still read the declared routes, not the tree. Median lookup + time against the old matcher (jarvis, `bench:lookup`): at 500 routes, static hit −54%, late + param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or + faster (late param hit +3.4%, 95% CI −5.0…+12.6%). + ### Fixed - **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard -- 2.54.1 From 55a4e282ad9b8d69f84225dbc2203578a3ac0141 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 11 Oct 2026 21:00:27 -0500 Subject: [PATCH 3/7] test(router): cover pruning across a static branch and a param sibling The walk takes the static branch first, so for `GET /a/:rest*` and `GET /:x/b` it reaches the catch-all on `/a/b` before the exact param route that outranks it. The corpus has no such pair, and a pruning bound off by one went unnoticed there. Checked against the oracle in both declaration orders. Refs #109 Signed-off-by: Diego Resendez --- test/router-index.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/router-index.test.ts b/test/router-index.test.ts index e67d2b5..7338a5b 100644 --- a/test/router-index.test.ts +++ b/test/router-index.test.ts @@ -92,6 +92,22 @@ describe('radix index: local and remote trees', () => { }); }); +describe('radix index: ranking across branches', () => { + it('lets an exact param route beat a catch-all the walk reached first through a static branch', () => { + // The static branch is walked first and yields the catch-all (rank 1); the param sibling still + // holds the rank-0 exact route, so pruning must not cut it, even by one. + for (const order of [ + ['/a/:rest*', '/:x/b'], + ['/:x/b', '/a/:rest*'], + ]) { + const routes = order.map((pattern) => route('GET', pattern)); + const expected = oracle.matchRoute(routes, 'GET', '/a/b'); + expect(expected?.def.pattern).toBe('/:x/b'); + expect(live.matchRoute(routes, 'GET', '/a/b')).toEqual(expected); + } + }); +}); + describe('radix index: lifetime', () => { it('rebuilds when the array it was built from changes length', () => { const routes = [route('GET', '/a')]; -- 2.54.1 From 996fb3f7a54e583087b9fe3245813074c5f6a6e2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 11 Oct 2026 21:00:35 -0500 Subject: [PATCH 4/7] test(router-parity): retarget mutants to the radix index (owner-approved) The owner approved editing this one file under test/router-parity/ so the PR ends with a single mutant check. The original search texts targeted lines of the linear scan that CARD-07 removed, so the script refused to run against the new router. The parity tests, oracle, frozen JSON and manifest are untouched. The twelve original mutants keep their names and the bug each models; six apply their original edit, six are rewritten against the index. Nine new mutants cover risks the index introduced: the static-route map ignoring the method or shadowing an earlier route, an off-by-one pruning bound, the empty-collection skip pruning a real match, a local/remote tie going remote, Allow and implicit HEAD from the local tree only, the stale-index guard removed, and a zero-segment catch-all skipped where the path ends on a static continuation. The suite now also runs test/router-index.test.ts, which covers the local/remote split and index lifetime the corpus cannot reach. Each edit must match exactly once and must change the file; a failed edit restores the copy before the run aborts. The script still ends with git diff --exit-code src. Removes test/router-index-mutants.ts and parity:mutants:index, which this replaces. Refs #109 Signed-off-by: Diego Resendez --- package.json | 1 - test/router-index-mutants.ts | 299 ---------------------------- test/router-parity/mutants.ts | 356 +++++++++++++++++++++++++++------- 3 files changed, 285 insertions(+), 371 deletions(-) delete mode 100644 test/router-index-mutants.ts diff --git a/package.json b/package.json index 2d8a1b2..15aba06 100644 --- a/package.json +++ b/package.json @@ -105,7 +105,6 @@ "bench:compare": "tsx bench/compare.ts", "bench:lookup": "tsx bench/lookup.ts", "parity:mutants": "tsx test/router-parity/mutants.ts", - "parity:mutants:index": "tsx test/router-index-mutants.ts", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build", "prepare": "git config core.hooksPath .githooks || true" }, diff --git a/test/router-index-mutants.ts b/test/router-index-mutants.ts deleted file mode 100644 index 6f6bcc9..0000000 --- a/test/router-index-mutants.ts +++ /dev/null @@ -1,299 +0,0 @@ -/** - * Mutation check for the radix index (CARD-07, #109): the twelve bug classes of the frozen - * `test/router-parity/mutants.ts`, re-targeted at the code that replaced the linear matcher. - * - * npm run parity:mutants:index - * - * The frozen script cannot run against this router: its search texts are lines of the old linear - * scan, and it refuses to start when one is missing — which is what it was written to do ("mutants - * against the new code belong to CARD-07"). This one keeps everything else identical: the same - * suite (`vitest run test/router-parity`, untouched), the same temporary copy of `src/`, the same - * exactly-once rule for every search text, the same unmutated control run, and the same final - * `git diff --exit-code src`. Ids and the bug each one models are unchanged; six mutants apply - * verbatim, six are re-targeted. A mutant may need more than one edit when the new code holds the - * same rule in two places (the walk filters, then `matchCompiled` collects params); every edit - * models the same bug. - * - * Not part of `npm test`: it runs the suite once per mutant. - */ -import { spawnSync, execFileSync } from 'child_process'; -import { cpSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'fs'; -import os from 'os'; -import { join, resolve } from 'path'; - -const ROOT = resolve(__dirname, '..'); -const ROUTER = 'src/http/router.ts'; - -interface Edit { - file: string; - from: string; - to: string; -} - -interface Mutant { - id: string; - models: string; - /** `verbatim`: the frozen mutant's own edit. `retargeted`: the same bug, written against the index. */ - origin: 'verbatim' | 'retargeted'; - edits: Edit[]; -} - -export const MUTANTS: Mutant[] = [ - { - id: 'no-backtrack', - models: 'no backtracking to a param branch once a static first segment was entered', - origin: 'retargeted', - edits: [ - { - file: ROUTER, - from: ` if (next) walk(next, search, segs, depth + 1);`, - to: ` if (next && depth === 0) return walk(next, search, segs, depth + 1); - if (next) walk(next, search, segs, depth + 1);`, - }, - ], - }, - { - id: 'precedence-swapped', - models: 'static and plain-param precedence swapped', - origin: 'verbatim', - edits: [ - { - file: ROUTER, - from: `.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),`, - to: `.map((segment) => (segment.kind === 'static' ? 1 : segment.constraint ? 2 : 3)),`, - }, - ], - }, - { - id: 'tie-last-registered', - models: 'equal-rank tie broken by the last-registered declaration', - origin: 'retargeted', - edits: [ - { - file: ROUTER, - from: ` bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));`, - to: ` bucket.reverse().sort((a, b) => moreSpecific(b.compiled, a.compiled));`, - }, - ], - }, - { - id: 'constraint-ignored', - models: 'param constraint not tested during lookup', - origin: 'retargeted', - edits: [ - { file: ROUTER, from: ` if (edge.constraint && !edge.constraint.test(value)) continue;\n`, to: `` }, - // the frozen mutant's own edit: without it the walk would pick a route whose params then fail to collect - { - file: ROUTER, - from: ` if (segment.constraint && !segment.constraint.test(value)) return undefined;\n`, - to: ``, - }, - ], - }, - { - id: 'decode-before-split', - models: 'path decoded before splitting, so %2F becomes a separator', - origin: 'verbatim', - edits: [ - { - file: ROUTER, - from: ` return path.split('/').filter(Boolean);`, - to: ` return decodeURIComponent(path).split('/').filter(Boolean);`, - }, - ], - }, - { - id: 'catch-all-needs-segment', - models: 'catch-all does not match zero segments', - origin: 'retargeted', - edits: [ - { - file: ROUTER, - from: ` if (node.catchAll.length) offer(search, node.catchAll);`, - to: ` if (node.catchAll.length && depth < segs.length) offer(search, node.catchAll);`, - }, - ], - }, - { - id: 'implicit-head-from-stream', - models: 'implicit HEAD served by a streaming GET', - origin: 'retargeted', - edits: [ - { - file: ROUTER, - from: ` const fallback = findRoute(index, 'GET', search, isBuffered);`, - to: ` const fallback = findRoute(index, 'GET', search);`, - }, - ], - }, - { - id: 'allow-one-pattern', - models: 'Allow built from the first matching pattern only', - origin: 'retargeted', - edits: [ - { - file: ROUTER, - from: ` if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('GET').add('HEAD'); - else if (findRoute(index, method, search)) methods.add(method);`, - to: ` const hit = findRoute(index, method, search); - if (!hit) continue; - onlyPattern ??= hit.def.pattern; - if (hit.def.pattern !== onlyPattern) continue; - methods.add(method); - if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('HEAD');`, - }, - { - file: ROUTER, - from: ` const methods = new Set();\n\n for (const method of index.methods) {`, - to: ` const methods = new Set();\n let onlyPattern: string | undefined;\n\n for (const method of index.methods) {`, - }, - ], - }, - { - id: 'allow-order', - models: 'Allow in discovery order instead of canonical order', - origin: 'verbatim', - edits: [ - { - file: ROUTER, - from: ` return [...methods].sort((a, b) => {`, - to: ` return [...methods]; - [...methods].sort((a, b) => {`, - }, - ], - }, - { - id: 'trailing-slash-kept', - models: 'trailing slash not normalized', - origin: 'verbatim', - edits: [ - { - file: ROUTER, - from: ` const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;`, - to: ` const normalized = resolved;`, - }, - ], - }, - { - id: 'ws-ranked-like-http', - models: 'WS upgrades ranked by specificity like HTTP instead of first registered', - origin: 'verbatim', - edits: [ - { - file: 'src/http/ws-core.ts', - from: ` .find((entry) => entry.params);`, - to: ` .filter((entry) => entry.params) - .sort((a, b) => a.def.pattern.split(':').length - b.def.pattern.split(':').length)[0];`, - }, - ], - }, - { - id: 'case-insensitive-static', - models: 'static segments compared case-insensitively', - origin: 'retargeted', - edits: [ - { - file: ROUTER, - from: ` const next = node.statics.size ? node.statics.get(segment) : undefined;`, - to: ` const next = [...node.statics].find(([key]) => key.toLowerCase() === segment.toLowerCase())?.[1];`, - }, - // the frozen mutant's own edit, so the chosen route also collects its params - { - file: ROUTER, - from: ` if (segment.value !== pathSegs[index]) return undefined;`, - to: ` if (segment.value.toLowerCase() !== pathSegs[index].toLowerCase()) return undefined;`, - }, - ], - }, -]; - -function runSuite(dir: string): { passed: boolean; failed: number } { - const out = join(dir, 'vitest.json'); - const res = spawnSync( - process.execPath, - [ - join(ROOT, 'node_modules/vitest/vitest.mjs'), - 'run', - 'test/router-parity', - '--reporter=json', - `--outputFile=${out}`, - ], - { cwd: dir, env: { ...process.env, ROUTER_PARITY_CAPTURE: '' }, encoding: 'utf8', stdio: 'pipe' }, - ); - let failed = 0; - try { - failed = (JSON.parse(readFileSync(out, 'utf8')) as { numFailedTests: number }).numFailedTests; - } catch { - failed = -1; // the suite did not even report, which also kills the mutant - } - return { passed: res.status === 0, failed }; -} - -function copyTree(): string { - const dir = mkdtempSync(join(os.tmpdir(), 'router-index-mutants-')); - for (const entry of ['src', 'test']) cpSync(join(ROOT, entry), join(dir, entry), { recursive: true }); - for (const file of ['package.json', 'tsconfig.json', 'vitest.config.ts']) cpSync(join(ROOT, file), join(dir, file)); - symlinkSync(join(ROOT, 'node_modules'), join(dir, 'node_modules'), 'dir'); - return dir; -} - -/** Applies every edit of one mutant, each of which must find its search text exactly once. */ -function applyMutant(dir: string, mutant: Mutant): Map { - const originals = new Map(); - - for (const edit of mutant.edits) { - const path = join(dir, edit.file); - if (!originals.has(path)) originals.set(path, readFileSync(path, 'utf8')); - const current = readFileSync(path, 'utf8'); - const hits = current.split(edit.from).length - 1; - if (hits !== 1) throw new Error(`${mutant.id}: search text found ${hits} times in ${edit.file}`); - writeFileSync(path, current.replace(edit.from, edit.to)); - } - - return originals; -} - -function main(): void { - const only = process.env.MUTANTS_ONLY?.split(','); - const mutants = only ? MUTANTS.filter((m) => only.includes(m.id)) : MUTANTS; - const dir = copyTree(); - const rows: Array<{ id: string; origin: string; models: string; result: string; failedTests: number }> = []; - - try { - const control = runSuite(dir); - if (!control.passed) - throw new Error('the unmutated copy fails the parity suite; no mutant result would mean anything'); - - for (const mutant of mutants) { - const originals = applyMutant(dir, mutant); - try { - const { passed, failed } = runSuite(dir); - rows.push({ - id: mutant.id, - origin: mutant.origin, - models: mutant.models, - result: passed ? 'SURVIVED' : 'killed', - failedTests: failed, - }); - process.stderr.write(`[mutants] ${mutant.id}: ${passed ? 'SURVIVED' : `killed (${failed} failing)`}\n`); - } finally { - for (const [path, original] of originals) writeFileSync(path, original); - } - } - } finally { - rmSync(dir, { recursive: true, force: true }); - } - - console.log('| mutant | edit | models | result | failing tests |'); - console.log('| --- | --- | --- | --- | --- |'); - for (const row of rows) - console.log(`| ${row.id} | ${row.origin} | ${row.models} | ${row.result} | ${row.failedTests} |`); - const killed = rows.filter((row) => row.result === 'killed').length; - console.log(`\n${killed}/${rows.length} killed`); - - // The guarantee this script makes: the real src/ was never touched. - execFileSync('git', ['diff', '--exit-code', '--', 'src'], { cwd: ROOT, stdio: 'inherit' }); - if (killed !== rows.length) process.exitCode = 1; -} - -main(); diff --git a/test/router-parity/mutants.ts b/test/router-parity/mutants.ts index dd74e72..cc7aa16 100644 --- a/test/router-parity/mutants.ts +++ b/test/router-parity/mutants.ts @@ -1,17 +1,27 @@ /** - * Mutation check for the router-parity corpus: does it catch the bugs a radix rewrite is likely to - * introduce? Each mutant is one targeted edit to a *temporary copy* of `src/`. The parity suite runs - * against that copy, and the mutant is killed if any test fails. + * Mutation check for the router-parity corpus: does it catch the bugs a radix router is likely to + * have? Each mutant is one targeted bug, applied as one or more edits to a *temporary copy* of + * `src/`. The suite runs against that copy, and the mutant is killed if any test fails. * * npm run parity:mutants * * Not part of `npm test`: it runs the suite once per mutant. `src/` in this checkout is never * written; the run ends by checking `git diff --exit-code src` to prove it. * - * Every mutant's search text must be found exactly once, so a refactor that moves the code fails - * loudly instead of silently testing an unmutated copy. CARD-07 replaces this matcher, so after it - * lands these mutants describe the old code. The kill table recorded in the PR is the evidence for - * the corpus as frozen; mutants against the new code belong to CARD-07. + * The suite is the frozen corpus (`test/router-parity`, untouched) plus `test/router-index.test.ts`, + * which covers the radix index's own seams (local/remote trees, index lifetime) that the corpus's + * flat-array matcher cases cannot reach. + * + * Retargeted at the radix index in CARD-07 with the owner's approval: the original search texts + * were lines of the linear scan that CARD-07 removed. The first twelve mutants keep their names and + * the bug each one models; `origin` says whether the edit is the original one (`verbatim`) or the + * same bug written against the index (`retargeted`). The rest (`radix`) model risks the index + * itself introduced. + * + * Every edit's search text must be found exactly once and must change the file, so a refactor that + * moves the code fails the run loudly instead of silently testing an unmutated copy. A mutant may + * need more than one edit when the index holds the same rule in two places (the walk filters, then + * `matchCompiled` collects params); every edit models the same bug. */ import { spawnSync, execFileSync } from 'child_process'; import { cpSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'fs'; @@ -19,116 +29,292 @@ import os from 'os'; import { join, resolve } from 'path'; const ROOT = resolve(__dirname, '..', '..'); +const ROUTER = 'src/http/router.ts'; -interface Mutant { - id: string; - models: string; +interface Edit { file: string; from: string; to: string; } -const ROUTER = 'src/http/router.ts'; +interface Mutant { + id: string; + models: string; + /** `verbatim`: the original edit. `retargeted`: the same bug, written against the index. `radix`: a risk of the index itself. */ + origin: 'verbatim' | 'retargeted' | 'radix'; + edits: Edit[]; +} export const MUTANTS: Mutant[] = [ { id: 'no-backtrack', models: 'no backtracking to a param branch once a static first segment was entered', - file: ROUTER, - from: ` const params = matchCompiled(compiled, pathSegs, decoded); - if (params) return { params, def };`, - to: ` const params = matchCompiled(compiled, pathSegs, decoded); - if (params) return { params, def }; - const first = compiled.segments[0]; - if (compiled.segments.length > 1 && first?.kind === 'static' && first.value === pathSegs[0]) return undefined;`, + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` if (next) walk(next, search, segs, depth + 1);`, + to: ` if (next && depth === 0) return walk(next, search, segs, depth + 1); + if (next) walk(next, search, segs, depth + 1);`, + }, + ], }, { id: 'precedence-swapped', models: 'static and plain-param precedence swapped', - file: ROUTER, - from: `.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),`, - to: `.map((segment) => (segment.kind === 'static' ? 1 : segment.constraint ? 2 : 3)),`, + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: `.map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)),`, + to: `.map((segment) => (segment.kind === 'static' ? 1 : segment.constraint ? 2 : 3)),`, + }, + ], }, { id: 'tie-last-registered', models: 'equal-rank tie broken by the last-registered declaration', - file: ROUTER, - from: `for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));`, - to: `for (const bucket of byMethod.values()) bucket.reverse().sort((a, b) => moreSpecific(b.compiled, a.compiled));`, + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled));`, + to: ` bucket.reverse().sort((a, b) => moreSpecific(b.compiled, a.compiled));`, + }, + ], }, { id: 'constraint-ignored', models: 'param constraint not tested during lookup', - file: ROUTER, - from: ` if (segment.constraint && !segment.constraint.test(value)) return undefined;\n`, - to: ``, + origin: 'retargeted', + edits: [ + { file: ROUTER, from: ` if (edge.constraint && !edge.constraint.test(value)) continue;\n`, to: `` }, + // the frozen mutant's own edit: without it the walk would pick a route whose params then fail to collect + { + file: ROUTER, + from: ` if (segment.constraint && !segment.constraint.test(value)) return undefined;\n`, + to: ``, + }, + ], }, { id: 'decode-before-split', models: 'path decoded before splitting, so %2F becomes a separator', - file: ROUTER, - from: ` return path.split('/').filter(Boolean);`, - to: ` return decodeURIComponent(path).split('/').filter(Boolean);`, + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: ` return path.split('/').filter(Boolean);`, + to: ` return decodeURIComponent(path).split('/').filter(Boolean);`, + }, + ], }, { id: 'catch-all-needs-segment', models: 'catch-all does not match zero segments', - file: ROUTER, - from: ` if (segment.kind === 'catchAll') { - params[segment.name]`, - to: ` if (segment.kind === 'catchAll') { - if (index >= pathSegs.length) return undefined; - params[segment.name]`, + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` if (node.catchAll.length) offer(search, node.catchAll);`, + to: ` if (node.catchAll.length && depth < segs.length) offer(search, node.catchAll);`, + }, + ], }, { id: 'implicit-head-from-stream', models: 'implicit HEAD served by a streaming GET', - file: ROUTER, - from: `routes.filter((route) => route.transport === 'buffer'),`, - to: `routes,`, + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` const fallback = findRoute(index, 'GET', search, isBuffered);`, + to: ` const fallback = findRoute(index, 'GET', search);`, + }, + ], }, { id: 'allow-one-pattern', models: 'Allow built from the first matching pattern only', - file: ROUTER, - from: ` for (const route of routes) { - if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue;`, - to: ` let onlyPattern: string | undefined; - for (const route of routes) { - if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue; - onlyPattern ??= route.pattern; - if (route.pattern !== onlyPattern) continue;`, + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('GET').add('HEAD'); + else if (findRoute(index, method, search)) methods.add(method);`, + to: ` const hit = findRoute(index, method, search); + if (!hit) continue; + onlyPattern ??= hit.def.pattern; + if (hit.def.pattern !== onlyPattern) continue; + methods.add(method); + if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('HEAD');`, + }, + { + file: ROUTER, + from: ` const methods = new Set();\n\n for (const method of index.methods) {`, + to: ` const methods = new Set();\n let onlyPattern: string | undefined;\n\n for (const method of index.methods) {`, + }, + ], }, { id: 'allow-order', models: 'Allow in discovery order instead of canonical order', - file: ROUTER, - from: ` return [...methods].sort((a, b) => {`, - // The original sort is left behind as unreachable code, which the transpiler accepts. - to: ` return [...methods]; + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: ` return [...methods].sort((a, b) => {`, + to: ` return [...methods]; [...methods].sort((a, b) => {`, + }, + ], }, { id: 'trailing-slash-kept', models: 'trailing slash not normalized', - file: ROUTER, - from: ` const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;`, - to: ` const normalized = resolved;`, + origin: 'verbatim', + edits: [ + { + file: ROUTER, + from: ` const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved;`, + to: ` const normalized = resolved;`, + }, + ], }, { id: 'ws-ranked-like-http', models: 'WS upgrades ranked by specificity like HTTP instead of first registered', - file: 'src/http/ws-core.ts', - from: ` .find((entry) => entry.params);`, - to: ` .filter((entry) => entry.params) + origin: 'verbatim', + edits: [ + { + file: 'src/http/ws-core.ts', + from: ` .find((entry) => entry.params);`, + to: ` .filter((entry) => entry.params) .sort((a, b) => a.def.pattern.split(':').length - b.def.pattern.split(':').length)[0];`, + }, + ], }, { id: 'case-insensitive-static', models: 'static segments compared case-insensitively', - file: ROUTER, - from: ` if (segment.value !== pathSegs[index]) return undefined;`, - to: ` if (segment.value.toLowerCase() !== pathSegs[index].toLowerCase()) return undefined;`, + origin: 'retargeted', + edits: [ + { + file: ROUTER, + from: ` const next = node.statics.size ? node.statics.get(segment) : undefined;`, + to: ` const next = [...node.statics].find(([key]) => key.toLowerCase() === segment.toLowerCase())?.[1];`, + }, + // the frozen mutant's own edit, so the chosen route also collects its params + { + file: ROUTER, + from: ` if (segment.value !== pathSegs[index]) return undefined;`, + to: ` if (segment.value.toLowerCase() !== pathSegs[index].toLowerCase()) return undefined;`, + }, + ], + }, + { + id: 'static-map-ignores-method', + models: 'the exact-path map for static routes is shared across methods, so a hit ignores the method', + origin: 'radix', + edits: [ + { + file: ROUTER, + from: ` const trees = new Map();`, + to: ` const trees = new Map();\n const anyMethod = new Map();`, + }, + { + file: ROUTER, + from: ` const tree: MethodTree = { root: newNode(), exactPaths: new Map() };`, + to: ` const tree: MethodTree = { root: newNode(), exactPaths: anyMethod };`, + }, + ], + }, + { + id: 'static-map-shadows-earlier', + models: 'the exact-path map lists identical static routes newest first, shadowing the earlier, higher-ranked one', + origin: 'radix', + edits: [{ file: ROUTER, from: ` if (same) same.push(terminal);`, to: ` if (same) same.unshift(terminal);` }], + }, + { + id: 'prune-bound-off-by-one', + models: 'branch pruning off by one, so the next-ranked route wins over the better one it pruned', + origin: 'radix', + edits: [ + { + file: ROUTER, + from: ` if (search.best && node.min >= search.best.rank) return;`, + to: ` if (search.best && node.min + 1 >= search.best.rank) return;`, + }, + ], + }, + { + id: 'empty-skip-prunes-match', + models: 'the empty-collection skip also skips a node with exactly one static child', + origin: 'radix', + edits: [ + { + file: ROUTER, + from: ` const next = node.statics.size ? node.statics.get(segment) : undefined;`, + to: ` const next = node.statics.size > 1 ? node.statics.get(segment) : undefined;`, + }, + ], + }, + { + id: 'tie-goes-remote', + models: 'an equal-specificity tie between the local and remote trees goes to the remote route', + origin: 'radix', + edits: [{ file: ROUTER, from: ` return local.order < remote.order ? local : remote;`, to: ` return remote;` }], + }, + { + id: 'allow-local-only', + models: 'Allow, 405 and OPTIONS computed from the local tree only', + origin: 'radix', + edits: [ + { + file: ROUTER, + from: ` if (method === 'GET' && findRoute(index, method, search, isBuffered)) methods.add('GET').add('HEAD'); + else if (findRoute(index, method, search)) methods.add(method);`, + to: ` const localOnly = { ...index, remote: undefined }; + if (method === 'GET' && findRoute(localOnly, method, search, isBuffered)) methods.add('GET').add('HEAD'); + else if (findRoute(localOnly, method, search)) methods.add(method);`, + }, + ], + }, + { + id: 'implicit-head-local-only', + models: 'implicit HEAD ignores buffered GETs in the remote tree', + origin: 'radix', + edits: [ + { + file: ROUTER, + from: ` const fallback = findRoute(index, 'GET', search, isBuffered);`, + to: ` const fallback = findRoute({ ...index, remote: undefined }, 'GET', search, isBuffered);`, + }, + ], + }, + { + id: 'stale-index-served', + models: 'stale-index guard removed: the cache is keyed by array identity only', + origin: 'radix', + edits: [ + { + file: ROUTER, + from: ` if (cached?.size === routes.length) return cached;`, + to: ` if (cached) return cached;`, + }, + ], + }, + { + id: 'zero-catch-all-after-static-dead-end', + models: 'a zero-segment catch-all is not tried where the path ends on a node that only continues statically', + origin: 'radix', + edits: [ + { + file: ROUTER, + from: ` if (node.exact.length) offer(search, node.exact);\n } else {`, + to: ` if (node.exact.length) offer(search, node.exact);\n if (node.statics.size) return;\n } else {`, + }, + ], }, ]; @@ -140,6 +326,7 @@ function runSuite(dir: string): { passed: boolean; failed: number } { join(ROOT, 'node_modules/vitest/vitest.mjs'), 'run', 'test/router-parity', + 'test/router-index.test.ts', '--reporter=json', `--outputFile=${out}`, ], @@ -162,11 +349,41 @@ function copyTree(): string { return dir; } +/** Applies every edit of one mutant. Each search text must be found exactly once and must change the file. */ +function applyMutant(dir: string, mutant: Mutant): Map { + const originals = new Map(); + + try { + for (const edit of mutant.edits) { + const path = join(dir, edit.file); + if (!originals.has(path)) originals.set(path, readFileSync(path, 'utf8')); + const current = readFileSync(path, 'utf8'); + const hits = current.split(edit.from).length - 1; + if (hits !== 1) throw new Error(`${mutant.id}: search text found ${hits} times in ${edit.file}`); + const mutated = current.replace(edit.from, edit.to); + if (mutated === current) throw new Error(`${mutant.id}: edit left ${edit.file} unchanged`); + writeFileSync(path, mutated); + } + + for (const [path, original] of originals) + if (readFileSync(path, 'utf8') === original) throw new Error(`${mutant.id}: ${path} is identical after mutation`); + } catch (err) { + restore(originals); + throw err; + } + + return originals; +} + +function restore(originals: Map): void { + for (const [path, original] of originals) writeFileSync(path, original); +} + function main(): void { const only = process.env.MUTANTS_ONLY?.split(','); const mutants = only ? MUTANTS.filter((m) => only.includes(m.id)) : MUTANTS; const dir = copyTree(); - const rows: Array<{ id: string; models: string; result: string; failedTests: number }> = []; + const rows: Array<{ id: string; origin: string; models: string; result: string; failedTests: number }> = []; try { const control = runSuite(dir); @@ -174,32 +391,29 @@ function main(): void { throw new Error('the unmutated copy fails the parity suite; no mutant result would mean anything'); for (const mutant of mutants) { - const path = join(dir, mutant.file); - const original = readFileSync(path, 'utf8'); - const hits = original.split(mutant.from).length - 1; - if (hits !== 1) throw new Error(`${mutant.id}: search text found ${hits} times in ${mutant.file}`); - - writeFileSync(path, original.replace(mutant.from, mutant.to)); + const originals = applyMutant(dir, mutant); try { const { passed, failed } = runSuite(dir); rows.push({ id: mutant.id, + origin: mutant.origin, models: mutant.models, result: passed ? 'SURVIVED' : 'killed', failedTests: failed, }); process.stderr.write(`[mutants] ${mutant.id}: ${passed ? 'SURVIVED' : `killed (${failed} failing)`}\n`); } finally { - writeFileSync(path, original); + restore(originals); } } } finally { rmSync(dir, { recursive: true, force: true }); } - console.log('| mutant | models | result | failing tests |'); - console.log('| --- | --- | --- | --- |'); - for (const row of rows) console.log(`| ${row.id} | ${row.models} | ${row.result} | ${row.failedTests} |`); + console.log('| mutant | edit | models | result | failing tests |'); + console.log('| --- | --- | --- | --- | --- |'); + for (const row of rows) + console.log(`| ${row.id} | ${row.origin} | ${row.models} | ${row.result} | ${row.failedTests} |`); const killed = rows.filter((row) => row.result === 'killed').length; console.log(`\n${killed}/${rows.length} killed`); -- 2.54.1 From 5e0ae94ba20c4fce8a3f12b1974bd7e7ad7b960c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 11 Oct 2026 22:06:49 -0500 Subject: [PATCH 5/7] fix(router): walk the radix index without recursion The lookup walk recursed once per path segment, so a valid deep route such as 4,999 static segments followed by /:x threw RangeError where the linear matcher matched. Walk on an explicit stack instead, visiting frames in the same order, and cover the case through buildFetch. Signed-off-by: Diego Resendez --- src/http/router.ts | 62 +++++++++++++++++++++++++++++++-------- test/router-index.test.ts | 18 ++++++++++++ 2 files changed, 67 insertions(+), 13 deletions(-) diff --git a/src/http/router.ts b/src/http/router.ts index 66944ab..ab64bc0 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -543,35 +543,71 @@ function offer(search: Search, terminals: Terminal[]): void { } } +/** + * Pending walk frames, shared by every lookup. A frame is a node and its depth; `POST` marks the + * frame that offers a node's catch-alls once its children are done. The walk is synchronous and + * calls no user code, and each call pops only what it pushed, so sharing is safe. + */ +const stackNodes: RadixNode[] = []; +const stackDepths: number[] = []; +const POST = -1; + /** * Depth-first walk with backtracking: a static branch that dead-ends deeper falls back to its param, * constrained and catch-all siblings. Params are decoded after splitting, so `%2F` stays inside one * segment. Every branch that could still hold a better rank is visited; `min` prunes the rest. * + * It runs on an explicit stack, not recursion, so a deep path that the linear matcher accepts cannot + * overflow the call stack. Frames pop in the order the recursive walk visited them: static child, + * then params in insertion order, then the node's catch-alls. + * * The indexed loops and the empty-collection guards are measured, not style: at 10 routes the old * linear scan is a handful of string compares, and these keep the walk within D4 of it (FPRD-001). */ -function walk(node: RadixNode, search: Search, segs: string[], depth: number): void { - if (search.best && node.min >= search.best.rank) return; +function walk(root: RadixNode, search: Search, segs: string[]): void { + const base = stackNodes.length; + stackNodes.push(root); + stackDepths.push(0); + + while (stackNodes.length > base) { + const node = stackNodes.pop()!; + const depth = stackDepths.pop()!; + + if (depth === POST) { + offer(search, node.catchAll); + continue; + } + + if (search.best && node.min >= search.best.rank) continue; + + if (node.catchAll.length) { + stackNodes.push(node); + stackDepths.push(POST); + } + + if (depth === segs.length) { + if (node.exact.length) offer(search, node.exact); + continue; + } - if (depth === segs.length) { - if (node.exact.length) offer(search, node.exact); - } else { const segment = segs[depth]; - const next = node.statics.size ? node.statics.get(segment) : undefined; - if (next) walk(next, search, segs, depth + 1); - const params = node.params; - for (let i = 0; i < params.length; i++) { + for (let i = params.length - 1; i >= 0; i--) { const edge = params[i]; const value = (search.decoded[depth] ??= decodeSegment(segment)); if (edge.constraint && !edge.constraint.test(value)) continue; - walk(edge.node, search, segs, depth + 1); + stackNodes.push(edge.node); + stackDepths.push(depth + 1); + } + + const next = node.statics.size ? node.statics.get(segment) : undefined; + + if (next) { + stackNodes.push(next); + stackDepths.push(depth + 1); } } - - if (node.catchAll.length) offer(search, node.catchAll); } function searchTree( @@ -585,7 +621,7 @@ function searchTree( const exact = tree.exactPaths.get(search.path); if (exact) offer(search, exact); - if (!search.best) walk(tree.root, search, segmentsOf(search), 0); + if (!search.best) walk(tree.root, search, segmentsOf(search)); return search.best; } diff --git a/test/router-index.test.ts b/test/router-index.test.ts index 7338a5b..f241101 100644 --- a/test/router-index.test.ts +++ b/test/router-index.test.ts @@ -10,6 +10,7 @@ import { describe, it, expect } from 'vitest'; import * as live from '../src/http/router'; import type { RouteDef } from '../src/http/types'; +import { buildFetch } from '../src/http/web'; import * as oracle from './router-parity/oracle'; import { runScenario, type MatcherImpl, type Scenario } from './router-parity/matcher'; import { HAND_SCENARIOS, OWNER_SCENARIOS } from './router-parity/cases'; @@ -108,6 +109,23 @@ describe('radix index: ranking across branches', () => { }); }); +describe('radix index: deep paths', () => { + it('matches a param under 4,999 static segments without overflowing the call stack', async () => { + // Every static segment is one walk frame, so a recursive walk throws RangeError here. + const prefix = '/s'.repeat(4999); + const routes = [route('GET', `${prefix}/:x`)]; + const path = `${prefix}/a`; + + const expected = oracle.matchRoute(routes, 'GET', path); + expect(expected?.params).toEqual({ x: 'a' }); + expect(live.matchRoute(routes, 'GET', path)).toEqual(expected); + + const res = await buildFetch(routes, undefined)(new Request(`http://x${path}`)); + expect(res.status).toBe(200); + expect(await res.text()).toBe(`${prefix}/:x`); + }); +}); + describe('radix index: lifetime', () => { it('rebuilds when the array it was built from changes length', () => { const routes = [route('GET', '/a')]; -- 2.54.1 From 4de9f32e3110d2e0588b946d5e71c3d0695e9929 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 11 Oct 2026 22:07:17 -0500 Subject: [PATCH 6/7] test(router-parity): retarget walk mutants to the iterative walk Same four mutants (no-backtrack, catch-all-needs-segment, prune-bound-off-by-one, zero-catch-all-after-static-dead-end), patched at their new sites in the stack-based walk. 21/21 still killed. Signed-off-by: Diego Resendez --- test/router-parity/mutants.ts | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/test/router-parity/mutants.ts b/test/router-parity/mutants.ts index cc7aa16..13f6716 100644 --- a/test/router-parity/mutants.ts +++ b/test/router-parity/mutants.ts @@ -53,9 +53,14 @@ export const MUTANTS: Mutant[] = [ edits: [ { file: ROUTER, - from: ` if (next) walk(next, search, segs, depth + 1);`, - to: ` if (next && depth === 0) return walk(next, search, segs, depth + 1); - if (next) walk(next, search, segs, depth + 1);`, + from: ` const segment = segs[depth];\n`, + to: ` const segment = segs[depth]; + const first = depth === 0 ? node.statics.get(segment) : undefined; + if (first) { + stackNodes.push(first); + stackDepths.push(1); + continue; + }\n`, }, ], }, @@ -116,8 +121,8 @@ export const MUTANTS: Mutant[] = [ edits: [ { file: ROUTER, - from: ` if (node.catchAll.length) offer(search, node.catchAll);`, - to: ` if (node.catchAll.length && depth < segs.length) offer(search, node.catchAll);`, + from: ` if (node.catchAll.length) {`, + to: ` if (node.catchAll.length && depth < segs.length) {`, }, ], }, @@ -242,8 +247,8 @@ export const MUTANTS: Mutant[] = [ edits: [ { file: ROUTER, - from: ` if (search.best && node.min >= search.best.rank) return;`, - to: ` if (search.best && node.min + 1 >= search.best.rank) return;`, + from: ` if (search.best && node.min >= search.best.rank) continue;`, + to: ` if (search.best && node.min + 1 >= search.best.rank) continue;`, }, ], }, @@ -311,8 +316,8 @@ export const MUTANTS: Mutant[] = [ edits: [ { file: ROUTER, - from: ` if (node.exact.length) offer(search, node.exact);\n } else {`, - to: ` if (node.exact.length) offer(search, node.exact);\n if (node.statics.size) return;\n } else {`, + from: ` if (node.catchAll.length) {`, + to: ` if (node.catchAll.length && !(depth === segs.length && node.statics.size)) {`, }, ], }, -- 2.54.1 From a2b71e24721f786dbffaa8350f0206f946c68be9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 12 Oct 2026 13:47:53 -0500 Subject: [PATCH 7/7] fix(router): drop pending walk frames when a segment fails to decode The walk stack is shared across lookups. A malformed % escape threw out of decodeSegment with frames still pushed, so repeated direct matcher calls on such paths retained them. Truncate both arrays back to the entry length in a finally block, and check it with a test. Signed-off-by: Diego Resendez --- src/http/router.ts | 67 ++++++++++++++++++++++----------------- test/router-index.test.ts | 10 ++++++ 2 files changed, 48 insertions(+), 29 deletions(-) diff --git a/src/http/router.ts b/src/http/router.ts index ab64bc0..55173c4 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -552,6 +552,9 @@ const stackNodes: RadixNode[] = []; const stackDepths: number[] = []; const POST = -1; +/** @internal Pending frames left on the shared walk stack; zero between lookups. For tests. */ +export const walkStackSize = (): number => stackNodes.length; + /** * Depth-first walk with backtracking: a static branch that dead-ends deeper falls back to its param, * constrained and catch-all siblings. Params are decoded after splitting, so `%2F` stays inside one @@ -569,44 +572,50 @@ function walk(root: RadixNode, search: Search, segs: string[]): void { stackNodes.push(root); stackDepths.push(0); - while (stackNodes.length > base) { - const node = stackNodes.pop()!; - const depth = stackDepths.pop()!; + try { + while (stackNodes.length > base) { + const node = stackNodes.pop()!; + const depth = stackDepths.pop()!; - if (depth === POST) { - offer(search, node.catchAll); - continue; - } + if (depth === POST) { + offer(search, node.catchAll); + continue; + } - if (search.best && node.min >= search.best.rank) continue; + if (search.best && node.min >= search.best.rank) continue; - if (node.catchAll.length) { - stackNodes.push(node); - stackDepths.push(POST); - } + if (node.catchAll.length) { + stackNodes.push(node); + stackDepths.push(POST); + } - if (depth === segs.length) { - if (node.exact.length) offer(search, node.exact); - continue; - } + if (depth === segs.length) { + if (node.exact.length) offer(search, node.exact); + continue; + } - const segment = segs[depth]; - const params = node.params; + const segment = segs[depth]; + const params = node.params; - for (let i = params.length - 1; i >= 0; i--) { - const edge = params[i]; - const value = (search.decoded[depth] ??= decodeSegment(segment)); - if (edge.constraint && !edge.constraint.test(value)) continue; - stackNodes.push(edge.node); - stackDepths.push(depth + 1); - } + for (let i = params.length - 1; i >= 0; i--) { + const edge = params[i]; + const value = (search.decoded[depth] ??= decodeSegment(segment)); + if (edge.constraint && !edge.constraint.test(value)) continue; + stackNodes.push(edge.node); + stackDepths.push(depth + 1); + } - const next = node.statics.size ? node.statics.get(segment) : undefined; + const next = node.statics.size ? node.statics.get(segment) : undefined; - if (next) { - stackNodes.push(next); - stackDepths.push(depth + 1); + if (next) { + stackNodes.push(next); + stackDepths.push(depth + 1); + } } + } finally { + // A malformed `%` escape throws out of `decodeSegment` with frames still pending; drop them. + stackNodes.length = base; + stackDepths.length = base; } } diff --git a/test/router-index.test.ts b/test/router-index.test.ts index f241101..a7efb22 100644 --- a/test/router-index.test.ts +++ b/test/router-index.test.ts @@ -126,6 +126,16 @@ describe('radix index: deep paths', () => { }); }); +describe('radix index: malformed paths', () => { + it('leaves no frames on the shared walk stack when a segment fails to decode', () => { + // `/:rest*` pushes a pending catch-all frame before `/:id` decodes `%GG` and throws. + const routes = [route('GET', '/:id'), route('GET', '/:rest*')]; + for (let i = 0; i < 3; i++) expect(() => live.matchRoute(routes, 'GET', '/%GG')).toThrow(URIError); + expect(live.walkStackSize()).toBe(0); + expect(live.matchRoute(routes, 'GET', '/a')?.params).toEqual({ id: 'a' }); + }); +}); + describe('radix index: lifetime', () => { it('rebuilds when the array it was built from changes length', () => { const routes = [route('GET', '/a')]; -- 2.54.1