Repository navigation
Make WTF::URLParser faster than Ada - #452
Conversation
…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
… userinfo runs and ports
…host path, cheaper short UTF-16 appends
…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
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. 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. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (10)
Comment |
Preview Builds
|
…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.
There was a problem hiding this comment.
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:
hasUnpairedSurrogateon raw host span before tab removal; both!hasPercentandelsebranches now agree. lastLabelMayBeANumbergate vs. the old unconditionalparseIPv4Host/dnsNameEndsInNumber— covers hex/octal/trailing-dot forms the spec's ends-in-a-number checker requires.- SIMD scanner stop-character sets vs.
scanClassTablebits (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_assertandcontrolSpaceOrNonASCIIcover. 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.
…ew-pr-452-c20a4294) No-Verification-Needed: version pin bump
…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** |
* 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]>
Summary
Makes
WTF::URLParser(whatnew URL(),fetch,Bun.serveetc. go through) faster than Ada in every scenario I could construct, without changing its output.How
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.WTF::SIMD(simde) helpers; UTF-16 input is narrowed to bytes for classification. Path runs span/unless it may start a dot segment.%; fused percent-decode+lowercase for percent-encoded ASCII hosts.URL, borrowsconst 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.hasUnpairedSurrogate()usessimdutf::validate_utf16instead of iterating code points (this is what everyUSVStringconversion goes through; it was ~40% ofURL.canParsefor 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?qgets a/inserted before?for non-special schemes when there are credentials.Numbers
Standalone harness (
WTF::URLvs Ada 4.0.0url_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:(top100: 6482 → ~700 instructions per URL; Ada is 1566.)
In Bun (release build of this branch + oven-sh/bun companion PR,
new URL()/URL.canParseper 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),canParse1.05×–2.8×.Verification
href+ every component offset) identical to the old parser on ~800k inputs × {Latin-1, UTF-16} — Ada's 6 datasets, the synthetic scenarios above, WPTurltestdata.jsonwith bases, and a 60k structured fuzz corpus (tabs/newlines, IPv4/IPv6 edge forms, percent-encoding, credentials,file:/Windows drive letters, relative forms).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 assertsallValuesEqual.test/js/web/url,test/js/node/url, and the nodetest-whatwg-url-*/test-url-*parallel tests pass against a release build.