4 Commits
Author SHA1 Message Date
chrnx 71fc027134 perf(bench): re-baseline lookup on jarvis with the interleaved harness
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 35s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
The first baseline came from a laptop on battery, with one router per process,
run one after the other. It moves to battery-run/ for reference. The new
baseline is the interleaved A/A run (live matcher as A, byte-identical oracle
as B) on jarvis.

Setup: Ryzen 7 3700X, cpuset 6,7,14,15 (two idle physical cores and their SMT
siblings), node:22 container, Node 22.23.1, load average 0.27-0.79, no CI job
running. 4 processes x 21 rounds give 84 paired rounds per cell.

Live medians in ns per lookup (static hit, late param, method miss, path miss):
  10 routes:   185, 328, 800, 626
  100 routes:  201, 878, 2525, 3054
  500 routes:  202, 2931, 11904, 15514

A/A noise floor (oracle/live median ratio, 95% CI): at 10 routes, static hit
-13.7..+11.9% and late param -1.6..+9.8%; misses within +-4.4%. At 100 and 500
routes, offsets are systematic but within about 3%.

In-process, the module imported first runs about 20% faster on the 10-route
static hit. Alternating import order per process removes the bias from the
median but not from that cell's CI. A 5% limit there cannot be resolved with
this method and sample size, so this is recorded for the D4 decision. The 20%
improvement target at 500 routes is far outside the noise.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:44:53 -05:00
chrnx ee7fdec541 perf(bench): interleave lookup comparisons and report B/A with a bootstrap CI
The first baseline ran each router in its own process, one after another, so
drift and background load landed on whichever side ran later. Comparing two
medians taken minutes apart cannot resolve a 5% threshold.

bench:lookup now loads every router into one process. In each cell it warms
every router, then takes one sample from each per round, alternating the
order: AB, BA, AB. There are at least 15 rounds per cell per run (default 21)
over 4 fresh processes, and module import order also alternates per run.
Every router after the first is reported against the first as the median of
the per-round paired B/A ratios, with a percentile-bootstrap 95% CI (4000
resamples, fixed seed, so the same samples always give the same interval).
With a single router it reports absolute medians as before.

The record now includes hostname, the effective cpuset when run in a Linux
container, and any LOOKUP_* note variables. The harness still runs on any
machine with Node 22.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:41:15 -05:00
chrnx 32caa21308 test(router): add a mutation check for the parity corpus
A frozen corpus is only worth what it catches. npm run parity:mutants applies 12
targeted mutants to a temporary copy of src/, one at a time, and runs the parity
suite against each. Every mutant models a bug a radix rewrite could plausibly
introduce:

  no backtracking to a param branch     static/param precedence swapped
  equal-rank tie to last-registered     constraint ignored
  decode before splitting (%2F)         catch-all needs a segment
  implicit HEAD from a streaming GET    Allow from one pattern only
  Allow in discovery order              trailing slash not normalized
  WS ranked like HTTP                   case-insensitive static match

All 12 are killed (4 to 74 failing tests each), so no corpus case had to be
added. A mutant whose search text is not found exactly once fails the run rather
than silently testing an unmutated copy. The real src/ is never written, and
the run ends with git diff --exit-code src. It is not part of npm test because
it runs the suite once per mutant.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:39:38 -05:00
chrnx 684795a2de test(router): run the parity differential on Deno, Bun and workerd
The matcher comparison does not depend on the runtime, so it should run on every
runtime core supports. Only the Node suite ran it before.

The comparison and the app.fetch fixtures move into differential.ts and
app-fixture.ts, which use neither vitest nor a file API. Each runtime passes in
a loader for the frozen JSON. The vitest files use the same modules, plus a
Node check that the neutral runners report no mismatch, so the two paths cannot
drift.

- Deno and Bun: test/{deno,bun}/router-parity.test.ts run all 1158 frozen
  matcher cases (hand-picked, owner, generated v1 and v2, WS) through the oracle
  and the live router, plus the 55 app.fetch cases.
- workerd: test/edge/parity-worker.ts bundles the frozen JSON and runs the
  same checks; test/edge/run.ts adds the phase after its existing assertions.

The Node-socket, WS-upgrade, boot and mesh captures stay Node-only: they need
http.request, the ws client, or a mesh peer on a port.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:38:36 -05:00
27 changed files with 10167 additions and 2021 deletions

No files matched your search

+1
View File
@@ -21,6 +21,7 @@ coverage/
# Edge (Miniflare) test bundle artifact # Edge (Miniflare) test bundle artifact
test/edge/_worker.mjs test/edge/_worker.mjs
test/edge/_parity-worker.mjs
# Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs # Bun writes this on `bun install`, and nothing here consumes it: `npm run test:bun` runs
# `bun test` against the node_modules npm installed, which package-lock.json already pins. # `bun test` against the node_modules npm installed, which package-lock.json already pins.
+61 -69
View File
@@ -1,90 +1,82 @@
# Pre-radix router baseline — `ed47836` # Pre-radix router baseline — `ed47836`
The performance half of the CARD-08 parity corpus (FPRD-001, #109). Captured before any CARD-07 The performance half of the CARD-08 parity corpus (FPRD-001, #109), captured before any CARD-07
router change; immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures the router change and immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures
radix index with the **same harness, same defaults, same machine class**, and compares against the radix index with the **same harness and defaults, on the same host, cpuset and image**, running
these files. Do not re-run into this directory: a new capture goes in a new directory. `LOOKUP_ROUTERS="base=<ed47836 router>,head=src/http/router.ts"`. Do not re-run into this directory:
a new capture goes in a new directory.
## Files ## Files
| File | What it is | | File | What it is |
|---|---| |---|---|
| `lookup-raw.json` | **The D4 baseline.** `bench:lookup` on the live linear matcher: environment, method, every sample of every run, and the summary. | | `lookup-raw.json` | **The D4 baseline.** Interleaved `bench:lookup` with the live linear matcher as A and the byte-identical frozen oracle as B: environment, method, every sample of every round, and the summary. The live column gives the absolute baseline; the B/A ratios give the A/A noise floor. |
| `lookup-summary.txt` | The table `bench:lookup` printed for that run. | | `lookup-summary.txt` | The tables that run printed. |
| `lookup-aa-raw.json`, `lookup-aa-summary.txt` | A/A noise check: the live router against the byte-identical frozen oracle (`test/router-parity/oracle.ts`), same alternating protocol. Any difference here is noise. | | `load.txt` | `uptime` and running CI job containers, before and after. |
| `compare-e2e-raw.json`, `compare-e2e-summary.txt`, `compare-e2e-stderr.txt` | `npm run bench:compare`, run once with this tree as both base and head. **End-to-end req/s signal only**: 50/200 *filler* routes plus base routes, not 10/100/500 total, and not lookup time. It cannot decide D4. | | `battery-run/` | The superseded first capture (laptop on battery, sequential harness), kept for reference, including its `bench:compare` end-to-end req/s run. |
| `load.txt` | `uptime` before and after each run. |
## Environment ## Environment
| | | | | |
|---|---| |---|---|
| Hardware | Apple M4 Max (`Mac16,5`), 16 cores (12 performance + 4 efficiency), 64 GiB | | Host | jarvis (homelab), Ubuntu 24.04.3 LTS, kernel 6.8.0-138-generic, x86_64 |
| Power | **On battery** (84%, discharging) for every run. macOS may manage clocks differently on AC; run the CARD-10 comparison on the same power source, or re-capture both on AC. | | CPU | AMD Ryzen 7 3700X, 8 cores / 16 threads, 2 × 16 MiB L3, governor `schedutil` (host default; not changed) |
| OS | macOS 27.0.1 (build 26A434), Darwin 27.0.0 arm64 | | Memory | 62.7 GiB |
| Node | v22.22.2 (V8 12.4.254.21-node.39) | | Isolation | `docker run --rm --cpuset-cpus 6,7,14,15`: physical cores 6 and 7 plus their SMT siblings, both on the second CCX. All 16 CPUs were 0.0–0.8% busy in a 5 s sample beforehand. |
| Packages | `@green-tea/core@26.9.0-beta.2`; tsx 4.23.5, typescript 5.9.3, vitest 4.1.11, autocannon 8.0.0 (from `package-lock.json`) | | Container | `node:22` (`sha256:5647be70…`), Node v22.23.1, V8 12.4.254.21-node.56; Docker 29.1.3 |
| Core revision | Router source at `ed47836c9820c47bf4ed5e902d91e019abdb110a`. The harness ran from `98ea948` (this branch), whose `src/` is byte-identical to `ed47836` — the branch adds only tests and bench files. | | Power | Not applicable (mains-powered server) |
| Env vars | `LOOKUP_OUT` only (and `LOOKUP_ROUTERS` for the A/A run); no `NODE_OPTIONS`. Recorded in each raw file under `meta.env`. | | Load | 1-minute load 0.27 before, 0.79 after; no CI job containers running (see `load.txt`). jarvis also runs long-lived services (payments-automation, open-webui, windmill, the Gitea act_runner, alloy, beszel), none of them pinned off these cores. |
| Load | 1-minute load average 2.4–3.4 on 16 cores throughout (see `load.txt` and `meta.loadavgAtStart/End`). Foreground apps were a browser and the window server; nothing else CPU-bound. | | Revision | Router at `ed47836c9820c47bf4ed5e902d91e019abdb110a`; harness `ee7fdec`, whose `src/` is byte-identical to `ed47836`. Copied with `git archive`, `npm ci --ignore-scripts` in the container. |
| Env vars | Only `LOOKUP_*` (recorded in `meta.env`); no `NODE_OPTIONS`. |
## Method (`bench/lookup.ts`, defaults) ## Method (`bench/lookup.ts` at `ee7fdec`, defaults)
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`. Normalization is excluded. - **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`.
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**. - **Route counts:** 10, 100 and 500 **total registered HTTP routes**, from the recorded generator (`meta.method.routeGenerator`).
- **Generator:** N−2 fillers cycling `GET /res{k}/items`, `POST /res{k}/items`, `GET /res{k}/items/:id`, `PUT /res{k}/items/:id(\d+)`, `GET /res{k}/files/:path*` (k = ⌊i/5⌋), then `GET /static/target/leaf`, then `GET /late/:group/:id` declared last. - **Workloads:** static hit, late parameter hit, method miss, path miss; each answer is asserted before timing.
- **Workloads:** static hit `GET /static/target/leaf`; late parameter hit `GET /late/g1/42`; method miss `DELETE /static/target/leaf` (Allow `GET, HEAD, OPTIONS`); path miss `GET /nowhere/at/all`. Each answer is asserted before timing. - **Interleaving:** for each cell, every router is warmed for 250 ms (also calibrating ≈25 ms samples), then 21 rounds of one sample per router with the order alternating AB / BA.
- **Order:** for each run, for each router (order alternates per run), for count 10 → 100 → 500, for the four workloads in the order above. - **Repetitions:** 4 fresh processes, with module import order alternating per process → 84 paired rounds per cell. Every sample is kept.
- **Warm-up:** 250 ms per cell, time-boxed; it also calibrates iterations so one sample lasts ≈25 ms (iteration counts are stored per cell). - **Statistics:** absolute = median ns per lookup over all 84 samples; ratio = median of the 84 per-round B/A ratios, with a percentile-bootstrap 95% CI (4000 resamples, seed 10908).
- **Repetitions:** 5 runs, each a fresh child process; 21 samples per cell per run → 105 samples per cell. Every sample is kept.
- **Statistic:** median ns per lookup over all 105 samples. Run spread = (max − min of the five per-run medians) / median.
## Baseline (median ns per lookup, `lookup-raw.json`) ## Baseline: live linear matcher (median ns per lookup)
| Routes | Static hit | Late param hit | Method miss | Path miss | | Routes | Workload | live median ns | run medians (ns) | run spread |
|---:|---:|---:|---:|---:| |---:|---|---:|---|---:|
| 10 | 61.3 (spread 17.5%) | 123.3 (6.2%) | 313.1 (4.6%) | 247.1 (6.8%) | | 10 | static hit | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
| 100 | 67.6 (8.0%) | 343.4 (2.1%) | 1 263.7 (3.5%) | 1 463.3 (3.2%) | | 10 | late param hit | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
| 500 | 67.8 (7.5%) | 1 326.8 (16.5%) | 6 732.2 (6.5%) | 8 973.4 (2.0%) | | 10 | method miss | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
| 10 | path miss | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
| 100 | static hit | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
| 100 | late param hit | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
| 100 | method miss | 2,525 | 2,424 / 2,514 / 2,580 / 2,531 | 6.2% |
| 100 | path miss | 3,054 | 2,965 / 3,024 / 3,114 / 3,071 | 4.9% |
| 500 | static hit | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
| 500 | late param hit | 2,931 | 2,830 / 2,804 / 2,980 / 3,016 | 7.2% |
| 500 | method miss | 11,904 | 11,635 / 11,518 / 11,946 / 12,031 | 4.3% |
| 500 | path miss | 15,514 | 15,103 / 14,972 / 15,665 / 16,034 | 6.8% |
## Noise floor (A/A, `lookup-aa-raw.json`) ## A/A noise floor: identical code, oracle / live
Identical matcher code under two labels, alternating order per run. Median difference | Routes | Workload | oracle / live median | 95% CI |
(oracle − live) / live: |---:|---|---:|---|
| 10 | static hit | 0.9507 (-4.9%) | -13.7% … +11.9% |
| 10 | late param hit | 1.0415 (+4.1%) | -1.6% … +9.8% |
| 10 | method miss | 0.9809 (-1.9%) | -4.4% … +0.8% |
| 10 | path miss | 0.9919 (-0.8%) | -3.2% … +1.4% |
| 100 | static hit | 1.0082 (+0.8%) | -1.9% … +4.5% |
| 100 | late param hit | 1.0247 (+2.5%) | +1.9% … +2.9% |
| 100 | method miss | 1.0055 (+0.6%) | +0.3% … +0.7% |
| 100 | path miss | 1.0165 (+1.7%) | +1.2% … +1.9% |
| 500 | static hit | 1.0107 (+1.1%) | -2.2% … +4.5% |
| 500 | late param hit | 0.9838 (-1.6%) | -2.2% … +0.8% |
| 500 | method miss | 1.0197 (+2.0%) | +1.6% … +2.3% |
| 500 | path miss | 1.0161 (+1.6%) | +0.5% … +2.6% |
| Routes | Static hit | Late param hit | Method miss | Path miss | **For D4:**
|---:|---:|---:|---:|---:|
| 10 | +5.2% | 0.0% | +1.2% | +0.2% |
| 100 | −0.1% | −0.8% | −0.1% | +0.1% |
| 500 | −2.7% | +0.3% | −0.4% | +0.1% |
**For D4:** with no code difference at all, the 10-route static hit already moves 5.2% — the - **Import order.** In-process, the module imported first is faster on the cheapest cell. At 10-route static hit (≈180 ns) the per-run medians swap by about 20% when the import order swaps (run 1: live 156, oracle 200 ns; run 2: live 188, oracle 162 ns). Alternating the import order removes that bias from the median, but it leaves that cell's 95% CI at −13.7 … +11.9%. A ≤5% regression limit cannot be resolved there with this method and sample size.
size of the proposed ≤5% regression limit — and per-run medians at 10 routes spread 4.5–17.5%. - **Other 10-route cells.** The CIs are within about ±10% (late parameter hit −1.6 … +9.8%), and the misses are within ±4.4%.
That cell is ~60 ns, where a few nanoseconds of timer and scheduling noise are a large fraction. - **100 and 500 routes.** Identical code shows small but systematic offsets of up to +2.9%, with CIs that exclude 1. Treat anything inside ±3% as indistinguishable from no change.
The ≥20% improvement at 500 routes is well clear of the noise (≤2.7% A/A, ≤16.5% spread on a - **500 routes.** The ≥20% improvement target is far outside the noise in every cell.
1.3–9 µs operation). Whether D4's 10-route limit applies per workload, to a mean across workloads,
or needs more runs is an owner decision; this baseline does not make it.
## End-to-end signal (`bench:compare`, req/s — not lookup time) The options for D4 are to apply the 10-route limit to the miss and late-parameter cells only, to require more rounds for the static cell, or to restate the limit relative to this measured floor. That decision belongs to the owner.
Run once, A/A: `AB_BASE` pointed at this same tree, so base and head are identical code. Defaults:
3 rounds × 10 s per case after a 10 s warm-up, 100 connections, alternating side order. Load
average 2.8–3.3 throughout. A few short parity-test runs (seconds each) happened during this
~22-minute run; the lookup runs above had nothing else running.
| Scenario | base req/s | head req/s | Δ |
|---|---:|---:|---:|
| hello | 88,212 | 88,236 | +0.0% |
| param | 86,508 | 85,885 | −0.7% |
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% |
| steps5 | 74,359 | 73,975 | −0.5% |
| validate (POST) | 70,607 | 69,903 | −1.0% |
| hello + security | 83,913 | 83,802 | −0.1% |
| hello + cors predicate | 82,028 | 80,445 | −1.9% |
| preflight + cors predicate | 114,377 | 114,010 | −0.3% |
| param, 50 routes | 82,476 | 82,045 | −0.5% |
| param, 200 routes | 72,957 | 73,306 | +0.5% |
Every row's sample ranges overlap. So with no code change, end-to-end throughput moves up to
±1.9%; the route-width rows show that 200 filler routes already cost ~12% req/s against
`param` with none.
@@ -0,0 +1,94 @@
# Superseded: first baseline, laptop on battery — `ed47836`
> Kept for reference only. **The baseline is `../README.md`**, captured on jarvis with the
> interleaved harness. This run used the earlier sequential harness (`98ea948`), one router per
> process, on a laptop running on battery.
The performance half of the CARD-08 parity corpus (FPRD-001, #109). Captured before any CARD-07
router change; immutable through CARD-07 review, like `test/router-parity/`. CARD-10 measures the
radix index with the **same harness, same defaults, same machine class**, and compares against
these files. Do not re-run into this directory: a new capture goes in a new directory.
## Files
| File | What it is |
|---|---|
| `lookup-raw.json` | **The D4 baseline.** `bench:lookup` on the live linear matcher: environment, method, every sample of every run, and the summary. |
| `lookup-summary.txt` | The table `bench:lookup` printed for that run. |
| `lookup-aa-raw.json`, `lookup-aa-summary.txt` | A/A noise check: the live router against the byte-identical frozen oracle (`test/router-parity/oracle.ts`), same alternating protocol. Any difference here is noise. |
| `compare-e2e-raw.json`, `compare-e2e-summary.txt`, `compare-e2e-stderr.txt` | `npm run bench:compare`, run once with this tree as both base and head. **End-to-end req/s signal only**: 50/200 *filler* routes plus base routes, not 10/100/500 total, and not lookup time. It cannot decide D4. |
| `load.txt` | `uptime` before and after each run. |
## Environment
| | |
|---|---|
| Hardware | Apple M4 Max (`Mac16,5`), 16 cores (12 performance + 4 efficiency), 64 GiB |
| Power | **On battery** (84%, discharging) for every run. macOS may manage clocks differently on AC; run the CARD-10 comparison on the same power source, or re-capture both on AC. |
| OS | macOS 27.0.1 (build 26A434), Darwin 27.0.0 arm64 |
| Node | v22.22.2 (V8 12.4.254.21-node.39) |
| Packages | `@green-tea/core@26.9.0-beta.2`; tsx 4.23.5, typescript 5.9.3, vitest 4.1.11, autocannon 8.0.0 (from `package-lock.json`) |
| Core revision | Router source at `ed47836c9820c47bf4ed5e902d91e019abdb110a`. The harness ran from `98ea948` (this branch), whose `src/` is byte-identical to `ed47836` — the branch adds only tests and bench files. |
| Env vars | `LOOKUP_OUT` only (and `LOOKUP_ROUTERS` for the A/A run); no `NODE_OPTIONS`. Recorded in each raw file under `meta.env`. |
| Load | 1-minute load average 2.4–3.4 on 16 cores throughout (see `load.txt` and `meta.loadavgAtStart/End`). Foreground apps were a browser and the window server; nothing else CPU-bound. |
## Method (`bench/lookup.ts`, defaults)
- **Operation:** `resolveRoute(routes, method, path)`, and on `undefined`, `allowedMethods(routes, path)` — what `dispatch` does after `normalizeRequestPath`. Normalization is excluded.
- **Route counts:** 10, 100 and 500 **total registered HTTP routes**.
- **Generator:** N−2 fillers cycling `GET /res{k}/items`, `POST /res{k}/items`, `GET /res{k}/items/:id`, `PUT /res{k}/items/:id(\d+)`, `GET /res{k}/files/:path*` (k = ⌊i/5⌋), then `GET /static/target/leaf`, then `GET /late/:group/:id` declared last.
- **Workloads:** static hit `GET /static/target/leaf`; late parameter hit `GET /late/g1/42`; method miss `DELETE /static/target/leaf` (Allow `GET, HEAD, OPTIONS`); path miss `GET /nowhere/at/all`. Each answer is asserted before timing.
- **Order:** for each run, for each router (order alternates per run), for count 10 → 100 → 500, for the four workloads in the order above.
- **Warm-up:** 250 ms per cell, time-boxed; it also calibrates iterations so one sample lasts ≈25 ms (iteration counts are stored per cell).
- **Repetitions:** 5 runs, each a fresh child process; 21 samples per cell per run → 105 samples per cell. Every sample is kept.
- **Statistic:** median ns per lookup over all 105 samples. Run spread = (max − min of the five per-run medians) / median.
## Baseline (median ns per lookup, `lookup-raw.json`)
| Routes | Static hit | Late param hit | Method miss | Path miss |
|---:|---:|---:|---:|---:|
| 10 | 61.3 (spread 17.5%) | 123.3 (6.2%) | 313.1 (4.6%) | 247.1 (6.8%) |
| 100 | 67.6 (8.0%) | 343.4 (2.1%) | 1 263.7 (3.5%) | 1 463.3 (3.2%) |
| 500 | 67.8 (7.5%) | 1 326.8 (16.5%) | 6 732.2 (6.5%) | 8 973.4 (2.0%) |
## Noise floor (A/A, `lookup-aa-raw.json`)
Identical matcher code under two labels, alternating order per run. Median difference
(oracle − live) / live:
| Routes | Static hit | Late param hit | Method miss | Path miss |
|---:|---:|---:|---:|---:|
| 10 | +5.2% | 0.0% | +1.2% | +0.2% |
| 100 | −0.1% | −0.8% | −0.1% | +0.1% |
| 500 | −2.7% | +0.3% | −0.4% | +0.1% |
**For D4:** with no code difference at all, the 10-route static hit already moves 5.2% — the
size of the proposed ≤5% regression limit — and per-run medians at 10 routes spread 4.5–17.5%.
That cell is ~60 ns, where a few nanoseconds of timer and scheduling noise are a large fraction.
The ≥20% improvement at 500 routes is well clear of the noise (≤2.7% A/A, ≤16.5% spread on a
1.3–9 µs operation). Whether D4's 10-route limit applies per workload, to a mean across workloads,
or needs more runs is an owner decision; this baseline does not make it.
## End-to-end signal (`bench:compare`, req/s — not lookup time)
Run once, A/A: `AB_BASE` pointed at this same tree, so base and head are identical code. Defaults:
3 rounds × 10 s per case after a 10 s warm-up, 100 connections, alternating side order. Load
average 2.8–3.3 throughout. A few short parity-test runs (seconds each) happened during this
~22-minute run; the lookup runs above had nothing else running.
| Scenario | base req/s | head req/s | Δ |
|---|---:|---:|---:|
| hello | 88,212 | 88,236 | +0.0% |
| param | 86,508 | 85,885 | −0.7% |
| pipeline (3 steps) | 80,189 | 80,934 | +0.9% |
| steps5 | 74,359 | 73,975 | −0.5% |
| validate (POST) | 70,607 | 69,903 | −1.0% |
| hello + security | 83,913 | 83,802 | −0.1% |
| hello + cors predicate | 82,028 | 80,445 | −1.9% |
| preflight + cors predicate | 114,377 | 114,010 | −0.3% |
| param, 50 routes | 82,476 | 82,045 | −0.5% |
| param, 200 routes | 72,957 | 73,306 | +0.5% |
Every row's sample ranges overlap. So with no code change, end-to-end throughput moves up to
±1.9%; the route-width rows show that 200 filler routes already cost ~12% req/s against
`param` with none.
@@ -0,0 +1,6 @@
uptime before: 17:01 up 9 days, 7:50, 1 user, load averages: 2.47 2.14 6.86
uptime after: 17:02 up 9 days, 7:51, 1 user, load averages: 2.58 2.21 6.64
A/A uptime before: 17:02 up 9 days, 7:51, 1 user, load averages: 3.42 2.40 6.66
A/A uptime after: 17:03 up 9 days, 7:53, 1 user, load averages: 2.89 2.48 6.26
bench:compare uptime before: 17:04 up 9 days, 7:53, 1 user, load averages: 2.98 2.51 6.25
bench:compare uptime after: 17:26 up 9 days, 8:15, 1 user, load averages: 2.82 3.32 4.29
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,21 @@
> @green-tea/core@26.9.0-beta.2 bench:lookup
> tsx bench/lookup.ts
| router | routes | workload | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- |
| live | 10 | static hit | 61.3 | 64.4 / 61.0 / 68.4 / 58.0 / 57.6 | 17.5% |
| live | 10 | late param hit | 123.3 | 122.4 / 128.1 / 123.3 / 123.7 / 120.4 | 6.2% |
| live | 10 | method miss | 313.1 | 303.2 / 314.0 / 317.6 / 317.2 / 304.7 | 4.6% |
| live | 10 | path miss | 247.1 | 243.8 / 246.0 / 256.5 / 251.7 / 239.7 | 6.8% |
| live | 100 | static hit | 67.6 | 67.6 / 70.3 / 71.7 / 66.9 / 66.3 | 8.0% |
| live | 100 | late param hit | 343.4 | 339.7 / 345.5 / 346.8 / 343.0 / 341.0 | 2.1% |
| live | 100 | method miss | 1263.7 | 1253.2 / 1236.5 / 1280.9 / 1261.0 / 1264.6 | 3.5% |
| live | 100 | path miss | 1463.3 | 1444.6 / 1442.4 / 1489.2 / 1467.6 / 1467.1 | 3.2% |
| live | 500 | static hit | 67.8 | 69.7 / 68.1 / 68.2 / 64.6 / 65.1 | 7.5% |
| live | 500 | late param hit | 1326.8 | 1480.6 / 1262.0 / 1309.9 / 1328.9 / 1331.8 | 16.5% |
| live | 500 | method miss | 6732.2 | 7072.0 / 6659.6 / 6796.0 / 6631.5 / 6699.6 | 6.5% |
| live | 500 | path miss | 8973.4 | 8915.3 / 8994.7 / 9052.0 / 8876.0 / 8981.4 | 2.0% |
load average: start 2.47 2.14 6.86, end 2.58 2.21 6.64
raw samples: bench/baseline/router-ed47836/lookup-raw.json
+3 -6
View File
@@ -1,6 +1,3 @@
uptime before: 17:01 up 9 days, 7:50, 1 user, load averages: 2.47 2.14 6.86 before: 2026-10-10T22:42:38Z 17:42:38 up 44 days, 17:31, 2 users, load average: 0.27, 0.11, 0.04
uptime after: 17:02 up 9 days, 7:51, 1 user, load averages: 2.58 2.21 6.64 ci job containers: 0
A/A uptime before: 17:02 up 9 days, 7:51, 1 user, load averages: 3.42 2.40 6.66 after: 2026-10-10T22:43:54Z 17:43:54 up 44 days, 17:32, 2 users, load average: 0.79, 0.31, 0.12
A/A uptime after: 17:03 up 9 days, 7:53, 1 user, load averages: 2.89 2.48 6.26
bench:compare uptime before: 17:04 up 9 days, 7:53, 1 user, load averages: 2.98 2.51 6.25
bench:compare uptime after: 17:26 up 9 days, 8:15, 1 user, load averages: 2.82 3.32 4.29
File diff suppressed because it is too large. Load diff
@@ -1,21 +1,44 @@
| routes | workload | router | median ns/op | run medians (ns) | run spread |
> @green-tea/core@26.9.0-beta.2 bench:lookup
> tsx bench/lookup.ts
| router | routes | workload | median ns/op | run medians (ns) | run spread |
| --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- |
| live | 10 | static hit | 61.3 | 64.4 / 61.0 / 68.4 / 58.0 / 57.6 | 17.5% | | 10 | static hit | live | 185.3 | 156.1 / 187.7 / 174.1 / 194.2 | 20.5% |
| live | 10 | late param hit | 123.3 | 122.4 / 128.1 / 123.3 / 123.7 / 120.4 | 6.2% | | 10 | static hit | oracle | 176.8 | 199.9 / 161.9 / 195.0 / 162.5 | 21.5% |
| live | 10 | method miss | 313.1 | 303.2 / 314.0 / 317.6 / 317.2 / 304.7 | 4.6% | | 10 | late param hit | live | 328.4 | 311.9 / 336.2 / 323.0 / 342.4 | 9.3% |
| live | 10 | path miss | 247.1 | 243.8 / 246.0 / 256.5 / 251.7 / 239.7 | 6.8% | | 10 | late param hit | oracle | 337.6 | 343.0 / 329.2 / 356.3 / 324.3 | 9.5% |
| live | 100 | static hit | 67.6 | 67.6 / 70.3 / 71.7 / 66.9 / 66.3 | 8.0% | | 10 | method miss | live | 800.4 | 762.6 / 801.2 / 798.6 / 804.4 | 5.2% |
| live | 100 | late param hit | 343.4 | 339.7 / 345.5 / 346.8 / 343.0 / 341.0 | 2.1% | | 10 | method miss | oracle | 768.8 | 770.0 / 764.6 / 833.1 / 762.5 | 9.2% |
| live | 100 | method miss | 1263.7 | 1253.2 / 1236.5 / 1280.9 / 1261.0 / 1264.6 | 3.5% | | 10 | path miss | live | 625.5 | 594.6 / 631.3 / 620.3 / 628.1 | 5.9% |
| live | 100 | path miss | 1463.3 | 1444.6 / 1442.4 / 1489.2 / 1467.6 / 1467.1 | 3.2% | | 10 | path miss | oracle | 606.6 | 603.8 / 610.1 / 657.9 / 591.5 | 10.9% |
| live | 500 | static hit | 67.8 | 69.7 / 68.1 / 68.2 / 64.6 / 65.1 | 7.5% | | 100 | static hit | live | 201.2 | 202.2 / 200.8 / 197.6 / 207.2 | 4.8% |
| live | 500 | late param hit | 1326.8 | 1480.6 / 1262.0 / 1309.9 / 1328.9 / 1331.8 | 16.5% | | 100 | static hit | oracle | 206.9 | 211.7 / 196.6 / 213.9 / 201.7 | 8.4% |
| live | 500 | method miss | 6732.2 | 7072.0 / 6659.6 / 6796.0 / 6631.5 / 6699.6 | 6.5% | | 100 | late param hit | live | 878.0 | 861.1 / 857.0 / 907.3 / 880.5 | 5.7% |
| live | 500 | path miss | 8973.4 | 8915.3 / 8994.7 / 9052.0 / 8876.0 / 8981.4 | 2.0% | | 100 | late param hit | oracle | 893.0 | 888.7 / 869.0 / 942.1 / 895.2 | 8.2% |
| 100 | method miss | live | 2524.8 | 2424.2 / 2513.7 / 2579.6 / 2531.5 | 6.2% |
| 100 | method miss | oracle | 2515.2 | 2473.4 / 2527.3 / 2595.9 / 2509.5 | 4.9% |
| 100 | path miss | live | 3054.2 | 2965.2 / 3023.7 / 3113.5 / 3070.6 | 4.9% |
| 100 | path miss | oracle | 3075.6 | 3002.5 / 3087.9 / 3179.5 / 3064.3 | 5.8% |
| 500 | static hit | live | 202.2 | 201.8 / 202.3 / 195.1 / 210.3 | 7.5% |
| 500 | static hit | oracle | 206.3 | 212.1 / 197.8 / 213.2 / 201.1 | 7.5% |
| 500 | late param hit | live | 2930.6 | 2829.6 / 2804.3 / 2980.0 / 3016.2 | 7.2% |
| 500 | late param hit | oracle | 2878.8 | 2865.8 / 2832.6 / 2916.8 / 2881.2 | 2.9% |
| 500 | method miss | live | 11903.6 | 11635.5 / 11518.4 / 11946.5 / 12031.2 | 4.3% |
| 500 | method miss | oracle | 12101.5 | 11822.5 / 11856.4 / 12275.6 / 12190.0 | 3.7% |
| 500 | path miss | live | 15513.7 | 15103.4 / 14971.6 / 15664.8 / 16034.1 | 6.8% |
| 500 | path miss | oracle | 15719.6 | 15158.8 / 15479.0 / 16084.0 / 15885.7 | 5.9% |
load average: start 2.47 2.14 6.86, end 2.58 2.21 6.64 | routes | workload | B / A | median ratio | 95% CI | rounds |
raw samples: bench/baseline/router-ed47836/lookup-raw.json | --- | --- | --- | --- | --- | --- |
| 10 | static hit | oracle / live | 0.9507 (-4.9%) | 0.8629 – 1.1186 (-13.7% … +11.9%) | 84 |
| 10 | late param hit | oracle / live | 1.0415 (+4.1%) | 0.9840 – 1.0982 (-1.6% … +9.8%) | 84 |
| 10 | method miss | oracle / live | 0.9809 (-1.9%) | 0.9563 – 1.0076 (-4.4% … +0.8%) | 84 |
| 10 | path miss | oracle / live | 0.9919 (-0.8%) | 0.9676 – 1.0141 (-3.2% … +1.4%) | 84 |
| 100 | static hit | oracle / live | 1.0082 (+0.8%) | 0.9808 – 1.0453 (-1.9% … +4.5%) | 84 |
| 100 | late param hit | oracle / live | 1.0247 (+2.5%) | 1.0192 – 1.0292 (+1.9% … +2.9%) | 84 |
| 100 | method miss | oracle / live | 1.0055 (+0.6%) | 1.0033 – 1.0072 (+0.3% … +0.7%) | 84 |
| 100 | path miss | oracle / live | 1.0165 (+1.7%) | 1.0119 – 1.0185 (+1.2% … +1.9%) | 84 |
| 500 | static hit | oracle / live | 1.0107 (+1.1%) | 0.9782 – 1.0453 (-2.2% … +4.5%) | 84 |
| 500 | late param hit | oracle / live | 0.9838 (-1.6%) | 0.9784 – 1.0076 (-2.2% … +0.8%) | 84 |
| 500 | method miss | oracle / live | 1.0197 (+2.0%) | 1.0161 – 1.0235 (+1.6% … +2.3%) | 84 |
| 500 | path miss | oracle / live | 1.0161 (+1.6%) | 1.0047 – 1.0257 (+0.5% … +2.6%) | 84 |
load average: start 0.27 0.11 0.04, end 0.79 0.31 0.12; cpuset 6-7,14-15
raw samples: out/lookup-raw.json
+165 -82
View File
@@ -10,15 +10,21 @@
* *
* npm run bench:lookup * npm run bench:lookup
* LOOKUP_ROUTERS="base=/tmp/base/src/http/router.ts,head=src/http/router.ts" npm run bench:lookup * LOOKUP_ROUTERS="base=/tmp/base/src/http/router.ts,head=src/http/router.ts" npm run bench:lookup
* LOOKUP_ROUTERS="live=src/http/router.ts,oracle=test/router-parity/oracle.ts" npm run bench:lookup # A/A
* *
* Each implementation is a module exporting `resolveRoute` and `allowedMethods` with the * Each router is a module exporting `resolveRoute` and `allowedMethods` with the `src/http/router.ts`
* `src/http/router.ts` signatures. With several, every run measures all of them in separate child * signatures. All routers are loaded into the same process and **interleaved**: per cell, every
* processes, alternating which goes first, on the same generated tables. Do not edit the generator, * router is warmed, then each round takes one sample from each router, alternating which goes first
* the workloads or the defaults below between a baseline and its comparison — they are the method. * (AB, BA, AB, ...). Every router after the first is reported against the first as the median of the
* per-round B/A ratios, with a bootstrap 95% CI. Interleaving puts drift and background load on both
* sides of each ratio instead of on whichever ran later. With one router it reports absolute numbers
* only. Do not edit the generator, the workloads or the defaults between a baseline and its
* comparison: they are the method.
* *
* Env: `LOOKUP_ROUTERS` (label=path list, default `live=src/http/router.ts`), `LOOKUP_RUNS` (5), * Env: `LOOKUP_ROUTERS` (label=path list, default `live=src/http/router.ts`), `LOOKUP_RUNS` (4 fresh
* `LOOKUP_SAMPLES` (21 per cell per run), `LOOKUP_SAMPLE_MS` (25), `LOOKUP_WARMUP_MS` (250), * processes, import order alternating), `LOOKUP_ROUNDS` (21 per cell per run, minimum 15), `LOOKUP_SAMPLE_MS` (25),
* `LOOKUP_OUT` (bench/lookup-results.json). * `LOOKUP_WARMUP_MS` (250 per router per cell), `LOOKUP_OUT` (bench/lookup-results.json). Any other
* `LOOKUP_*` variable (e.g. `LOOKUP_HOST`, `LOOKUP_CPUSET`) is copied into the record as a note.
*/ */
import { spawn, execFileSync } from 'child_process'; import { spawn, execFileSync } from 'child_process';
import { writeFileSync, readFileSync } from 'fs'; import { writeFileSync, readFileSync } from 'fs';
@@ -27,8 +33,9 @@ import { dirname, resolve } from 'path';
import { pathToFileURL } from 'url'; import { pathToFileURL } from 'url';
const ROUTE_COUNTS = [10, 100, 500]; const ROUTE_COUNTS = [10, 100, 500];
const RUNS = Number(process.env.LOOKUP_RUNS ?? 5); const RUNS = Number(process.env.LOOKUP_RUNS ?? 4);
const SAMPLES = Number(process.env.LOOKUP_SAMPLES ?? 21); const ROUNDS = Math.max(15, Number(process.env.LOOKUP_ROUNDS ?? 21));
const BOOTSTRAP = 4000;
const SAMPLE_MS = Number(process.env.LOOKUP_SAMPLE_MS ?? 25); const SAMPLE_MS = Number(process.env.LOOKUP_SAMPLE_MS ?? 25);
const WARMUP_MS = Number(process.env.LOOKUP_WARMUP_MS ?? 250); const WARMUP_MS = Number(process.env.LOOKUP_WARMUP_MS ?? 250);
const OUT = process.env.LOOKUP_OUT ?? 'bench/lookup-results.json'; const OUT = process.env.LOOKUP_OUT ?? 'bench/lookup-results.json';
@@ -98,16 +105,23 @@ function lookup(router: RouterModule, routes: Route[], w: Workload): string {
interface Cell { interface Cell {
routes: number; routes: number;
workload: string; workload: string;
iterations: number; /** Calibrated per router; a sample is `iterations` lookups. */
samplesNs: number[]; iterations: Record<string, number>;
/** Round order, e.g. ['live', 'oracle'] then ['oracle', 'live']. */
orders: string[][];
/** One entry per router, one sample (ns per lookup) per round, in round order. */
samplesNs: Record<string, number[]>;
} }
function measure(router: RouterModule, routes: Route[], w: Workload): { iterations: number; samplesNs: number[] } { type Loaded = Array<{ label: string; router: RouterModule }>;
let sink = 0;
function warm(router: RouterModule, routes: Route[], w: Workload): number {
const answer = lookup(router, routes, w); const answer = lookup(router, routes, w);
if (answer !== w.expect) throw new Error(`${w.name} @ ${routes.length}: expected '${w.expect}', got '${answer}'`); if (answer !== w.expect) throw new Error(`${w.name} @ ${routes.length}: expected '${w.expect}', got '${answer}'`);
// Warm-up, time-boxed; it also calibrates how many iterations make one sample last SAMPLE_MS. // Time-boxed; it also calibrates how many iterations make one sample last SAMPLE_MS.
let sink = 0;
let ops = 0; let ops = 0;
const warmStart = process.hrtime.bigint(); const warmStart = process.hrtime.bigint();
const warmBudget = BigInt(WARMUP_MS * 1_000_000); const warmBudget = BigInt(WARMUP_MS * 1_000_000);
@@ -116,41 +130,63 @@ function measure(router: RouterModule, routes: Route[], w: Workload): { iteratio
ops += 100; ops += 100;
} }
const nsPerOp = Number(process.hrtime.bigint() - warmStart) / ops; const nsPerOp = Number(process.hrtime.bigint() - warmStart) / ops;
const iterations = Math.max(100, Math.round((SAMPLE_MS * 1e6) / nsPerOp)); return Math.max(100, Math.round((SAMPLE_MS * 1e6) / nsPerOp));
}
const samplesNs: number[] = []; function sample(router: RouterModule, routes: Route[], w: Workload, iterations: number): number {
for (let s = 0; s < SAMPLES; s++) {
const start = process.hrtime.bigint(); const start = process.hrtime.bigint();
for (let i = 0; i < iterations; i++) sink += lookup(router, routes, w).length; for (let i = 0; i < iterations; i++) sink += lookup(router, routes, w).length;
samplesNs.push(Number(process.hrtime.bigint() - start) / iterations); return Number(process.hrtime.bigint() - start) / iterations;
}
function measureCell(loaded: Loaded, routes: Route[], w: Workload): Cell {
const iterations: Record<string, number> = {};
const samplesNs: Record<string, number[]> = {};
const orders: string[][] = [];
for (const { label, router } of loaded) {
iterations[label] = warm(router, routes, w);
samplesNs[label] = [];
}
for (let round = 0; round < ROUNDS; round++) {
const order = round % 2 === 0 ? loaded : [...loaded].reverse();
orders.push(order.map(({ label }) => label));
for (const { label, router } of order) samplesNs[label].push(sample(router, routes, w, iterations[label]));
}
return { routes: routes.length, workload: w.name, iterations, orders, samplesNs };
}
async function child(routers: Array<[string, string]>): Promise<void> {
// Import order alternates per run (LOOKUP_IMPORT_REVERSED): which copy V8 sees first can bias an
// in-process comparison of otherwise identical code, and alternating spreads that over both sides.
const imports = process.env.LOOKUP_IMPORT_REVERSED === '1' ? [...routers].reverse() : routers;
const modules = new Map<string, RouterModule>();
for (const [label, path] of imports)
modules.set(label, (await import(pathToFileURL(resolve(path)).href)) as RouterModule);
const loaded: Loaded = routers.map(([label]) => ({ label, router: modules.get(label)! }));
const cells: Cell[] = [];
for (const count of ROUTE_COUNTS) {
const routes = buildRoutes(count);
for (const w of WORKLOADS) cells.push(measureCell(loaded, routes, w));
} }
if (sink === 42) process.stderr.write(''); // keeps `sink` observable if (sink === 42) process.stderr.write(''); // keeps `sink` observable
return { iterations, samplesNs }; process.stdout.write(`${JSON.stringify({ cells })}\n`);
} }
async function child(label: string, path: string): Promise<void> { function runChild(spec: string, importReversed: boolean): Promise<{ cells: Cell[] }> {
const router = (await import(pathToFileURL(resolve(path)).href)) as RouterModule;
const cells: Cell[] = [];
for (const count of ROUTE_COUNTS) {
const routes = buildRoutes(count);
for (const w of WORKLOADS) cells.push({ routes: count, workload: w.name, ...measure(router, routes, w) });
}
process.stdout.write(`${JSON.stringify({ label, cells })}\n`);
}
function runChild(label: string, path: string): Promise<{ label: string; cells: Cell[] }> {
return new Promise((resolvePromise, reject) => { return new Promise((resolvePromise, reject) => {
const proc = spawn(process.execPath, ['--import', 'tsx', 'bench/lookup.ts'], { const proc = spawn(process.execPath, ['--import', 'tsx', 'bench/lookup.ts'], {
env: { ...process.env, LOOKUP_CHILD: `${label}=${path}` }, env: { ...process.env, LOOKUP_CHILD: spec, LOOKUP_IMPORT_REVERSED: importReversed ? '1' : '0' },
stdio: ['ignore', 'pipe', 'inherit'], stdio: ['ignore', 'pipe', 'inherit'],
}); });
let out = ''; let out = '';
proc.stdout.on('data', (d) => (out += d)); proc.stdout.on('data', (d) => (out += d));
proc.on('exit', (code) => proc.on('exit', (code) =>
code === 0 ? resolvePromise(JSON.parse(out)) : reject(new Error(`${label} exited ${code}`)), code === 0 ? resolvePromise(JSON.parse(out)) : reject(new Error(`child exited ${code}`)),
); );
}); });
} }
@@ -161,33 +197,62 @@ const median = (xs: number[]): number => {
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
}; };
/** Deterministic PRNG for the bootstrap, so the same raw samples always give the same interval. */
function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** Percentile bootstrap 95% CI of the median of `xs`. */
function bootstrapMedianCi(xs: number[]): [number, number] {
const rng = mulberry32(10908);
const medians: number[] = [];
for (let b = 0; b < BOOTSTRAP; b++) medians.push(median(xs.map(() => xs[Math.floor(rng() * xs.length)])));
medians.sort((a, b) => a - b);
return [medians[Math.floor(BOOTSTRAP * 0.025)], medians[Math.ceil(BOOTSTRAP * 0.975) - 1]];
}
function git(cwd: string, ...args: string[]): string { function git(cwd: string, ...args: string[]): string {
try { try {
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8' }).trim(); return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch { } catch {
return 'unavailable'; return 'unavailable';
} }
} }
function cpuset(): string {
for (const file of ['/sys/fs/cgroup/cpuset.cpus.effective', '/sys/fs/cgroup/cpuset/cpuset.effective_cpus']) {
try {
return readFileSync(file, 'utf8').trim();
} catch {
/* not Linux, or not this cgroup layout */
}
}
return 'n/a';
}
function environment(routers: Array<[string, string]>) { function environment(routers: Array<[string, string]>) {
const pkg = JSON.parse(readFileSync('package.json', 'utf8')) as { name: string; version: string }; const pkg = JSON.parse(readFileSync('package.json', 'utf8')) as { name: string; version: string };
return { return {
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
hostname: os.hostname(),
node: process.version, node: process.version,
v8: process.versions.v8, v8: process.versions.v8,
platform: `${os.platform()} ${os.release()} ${os.arch()}`, platform: `${os.platform()} ${os.release()} ${os.arch()}`,
cpu: os.cpus()[0]?.model, cpu: os.cpus()[0]?.model,
cpus: os.cpus().length, cpus: os.cpus().length,
cpuset: cpuset(),
memoryBytes: os.totalmem(), memoryBytes: os.totalmem(),
loadavgAtStart: os.loadavg(), loadavgAtStart: os.loadavg(),
package: `${pkg.name}@${pkg.version}`, package: `${pkg.name}@${pkg.version}`,
harnessCommit: git('.', 'rev-parse', 'HEAD'), harnessCommit: process.env.LOOKUP_COMMIT ?? git('.', 'rev-parse', 'HEAD'),
routers: routers.map(([label, path]) => ({ routers: routers.map(([label, path]) => ({ label, path })),
label,
path,
commit: git(dirname(resolve(path)), 'rev-parse', 'HEAD'),
dirty: git(dirname(resolve(path)), 'status', '--porcelain', '--', resolve(path)) !== '',
})),
env: Object.fromEntries( env: Object.fromEntries(
Object.entries(process.env).filter(([k]) => k.startsWith('LOOKUP_') || k === 'NODE_OPTIONS'), Object.entries(process.env).filter(([k]) => k.startsWith('LOOKUP_') || k === 'NODE_OPTIONS'),
), ),
@@ -197,72 +262,90 @@ function environment(routers: Array<[string, string]>) {
routeGenerator: ROUTE_GENERATOR, routeGenerator: ROUTE_GENERATOR,
workloads: WORKLOADS, workloads: WORKLOADS,
workloadOrder: workloadOrder:
'for each run: for each router (order alternates per run): for count in routeCounts: for workload in workloads', 'for each run (fresh process; module import order reversed on even-numbered runs): for count in routeCounts: ' +
'for workload in workloads: warm every router, ' +
'then ROUNDS rounds of one sample per router, order alternating AB/BA per round',
operation: 'resolveRoute(routes, method, path); on undefined, allowedMethods(routes, path)', operation: 'resolveRoute(routes, method, path); on undefined, allowedMethods(routes, path)',
runs: RUNS, runs: RUNS,
samplesPerCellPerRun: SAMPLES, roundsPerCellPerRun: ROUNDS,
sampleMs: SAMPLE_MS, sampleMs: SAMPLE_MS,
warmupMsPerCell: WARMUP_MS, warmupMsPerRouterPerCell: WARMUP_MS,
ratio: 'per round, sample(B) / sample(A) with A the first router; median over all rounds of all runs',
ci: `percentile bootstrap of the median ratio, ${BOOTSTRAP} resamples, seed 10908`,
unit: 'ns per lookup (sample time / iterations)', unit: 'ns per lookup (sample time / iterations)',
}, },
}; };
} }
async function main(): Promise<void> { function summarize(labels: string[], runs: Array<{ run: number; cells: Cell[] }>) {
if (process.env.LOOKUP_CHILD) { return ROUTE_COUNTS.flatMap((count) =>
const [label, path] = process.env.LOOKUP_CHILD.split('=');
return child(label, path);
}
const routers = (process.env.LOOKUP_ROUTERS ?? 'live=src/http/router.ts')
.split(',')
.map((entry) => entry.split('=') as [string, string]);
const meta = environment(routers);
const runs: Array<{ run: number; order: string[]; label: string; cells: Cell[] }> = [];
for (let run = 0; run < RUNS; run++) {
const order = run % 2 === 0 ? routers : [...routers].reverse();
for (const [label, path] of order) {
const result = await runChild(label, path);
runs.push({ run: run + 1, order: order.map(([l]) => l), ...result });
process.stderr.write(`[lookup] run ${run + 1}/${RUNS} ${label} done\n`);
}
}
const summary = routers.flatMap(([label]) =>
ROUTE_COUNTS.flatMap((count) =>
WORKLOADS.map((w) => { WORKLOADS.map((w) => {
const cells = runs const cells = runs.map((r) => r.cells.find((c) => c.routes === count && c.workload === w.name)!);
.filter((r) => r.label === label) const routers = labels.map((label) => {
.map((r) => r.cells.find((c) => c.routes === count && c.workload === w.name)!); const runMedians = cells.map((c) => median(c.samplesNs[label]));
const runMedians = cells.map((c) => median(c.samplesNs)); const med = median(cells.flatMap((c) => c.samplesNs[label]));
const all = cells.flatMap((c) => c.samplesNs);
const med = median(all);
return { return {
router: label, router: label,
routes: count,
workload: w.name,
medianNs: med, medianNs: med,
runMediansNs: runMedians, runMediansNs: runMedians,
runSpreadPct: ((Math.max(...runMedians) - Math.min(...runMedians)) / med) * 100, runSpreadPct: ((Math.max(...runMedians) - Math.min(...runMedians)) / med) * 100,
}; };
});
const ratios = labels.slice(1).map((label) => {
const paired = cells.flatMap((c) => c.samplesNs[label].map((b, i) => b / c.samplesNs[labels[0]][i]));
const [low, high] = bootstrapMedianCi(paired);
return { b: label, a: labels[0], medianRatio: median(paired), ci95: [low, high], rounds: paired.length };
});
return { routes: count, workload: w.name, routers, ratios };
}), }),
),
); );
}
const pct = (ratio: number): string => `${ratio >= 1 ? '+' : ''}${((ratio - 1) * 100).toFixed(1)}%`;
async function main(): Promise<void> {
const spec = process.env.LOOKUP_CHILD
? process.env.LOOKUP_CHILD
: (process.env.LOOKUP_ROUTERS ?? 'live=src/http/router.ts');
const routers = spec.split(',').map((entry) => entry.split('=') as [string, string]);
if (process.env.LOOKUP_CHILD) return child(routers);
const labels = routers.map(([label]) => label);
const meta = environment(routers);
const runs: Array<{ run: number; importReversed: boolean; cells: Cell[] }> = [];
for (let run = 0; run < RUNS; run++) {
runs.push({ run: run + 1, importReversed: run % 2 === 1, ...(await runChild(spec, run % 2 === 1)) });
process.stderr.write(`[lookup] run ${run + 1}/${RUNS} done\n`);
}
const summary = summarize(labels, runs);
const loadavgAtEnd = os.loadavg(); const loadavgAtEnd = os.loadavg();
writeFileSync(OUT, `${JSON.stringify({ meta: { ...meta, loadavgAtEnd }, summary, runs }, null, 2)}\n`); writeFileSync(OUT, `${JSON.stringify({ meta: { ...meta, loadavgAtEnd }, summary, runs }, null, 2)}\n`);
console.log('| router | routes | workload | median ns/op | run medians (ns) | run spread |'); console.log('| routes | workload | router | median ns/op | run medians (ns) | run spread |');
console.log('| --- | --- | --- | --- | --- | --- |'); console.log('| --- | --- | --- | --- | --- | --- |');
for (const row of summary) { for (const cell of summary)
const runsText = row.runMediansNs.map((n) => n.toFixed(1)).join(' / '); for (const r of cell.routers)
console.log( console.log(
`| ${row.router} | ${row.routes} | ${row.workload} | ${row.medianNs.toFixed(1)} | ${runsText} | ${row.runSpreadPct.toFixed(1)}% |`, `| ${cell.routes} | ${cell.workload} | ${r.router} | ${r.medianNs.toFixed(1)} | ` +
`${r.runMediansNs.map((n) => n.toFixed(1)).join(' / ')} | ${r.runSpreadPct.toFixed(1)}% |`,
);
if (labels.length > 1) {
console.log('\n| routes | workload | B / A | median ratio | 95% CI | rounds |');
console.log('| --- | --- | --- | --- | --- | --- |');
for (const cell of summary)
for (const r of cell.ratios)
console.log(
`| ${cell.routes} | ${cell.workload} | ${r.b} / ${r.a} | ${r.medianRatio.toFixed(4)} (${pct(r.medianRatio)}) | ` +
`${r.ci95.map((x) => x.toFixed(4)).join(' – ')} (${pct(r.ci95[0])} … ${pct(r.ci95[1])}) | ${r.rounds} |`,
); );
} }
console.log( console.log(
`\nload average: start ${meta.loadavgAtStart.map((n) => n.toFixed(2)).join(' ')}, end ${loadavgAtEnd.map((n) => n.toFixed(2)).join(' ')}`, `\nload average: start ${meta.loadavgAtStart.map((n) => n.toFixed(2)).join(' ')}, ` +
`end ${loadavgAtEnd.map((n) => n.toFixed(2)).join(' ')}; cpuset ${meta.cpuset}`,
); );
console.log(`raw samples: ${OUT}`); console.log(`raw samples: ${OUT}`);
} }
+1
View File
@@ -104,6 +104,7 @@
"bench": "tsx bench/run.ts", "bench": "tsx bench/run.ts",
"bench:compare": "tsx bench/compare.ts", "bench:compare": "tsx bench/compare.ts",
"bench:lookup": "tsx bench/lookup.ts", "bench:lookup": "tsx bench/lookup.ts",
"parity:mutants": "tsx test/router-parity/mutants.ts",
"prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build",
"prepare": "git config core.hooksPath .githooks || true" "prepare": "git config core.hooksPath .githooks || true"
}, },
+22
View File
@@ -0,0 +1,22 @@
// The frozen router-parity differential under the real Bun runtime: every matcher case (hand-picked,
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { runDifferential } from '../router-parity/differential.ts';
import { runAppDifferential } from '../router-parity/app-fixture.ts';
const load = (name: string) => Bun.file(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)).json();
test('router parity on Bun: frozen matcher differential, oracle and live', async () => {
const report = await runDifferential(load);
expect(report.mismatches).toEqual([]);
expect(report.sets.length).toBe(5);
});
test('router parity on Bun: app.fetch cases', async () => {
const report = await runAppDifferential(load);
expect(report.mismatches).toEqual([]);
});
+23
View File
@@ -0,0 +1,23 @@
// The frozen router-parity differential under the real Deno runtime: every matcher case (hand-picked,
// owner, generated v1/v2, WS) through the oracle and the live router, and the app.fetch cases, all
// against the same frozen files the Node suite uses. See test/router-parity/README.md.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { runDifferential } from '../router-parity/differential.ts';
import { runAppDifferential } from '../router-parity/app-fixture.ts';
const load = async (name: string) =>
JSON.parse(await Deno.readTextFile(new URL(`../router-parity/frozen/${name}.json`, import.meta.url)));
Deno.test('router parity on Deno: frozen matcher differential, oracle and live', async () => {
const report = await runDifferential(load);
assertEquals(report.mismatches, []);
assertEquals(report.sets.length, 5);
});
Deno.test('router parity on Deno: app.fetch cases', async () => {
const report = await runAppDifferential(load);
assertEquals(report.mismatches, []);
});
+32
View File
@@ -0,0 +1,32 @@
// Worker entry that runs the frozen router-parity differential inside workerd: every matcher case
// through the oracle and the live router, and the app.fetch cases, against the same frozen files the
// Node suite uses. The frozen JSON is bundled in, since a worker has no file system. Driven by
// test/edge/run.ts; see test/router-parity/README.md.
import { runDifferential } from '../router-parity/differential';
import { runAppDifferential } from '../router-parity/app-fixture';
import matcherHand from '../router-parity/frozen/matcher-hand.json';
import matcherOwner from '../router-parity/frozen/matcher-owner.json';
import matcherGenerated from '../router-parity/frozen/matcher-generated.json';
import matcherGeneratedV2 from '../router-parity/frozen/matcher-generated-v2.json';
import matcherWs from '../router-parity/frozen/matcher-ws.json';
import appFetch from '../router-parity/frozen/app-fetch.json';
import ownerAppAllow from '../router-parity/frozen/owner-app-allow.json';
const FROZEN: Record<string, unknown> = {
'matcher-hand': matcherHand,
'matcher-owner': matcherOwner,
'matcher-generated': matcherGenerated,
'matcher-generated-v2': matcherGeneratedV2,
'matcher-ws': matcherWs,
'app-fetch': appFetch,
'owner-app-allow': ownerAppAllow,
};
export default {
fetch: async (): Promise<Response> => {
const load = (name: string) => FROZEN[name];
const matcher = await runDifferential(load);
const app = await runAppDifferential(load);
return Response.json({ matcher, app });
},
};
+57 -2
View File
@@ -118,7 +118,9 @@ async function main() {
const bad = badRes.webSocket; const bad = badRes.webSocket;
assert.ok(bad, 'expected a client webSocket on the 101 response'); assert.ok(bad, 'expected a client webSocket on the 101 response');
const closed = new Promise<{ code: number; reason: string }>((resolve) => const closed = new Promise<{ code: number; reason: string }>((resolve) =>
bad.addEventListener('close', (e: { code: number; reason: string }) => resolve({ code: e.code, reason: e.reason })), bad.addEventListener('close', (e: { code: number; reason: string }) =>
resolve({ code: e.code, reason: e.reason }),
),
); );
bad.accept(); bad.accept();
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' }); assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
@@ -142,6 +144,57 @@ async function main() {
} }
} }
const PARITY_BUNDLE = 'test/edge/_parity-worker.mjs';
/**
* The frozen router-parity differential inside workerd (test/router-parity/README.md). Same bundling
* as the main worker; the worker runs every case itself and answers with its mismatch report.
*/
async function parity() {
await build({
entryPoints: ['test/edge/parity-worker.ts'],
bundle: true,
format: 'esm',
outfile: PARITY_BUNDLE,
platform: 'browser',
target: 'esnext',
external: ['node:*', 'http', 'https'],
alias: {
crypto: 'node:crypto',
stream: 'node:stream',
zlib: 'node:zlib',
buffer: 'node:buffer',
events: 'node:events',
net: 'node:net',
tls: 'node:tls',
util: 'node:util',
},
});
const mf = new Miniflare({
modules: true,
scriptPath: PARITY_BUNDLE,
compatibilityDate: '2024-11-01',
compatibilityFlags: ['nodejs_compat'],
});
try {
const res = await mf.dispatchFetch('http://localhost/');
const report = (await res.json()) as {
matcher: { sets: Array<{ name: string; requests: number }>; mismatches: string[] };
app: { requests: number; mismatches: string[] };
};
assert.deepEqual(report.matcher.mismatches, [], 'matcher differential mismatches under workerd');
assert.deepEqual(report.app.mismatches, [], 'app.fetch parity mismatches under workerd');
const requests = report.matcher.sets.reduce((sum, set) => sum + set.requests, 0);
console.log(
`edge (workerd): router parity — ${requests} matcher cases + ${report.app.requests} app.fetch cases — PASS`,
);
} finally {
await mf.dispose();
}
}
/** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */ /** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */
async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) { async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) {
const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } }); const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } });
@@ -164,7 +217,9 @@ async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000)
return result; return result;
} }
main().catch((err) => { main()
.then(parity)
.catch((err) => {
console.error(err); console.error(err);
process.exit(1); process.exit(1);
}); });
+15
View File
@@ -49,4 +49,19 @@ Application-level, WS, boot and introspection files are compared against the liv
because there is no second implementation of `app.fetch` to diff against; the frozen capture plays because there is no second implementation of `app.fetch` to diff against; the frozen capture plays
the oracle's role. the oracle's role.
### On every runtime
`differential.ts` and `app-fixture.ts` hold the same comparison with no vitest and no file API, so
it runs unchanged on Deno (`test/deno/router-parity.test.ts`), Bun (`test/bun/router-parity.test.ts`)
and workerd (`test/edge/parity-worker.ts`, driven by `test/edge/run.ts`). Each runtime runs every frozen
matcher case through both the oracle and the live router, plus the `app.fetch` cases from
`app-fetch.json` and `owner-app-allow.json`. The Node-socket, WS-upgrade, boot and mesh files stay
Node-only: they need `http.request`, the `ws` client, or a mesh peer listening on a port.
### Mutation check
`npm run parity:mutants` (not part of `npm test`) applies targeted mutants modelling likely radix
bugs to a temporary copy of `src/`, runs this suite against each, and reports which were killed.
`src/` itself is never modified.
The performance half of the baseline is in `bench/lookup.ts` and `bench/baseline/router-ed47836/`. The performance half of the baseline is in `bench/lookup.ts` and `bench/baseline/router-ed47836/`.
+241
View File
@@ -0,0 +1,241 @@
/**
* The application-level fetch fixtures, free of vitest and of any runtime API, so the same app and
* requests run through `app.fetch` on Node, Deno, Bun and workerd. `app.test.ts` and
* `owner.test.ts` use them with the frozen files; the runtime runners call {@link runAppDifferential}.
*/
import 'reflect-metadata';
import { createApp, Route, Get, Head, Post, Put, Patch, Delete, Options, Sse, Module, param } from '../../src/index';
import type { App } from '../../src/app/types';
import type { FrozenLoader } from './differential';
const reply = (id: string, params: Record<string, string>) => ({ id, params });
// Ordered on purpose: the overlapping declarations are registered least-specific first, so a
// lookup that fell back to registration order would answer differently from one that ranks.
@Route('/')
class ParityHttp {
@Get('/a/:rest*') aRest(@param() p: Record<string, string>) {
return reply('aRest', p);
}
@Get('/a/:id') aId(@param() p: Record<string, string>) {
return reply('aId', p);
}
@Get('/a/b') aB(@param() p: Record<string, string>) {
return reply('aB', p);
}
@Get('/users/:value') usersValue(@param() p: Record<string, string>) {
return reply('usersValue', p);
}
@Get('/users/:id(\\d+)') usersId(@param() p: Record<string, string>) {
return reply('usersId', p);
}
@Get('/n/:num(\\d+)') nNum(@param() p: Record<string, string>) {
return reply('nNum', p);
}
@Get('/n/:code([0-9a-f]+)') nCode(@param() p: Record<string, string>) {
return reply('nCode', p);
}
@Get('/files') files(@param() p: Record<string, string>) {
return reply('files', p);
}
@Get('/files/:rest*') filesRest(@param() p: Record<string, string>) {
return reply('filesRest', p);
}
@Get('/m') mGet(@param() p: Record<string, string>) {
return reply('mGet', p);
}
@Post('/m') mPost(@param() p: Record<string, string>) {
return reply('mPost', p);
}
@Get('/h') hGet(@param() p: Record<string, string>) {
return reply('hGet', p);
}
@Head('/h') hHead(@param() p: Record<string, string>) {
return reply('hHead', p);
}
@Sse('/stream') stream() {
return (async function* () {
yield { id: 'stream' };
})();
}
@Sse('/s/live') sLive() {
return (async function* () {
yield { id: 'sLive' };
})();
}
@Get('/s/:id') sId(@param() p: Record<string, string>) {
return reply('sId', p);
}
@Get('/Case') caseUpper(@param() p: Record<string, string>) {
return reply('caseUpper', p);
}
@Get('/u/:name') uName(@param() p: Record<string, string>) {
return reply('uName', p);
}
@Get('/admin') admin(@param() p: Record<string, string>) {
return reply('admin', p);
}
@Get('/public/:file') publicFile(@param() p: Record<string, string>) {
return reply('publicFile', p);
}
@Delete('/r') rDelete(@param() p: Record<string, string>) {
return reply('rDelete', p);
}
@Patch('/r') rPatch(@param() p: Record<string, string>) {
return reply('rPatch', p);
}
@Options('/r') rOptions(@param() p: Record<string, string>) {
return reply('rOptions', p);
}
@Put('/r') rPut(@param() p: Record<string, string>) {
return reply('rPut', p);
}
@Get('/') root(@param() p: Record<string, string>) {
return reply('root', p);
}
}
@Module({ mountpoint: '/', controllers: [ParityHttp] })
export class ParityHttpModule {}
export type Req = [method: string, raw: string];
export const REQUESTS: Req[] = [
['GET', '/a/b'],
['GET', '/a/x'],
['GET', '/a/x/y'],
['GET', '/a'],
['GET', '/users/42'],
['GET', '/users/alice'],
['GET', '/users/a%20b'],
['GET', '/n/42'],
['GET', '/n/ff'],
['GET', '/files'],
['GET', '/files/'],
['GET', '/files/a%2Fb'],
['GET', '/m'],
['HEAD', '/m'],
['OPTIONS', '/m'],
['PUT', '/m'],
['DELETE', '/m'],
['POST', '/m'],
['GET', '/h'],
['HEAD', '/h'],
['GET', '/stream'],
['HEAD', '/stream'],
['OPTIONS', '/stream'],
['HEAD', '/s/live'],
['HEAD', '/s/x'],
['GET', '/absent'],
['HEAD', '/absent'],
['OPTIONS', '/absent'],
['GET', '/users/%E0%A4%A'],
['HEAD', '/users/%E0%A4%A'],
['GET', '/a//b'],
['GET', '/Case'],
['GET', '/case'],
['GET', '/caf%C3%A9'],
['GET', '/u/caf%C3%A9'],
['GET', '/public/../admin'],
['GET', '/public/%2e%2e/admin'],
['GET', '/public/..%2fadmin'],
['GET', '/admin/'],
['OPTIONS', '/r'],
['HEAD', '/r'],
['GET', '/r'],
['PURGE', '/r'], // TRACE is a forbidden method for `new Request`
['GET', '/'],
['GET', '/?q=1'],
];
/** Headers that vary per run or per connection rather than per route decision. */
const VOLATILE = new Set(['date', 'connection', 'keep-alive', 'x-request-id']);
export function stableHeaders(entries: Iterable<[string, string]>): Record<string, string> {
const out: Record<string, string> = {};
for (const [name, value] of [...entries].sort(([a], [b]) => a.localeCompare(b)))
if (!VOLATILE.has(name)) out[name] = value;
return out;
}
export interface Observed {
method: string;
raw: string;
status: number;
headers: Record<string, string>;
body: string;
}
export async function viaFetch(app: App, [method, raw]: Req): Promise<Observed> {
// `new Request` applies the URL parser first — exactly what Deno, Bun and workerd do.
const res = await app.fetch(new Request(`http://parity.test${raw}`, { method }));
return { method, raw, status: res.status, headers: stableHeaders(res.headers), body: await res.text() };
}
// `/ca` is GET :id + POST b; `/cb` adds DELETE :rest*. Two prefixes because one app cannot hold both
// variants at the same path.
@Route('/')
class CrossAllow {
@Get('/ca/:id') caGet(@param() p: Record<string, string>) {
return { id: 'caGet', p };
}
@Post('/ca/b') caPost() {
return { id: 'caPost' };
}
@Get('/cb/:id') cbGet(@param() p: Record<string, string>) {
return { id: 'cbGet', p };
}
@Post('/cb/b') cbPost() {
return { id: 'cbPost' };
}
@Delete('/cb/:rest*') cbDelete(@param() p: Record<string, string>) {
return { id: 'cbDelete', p };
}
}
@Module({ mountpoint: '/', controllers: [CrossAllow] })
export class CrossAllowModule {}
export const ALLOW_REQUESTS: Array<[string, string]> = ['/ca', '/cb'].flatMap((base): Array<[string, string]> => [
['PUT', `${base}/b`],
['OPTIONS', `${base}/b`],
['PUT', `${base}/x`],
['HEAD', `${base}/b`],
['PUT', `${base}/x/y`],
]);
export interface Seen {
method: string;
path: string;
status: number;
allow: string | null;
body: string;
}
export async function fetchRequest(app: App, method: string, path: string): Promise<Seen> {
const res = await app.fetch(new Request(`http://parity.test${path}`, { method }));
return { method, path, status: res.status, allow: res.headers.get('allow'), body: await res.text() };
}
/**
* Runs the frozen `app.fetch` cases — `app-fetch.json` and the fetch rows of `owner-app-allow.json`
* — on whatever runtime calls it, and returns every mismatch.
*/
export async function runAppDifferential(load: FrozenLoader): Promise<{ requests: number; mismatches: string[] }> {
const mismatches: string[] = [];
const parity = createApp({ modules: [ParityHttpModule] });
const appFetch = ((await load('app-fetch')) as { data: Observed[] }).data;
for (const [index, req] of REQUESTS.entries()) {
const seen = await viaFetch(parity, req);
if (JSON.stringify(seen) !== JSON.stringify(appFetch[index])) mismatches.push(`app-fetch ${req[0]} ${req[1]}`);
}
const cross = createApp({ modules: [CrossAllowModule] });
const allow = ((await load('owner-app-allow')) as { data: Array<Seen & { adapter: string }> }).data;
const fetchRows = allow.filter((row) => row.adapter === 'fetch');
for (const [index, [method, path]] of ALLOW_REQUESTS.entries()) {
const seen = { adapter: 'fetch', ...(await fetchRequest(cross, method, path)) };
if (JSON.stringify(seen) !== JSON.stringify(fetchRows[index])) mismatches.push(`owner-app-allow ${method} ${path}`);
}
return { requests: REQUESTS.length + ALLOW_REQUESTS.length, mismatches };
}
+19 -167
View File
@@ -4,178 +4,24 @@
* cannot prove these: the 404/405/OPTIONS decisions, the 400 for a bad path and the HEAD body rule * cannot prove these: the 404/405/OPTIONS decisions, the 400 for a bad path and the HEAD body rule
* live in `src/http/core.ts`, around the matcher. * live in `src/http/core.ts`, around the matcher.
*/ */
import 'reflect-metadata';
import http from 'http'; import http from 'http';
import type { AddressInfo } from 'net'; import type { AddressInfo } from 'net';
import { describe, it, beforeAll, afterAll } from 'vitest'; import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createApp, Route, Get, Head, Post, Put, Patch, Delete, Options, Sse, Module, param } from '../../src/index'; import { createApp } from '../../src/index';
import { readFileSync } from 'fs';
import { join } from 'path';
import {
ParityHttpModule,
REQUESTS,
runAppDifferential,
stableHeaders,
viaFetch,
type Observed,
type Req,
} from './app-fixture';
import type { App } from '../../src/app/types'; import type { App } from '../../src/app/types';
import { frozen, expectFrozenEqual } from './frozen'; import { frozen, expectFrozenEqual } from './frozen';
const reply = (id: string, params: Record<string, string>) => ({ id, params });
// Ordered on purpose: the overlapping declarations are registered least-specific first, so a
// lookup that fell back to registration order would answer differently from one that ranks.
@Route('/')
class ParityHttp {
@Get('/a/:rest*') aRest(@param() p: Record<string, string>) {
return reply('aRest', p);
}
@Get('/a/:id') aId(@param() p: Record<string, string>) {
return reply('aId', p);
}
@Get('/a/b') aB(@param() p: Record<string, string>) {
return reply('aB', p);
}
@Get('/users/:value') usersValue(@param() p: Record<string, string>) {
return reply('usersValue', p);
}
@Get('/users/:id(\\d+)') usersId(@param() p: Record<string, string>) {
return reply('usersId', p);
}
@Get('/n/:num(\\d+)') nNum(@param() p: Record<string, string>) {
return reply('nNum', p);
}
@Get('/n/:code([0-9a-f]+)') nCode(@param() p: Record<string, string>) {
return reply('nCode', p);
}
@Get('/files') files(@param() p: Record<string, string>) {
return reply('files', p);
}
@Get('/files/:rest*') filesRest(@param() p: Record<string, string>) {
return reply('filesRest', p);
}
@Get('/m') mGet(@param() p: Record<string, string>) {
return reply('mGet', p);
}
@Post('/m') mPost(@param() p: Record<string, string>) {
return reply('mPost', p);
}
@Get('/h') hGet(@param() p: Record<string, string>) {
return reply('hGet', p);
}
@Head('/h') hHead(@param() p: Record<string, string>) {
return reply('hHead', p);
}
@Sse('/stream') stream() {
return (async function* () {
yield { id: 'stream' };
})();
}
@Sse('/s/live') sLive() {
return (async function* () {
yield { id: 'sLive' };
})();
}
@Get('/s/:id') sId(@param() p: Record<string, string>) {
return reply('sId', p);
}
@Get('/Case') caseUpper(@param() p: Record<string, string>) {
return reply('caseUpper', p);
}
@Get('/u/:name') uName(@param() p: Record<string, string>) {
return reply('uName', p);
}
@Get('/admin') admin(@param() p: Record<string, string>) {
return reply('admin', p);
}
@Get('/public/:file') publicFile(@param() p: Record<string, string>) {
return reply('publicFile', p);
}
@Delete('/r') rDelete(@param() p: Record<string, string>) {
return reply('rDelete', p);
}
@Patch('/r') rPatch(@param() p: Record<string, string>) {
return reply('rPatch', p);
}
@Options('/r') rOptions(@param() p: Record<string, string>) {
return reply('rOptions', p);
}
@Put('/r') rPut(@param() p: Record<string, string>) {
return reply('rPut', p);
}
@Get('/') root(@param() p: Record<string, string>) {
return reply('root', p);
}
}
@Module({ mountpoint: '/', controllers: [ParityHttp] })
class ParityHttpModule {}
type Req = [method: string, raw: string];
const REQUESTS: Req[] = [
['GET', '/a/b'],
['GET', '/a/x'],
['GET', '/a/x/y'],
['GET', '/a'],
['GET', '/users/42'],
['GET', '/users/alice'],
['GET', '/users/a%20b'],
['GET', '/n/42'],
['GET', '/n/ff'],
['GET', '/files'],
['GET', '/files/'],
['GET', '/files/a%2Fb'],
['GET', '/m'],
['HEAD', '/m'],
['OPTIONS', '/m'],
['PUT', '/m'],
['DELETE', '/m'],
['POST', '/m'],
['GET', '/h'],
['HEAD', '/h'],
['GET', '/stream'],
['HEAD', '/stream'],
['OPTIONS', '/stream'],
['HEAD', '/s/live'],
['HEAD', '/s/x'],
['GET', '/absent'],
['HEAD', '/absent'],
['OPTIONS', '/absent'],
['GET', '/users/%E0%A4%A'],
['HEAD', '/users/%E0%A4%A'],
['GET', '/a//b'],
['GET', '/Case'],
['GET', '/case'],
['GET', '/caf%C3%A9'],
['GET', '/u/caf%C3%A9'],
['GET', '/public/../admin'],
['GET', '/public/%2e%2e/admin'],
['GET', '/public/..%2fadmin'],
['GET', '/admin/'],
['OPTIONS', '/r'],
['HEAD', '/r'],
['GET', '/r'],
['PURGE', '/r'], // TRACE is a forbidden method for `new Request`
['GET', '/'],
['GET', '/?q=1'],
];
/** Headers that vary per run or per connection rather than per route decision. */
const VOLATILE = new Set(['date', 'connection', 'keep-alive', 'x-request-id']);
function stableHeaders(entries: Iterable<[string, string]>): Record<string, string> {
const out: Record<string, string> = {};
for (const [name, value] of [...entries].sort(([a], [b]) => a.localeCompare(b)))
if (!VOLATILE.has(name)) out[name] = value;
return out;
}
interface Observed {
method: string;
raw: string;
status: number;
headers: Record<string, string>;
body: string;
}
async function viaFetch(app: App, [method, raw]: Req): Promise<Observed> {
// `new Request` applies the URL parser first — exactly what Deno, Bun and workerd do.
const res = await app.fetch(new Request(`http://parity.test${raw}`, { method }));
return { method, raw, status: res.status, headers: stableHeaders(res.headers), body: await res.text() };
}
function viaNode(port: number, [method, raw]: Req): Promise<Observed> { function viaNode(port: number, [method, raw]: Req): Promise<Observed> {
// `http.request` sends the path bytes as given, so the server sees the raw target. // `http.request` sends the path bytes as given, so the server sees the raw target.
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -231,4 +77,10 @@ describe('router parity: application-level HTTP outcomes', () => {
const expected = await frozen('app-node', run); const expected = await frozen('app-node', run);
expectFrozenEqual(await run(), expected, 'node listener'); expectFrozenEqual(await run(), expected, 'node listener');
}); });
it('the runtime-neutral app differential (the one Deno, Bun and workerd run) reports no mismatch', async () => {
const dir = join(__dirname, 'frozen');
const report = await runAppDifferential((name) => JSON.parse(readFileSync(join(dir, `${name}.json`), 'utf8')));
expect(report.mismatches).toEqual([]);
});
}); });
+124
View File
@@ -0,0 +1,124 @@
/**
* The frozen matcher differential, free of vitest and of any runtime's file API, so the same
* comparison runs on Node (vitest), Deno, Bun and workerd. Each runtime passes a loader that
* returns a frozen file's parsed JSON.
*
* It compares exactly what `matcher.test.ts` compares — regenerated inputs, oracle outputs and live
* outputs against the frozen capture, key and array order included — and returns mismatches instead
* of throwing, so a runner can report them all.
*/
import * as live from '../../src/http/router';
import { matchWsRoute as liveMatchWsRoute } from '../../src/http/ws-core';
import type { WsRouteDef } from '../../src/http/types';
import * as oracle from './oracle';
import { runScenario, type MatcherImpl, type Outcome, type Scenario } from './matcher';
import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases';
import { generateScenarios, generateScenariosV2, GENERATOR_SEED } from './generator';
export type FrozenLoader = (name: string) => unknown | Promise<unknown>;
interface CapturedScenario extends Scenario {
outcomes: Outcome[];
}
// ── WebSocket matcher cases (first registered wins) ─────────────────────────────────────────────
type WsDecl = WsRouteDef & { id: string };
export type WsMatcher = (
routes: WsRouteDef[],
path: string,
) => { def: WsRouteDef; params: Record<string, string> | undefined } | undefined;
const ws = (id: string, pattern: string): WsDecl => ({ id, pattern, open: async () => (async function* () {})() });
const overlap = [ws('param', '/ws/:id'), ws('static', '/ws/static'), ws('rest', '/ws/:rest*')];
const WS_SCENARIOS = [
{ id: 'W01-overlap', routes: overlap },
{ id: 'W02-overlap-reversed', routes: [...overlap].reverse() },
{ id: 'W03-catch-all-first', routes: [ws('rest', '/w/:rest*'), ws('exact', '/w')] },
];
// Fed already normalized, as both upgrade adapters do since #117.
const WS_PATHS = ['/ws/static', '/ws/x', '/ws/a%20b', '/ws', '/ws/x/y', '/w', '/w/a%2Fb/c', '/nope'];
export function runWsMatcher(matchWs: WsMatcher) {
return WS_SCENARIOS.map(({ id, routes }) => ({
id,
declarations: routes.map((route) => ({ id: route.id, pattern: route.pattern })),
outcomes: WS_PATHS.map((path) => {
const hit = matchWs(routes, path);
return { path, route: hit ? { id: (hit.def as WsDecl).id, params: hit.params } : null };
}),
}));
}
export const LIVE_WS_MATCHER: WsMatcher = liveMatchWsRoute;
export const ORACLE_WS_MATCHER: WsMatcher = oracle.matchWsRoute;
// ── the comparison ──────────────────────────────────────────────────────────────────────────────
const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
const plain = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
export interface DifferentialReport {
sets: Array<{ name: string; scenarios: number; requests: number }>;
mismatches: string[];
}
const SETS: Array<{ name: string; scenarios: () => Scenario[]; inFile: (data: any) => CapturedScenario[] }> = [
{ name: 'matcher-hand', scenarios: () => HAND_SCENARIOS, inFile: (data) => data },
{ name: 'matcher-owner', scenarios: () => OWNER_SCENARIOS, inFile: (data) => data },
{ name: 'matcher-generated', scenarios: () => generateScenarios(GENERATOR_SEED), inFile: (data) => data.scenarios },
{
name: 'matcher-generated-v2',
scenarios: () => generateScenariosV2(GENERATOR_SEED),
inFile: (data) => data.scenarios,
},
];
function compareSet(name: string, scenarios: Scenario[], expected: CapturedScenario[], mismatches: string[]): number {
const byId = new Map(expected.map((scenario) => [scenario.id, scenario]));
if (
!same(
expected.map((s) => s.id),
scenarios.map((s) => s.id),
)
)
mismatches.push(`${name}: scenario ids differ from the frozen file`);
let requests = 0;
for (const scenario of scenarios) {
const frozen = byId.get(scenario.id);
if (!frozen) continue;
const { outcomes, ...inputs } = frozen;
requests += scenario.requests.length;
if (!same(plain(scenario), inputs)) mismatches.push(`${name} ${scenario.id}: inputs`);
const impls: Array<[string, MatcherImpl]> = [
['oracle', oracle],
['live', live],
];
for (const [label, impl] of impls)
if (!same(plain(runScenario(impl, scenario)), outcomes)) mismatches.push(`${name} ${scenario.id}: ${label}`);
}
return requests;
}
export async function runDifferential(load: FrozenLoader): Promise<DifferentialReport> {
const mismatches: string[] = [];
const sets: DifferentialReport['sets'] = [];
for (const set of SETS) {
const scenarios = set.scenarios();
const file = (await load(set.name)) as { data: unknown };
const requests = compareSet(set.name, scenarios, set.inFile(file.data), mismatches);
sets.push({ name: set.name, scenarios: scenarios.length, requests });
}
const wsFile = (await load('matcher-ws')) as { data: unknown };
for (const [label, matcher] of [
['oracle', ORACLE_WS_MATCHER],
['live', LIVE_WS_MATCHER],
] as const)
if (!same(plain(runWsMatcher(matcher)), wsFile.data)) mismatches.push(`matcher-ws: ${label}`);
sets.push({ name: 'matcher-ws', scenarios: WS_SCENARIOS.length, requests: WS_SCENARIOS.length * WS_PATHS.length });
return { sets, mismatches };
}
+14 -30
View File
@@ -7,10 +7,10 @@
* for a radix index behind the same exports, the same test compares oracle against radix with no * for a radix index behind the same exports, the same test compares oracle against radix with no
* edit here. * edit here.
*/ */
import { readFileSync } from 'fs';
import { join } from 'path';
import { describe, it, expect, beforeAll } from 'vitest'; import { describe, it, expect, beforeAll } from 'vitest';
import * as live from '../../src/http/router'; import * as live from '../../src/http/router';
import { matchWsRoute as liveMatchWsRoute } from '../../src/http/ws-core';
import type { WsRouteDef } from '../../src/http/types';
import * as oracle from './oracle'; import * as oracle from './oracle';
import { runScenario, type MatcherImpl, type Outcome, type Scenario } from './matcher'; import { runScenario, type MatcherImpl, type Outcome, type Scenario } from './matcher';
import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases'; import { HAND_SCENARIOS, OWNER_SCENARIOS } from './cases';
@@ -25,6 +25,7 @@ import {
GENERATOR_V2_VERSION, GENERATOR_V2_VERSION,
} from './generator'; } from './generator';
import { frozen, expectFrozenEqual } from './frozen'; import { frozen, expectFrozenEqual } from './frozen';
import { runDifferential, runWsMatcher, LIVE_WS_MATCHER, ORACLE_WS_MATCHER } from './differential';
const LIVE: MatcherImpl = live; const LIVE: MatcherImpl = live;
const ORACLE: MatcherImpl = oracle; const ORACLE: MatcherImpl = oracle;
@@ -139,34 +140,17 @@ describe(`router parity: generated shared-prefix cases (${GENERATOR_V2_VERSION},
describe('router parity: WebSocket matcher (first registered wins)', () => { describe('router parity: WebSocket matcher (first registered wins)', () => {
// WS selection is a separate contract from HTTP: no specificity ranking, registration order only. // WS selection is a separate contract from HTTP: no specificity ranking, registration order only.
// Paths are fed already normalized, as both upgrade adapters do since #117.
type WsDecl = WsRouteDef & { id: string };
type WsMatcher = (
routes: WsRouteDef[],
path: string,
) => { def: WsRouteDef; params: Record<string, string> | undefined } | undefined;
const ws = (id: string, pattern: string): WsDecl => ({ id, pattern, open: async () => (async function* () {})() });
const overlap = [ws('param', '/ws/:id'), ws('static', '/ws/static'), ws('rest', '/ws/:rest*')];
const scenarios = [
{ id: 'W01-overlap', routes: overlap },
{ id: 'W02-overlap-reversed', routes: [...overlap].reverse() },
{ id: 'W03-catch-all-first', routes: [ws('rest', '/w/:rest*'), ws('exact', '/w')] },
];
const paths = ['/ws/static', '/ws/x', '/ws/a%20b', '/ws', '/ws/x/y', '/w', '/w/a%2Fb/c', '/nope'];
const run = (matchWs: WsMatcher) =>
scenarios.map(({ id, routes }) => ({
id,
declarations: routes.map((route) => ({ id: route.id, pattern: route.pattern })),
outcomes: paths.map((path) => {
const hit = matchWs(routes, path);
return { path, route: hit ? { id: (hit.def as WsDecl).id, params: hit.params } : null };
}),
}));
it('oracle and live matchWsRoute equal the frozen capture', async () => { it('oracle and live matchWsRoute equal the frozen capture', async () => {
const expected = await frozen('matcher-ws', () => run(liveMatchWsRoute)); const expected = await frozen('matcher-ws', () => runWsMatcher(LIVE_WS_MATCHER));
expectFrozenEqual(run(oracle.matchWsRoute), expected, 'ws oracle'); expectFrozenEqual(runWsMatcher(ORACLE_WS_MATCHER), expected, 'ws oracle');
expectFrozenEqual(run(liveMatchWsRoute), expected, 'ws live'); expectFrozenEqual(runWsMatcher(LIVE_WS_MATCHER), expected, 'ws live');
});
});
describe('router parity: runtime-neutral differential (the one Deno, Bun and workerd run)', () => {
it('reports no mismatch on Node', async () => {
const dir = join(__dirname, 'frozen');
const report = await runDifferential((name) => JSON.parse(readFileSync(join(dir, `${name}.json`), 'utf8')));
expect(report.mismatches).toEqual([]);
}); });
}); });
+211
View File
@@ -0,0 +1,211 @@
/**
* 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.
*
* 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.
*/
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, '..', '..');
interface Mutant {
id: string;
models: string;
file: string;
from: string;
to: string;
}
const ROUTER = 'src/http/router.ts';
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;`,
},
{
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)),`,
},
{
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));`,
},
{
id: 'constraint-ignored',
models: 'param constraint not tested during lookup',
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);`,
},
{
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]`,
},
{
id: 'implicit-head-from-stream',
models: 'implicit HEAD served by a streaming GET',
file: ROUTER,
from: `routes.filter((route) => route.transport === 'buffer'),`,
to: `routes,`,
},
{
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;`,
},
{
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];
[...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;`,
},
{
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)
.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;`,
},
];
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-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;
}
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 }> = [];
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 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));
try {
const { passed, failed } = runSuite(dir);
rows.push({
id: mutant.id,
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);
}
}
} 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} |`);
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();
+2 -45
View File
@@ -7,50 +7,12 @@ import http from 'http';
import net from 'net'; import net from 'net';
import type { AddressInfo } from 'net'; import type { AddressInfo } from 'net';
import { describe, it, afterAll, beforeAll } from 'vitest'; import { describe, it, afterAll, beforeAll } from 'vitest';
import { createApp, Route, Get, Post, Delete, Module, param } from '../../src/index'; import { createApp, Route, Get, Module } from '../../src/index';
import { ALLOW_REQUESTS, CrossAllowModule, fetchRequest, type Seen } from './app-fixture';
import type { App } from '../../src/app/types'; import type { App } from '../../src/app/types';
import type { Logger } from '../../src/logger'; import type { Logger } from '../../src/logger';
import { frozen, expectFrozenEqual } from './frozen'; import { frozen, expectFrozenEqual } from './frozen';
// `/ca` is GET :id + POST b; `/cb` adds DELETE :rest*. Two prefixes because one app cannot hold both
// variants at the same path.
@Route('/')
class CrossAllow {
@Get('/ca/:id') caGet(@param() p: Record<string, string>) {
return { id: 'caGet', p };
}
@Post('/ca/b') caPost() {
return { id: 'caPost' };
}
@Get('/cb/:id') cbGet(@param() p: Record<string, string>) {
return { id: 'cbGet', p };
}
@Post('/cb/b') cbPost() {
return { id: 'cbPost' };
}
@Delete('/cb/:rest*') cbDelete(@param() p: Record<string, string>) {
return { id: 'cbDelete', p };
}
}
@Module({ mountpoint: '/', controllers: [CrossAllow] })
class CrossAllowModule {}
const ALLOW_REQUESTS: Array<[string, string]> = ['/ca', '/cb'].flatMap((base): Array<[string, string]> => [
['PUT', `${base}/b`],
['OPTIONS', `${base}/b`],
['PUT', `${base}/x`],
['HEAD', `${base}/b`],
['PUT', `${base}/x/y`],
]);
interface Seen {
method: string;
path: string;
status: number;
allow: string | null;
body: string;
}
function nodeRequest(port: number, method: string, path: string): Promise<Seen> { function nodeRequest(port: number, method: string, path: string): Promise<Seen> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => { const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => {
@@ -66,11 +28,6 @@ function nodeRequest(port: number, method: string, path: string): Promise<Seen>
}); });
} }
async function fetchRequest(app: App, method: string, path: string): Promise<Seen> {
const res = await app.fetch(new Request(`http://parity.test${path}`, { method }));
return { method, path, status: res.status, allow: res.headers.get('allow'), body: await res.text() };
}
// ── mesh: the HTTP route table across a peer's lifetime ───────────────────────────────────────── // ── mesh: the HTTP route table across a peer's lifetime ─────────────────────────────────────────
const SECRET = 'parity-secret'; const SECRET = 'parity-secret';