Skip to content

Make WTF::URLParser faster than Ada - #452

Merged
Jarred-Sumner merged 21 commits into
mainfrom
claude/faster-url-parser
Aug 16, 2026
Merged

Jarred-Sumner merged 21 commits into
mainfrom
claude/faster-url-parser

Conversation

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Summary

Makes WTF::URLParser (what new URL(), fetch, Bun.serve etc. go through) faster than Ada in every scenario I could construct, without changing its output.

How

  • A straight-line pass over the common special-scheme://host[/path][?query][#fragment] shape that hands off to the existing state machine at the first code unit needing more than a copy — so inputs that leave the fast path never pay twice.
  • Table-driven run scanners for the scheme / authority / path / query / fragment / opaque-path states, 16 characters at a time with the existing WTF::SIMD (simde) helpers; UTF-16 input is narrowed to bytes for classification. Path runs span / unless it may start a dot segment.
  • Host parsing only attempts IPv4 / ends-in-a-number when the last label can be a number; IPv4/IPv6/port/userinfo parsing rewritten over character pointers; canonical dotted-quad fast path; no UTF-8 round trip for IDN hosts without %; fused percent-decode+lowercase for percent-encoded ASCII hosts.
  • Fixed overhead: parser writes into the caller's URL, borrows const String& input (one fewer atomic ref/deref), URL::invalidate() inline, scheme classified from raw characters, 256-byte inline buffer + single reserve for the syntax-violation path, scheme://host → scheme://host/ built directly.
  • Two small WTF changes found along the way, in separate commits so they can be dropped independently:
    • hasUnpairedSurrogate() uses simdutf::validate_utf16 instead of iterating code points (this is what every USVString conversion goes through; it was ~40% of URL.canParse for 16-bit strings).
    • StringImpl::deref() skips the atomic read-modify-write when the count says this is the only reference (nobody else can hold a reference to add one from). This is broader than the URL parser; happy to split it out if you'd rather review it separately.

Behavior: intended to be byte-for-byte identical. One pre-existing quirk noticed and deliberately preserved (marked FIXME): foo://user@host?q gets a / inserted before ? for non-special schemes when there are credentials.

Numbers

Standalone harness (WTF::URL vs Ada 4.0.0 url_aggregator, its own http(s) fast path included; same clang 21 / -O3 / -march=nehalem; min of interleaved runs; this box is shared and noisy so treat ±10%). Cycles ratio WebKit/Ada, lower is better, before → after:

scenario 8-bit before 8-bit after UTF-16 after
top100 (Ada's dataset) 3.83 0.60 0.65
wikipedia 100k 3.39 0.46 0.60
linux_files / node_files 2.02 / 2.16 0.39 / 0.41 0.49 / 0.54
kasztp / userbait 3.04 / 3.55 0.61 / 0.56 0.74 / 0.68
tiny (9 B) / short (26 B) / medium (76 B) 1.97 / 1.48 / 3.05 0.67 / 0.48 / 0.61 0.83 / 0.51 / 0.64
long (3.9 KB avg) 3.32 0.25 0.42
relative / relative_wiki (with base) 1.48 / 2.38 0.68 / 0.78 0.74 / 0.83
WPT urltestdata ×20 1.26 0.68 0.78
ipv4 / ipv6 / idn 1.86 / 1.82 / 1.59 0.70 / 0.93 / 0.80 0.88 / 0.94 / 0.78
host_normalize / path_normalize / userinfo_port 2.29 / 1.91 / 1.13 0.77 / 0.63 / 0.59 0.84 / 0.73 / 0.80
nonspecial / file / invalid 1.41 / 1.37 / 1.21 0.52 / 0.45 / 0.48 0.59 / 0.59 / 0.56

(top100: 6482 → ~700 instructions per URL; Ada is 1566.)

In Bun (release build of this branch + oven-sh/bun companion PR, new URL() / URL.canParse per URL, min of 3, vs Node 26.3 and Bun 1.4): new URL() 1.1×–5.4× faster than Node across all 17 scenarios (was 1.3–3× slower), canParse 1.05×–2.8×.

Verification

  • Differential: output (href + every component offset) identical to the old parser on ~800k inputs × {Latin-1, UTF-16} — Ada's 6 datasets, the synthetic scenarios above, WPT urltestdata.json with bases, and a 60k structured fuzz corpus (tabs/newlines, IPv4/IPv6 edge forms, percent-encoding, credentials, file:/Windows drive letters, relative forms).
  • WPT urltestdata.json: 891/891 (unchanged).
  • TestWTF --gtest_filter='*URL*' (36 tests) and the string suites pass in a Debug build, where the parser also re-parses every input through the slow path (leading-space trick) and asserts allValuesEqual.
  • Same corpus under an ASan build of WTF: clean.
  • Bun's test/js/web/url, test/js/node/url, and the node test-whatwg-url-* / test-url-* parallel tests pass against a release build.

…r code point

Adds table-driven run scanners for the scheme, authority, path, query,
fragment and opaque-path states plus a straight-line pass over the common
special-scheme://host/path?query#fragment shape that hands off to the
state machine at the first character needing more than a copy. Host
parsing only attempts IPv4 / ends-in-a-number when the last label could
be a number, the parser writes into the caller's URL and borrows const
input strings, and URL::invalidate is inline.
…oid UTF-8 round trip for IDN hosts, cheaper isTabOrNewline
…ing code points

This is what every USVString conversion goes through; for 16-bit strings it
was ~40% of URL.canParse.
If the reference being dropped is the only one, no other thread can hold a
reference from which to add another, so a relaxed load suffices before
destroying.
…MD to end of authority for non-plain hosts, leaner CodePointIterator
@coderabbitai

coderabbitai Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 47 minutes

Limit details: You’ve used all 1 included review currently available under your plan. You completed 71 included PR reviews in the past 7 days; at that activity level, included reviews refill at 1 review per hour.

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9c1bb86e-4700-472a-82d1-0760ce636d62

📥 Commits

Reviewing files that changed from the base of the PR and between 592a255 and c20a429.

📒 Files selected for processing (10)
  • Source/WTF/wtf/URL.cpp
  • Source/WTF/wtf/URL.h
  • Source/WTF/wtf/URLParser.cpp
  • Source/WTF/wtf/URLParser.h
  • Source/WTF/wtf/cf/URLCF.cpp
  • Source/WTF/wtf/glib/URLGLib.cpp
  • Source/WTF/wtf/text/CodePointIterator.h
  • Source/WTF/wtf/text/StringImpl.h
  • Source/WTF/wtf/text/StringView.h
  • Tools/TestWebKitAPI/Tests/WTF/URLParser.cpp

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Preview Builds

Commit Release Date
c20a4294 autobuild-preview-pr-452-c20a4294 2026-08-16 06:20:51 UTC
dd3a1e3b autobuild-preview-pr-452-dd3a1e3b 2026-08-16 02:52:10 UTC

Comment thread Source/WTF/wtf/URLParser.cpp Resolved
…arser did; own the input string; one lastLabelMayBeANumber; update URLGLib.cpp

- parseHostAndPort checked for unpaired surrogates after removing tabs and
  newlines, so a pair split by one was reunited and accepted. The old parser
  iterated code points over the raw host and saw two unpaired surrogates.
  Check before stripping. Adds a TestWTF case.
- Replace the borrowed 'const String& m_inputString' + m_ownedInputString pair
  with one owned String that is moved into the result; same refcount traffic
  on the no-violation path, no self-referential member.
- Hoist the three copies of the ends-in-a-number pre-check into one helper.
- URL(GUri*) still used the removed URLParser(String&&)/result() API.

@claude claude 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.

Re-reviewed after c20a429 — the surrogate-split-by-tab fix looks correct (raw hasUnpairedSurrogate(host) check now precedes tab stripping, and the new TestWTF cases cover both http and file hosts). This run found no further issues.

Given the scope — a near-complete rewrite of the URL parser state machine with SIMD scanners, new IPv4/IPv6/host fast paths, and the StringImpl::deref() refcount change that reaches well beyond URL parsing — a human review is still warranted before merge.

What was reviewed:

  • c20a429 fix: hasUnpairedSurrogate on raw host span before tab removal; both !hasPercent and else branches now agree.
  • lastLabelMayBeANumber gate vs. the old unconditional parseIPv4Host/dnsNameEndsInNumber — covers hex/octal/trailing-dot forms the spec's ends-in-a-number checker requires.
  • SIMD scanner stop-character sets vs. scanClassTable bits (PathStop/QueryStop/FragmentStop/HostStop) and the x86 signed-pack-to-0 note — 0 is a stop in every vectorStop lambda.
  • StringImpl::deref() single-ref fast path — relaxed load followed by RMW fallback preserves the destroy-on-last-ref invariant.
Extended reasoning...

Overview

This PR rewrites the hot paths of WTF::URLParser for performance: a straight-line fast path for the common scheme://host/path?query#fragment shape, SIMD-based (16-wide) run scanners for each state, pointer-based IPv4/IPv6/port/userinfo parsing replacing CodePointIterator loops, a lastLabelMayBeANumber gate to skip IPv4/ends-in-a-number checks, and fused percent-decode+lowercase for ASCII hosts. It also changes the URLParser constructor to write into a caller-owned URL&, inlines URL::invalidate(), adds a 256-byte inline capacity to m_asciiBuffer, and rewrites CodePointIterator's operators. Two independent WTF-wide changes ride along: hasUnpairedSurrogate() now uses isWellFormedUTF16 (simdutf), and StringImpl::deref() skips the atomic RMW when refcount is already 1.

The diff is ~1500 lines across 10 files, with the bulk in URLParser.cpp.

Security risks

URL parsing is security-critical: the host component determines origin, and any divergence in what is accepted as a host, how IPv4 shorthand/overflow is handled, how percent-decoding interacts with IDN, or where the authority terminates can create origin-confusion or SSRF-style bugs. Specific surfaces this PR touches:

  • Host termination scanning (findHostCharacterOfInterest, findEndOfSpecialAuthority): a missed stop character could shift the host/path boundary.
  • IPv4 ends-in-a-number gate (lastLabelMayBeANumber): if it under-matches, a numeric host that should fail or canonicalize could pass through as a DNS name.
  • SIMD narrowing of UTF-16 to bytes for classification: relies on every scanner treating both 0 and 0xFF (and >0x7E) as stops, which the static_assert and controlSpaceOrNonASCII cover.
  • StringImpl::deref(): a refcounting change that affects every string in the process. The reasoning (relaxed load of 1 means no other thread can hold a ref to race on) is sound for the ownership model here, but it's a process-wide invariant change.

The PR's verification (800k+120k differential inputs against the old parser, WPT, ASan, debug self-check re-parse) is strong mitigation, and the one divergence I found in the previous run was fixed and regression-tested.

Level of scrutiny

High. This is not a mechanical refactor — it's a performance rewrite of a spec-driven, security-relevant parser with many hand-rolled fast paths that must each fall back to the slow path at exactly the right boundary. The differential testing is excellent and the debug-build allValuesEqual self-check is a strong invariant, but the change is large enough that a human familiar with the WHATWG URL spec and this parser's history should sign off, particularly on the StringImpl::deref() change (which the author explicitly offered to split out).

Other factors

  • My prior review's finding (surrogate pair split by tab in host) was confirmed, fixed in c20a429, and covered by new TestWTF cases plus an expanded fuzz corpus.
  • The author explicitly flagged the StringImpl::deref() change as broader-scope and offered to split it — a reviewer may want to take them up on that.
  • CI preview builds are green; TestWTF URL suite and Bun's URL tests pass per the description.

Jarred-Sumner added a commit to oven-sh/bun that referenced this pull request Aug 16, 2026
…ew-pr-452-c20a4294)

No-Verification-Needed: version pin bump
@Jarred-Sumner
Jarred-Sumner merged commit 0cbb4a1 into main Aug 16, 2026
47 checks passed
Jarred-Sumner added a commit to oven-sh/bun that referenced this pull request Aug 16, 2026
…unycode (#39273)

### What does this PR do?

Bumps WebKit to oven-sh/WebKit@0cbb4a194653 — the rewritten
`WTF::URLParser` (oven-sh/WebKit#452), which is what `new URL()`,
`URL.canParse`, `fetch`, `Bun.serve` routing etc. go through — plus one
Bun-side fix it exposed:

- **Only re-run ICU on `xn--` labels that were literally in the input.**
`hasValidParsedHost()` (Node-compat rejection of invalid punycode)
re-ran ICU ToASCII on every host containing `xn--`, including punycode
the parser had just produced from a Unicode host, so IDN URLs paid for
ICU twice. Now it only does that when the input's authority could have
contained the label literally (contains `xn--` case-insensitively, or
`%`; tabs/newlines anywhere also force the check).
- Adds a full WPT `url-constructor` test over the vendored
`urltestdata.json` (868 cases; previously only the failure half ran via
the node suite).

(The DOM wrapper-cache change that was previously in this PR has been
dropped in favour of a separate PR.)

### How did you verify your code works?

- `test/js/web/url`, `test/js/node/url`, node `test-whatwg-url-*` /
`test-url-*` pass against a release build with the new WebKit.
- The parser itself: byte-identical to the old one on ~2.3M differential
parses (Ada's datasets + everything harvestable from Ada's repo, WPT
with bases, Windows/UNC and surrogate-focused sets, structured fuzz) in
both string widths, plus a libFuzzer old-vs-new differential run (150M+
execs, ASan + parser asserts) with zero mismatches; WPT 891/891; TestWTF
URL suites.
- JS-level, ns per URL (min of 3), Node 26.3 / Bun 1.4 / this branch —
note the `new URL()` column here still includes the wrapper-cache cost
that the separate PR removes:

| scenario | `URL.canParse`: node / 1.4 / **new** |
|---|---|
| tiny (9 B) | 163 / 156 / **72** |
| short (26 B) | 210 / 286 / **97** |
| top100 (Ada dataset) | 515 / 987 / **184** |
| wikipedia 100k | 157 / 429 / **140** |
| long (3.9 KB) | 1757 / 15451 / **829** |
| relative (with base) | 433 / 944 / **343** |
| ipv4 · ipv6 | 220/262/**151** · 229/575/**219** |
| idn | 1674 / 2829 / **1303** |
| host · path normalize | 420/1000/**400** · 537/1156/**439** |
| userinfo · nonspecial · file · invalid | 479/850/**217** ·
290/377/**198** · 194/385/**114** · 168/227/**94** |
anonrig added a commit to ada-url/ada that referenced this pull request Aug 17, 2026
* perf: SIMD scanners, last-label IPv4 gate, and host-preserving fast path

Port the high-impact ideas from oven-sh/WebKit#452 into Ada:

- Scan host/path/query/fragment 16 bytes at a time (SSE2/NEON) on the
  special-scheme absolute fast path, instead of a byte-at-a-time table walk.
- When the host is a plain domain but the rest needs encoding or dot-segment
  work, keep the parsed host and finish with the existing helpers so those
  inputs never pay for a second full parse.
- Accept ws/wss/ftp on the same fast path, and allow apostrophes in paths
  (they are not in the path percent-encode set).
- Gate IPv4 parsing on last_label_may_be_a_number so ordinary domain names
  skip try_parse_ipv4_fast and is_ipv4. This also avoids the .com/.org case
  where is_ipv4's last-character check is a false positive (m/g are hex).

Co-authored-by: Yagiz Nizipli <[email protected]>

* fix: clang-tidy string_view assign, restore IPv4 fast path, add coverage

- Use assign(substr) instead of assign(data(), n) so clang-tidy does not
  flag bugprone-suspicious-stringview-data-usage.
- Run try_parse_ipv4_fast before the last-label gate again. Wrapping the
  decimal IPv4 kernel in last_label_may_be_a_number added a second walk
  on every IPv4 host and regressed the IPv4 benches. The gate still skips
  is_ipv4 on ordinary domain names.
- Drop a dead rest-scan branch (plain-host scan only stops at / ? # or
  EOF) and add tests for SIMD-length hosts/paths, handoff cases, and
  last_label_may_be_a_number edge cases.

Co-authored-by: Yagiz Nizipli <[email protected]>

* fix: drop last_label from parse_host and skip IPv6 fast path

The last_label gate before is_ipv4 was redundant and slowed IPv4
microbenchmarks. Skip '[' hosts so IPv6 does not enter the SIMD
scanner. Hide the big-endian HTTP matcher behind #else and add
fast-path edge-case tests for patch coverage.

Co-authored-by: Yagiz Nizipli <[email protected]>

* test: correct fast-path edge assertions for empty host and FQDN

http:/// is invalid, and a trailing-dot domain keeps the dot.

Co-authored-by: Yagiz Nizipli <[email protected]>

* refactor: keep last-label gate private and dedupe handoff

Do not add last_label_may_be_a_number to the public checkers API.
Keep it in the parser fast path only, and share query/hash handoff
between url and url_aggregator.

Co-authored-by: Yagiz Nizipli <[email protected]>

* perf: skip SIMD fast path when userinfo is present

SetHref parses https://user:pass@... and was 3.29% slower because it
entered the larger SIMD scanner only to reject at ':'. A 24-byte '@'
peek keeps that path on the original parser.

Co-authored-by: Yagiz Nizipli <[email protected]>

* perf: detect userinfo only in the authority prefix

The 24-byte '@' peek treated https://www.tiktok.com/@user as userinfo
and skipped the SIMD path, regressing Bench_BasicBench by ~4.5%. Scan
':' and '@' in the first 16 authority bytes and stop at '/' '?' '#'.

Co-authored-by: Yagiz Nizipli <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Yagiz Nizipli <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant