FPRD-001b CARD-07: replaces the linear, specificity-sorted HTTP route scan in src/http/router.ts with a radix index. Behaviour is unchanged: the frozen CARD-08 corpus passes without a single edit under test/router-parity/.
Refs #109. This does not close the issue: acceptance also needs CARD-09 (introspection) and CARD-10 (formal D4 evidence).
Design
Index shape. A segment trie per HTTP method, built from the finalized RouteDef[] using the segments compilePattern already produces. There is no second grammar, and compilePattern is untouched. Static children sit in a Map. Plain params share one edge, and constrained params get one edge per constraint source.
Ranking stays global. Each terminal carries rank: its position in exactly the bucket the linear matcher sorted (moreSpecific, stable, so declaration order breaks ties). The tree only decides which routes can match. The lowest rank among them decides which one does. The walk keeps the best rank it has reached and prunes any subtree whose min rank cannot beat it, so tree branch order never overrides the ranking. That covers overlapping constraints, equal-rank ties, a catch-all at one depth against a param at another, and a higher-ranked streaming GET against a lower-ranked buffered GET for implicit HEAD (the buffer filter runs inside the ranked search).
Backtracking. The walk is depth-first. A static branch that dead-ends deeper falls back to its param, constrained and catch-all siblings. A catch-all is offered at every node on the way back, so it matches zero or more segments. Params are decoded after splitting, so %2F stays inside one param. Decoded values are memoized per position, as before.
All-static fast path. All-static routes are also kept in a per-method map keyed by their normalized pattern. A hit there is provably the tree's best match: every other exact route matching that path has the same segment count with nothing more specific than static, and catch-alls rank below exact routes. So a static request is answered without splitting the path. A miss falls through to the walk.
Local and remote trees (owner decision, 2026-10-10).spliceRemoteScopes marks teapot routes (markRemoteRoute, an internal WeakSet; it is not in http/index.ts or any package export). The index files them in a second tree. A lookup queries both trees, and the more specific match wins via moreSpecific. On equal specificity the earlier array position wins, so local beats remote, as with [...local, ...remote]. A dev route after a remote one still loses a tie, exactly as before. Allow, 405, OPTIONS and implicit HEAD run over the union. An app with no remote routes has no remote tree and does one lookup.
allowedMethods. One indexed lookup per registered method. The buffered-GET lookup runs first and covers both GET and HEAD. Nothing is recompiled or rescanned on a miss. The canonical sort is unchanged.
Index lifetime. The cache is still keyed by array identity (WeakMap) and now also stores the array length. An array that grows or shrinks after its index was built is re-indexed, never served stale. buildAppFetch and listen() assemble local + remote + dev routes once after boot, so the index is built after the effective array is final. The old resolveRoute built a fresh filtered array for every implicit-HEAD request, so it re-indexed per HEAD; that is gone.
WebSocket. Untouched. matchWsRoute keeps its first-registered contract over matchPattern.
Introspection. Untouched. routePlans remains the source for graph(), explain() and openapi().
Known quirks (#124, #125, #126). Preserved as captured; the corpus checks them.
ponytail: ceilings:
src/http/router.ts, RadixNode: a segment trie with no compression of single-child static chains. Lookup cost already follows path depth, not route count.
Deliberate limit, documented in the cache comment: the staleness guard is by length. An in-place element replacement at the same length is not detected, and no caller does that.
Corpus
npx vitest run test/router-parity: 7 files, 150 tests pass. That covers 1,158 matcher cases (hand, owner, generator v1 and v2) differential against the oracle, plus app, WS, boot, mesh and introspection captures. Against 7ee7ab7, the only change under test/router-parity/ is mutants.ts. The parity tests, oracle, frozen JSON, manifest and bench/baseline are untouched. The edge runner also passes 1,158 matcher cases + 55 app.fetch cases.
New test/router-index.test.ts (10 tests) covers what the corpus can't reach. The corpus drives the matcher with flat arrays, so every matcher case lands in the local tree, and only 7 mesh app-level cases reach the remote one. This file replays every frozen scenario with its declarations split across both trees in four ways (all remote, second half, odd positions, first half) and requires the oracle's answer each time. It also covers M05-style cross-tree precedence, the cross-tree tie by array position, Allow and implicit HEAD over the union, streaming GET in one tree versus buffered GET in the other, the stale-index guard, and one case found by the mutant run: an exact param route that must beat a catch-all the walk reached first through a static branch (GET /a/:rest* vs GET /:x/b on /a/b). The corpus has no such pair, so an off-by-one pruning bound survived it; this test is checked against the oracle in both declaration orders.
Mutants
The owner approved editing test/router-parity/mutants.ts, the only file touched under test/router-parity/. Its search texts targeted lines of the linear scan this PR removes, so it refused to run against the new router. It is now retargeted at the index, and it is the single mutant check (npm run parity:mutants). The interim test/router-index-mutants.ts and parity:mutants:index are gone.
The original 12 keep their names and the bug each models. Six apply their original edit (verbatim); six are rewritten against the index (retargeted).
Nine new radix mutants cover risks the index introduced.
Suite: the untouched corpus plus test/router-index.test.ts.
Robustness: every edit must match exactly once and must change the file, or the run fails loudly. A failed edit restores the temp copy before aborting. Each mutant is restored in finally, and the run ends with git diff --exit-code src.
mutant
origin
killed by (failing tests)
no-backtrack
retargeted
13
precedence-swapped
verbatim
18
tie-last-registered
retargeted
16
constraint-ignored
retargeted
75
decode-before-split
verbatim
12
catch-all-needs-segment
retargeted
41
implicit-head-from-stream
retargeted
26
allow-one-pattern
retargeted
53
allow-order
verbatim
47
trailing-slash-kept
verbatim
78
ws-ranked-like-http
verbatim
4
case-insensitive-static
retargeted
9
static-map-ignores-method
radix
74
static-map-shadows-earlier
radix
6
prune-bound-off-by-one
radix
1 (the new router-index test)
empty-skip-prunes-match
radix
91
tie-goes-remote
radix
4
allow-local-only
radix
7
implicit-head-local-only
radix
7
stale-index-served
radix
1
zero-catch-all-after-static-dead-end
radix
14
21/21 killed.
Gates
gate
result
npm run lint
0 errors (50 pre-existing no-explicit-any warnings, none in router.ts)
npm run format:check
clean
npm run typecheck
clean (after build; it resolves dist/ through bench/servers, as on develop)
npm run typecheck:bench
clean
npm test
88 files, 813 tests pass
npm run complexity:check
every function ≤ 25 (limit unchanged)
npm run build
ok
npm run test:deno
36 passed, 0 failed
npm run test:bun
26 pass, 0 fail
npm run test:edge
PASS (incl. router parity, 1,158 + 55)
npm audit --omit=dev / --audit-level=moderate
0 vulnerabilities
Lookup performance (sanity check; the formal D4 record belongs to CARD-10)
Current head: stack-based walk (5e0ae94)
The review fixes replaced the recursive walk with an explicit stack (5e0ae94) and added a finally that resets the stack (a2b71e2, off the hot path). This run is one interleaved run of three routers, using the same method, image and cpuset as the run below. Load was 0.08 at start and 1.33 at end. Raw output is on jarvis in out-iter/.
routes
workload
stack walk / oracle
95% CI
D4 rule
verdict
recursive / oracle
10
static hit
−59.7%
−66.7% … −49.7%
no regression
pass
−48.7%
10
late param hit
+5.9%
−3.4% … +14.8%
no regression
pass
+7.7%
10
method miss
−6.2%
−7.7% … −3.3%
no regression
pass
−7.0%
10
path miss
−1.2%
−1.6% … −0.9%
no regression
pass
−3.6%
100
static hit
−50.3%
−53.6% … −47.4%
no regression
pass
−49.7%
100
late param hit
−55.5%
−56.8% … −55.1%
no regression
pass
−57.8%
100
method miss
−69.8%
−70.5% … −69.4%
no regression
pass
−70.3%
100
path miss
−79.4%
−79.5% … −79.3%
no regression
pass
−80.1%
500
static hit
−50.2%
−52.8% … −47.7%
no regression
pass
−47.2%
500
late param hit
−86.6%
−86.8% … −86.3%
CI upper ≤ −20%
pass
−86.9%
500
method miss
−93.7%
−93.8% … −93.7%
CI upper ≤ −20%
pass
−93.6%
500
path miss
−96.0%
−96.0% … −96.0%
CI upper ≤ −20%
pass
−96.1%
Original head: recursive walk (815f761)
npm run bench:lookup with LOOKUP_ROUTERS="oracle=test/router-parity/oracle.ts,radix=src/http/router.ts", using the same harness defaults as the baseline. It ran on jarvis in ~/bench/green-tea-radix/, with docker run --rm --cpuset-cpus 6,7,14,15 node:22 (the same image as the baseline, sha256:5647be70…). The branch was copied with git archive at 815f761 and installed with npm ci --ignore-scripts. Interleaved, 4 processes × 21 rounds = 84 paired rounds per cell; median B/A with a bootstrap 95% CI. Load was 0.37 at start and 0.91 at end. Raw output is retained on jarvis (out/) and is not committed.
routes
workload
radix / oracle
95% CI
D4 rule
verdict
10
static hit
0.368 (−63.2%)
−68.2% … −55.7%
no regression
pass
10
late param hit
1.035 (+3.4%)
−5.0% … +12.6%
no regression
pass
10
method miss
0.902 (−9.8%)
−11.0% … −8.9%
no regression
pass
10
path miss
0.929 (−7.1%)
−9.2% … −5.2%
no regression
pass
100
static hit
0.458 (−54.2%)
−57.1% … −51.7%
no regression
pass
100
late param hit
0.405 (−59.5%)
−59.6% … −57.8%
no regression
pass
100
method miss
0.296 (−70.4%)
−70.7% … −70.3%
no regression
pass
100
path miss
0.188 (−81.2%)
−81.5% … −80.7%
no regression
pass
500
static hit
0.456 (−54.4%)
−58.6% … −50.5%
no regression
pass
500
late param hit
0.122 (−87.8%)
−87.9% … −87.3%
CI upper ≤ −20%
pass
500
method miss
0.061 (−93.9%)
−93.9% … −93.8%
CI upper ≤ −20%
pass
500
path miss
0.038 (−96.3%)
−96.3% … −96.2%
CI upper ≤ −20%
pass
The 10-route late param hit is the cell to watch. It is the only one with a positive point estimate, and its 95% CI sits inside that cell's own A/A noise band from the baseline (+4.1%, −1.6 … +9.8%). The first version of this branch failed D4 there and on static hits: static hit was +39% to +52% at all sizes, and the 10-route method miss was +24%. The exact-path map and the empty-collection guards in the walk are what fixed it, each measured as an A/B on jarvis. Earlier runs of near-identical variants put that cell at +5.0% to +10.9%, every one under the D4 limit (lower CI bound ≤ +4.2%), so expect CARD-10's run to land anywhere in that range.
Deviations
src/app/index.ts: the only change is wrapping the spliced remote RouteDef in markRemoteRoute(...). The diff is larger than that because of re-indentation.
FPRD-001b **CARD-07**: replaces the linear, specificity-sorted HTTP route scan in `src/http/router.ts` with a radix index. Behaviour is unchanged: the frozen CARD-08 corpus passes without a single edit under `test/router-parity/`.
Refs #109. This does not close the issue: acceptance also needs CARD-09 (introspection) and CARD-10 (formal D4 evidence).
## Design
- **Index shape.** A segment trie per HTTP method, built from the finalized `RouteDef[]` using the segments `compilePattern` already produces. There is no second grammar, and `compilePattern` is untouched. Static children sit in a `Map`. Plain params share one edge, and constrained params get one edge per constraint source.
- **Ranking stays global.** Each terminal carries `rank`: its position in exactly the bucket the linear matcher sorted (`moreSpecific`, stable, so declaration order breaks ties). The tree only decides which routes *can* match. The lowest rank among them decides which one *does*. The walk keeps the best rank it has reached and prunes any subtree whose `min` rank cannot beat it, so tree branch order never overrides the ranking. That covers overlapping constraints, equal-rank ties, a catch-all at one depth against a param at another, and a higher-ranked streaming GET against a lower-ranked buffered GET for implicit HEAD (the buffer filter runs inside the ranked search).
- **Backtracking.** The walk is depth-first. A static branch that dead-ends deeper falls back to its param, constrained and catch-all siblings. A catch-all is offered at every node on the way back, so it matches zero or more segments. Params are decoded after splitting, so `%2F` stays inside one param. Decoded values are memoized per position, as before.
- **All-static fast path.** All-static routes are also kept in a per-method map keyed by their normalized pattern. A hit there is provably the tree's best match: every other exact route matching that path has the same segment count with nothing more specific than static, and catch-alls rank below exact routes. So a static request is answered without splitting the path. A miss falls through to the walk.
- **Local and remote trees (owner decision, 2026-10-10).** `spliceRemoteScopes` marks teapot routes (`markRemoteRoute`, an internal `WeakSet`; it is not in `http/index.ts` or any package export). The index files them in a second tree. A lookup queries both trees, and the more specific match wins via `moreSpecific`. On equal specificity the earlier array position wins, so local beats remote, as with `[...local, ...remote]`. A dev route after a remote one still loses a tie, exactly as before. `Allow`, 405, OPTIONS and implicit HEAD run over the union. An app with no remote routes has no remote tree and does one lookup.
- **`allowedMethods`.** One indexed lookup per registered method. The buffered-GET lookup runs first and covers both GET and HEAD. Nothing is recompiled or rescanned on a miss. The canonical sort is unchanged.
- **Index lifetime.** The cache is still keyed by array identity (`WeakMap`) and now also stores the array length. An array that grows or shrinks after its index was built is re-indexed, never served stale. `buildAppFetch` and `listen()` assemble local + remote + dev routes once after boot, so the index is built after the effective array is final. The old `resolveRoute` built a fresh filtered array for every implicit-HEAD request, so it re-indexed per HEAD; that is gone.
- **WebSocket.** Untouched. `matchWsRoute` keeps its first-registered contract over `matchPattern`.
- **Introspection.** Untouched. `routePlans` remains the source for `graph()`, `explain()` and `openapi()`.
- **Known quirks (#124, #125, #126).** Preserved as captured; the corpus checks them.
`ponytail:` ceilings:
- `src/http/router.ts`, `RadixNode`: a segment trie with no compression of single-child static chains. Lookup cost already follows path depth, not route count.
Deliberate limit, documented in the cache comment: the staleness guard is by length. An in-place element replacement at the same length is not detected, and no caller does that.
## Corpus
`npx vitest run test/router-parity`: **7 files, 150 tests pass**. That covers 1,158 matcher cases (hand, owner, generator v1 and v2) differential against the oracle, plus app, WS, boot, mesh and introspection captures. Against `7ee7ab7`, the only change under `test/router-parity/` is `mutants.ts`. The parity tests, oracle, frozen JSON, manifest and `bench/baseline` are untouched. The edge runner also passes **1,158 matcher cases + 55 `app.fetch` cases**.
New `test/router-index.test.ts` (10 tests) covers what the corpus can't reach. The corpus drives the matcher with flat arrays, so every matcher case lands in the local tree, and only 7 mesh app-level cases reach the remote one. This file replays **every frozen scenario** with its declarations split across both trees in four ways (all remote, second half, odd positions, first half) and requires the oracle's answer each time. It also covers M05-style cross-tree precedence, the cross-tree tie by array position, `Allow` and implicit HEAD over the union, streaming GET in one tree versus buffered GET in the other, the stale-index guard, and one case found by the mutant run: an exact param route that must beat a catch-all the walk reached first through a static branch (`GET /a/:rest*` vs `GET /:x/b` on `/a/b`). The corpus has no such pair, so an off-by-one pruning bound survived it; this test is checked against the oracle in both declaration orders.
## Mutants
The owner approved editing `test/router-parity/mutants.ts`, the only file touched under `test/router-parity/`. Its search texts targeted lines of the linear scan this PR removes, so it refused to run against the new router. It is now retargeted at the index, and it is the single mutant check (`npm run parity:mutants`). The interim `test/router-index-mutants.ts` and `parity:mutants:index` are gone.
- **The original 12** keep their names and the bug each models. Six apply their original edit (`verbatim`); six are rewritten against the index (`retargeted`).
- **Nine new `radix` mutants** cover risks the index introduced.
- **Suite:** the untouched corpus plus `test/router-index.test.ts`.
- **Robustness:** every edit must match exactly once and must change the file, or the run fails loudly. A failed edit restores the temp copy before aborting. Each mutant is restored in `finally`, and the run ends with `git diff --exit-code src`.
| mutant | origin | killed by (failing tests) |
| --- | --- | ---: |
| no-backtrack | retargeted | 13 |
| precedence-swapped | verbatim | 18 |
| tie-last-registered | retargeted | 16 |
| constraint-ignored | retargeted | 75 |
| decode-before-split | verbatim | 12 |
| catch-all-needs-segment | retargeted | 41 |
| implicit-head-from-stream | retargeted | 26 |
| allow-one-pattern | retargeted | 53 |
| allow-order | verbatim | 47 |
| trailing-slash-kept | verbatim | 78 |
| ws-ranked-like-http | verbatim | 4 |
| case-insensitive-static | retargeted | 9 |
| static-map-ignores-method | radix | 74 |
| static-map-shadows-earlier | radix | 6 |
| prune-bound-off-by-one | radix | 1 (the new `router-index` test) |
| empty-skip-prunes-match | radix | 91 |
| tie-goes-remote | radix | 4 |
| allow-local-only | radix | 7 |
| implicit-head-local-only | radix | 7 |
| stale-index-served | radix | 1 |
| zero-catch-all-after-static-dead-end | radix | 14 |
**21/21 killed.**
## Gates
| gate | result |
| --- | --- |
| `npm run lint` | 0 errors (50 pre-existing `no-explicit-any` warnings, none in `router.ts`) |
| `npm run format:check` | clean |
| `npm run typecheck` | clean (after `build`; it resolves `dist/` through `bench/servers`, as on `develop`) |
| `npm run typecheck:bench` | clean |
| `npm test` | 88 files, 813 tests pass |
| `npm run complexity:check` | every function ≤ 25 (limit unchanged) |
| `npm run build` | ok |
| `npm run test:deno` | 36 passed, 0 failed |
| `npm run test:bun` | 26 pass, 0 fail |
| `npm run test:edge` | PASS (incl. router parity, 1,158 + 55) |
| `npm audit --omit=dev` / `--audit-level=moderate` | 0 vulnerabilities |
## Lookup performance (sanity check; the formal D4 record belongs to CARD-10)
### Current head: stack-based walk (`5e0ae94`)
The review fixes replaced the recursive walk with an explicit stack (`5e0ae94`) and added a `finally` that resets the stack (`a2b71e2`, off the hot path). This run is one interleaved run of three routers, using the same method, image and cpuset as the run below. Load was 0.08 at start and 1.33 at end. Raw output is on jarvis in `out-iter/`.
| routes | workload | stack walk / oracle | 95% CI | D4 rule | verdict | recursive / oracle |
| ---: | --- | ---: | --- | --- | --- | ---: |
| 10 | static hit | −59.7% | −66.7% … −49.7% | no regression | pass | −48.7% |
| 10 | late param hit | +5.9% | −3.4% … +14.8% | no regression | pass | +7.7% |
| 10 | method miss | −6.2% | −7.7% … −3.3% | no regression | pass | −7.0% |
| 10 | path miss | −1.2% | −1.6% … −0.9% | no regression | pass | −3.6% |
| 100 | static hit | −50.3% | −53.6% … −47.4% | no regression | pass | −49.7% |
| 100 | late param hit | −55.5% | −56.8% … −55.1% | no regression | pass | −57.8% |
| 100 | method miss | −69.8% | −70.5% … −69.4% | no regression | pass | −70.3% |
| 100 | path miss | −79.4% | −79.5% … −79.3% | no regression | pass | −80.1% |
| 500 | static hit | −50.2% | −52.8% … −47.7% | no regression | pass | −47.2% |
| 500 | late param hit | −86.6% | −86.8% … −86.3% | CI upper ≤ −20% | pass | −86.9% |
| 500 | method miss | −93.7% | −93.8% … −93.7% | CI upper ≤ −20% | pass | −93.6% |
| 500 | path miss | −96.0% | −96.0% … −96.0% | CI upper ≤ −20% | pass | −96.1% |
### Original head: recursive walk (`815f761`)
`npm run bench:lookup` with `LOOKUP_ROUTERS="oracle=test/router-parity/oracle.ts,radix=src/http/router.ts"`, using the same harness defaults as the baseline. It ran on jarvis in `~/bench/green-tea-radix/`, with `docker run --rm --cpuset-cpus 6,7,14,15 node:22` (the same image as the baseline, `sha256:5647be70…`). The branch was copied with `git archive` at `815f761` and installed with `npm ci --ignore-scripts`. Interleaved, 4 processes × 21 rounds = 84 paired rounds per cell; median B/A with a bootstrap 95% CI. Load was 0.37 at start and 0.91 at end. Raw output is retained on jarvis (`out/`) and is not committed.
| routes | workload | radix / oracle | 95% CI | D4 rule | verdict |
| ---: | --- | ---: | --- | --- | --- |
| 10 | static hit | 0.368 (−63.2%) | −68.2% … −55.7% | no regression | pass |
| 10 | late param hit | 1.035 (+3.4%) | −5.0% … +12.6% | no regression | pass |
| 10 | method miss | 0.902 (−9.8%) | −11.0% … −8.9% | no regression | pass |
| 10 | path miss | 0.929 (−7.1%) | −9.2% … −5.2% | no regression | pass |
| 100 | static hit | 0.458 (−54.2%) | −57.1% … −51.7% | no regression | pass |
| 100 | late param hit | 0.405 (−59.5%) | −59.6% … −57.8% | no regression | pass |
| 100 | method miss | 0.296 (−70.4%) | −70.7% … −70.3% | no regression | pass |
| 100 | path miss | 0.188 (−81.2%) | −81.5% … −80.7% | no regression | pass |
| 500 | static hit | 0.456 (−54.4%) | −58.6% … −50.5% | no regression | pass |
| 500 | late param hit | 0.122 (−87.8%) | −87.9% … −87.3% | CI upper ≤ −20% | pass |
| 500 | method miss | 0.061 (−93.9%) | −93.9% … −93.8% | CI upper ≤ −20% | pass |
| 500 | path miss | 0.038 (−96.3%) | −96.3% … −96.2% | CI upper ≤ −20% | pass |
The 10-route late param hit is the cell to watch. It is the only one with a positive point estimate, and its 95% CI sits inside that cell's own A/A noise band from the baseline (+4.1%, −1.6 … +9.8%). The first version of this branch failed D4 there and on static hits: static hit was +39% to +52% at all sizes, and the 10-route method miss was +24%. The exact-path map and the empty-collection guards in the walk are what fixed it, each measured as an A/B on jarvis. Earlier runs of near-identical variants put that cell at +5.0% to +10.9%, every one under the D4 limit (lower CI bound ≤ +4.2%), so expect CARD-10's run to land anywhere in that range.
## Deviations
- `src/app/index.ts`: the only change is wrapping the spliced remote `RouteDef` in `markRemoteRoute(...)`. The diff is larger than that because of re-indentation.
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 <diego.resendez@zero-oneit.com>
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 <diego.resendez@zero-oneit.com>
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 <diego.resendez@zero-oneit.com>
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 <diego.resendez@zero-oneit.com>
P2 — deep valid routes now overflow the lookup stack (src/http/router.ts:554-575). The new walk recurses once per path segment without a depth limit. A GET route with 4,999 static segments followed by /:x and a matching 10,000-character URL succeeds in the frozen linear oracle (x === 'a'), but matchRoute throws RangeError: Maximum call stack size exceeded. I also reproduced the uncaught rejection through buildFetch(routes, undefined)(new Request(...)); this is a behavior regression for a route and URL the framework accepts. Static-only routes hide the issue through exactPaths. Please use an iterative traversal (or another approach that preserves matching for supported path depths) and add a regression case through the fetch adapter.
**P2 — deep valid routes now overflow the lookup stack (`src/http/router.ts:554-575`).** The new `walk` recurses once per path segment without a depth limit. A GET route with 4,999 static segments followed by `/:x` and a matching 10,000-character URL succeeds in the frozen linear oracle (`x === 'a'`), but `matchRoute` throws `RangeError: Maximum call stack size exceeded`. I also reproduced the uncaught rejection through `buildFetch(routes, undefined)(new Request(...))`; this is a behavior regression for a route and URL the framework accepts. Static-only routes hide the issue through `exactPaths`. Please use an iterative traversal (or another approach that preserves matching for supported path depths) and add a regression case through the fetch adapter.
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 <diego.resendez@zero-oneit.com>
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 <diego.resendez@zero-oneit.com>
Fixed in 5e0ae94. walk now runs on an explicit stack instead of recursion. Frames pop in the same order the recursive walk visited them: static child, then params in insertion order, then the node's catch-alls. Pruning is unchanged.
Regression test:test/router-index.test.ts › "radix index: deep paths". It declares GET + 4,999 static segments + /:x and checks matchRoute against the oracle ({ x: 'a' }). It also checks the same request through buildFetch(routes, undefined), which returns 200. With the previous walk, the test fails with RangeError: Maximum call stack size exceeded.
Mutants (4de9f32): four mutants patched the recursive walk. I moved their patch sites to the new walk: no-backtrack, catch-all-needs-segment, prune-bound-off-by-one and zero-catch-all-after-static-dead-end. The site check caught the stale sites, and npm run parity:mutants reports 21/21 killed.
Gates: lint, typecheck, format, complexity, 812 Node tests, Deno 36, Bun 26, edge (parity 1158 + 55), build, and npm audit at 0.
Lookup performance after the change (sanity check)
Run on jarvis with the same method as before: node:22, --cpuset-cpus 6,7,14,15, interleaved, 84 paired rounds per cell, bootstrap 95% CI. Three routers ran in one interleaved run: the oracle, the previous recursive walk and the new stack walk. Load was 0.08 at start and 1.33 at end.
routes
workload
iter / oracle
95% CI
recursive / oracle
10
static hit
−59.7%
−66.7% … −49.7%
−48.7%
10
late param hit
+5.9%
−3.4% … +14.8%
+7.7%
10
method miss
−6.2%
−7.7% … −3.3%
−7.0%
10
path miss
−1.2%
−1.6% … −0.9%
−3.6%
100
late param hit
−55.5%
−56.8% … −55.1%
−57.8%
500
late param hit
−86.6%
−86.8% … −86.3%
−86.9%
500
method miss
−93.7%
−93.8% … −93.7%
−93.6%
500
path miss
−96.0%
−96.0% … −96.0%
−96.1%
D4: every cell passes. On the 10-route late-param cell the CI lower bound is −3.4%, below +5%. At 500 routes every CI upper bound is far below −20%.
Recursive vs. stack walk: the two are within about 1–3 points on every cell.
Raw output: kept on jarvis in out-iter/, not committed.
Formal record: the formal D4 record is still CARD-10.
Fixed in `5e0ae94`. `walk` now runs on an explicit stack instead of recursion. Frames pop in the same order the recursive walk visited them: static child, then params in insertion order, then the node's catch-alls. Pruning is unchanged.
- **Regression test:** `test/router-index.test.ts` › "radix index: deep paths". It declares `GET` + 4,999 static segments + `/:x` and checks `matchRoute` against the oracle (`{ x: 'a' }`). It also checks the same request through `buildFetch(routes, undefined)`, which returns 200. With the previous walk, the test fails with `RangeError: Maximum call stack size exceeded`.
- **Mutants (`4de9f32`):** four mutants patched the recursive walk. I moved their patch sites to the new walk: no-backtrack, catch-all-needs-segment, prune-bound-off-by-one and zero-catch-all-after-static-dead-end. The site check caught the stale sites, and `npm run parity:mutants` reports 21/21 killed.
- **Gates:** lint, typecheck, format, complexity, 812 Node tests, Deno 36, Bun 26, edge (parity 1158 + 55), build, and `npm audit` at 0.
### Lookup performance after the change (sanity check)
Run on jarvis with the same method as before: `node:22`, `--cpuset-cpus 6,7,14,15`, interleaved, 84 paired rounds per cell, bootstrap 95% CI. Three routers ran in one interleaved run: the oracle, the previous recursive walk and the new stack walk. Load was 0.08 at start and 1.33 at end.
| routes | workload | iter / oracle | 95% CI | recursive / oracle |
|---|---|---|---|---|
| 10 | static hit | −59.7% | −66.7% … −49.7% | −48.7% |
| 10 | late param hit | +5.9% | −3.4% … +14.8% | +7.7% |
| 10 | method miss | −6.2% | −7.7% … −3.3% | −7.0% |
| 10 | path miss | −1.2% | −1.6% … −0.9% | −3.6% |
| 100 | late param hit | −55.5% | −56.8% … −55.1% | −57.8% |
| 500 | late param hit | −86.6% | −86.8% … −86.3% | −86.9% |
| 500 | method miss | −93.7% | −93.8% … −93.7% | −93.6% |
| 500 | path miss | −96.0% | −96.0% … −96.0% | −96.1% |
- **D4:** every cell passes. On the 10-route late-param cell the CI lower bound is −3.4%, below +5%. At 500 routes every CI upper bound is far below −20%.
- **Recursive vs. stack walk:** the two are within about 1–3 points on every cell.
- **Raw output:** kept on jarvis in `out-iter/`, not committed.
- **Formal record:** the formal D4 record is still CARD-10.
Second-round review at 4de9f32 (follow-up to review #4): the deep-route regression is fixed. The iterative walk matches the frozen oracle on the 4,999-static-segment + /:x case, and the new buildFetch regression returns 200. I reviewed the revised traversal and retargeted mutants; Node 812/812, Deno 36/36, Bun 26/26, edge parity, lint (0 errors), format, typecheck, bench typecheck, build, complexity, and 21/21 mutants pass. No merge-blocking correctness issue found in this round.
P3 follow-up at src/http/router.ts:567-611: stackNodes and stackDepths are module-scoped, but walk() does not restore their entry lengths if decodeSegment() throws. With routes /:id and /:rest*, repeated direct matchRoute(routes, 'GET', '/%GG') calls each retain a pending catch-all frame. In a Node 26 probe, 100,000 caught URI errors retained about 1.86 MiB after GC. A subsequent valid match still works. Standard buildFetch returns 400 before lookup for this malformed path, so the observed accumulation is confined to direct matcher calls. Please clear both arrays to base in a finally block (or keep per-call stacks) and add one error-path check when this is addressed.
The formal D4 benchmark on the iterative head remains CARD-10 work; the PR description's lookup figures are from the pre-fix implementation (815f761).
Second-round review at `4de9f32` (follow-up to review #4): the deep-route regression is fixed. The iterative walk matches the frozen oracle on the 4,999-static-segment + `/:x` case, and the new `buildFetch` regression returns 200. I reviewed the revised traversal and retargeted mutants; Node 812/812, Deno 36/36, Bun 26/26, edge parity, lint (0 errors), format, typecheck, bench typecheck, build, complexity, and 21/21 mutants pass. No merge-blocking correctness issue found in this round.
P3 follow-up at `src/http/router.ts:567-611`: `stackNodes` and `stackDepths` are module-scoped, but `walk()` does not restore their entry lengths if `decodeSegment()` throws. With routes `/:id` and `/:rest*`, repeated direct `matchRoute(routes, 'GET', '/%GG')` calls each retain a pending catch-all frame. In a Node 26 probe, 100,000 caught URI errors retained about 1.86 MiB after GC. A subsequent valid match still works. Standard `buildFetch` returns 400 before lookup for this malformed path, so the observed accumulation is confined to direct matcher calls. Please clear both arrays to `base` in a `finally` block (or keep per-call stacks) and add one error-path check when this is addressed.
The formal D4 benchmark on the iterative head remains CARD-10 work; the PR description's lookup figures are from the pre-fix implementation (`815f761`).
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 <diego.resendez@zero-oneit.com>
Fixed in a2b71e2. walk now resets stackNodes and stackDepths to base in a finally, so a URIError from decodeSegment no longer leaves frames on the shared stack.
Regression test:test/router-index.test.ts › "radix index: malformed paths". With /:id + /:rest*, it calls matchRoute on /%GG three times; each call throws, the stack is still empty afterwards, and a later /a still matches :id. Without the finally, the stack holds 3 frames.
Stack check: the test reads the stack through an internal walkStackSize() export. src/http/router.ts is not a package entry, so nothing public changes.
Gates: 813 Node tests, Deno 36, Bun 26, edge, build, npm audit 0, and 21/21 mutants killed.
The PR description now shows the stack-walk benchmark (5e0ae94, jarvis) above the original 815f761 table. The formal D4 record stays with CARD-10, run on the merged head.
Fixed in `a2b71e2`. `walk` now resets `stackNodes` and `stackDepths` to `base` in a `finally`, so a `URIError` from `decodeSegment` no longer leaves frames on the shared stack.
- **Regression test:** `test/router-index.test.ts` › "radix index: malformed paths". With `/:id` + `/:rest*`, it calls `matchRoute` on `/%GG` three times; each call throws, the stack is still empty afterwards, and a later `/a` still matches `:id`. Without the `finally`, the stack holds 3 frames.
- **Stack check:** the test reads the stack through an internal `walkStackSize()` export. `src/http/router.ts` is not a package entry, so nothing public changes.
- **Gates:** 813 Node tests, Deno 36, Bun 26, edge, build, `npm audit` 0, and 21/21 mutants killed.
The PR description now shows the stack-walk benchmark (`5e0ae94`, jarvis) above the original `815f761` table. The formal D4 record stays with CARD-10, run on the merged head.
chrnx
merged commit cb123e3774 into develop2026-10-12 18:54:47 +00:00
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
FPRD-001b CARD-07: replaces the linear, specificity-sorted HTTP route scan in
src/http/router.tswith a radix index. Behaviour is unchanged: the frozen CARD-08 corpus passes without a single edit undertest/router-parity/.Refs #109. This does not close the issue: acceptance also needs CARD-09 (introspection) and CARD-10 (formal D4 evidence).
Design
RouteDef[]using the segmentscompilePatternalready produces. There is no second grammar, andcompilePatternis untouched. Static children sit in aMap. Plain params share one edge, and constrained params get one edge per constraint source.rank: its position in exactly the bucket the linear matcher sorted (moreSpecific, stable, so declaration order breaks ties). The tree only decides which routes can match. The lowest rank among them decides which one does. The walk keeps the best rank it has reached and prunes any subtree whoseminrank cannot beat it, so tree branch order never overrides the ranking. That covers overlapping constraints, equal-rank ties, a catch-all at one depth against a param at another, and a higher-ranked streaming GET against a lower-ranked buffered GET for implicit HEAD (the buffer filter runs inside the ranked search).%2Fstays inside one param. Decoded values are memoized per position, as before.spliceRemoteScopesmarks teapot routes (markRemoteRoute, an internalWeakSet; it is not inhttp/index.tsor any package export). The index files them in a second tree. A lookup queries both trees, and the more specific match wins viamoreSpecific. On equal specificity the earlier array position wins, so local beats remote, as with[...local, ...remote]. A dev route after a remote one still loses a tie, exactly as before.Allow, 405, OPTIONS and implicit HEAD run over the union. An app with no remote routes has no remote tree and does one lookup.allowedMethods. One indexed lookup per registered method. The buffered-GET lookup runs first and covers both GET and HEAD. Nothing is recompiled or rescanned on a miss. The canonical sort is unchanged.WeakMap) and now also stores the array length. An array that grows or shrinks after its index was built is re-indexed, never served stale.buildAppFetchandlisten()assemble local + remote + dev routes once after boot, so the index is built after the effective array is final. The oldresolveRoutebuilt a fresh filtered array for every implicit-HEAD request, so it re-indexed per HEAD; that is gone.matchWsRoutekeeps its first-registered contract overmatchPattern.routePlansremains the source forgraph(),explain()andopenapi().ponytail:ceilings:src/http/router.ts,RadixNode: a segment trie with no compression of single-child static chains. Lookup cost already follows path depth, not route count.Deliberate limit, documented in the cache comment: the staleness guard is by length. An in-place element replacement at the same length is not detected, and no caller does that.
Corpus
npx vitest run test/router-parity: 7 files, 150 tests pass. That covers 1,158 matcher cases (hand, owner, generator v1 and v2) differential against the oracle, plus app, WS, boot, mesh and introspection captures. Against7ee7ab7, the only change undertest/router-parity/ismutants.ts. The parity tests, oracle, frozen JSON, manifest andbench/baselineare untouched. The edge runner also passes 1,158 matcher cases + 55app.fetchcases.New
test/router-index.test.ts(10 tests) covers what the corpus can't reach. The corpus drives the matcher with flat arrays, so every matcher case lands in the local tree, and only 7 mesh app-level cases reach the remote one. This file replays every frozen scenario with its declarations split across both trees in four ways (all remote, second half, odd positions, first half) and requires the oracle's answer each time. It also covers M05-style cross-tree precedence, the cross-tree tie by array position,Allowand implicit HEAD over the union, streaming GET in one tree versus buffered GET in the other, the stale-index guard, and one case found by the mutant run: an exact param route that must beat a catch-all the walk reached first through a static branch (GET /a/:rest*vsGET /:x/bon/a/b). The corpus has no such pair, so an off-by-one pruning bound survived it; this test is checked against the oracle in both declaration orders.Mutants
The owner approved editing
test/router-parity/mutants.ts, the only file touched undertest/router-parity/. Its search texts targeted lines of the linear scan this PR removes, so it refused to run against the new router. It is now retargeted at the index, and it is the single mutant check (npm run parity:mutants). The interimtest/router-index-mutants.tsandparity:mutants:indexare gone.verbatim); six are rewritten against the index (retargeted).radixmutants cover risks the index introduced.test/router-index.test.ts.finally, and the run ends withgit diff --exit-code src.router-indextest)21/21 killed.
Gates
npm run lintno-explicit-anywarnings, none inrouter.ts)npm run format:checknpm run typecheckbuild; it resolvesdist/throughbench/servers, as ondevelop)npm run typecheck:benchnpm testnpm run complexity:checknpm run buildnpm run test:denonpm run test:bunnpm run test:edgenpm audit --omit=dev/--audit-level=moderateLookup performance (sanity check; the formal D4 record belongs to CARD-10)
Current head: stack-based walk (
5e0ae94)The review fixes replaced the recursive walk with an explicit stack (
5e0ae94) and added afinallythat resets the stack (a2b71e2, off the hot path). This run is one interleaved run of three routers, using the same method, image and cpuset as the run below. Load was 0.08 at start and 1.33 at end. Raw output is on jarvis inout-iter/.Original head: recursive walk (
815f761)npm run bench:lookupwithLOOKUP_ROUTERS="oracle=test/router-parity/oracle.ts,radix=src/http/router.ts", using the same harness defaults as the baseline. It ran on jarvis in~/bench/green-tea-radix/, withdocker run --rm --cpuset-cpus 6,7,14,15 node:22(the same image as the baseline,sha256:5647be70…). The branch was copied withgit archiveat815f761and installed withnpm ci --ignore-scripts. Interleaved, 4 processes × 21 rounds = 84 paired rounds per cell; median B/A with a bootstrap 95% CI. Load was 0.37 at start and 0.91 at end. Raw output is retained on jarvis (out/) and is not committed.The 10-route late param hit is the cell to watch. It is the only one with a positive point estimate, and its 95% CI sits inside that cell's own A/A noise band from the baseline (+4.1%, −1.6 … +9.8%). The first version of this branch failed D4 there and on static hits: static hit was +39% to +52% at all sizes, and the 10-route method miss was +24%. The exact-path map and the empty-collection guards in the walk are what fixed it, each measured as an A/B on jarvis. Earlier runs of near-identical variants put that cell at +5.0% to +10.9%, every one under the D4 limit (lower CI bound ≤ +4.2%), so expect CARD-10's run to land anywhere in that range.
Deviations
src/app/index.ts: the only change is wrapping the spliced remoteRouteDefinmarkRemoteRoute(...). The diff is larger than that because of re-indentation.P2 — deep valid routes now overflow the lookup stack (
src/http/router.ts:554-575). The newwalkrecurses once per path segment without a depth limit. A GET route with 4,999 static segments followed by/:xand a matching 10,000-character URL succeeds in the frozen linear oracle (x === 'a'), butmatchRoutethrowsRangeError: Maximum call stack size exceeded. I also reproduced the uncaught rejection throughbuildFetch(routes, undefined)(new Request(...)); this is a behavior regression for a route and URL the framework accepts. Static-only routes hide the issue throughexactPaths. Please use an iterative traversal (or another approach that preserves matching for supported path depths) and add a regression case through the fetch adapter.Fixed in
5e0ae94.walknow runs on an explicit stack instead of recursion. Frames pop in the same order the recursive walk visited them: static child, then params in insertion order, then the node's catch-alls. Pruning is unchanged.test/router-index.test.ts› "radix index: deep paths". It declaresGET+ 4,999 static segments +/:xand checksmatchRouteagainst the oracle ({ x: 'a' }). It also checks the same request throughbuildFetch(routes, undefined), which returns 200. With the previous walk, the test fails withRangeError: Maximum call stack size exceeded.4de9f32): four mutants patched the recursive walk. I moved their patch sites to the new walk: no-backtrack, catch-all-needs-segment, prune-bound-off-by-one and zero-catch-all-after-static-dead-end. The site check caught the stale sites, andnpm run parity:mutantsreports 21/21 killed.npm auditat 0.Lookup performance after the change (sanity check)
Run on jarvis with the same method as before:
node:22,--cpuset-cpus 6,7,14,15, interleaved, 84 paired rounds per cell, bootstrap 95% CI. Three routers ran in one interleaved run: the oracle, the previous recursive walk and the new stack walk. Load was 0.08 at start and 1.33 at end.out-iter/, not committed.Second-round review at
4de9f32(follow-up to review #4): the deep-route regression is fixed. The iterative walk matches the frozen oracle on the 4,999-static-segment +/:xcase, and the newbuildFetchregression returns 200. I reviewed the revised traversal and retargeted mutants; Node 812/812, Deno 36/36, Bun 26/26, edge parity, lint (0 errors), format, typecheck, bench typecheck, build, complexity, and 21/21 mutants pass. No merge-blocking correctness issue found in this round.P3 follow-up at
src/http/router.ts:567-611:stackNodesandstackDepthsare module-scoped, butwalk()does not restore their entry lengths ifdecodeSegment()throws. With routes/:idand/:rest*, repeated directmatchRoute(routes, 'GET', '/%GG')calls each retain a pending catch-all frame. In a Node 26 probe, 100,000 caught URI errors retained about 1.86 MiB after GC. A subsequent valid match still works. StandardbuildFetchreturns 400 before lookup for this malformed path, so the observed accumulation is confined to direct matcher calls. Please clear both arrays tobasein afinallyblock (or keep per-call stacks) and add one error-path check when this is addressed.The formal D4 benchmark on the iterative head remains CARD-10 work; the PR description's lookup figures are from the pre-fix implementation (
815f761).Fixed in
a2b71e2.walknow resetsstackNodesandstackDepthstobasein afinally, so aURIErrorfromdecodeSegmentno longer leaves frames on the shared stack.test/router-index.test.ts› "radix index: malformed paths". With/:id+/:rest*, it callsmatchRouteon/%GGthree times; each call throws, the stack is still empty afterwards, and a later/astill matches:id. Without thefinally, the stack holds 3 frames.walkStackSize()export.src/http/router.tsis not a package entry, so nothing public changes.npm audit0, and 21/21 mutants killed.The PR description now shows the stack-walk benchmark (
5e0ae94, jarvis) above the original815f761table. The formal D4 record stays with CARD-10, run on the merged head.