Skip to content

perf: index dynamic app-core routes by last static segment - #955

Merged
leonidaz merged 4 commits into
mainfrom
cursor/runtime-perf-audit-8104
Sep 6, 2026
Merged

leonidaz merged 4 commits into
mainfrom
cursor/runtime-perf-audit-8104

Conversation

@jonkwheeler

@jonkwheeler jonkwheeler commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Index @octanejs/app-core parameter and catch-all routes by their last static segment so createRouter().match() does not RegExp-scan the whole dynamic table.
  • Static exact matches use perf: index static app-core routes for O(1) dispatch #951's path Map first (a matching static path always out-scores a dynamic one). After a method miss, matching still falls through to other static methods and then to dynamic candidates, including catch-alls.
  • Equal-specificity overlaps keep insertion order (/users/:id vs /:org/users on /users/users).
  • Mid-path catch-alls with a later static token (/files/*rest/download) stay on the linear remainder, because (.+) can shift that token past a fixed index.
  • This is a second-pass win after perf: index static app-core routes for O(1) dispatch #951's static Map. It does not redo that work; the two compose (static exact first, then indexed dynamic). main is merged so those two indexes sit together.

Why

router-dispatch still walked every dynamic candidate for a last-row /:value/dynamic-N hit. Exact-string static matching already beat RegExp, but the remaining scan was the next cost. Linear segment compare without an index was not faster than RegExp. Bucketing by last static segment removes that work without changing match semantics.

Changes

  • packages/app-core/src/server/router.js: split compiled routes into perf: index static app-core routes for O(1) dispatch #951's static path Map, a last-static-segment index, and a no-static remainder (pure params, root catch-alls, and static-after-catchall patterns). Gather overlapping buckets, then walk in specificity/insertion order with the existing RegExp + decodeURIComponent matcher.
  • packages/app-core/tests/router.test.ts: pin method-miss → catch-all (static and dynamic), same-path static method selection, equal-spec insertion order, param-over-catchall, trailing-slash catch-all capture, and mid-path catch-all + static suffix.
  • Changeset for @octanejs/app-core (patch).
  • benchmarks/router-dispatch: add a linear dynamic-scan control and retarget ratio guards at that control.

Benchmarks

Environment: Node v22.22.2, Linux 6.12.94+ x86_64, 4 CPUs. Command: node benchmarks/router-dispatch/run.mjs 20. Scores are ms/million candidates (lower is better).

run static wrong-method dynamic
A1 baseline 5.515 5.282 125.642
A2 baseline 5.661 5.647 129.682
A3 baseline 5.560 5.211 117.260
B1 indexed 4.542 5.288 0.268
B2 indexed 4.601 5.925 0.264
  • Dynamic last-hit: ~440–490× faster (117–130 → 0.26 ms/million)
  • Static / wrong-method: unchanged within noise
  • Same-process dynamic-scan control stayed at ~112–116 ms/million
  • After the mid-path catch-all remainder fix: node benchmarks/router-dispatch/run.mjs 8 still reported dynamic 0.266 vs scan 113.736
  • node benchmarks/bench.mjs --quick --ratios router-dispatch: 3/3 ratio guards passed (dynamic-routes / dynamic-scan ≈ 0.003, ceiling 0.05)

Other candidates measured (not in this PR)

  • escapeHtml clean-path indexOf reject was ~2× a regex test; dirty-path char-walk was ~1.9× three replaceAlls. Real page-level savings are small next to this router win.
  • Linear segment compare without an index was slower than RegExp (0.88×). Not shipped.
  • normalizeClass string path is already ~444M ops/s.

Validation

  • pnpm format:check (not run; scoped Prettier on the changed JS/TS files)
  • pnpm format:files:check on the changed JS/TS files
  • tsgo --noEmit -p packages/app-core/tsconfig.typecheck.json
  • pnpm test (full suite not run locally; targeted router tests below)
  • targeted tests: packages/app-core/tests/router.test.ts (9 tests, including perf: index static app-core routes for O(1) dispatch #951's static method-miss → catch-all). Equal-spec insertion order was confirmed red when the sort tie-breaker was reversed. Mid-path catch-all was confirmed null before the remainder change, then green after restore.
  • node benchmarks/router-dispatch/run.mjs 20 A/B as above
  • node benchmarks/bench.mjs --quick --ratios router-dispatch

Risk / follow-ups

  • Pure-param, root catch-all, and static-after-catchall routes stay on a short linear remainder. Tables that are only /:a/:b do not get the index win.
  • Callers still receive a fresh params object; public match identity and decoded params are unchanged.
  • perf: index static app-core routes for O(1) dispatch #951's static Map is complementary and composed here, not duplicated or replaced.
  • escapeHtml remains a smaller, separate SSR candidate if someone wants a third pass.

Provenance

  • An agent produced this diff (agent-authored)
Open in Web Open in Cursor 

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Skip the linear RegExp scan for parameter and catch-all routes by
bucketing them on their last static segment, while keeping static
exact-match first and preserving specificity plus equal-spec order.

Co-authored-by: Jon Wheeler <[email protected]>
@jonkwheeler
jonkwheeler marked this pull request as ready for review September 4, 2026 17:35
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work labels Sep 4, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Mid-path catch-alls miss matches
    • Routes with a catch-all before the last static token are no longer indexed at a fixed pathname slot and fall back to the remainder scan, restoring matches such as /files/*path/raw against /files/a/b/raw.

Create PR

Or push these changes by commenting:

@cursor push 24468eb901
Preview (24468eb901)
diff --git a/packages/app-core/src/server/router.js b/packages/app-core/src/server/router.js
--- a/packages/app-core/src/server/router.js
+++ b/packages/app-core/src/server/router.js
@@ -72,6 +72,8 @@
 /**
  * Last static segment of a dynamic route pattern. Positions skip empty
  * segments so they line up with a leading-slash pathname split.
+ * Returns null when a catch-all precedes that token: `*` can span slashes,
+ * so the token's pathname index is not fixed and the route is scanned.
  *
  * @param {string} path
  * @returns {{ pos: number, value: string } | null}
@@ -81,17 +83,22 @@
 	let pos = -1;
 	let value = '';
 	let index = 0;
+	let sawCatchAll = false;
+	let catchAllBefore = false;
 	for (let i = 0; i < raw.length; i++) {
 		const segment = raw[i];
 		if (!segment) continue;
 		const first = segment.charCodeAt(0);
-		if (first !== 58 /* : */ && first !== 42 /* * */) {
+		if (first === 42 /* * */) {
+			sawCatchAll = true;
+		} else if (first !== 58 /* : */) {
 			pos = index;
 			value = segment;
+			catchAllBefore = sawCatchAll;
 		}
 		index++;
 	}
-	if (pos === -1) return null;
+	if (pos === -1 || catchAllBefore) return null;
 	return { pos, value };
 }
 

diff --git a/packages/app-core/tests/router.test.ts b/packages/app-core/tests/router.test.ts
--- a/packages/app-core/tests/router.test.ts
+++ b/packages/app-core/tests/router.test.ts
@@ -143,4 +143,19 @@
 			params: { slug: 'guides/setup/' },
 		});
 	});
+
+	it('matches a catch-all that sits before a later static segment', function () {
+		const raw = new RenderRoute({ path: '/files/*path/raw', entry: '/src/raw.tsrx' });
+		const router = createRouter([raw]);
+
+		expect(router.match('GET', '/files/a/b/raw')).toEqual({
+			route: raw,
+			params: { path: 'a/b' },
+		});
+		expect(router.match('GET', '/files/a/raw')).toEqual({
+			route: raw,
+			params: { path: 'a' },
+		});
+		expect(router.match('GET', '/files/raw')).toBeNull();
+	});
 });

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit d4a6e8b. Configure here.

Comment thread packages/app-core/src/server/router.js Resolved
A static token after `*rest` is not at a fixed pathname index because
`(.+)` can consume several segments. Leave those patterns unindexed so
the existing RegExp matcher still finds them.

Co-authored-by: Jon Wheeler <[email protected]>
@cursor

cursor Bot commented Sep 4, 2026

Copy link
Copy Markdown

READY FOR REVIEW

@leonidaz

leonidaz commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator

this needs a merge from main and conflicts resolved.

Compose the #951 static path Map with last-static-segment dynamic indexing
and keep both sides' router tests.

Co-authored-by: Jon Wheeler <[email protected]>
@cursor

cursor Bot commented Sep 6, 2026

Copy link
Copy Markdown

Merged main (including #951's static path Map) and resolved the conflicts.

Static exact lookup stays O(1) via staticByPath. Dynamic routes still use the last-static-segment index, with mid-path catch-alls on the linear remainder. GitHub now reports the PR as mergeable.

Local re-check after the merge: 9/9 router tests, app-core typecheck, and router-dispatch ratio guards all passed. Composed scores on this machine (node benchmarks/router-dispatch/run.mjs 8): static 0.061, wrong-method 0.105, dynamic 0.289, dynamic-scan 119.029 ms/million.

The website Nitro preview playground hover assertion failed on justify-items.
Website files match main; the same test passed on the Vite-dev pass in that job.

Co-authored-by: Jon Wheeler <[email protected]>
@cursor

cursor Bot commented Sep 6, 2026

Copy link
Copy Markdown

CI on 1db484b90 failed for one website e2e, which then failed test (24) and CI provenance.

The only real failure was website/tests/ssr-hydration.e2e.test.ts on the Nitro preview pass: hovering justify-items in the playground source pane. The same assertion passed on the Vite-dev pass in that job. Website files on this branch match main (which is green); this PR only changes app-core routing and router-dispatch.

Pushed empty commit f92f9a111 to retrigger CI.

@vercel

vercel Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

2 Skipped Deployments
Project Deployment Actions Updated
octane-website Skipped Skipped Sep 6, 2026 7:31pm UTC
octane-website-mcp Skipped Skipped Sep 6, 2026 7:31pm UTC

Request Review

@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp September 6, 2026 19:31 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website September 6, 2026 19:31 Inactive
@leonidaz
leonidaz merged commit ab7bbc1 into main Sep 6, 2026
31 checks passed
@leonidaz
leonidaz deleted the cursor/runtime-perf-audit-8104 branch September 6, 2026 19:50

This branch was previously deployed

2 inactive deployments
Preview – octane-website-mcp — f92f9a11 Deployed Sep 6, 2026 by vercel[bot]
Preview – octane-website — f92f9a11 Deployed Sep 6, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work READY FOR REVIEW

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants