← Back to Pull requests

perf: optimize native parse_url extraction #7329

Merged
sunchao merged 3 files (437 lines) on Oct 31, 2026 01:16 UTC
View on GitHub
sunchao sunchao commented on Oct 30, 2026 00:00 UTC
Author

Which issue does this PR close?

This optimizes the existing native URL expressions. There is no linked issue.

Rationale for this change

On the base revision, native parse_url and try_parse_url use a general URI regular expression to find components. Successful extractions produce temporary owned strings before Arrow copies the values into its output buffers. Both costs recur across the rows in a batch.

What changes are included in this PR?

Split raw URI components at their delimiters for all schemes, including HTTP, HTTPS and FTP. Borrow the requested component until Arrow copies it into independently owned output buffers. FILE uses the contiguous raw path and optional query. A query-key lookup still uses the existing cached regular expression and capture semantics.

Extend the benchmark to cover all three Arrow string layouts, short and long URLs, nulls, Unicode, query keys, invalid inputs, and FTP host extraction.

How are these changes tested?

  • All 31 native URL tests passed on the checked-in dependency lock. They cover parity with the old Appendix B regex, raw FILE and query captures, strict and tolerant errors, and the memory retained by a short Utf8View host.

  • A standalone comparison of the parser functions matched 728,874 component results against both the upstream base and the previous PR revision, including relative URLs, non-HTTP schemes and malformed inputs.

  • Focused Clippy passed with warnings treated as errors for the library, tests and benchmark. Rust formatting, the JVM formatting tasks and git diff --check passed.
  • Benchmark measurements

    Compared source commit fd76067feab04eecba8c462f04c7a25a8f80bc38 with upstream base 7f73d86fb841f5662f1343cf52b6e6b31eb17dfb using the same benchmark harness. Each measurement covers a complete native UDF call over 8,192 rows, including scalar argument broadcasting and Arrow output construction. Spark query execution is outside the measurement.

    Times are Criterion means in milliseconds per batch. Speedup is the unrounded base mean divided by the unrounded PR mean.

    | Workload | Arrow layout | Base (ms) | PR (ms) | Speedup |
    | --- | --- | ---: | ---: | ---: |
    | HTTP host | Utf8 | 8.767 | 1.667 | 5.26× |
    | HTTPS host | Utf8 | 9.236 | 1.541 | 5.99× |
    | Long HTTPS path | Utf8 | 213.976 | 33.715 | 6.35× |
    | Long HTTPS path | Utf8View | 188.189 | 18.158 | 10.36× |
    | HTTPS query by key | Utf8 | 10.702 | 3.154 | 3.39× |
    | HTTPS path, 10% null | Utf8 | 7.888 | 1.279 | 6.17× |
    | HTTPS path, 90% null | Utf8 | 1.016 | 0.241 | 4.21× |
    | FTP host | Utf8 | 9.189 | 1.444 | 6.37× |

    <details>
    <summary>Full results for all 25 benchmark cases</summary>

    | Case | Base (ms) | PR (ms) | Speedup |
    | --- | ---: | ---: | ---: |
    | dense_nulls/Utf8/PATH | 1.016 | 0.241 | 4.21× |
    | ftp/LargeUtf8/HOST | 8.658 | 1.501 | 5.77× |
    | ftp/Utf8/HOST | 9.189 | 1.444 | 6.37× |
    | ftp/Utf8View/HOST | 8.616 | 1.489 | 5.79× |
    | http/Utf8/HOST | 8.767 | 1.667 | 5.26× |
    | https/LargeUtf8/FILE | 9.626 | 1.367 | 7.04× |
    | https/LargeUtf8/HOST | 9.029 | 1.592 | 5.67× |
    | https/LargeUtf8/PATH | 8.934 | 1.341 | 6.66× |
    | https/Utf8/AUTHORITY | 8.714 | 1.332 | 6.54× |
    | https/Utf8/FILE | 9.727 | 1.332 | 7.31× |
    | https/Utf8/HOST | 9.236 | 1.541 | 5.99× |
    | https/Utf8/PATH | 9.032 | 1.333 | 6.78× |
    | https/Utf8/PROTOCOL | 8.719 | 1.359 | 6.42× |
    | https/Utf8/QUERY | 8.600 | 1.385 | 6.21× |
    | https/Utf8/REF | 8.748 | 1.338 | 6.54× |
    | https/Utf8View/FILE | 9.544 | 1.357 | 7.03× |
    | https/Utf8View/HOST | 9.018 | 1.594 | 5.66× |
    | https/Utf8View/PATH | 8.904 | 1.441 | 6.18× |
    | https_long/LargeUtf8/PATH | 207.091 | 33.641 | 6.16× |
    | https_long/Utf8/PATH | 213.976 | 33.715 | 6.35× |
    | https_long/Utf8View/PATH | 188.189 | 18.158 | 10.36× |
    | query_key | 10.702 | 3.154 | 3.39× |
    | sparse_nulls/Utf8/PATH | 7.888 | 1.279 | 6.17× |
    | try_invalid/Utf8/PATH | 7.944 | 1.281 | 6.20× |
    | unicode/Utf8/PATH | 9.306 | 1.444 | 6.45× |

    </details>

    Non-null HTTP(S) component cases measured 5.26× to 10.36×. FTP host extraction measured 5.77× to 6.37× across the three Arrow layouts. FTP uses the same delimiter parser as HTTP(S).

    Criterion collected 20 samples per case per revision with a 1-second warmup and a 2-second requested measurement period.

    Both release builds used the checked-in native/Cargo.lock, Rust 1.98.1, the default allocator, LTO disabled and 16 codegen units. Measurements ran serially on the same AMD EPYC Milan Linux x86-64 host with the same CPU affinity. Criterion extended the sampling time for longer cases.

    From the root of a checkout of this PR, run the same benchmark harness on both revisions and save the baseline in a shared Criterion directory. Both builds use the same dependency lock.

    bench_dir=$(mktemp -d)
    git worktree add --detach "$bench_dir/base" 7f73d86fb841
    bench_file=native/spark-expr/benches/parse_url.rs
    cp "$bench_file" "$bench_dir/base/$bench_file"
    export CRITERION_HOME="$bench_dir/criterion"
    export CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16
    
    bench() {
      cargo bench --locked -p datafusion-comet-spark-expr --bench parse_url -- \
        --sample-size 20 --warm-up-time 1 --measurement-time 2 --noplot "$@"
    }
    (cd "$bench_dir/base/native" && bench --save-baseline main)
    (cd native && bench --baseline main)
    

    Diff: 437 lines (+331 / -106) across 3 files Reviewer: viirya Review duration: 1515m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.42) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.42 · 437 lines diff across 3 files
    0.42
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.93 · 5 substantive comment(s)
    0.93
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.364
    Real PR Conversation Timeline
    16 items
    sunchao sunchao commented on Oct 30, 2026 00:19 UTC
    Author

    cc @andygrove @comphead @viirya for review

    comphead comphead commented on code on Oct 30, 2026 01:25 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -133,17 +194,18 @@ fn parse_url_component(value: &str, part: &str, key: Option<&str>) -> Result<Opt
             return Err(invalid_url_err(value));
         }
     
    -    let caps = match URI_REGEX.captures(value) {
    -        Some(c) => c,
    -        None => return Ok(None),
    +    let Some(UriParts {
    +        scheme,
    +        authority,
    +        path,
    +        file,
    +        query,
    +        fragment,
    +    }) = decompose_http(value).or_else(|| decompose_generic(value))

    The Appendix B regex is a fixed delimiter split, so one hand-written splitter could replace both decompose_http and decompose_generic for every input, removing URI_REGEX, the second decomposer and the parity test, and extending the speedup to ftp://, HTTP://, mailto: and scheme-relative inputs (the FTP control is 1.03x today). With leftmost-first matching, (([^:/?#]+):)? is taken exactly when the first of :/?# is a : at index > 0, and the rest always matches unless there is a \n in the fragment, which has_invalid_uri_chars already rejects. Roughly:

    let (scheme, rest) = match value.find([':', '/', '?', '#']) {
        Some(i) if i > 0 && value.as_bytes()[i] == b':' => (Some(&value[..i]), &value[i + 1..]),
        _ => (None, value),
    };
    // then the authority split on "//" and the remainder as in decompose_http
    

    In a local probe outside the repo, against regex 1.13.1 from the lockfile, such a splitter matched URI_REGEX on 1.78M random inputs that pass validation, and decomposed 8,192 benchmark-shaped FTP URLs in about 0.16 ms against 4.3 to 5.4 ms for the regex (decomposition only, not the UDF).

    comphead comphead commented on code on Oct 30, 2026 01:25 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -388,11 +449,100 @@ mod tests {
         // Unit tests for parse_url_component
         // -----------------------------------------------------------------------
     
    +    #[test]
    +    fn http_decomposition_matches_generic_parser() {
    +        for scheme in ["http", "https"] {
    +            for authority in [
    +                "example.com",
    +                "u:p@host:80",
    +                "",
    +                "[::1]:80",
    +                "[::1",
    +                "host:",
    +                "例子.com",
    +            ] {
    +                for tail in [
    +                    "",
    +                    "/",
    +                    "//a/b",
    +                    "?",
    +                    "#",
    +                    "?#",
    +                    "?x=1#f?y",
    +                    "#f?x=1",
    +                    "/é?k=值#片",
    +                    "/p?a=?b#f#x",
    +                ] {
    +                    let url = format!("{scheme}://{authority}{tail}");
    +                    assert_eq!(decompose_http(&url), decompose_generic(&url), "{url}");
    +                }
    +            }
    +        }
    +        for url in ["HTTP://host/p", "https:/p", "ftp://host/p", "mailto:a@b"] {
    +            assert!(decompose_http(url).is_none(), "{url}");
    +        }
    +    }
    +
    +    #[test]
    +    fn file_and_query_components() -> Result<()> {
    +        for (url, part, key, expected) in [
    +            ("http://h?x=1#f?y", "FILE", None, "?x=1"),
    +            ("http://h?#", "FILE", None, "?"),
    +            ("HTTP://h/p?#f", "FILE", None, "/p?"),
    +            ("ftp://h/p?x=1#f", "FILE", None, "/p?x=1"),
    +            ("https://h/é?k=值#片", "PATH", None, "/é"),
    +            // The key may introduce capture groups; both Spark and the existing
    +            // matcher return group 2 of the full pattern, not its last group.
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("v"), "2"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),

    This row repeats line 496 exactly.

    comphead comphead commented on code on Oct 30, 2026 01:25 UTC
    Code Review
    docs/source/contributor-guide/expression-audits/url_funcs.md:1
    @@ -25,6 +25,8 @@
     
     - Performance (tuned 2026-07-11, PR [#4893](https://github.com/apache/datafusion-comet/pull/4893)): cache the compiled query regex in a thread-local single-slot cache keyed by the query key, eliminating per-row `Regex::new()` recompilation in the QUERY-with-key path (the key is constant across a batch in practice). Up to 50x faster. Benchmark: `benches/parse_url.rs`.
     
    +- Performance (tuned 2026-10-30, PR [#7329](https://github.com/apache/datafusion-comet/pull/7329)): borrow raw URL components and use delimiter decomposition for HTTP/HTTPS. Non-null HTTP(S) component microbenchmarks are 5.5–9.4x faster and query-key extraction is 3.1x faster. The PR records the alternate-lockfile measurement environment and generic-parser controls. Benchmark: `benches/parse_url.rs`.

    The other entries here name the technique, the speedup, the PR and the benchmark. The lockfile sentence describes how this PR was measured, which the description already covers, and will not help someone checking later whether parse_url has been tuned. Could it go?

    comphead comphead commented on Oct 30, 2026 01:25 UTC
    Reviewer

    The fast path sits after has_invalid_uri_chars and feeds the same bracket, scheme and :// checks, so it changes results only if the two decomposers disagree, and in a local probe of 3M random strings (558k starting with http:// or https://) they never did on inputs that pass validation. The query-key regex and group 2 match Spark's UrlExpressionEvalUtils, and FromIterator<Option<&str>> copies into fresh buffers for all three layouts. Three comments.

    Separately, and not caused by this PR: a JDK 17 probe of java.net.URI shows main already differs from Spark on a few inputs. http://a_b.com/p and http://u@v@h/p give a null host in Java (registry-based authority), where extract_host returns a_b.com and h, and http://h/%zz and http://h/p#a#b throw URISyntaxException in Java, so Spark returns NULL or raises, while has_invalid_uri_chars lets both through. That seems worth its own issue.

    viirya viirya commented on Oct 30, 2026 08:11 UTC
    Reviewer

    The HTTP(S) fast path is equivalent to the regex on validated input: it splits at the first #, then at the first ?, which is what [^?#] / [^#] do. Borrowed slices are copied into fresh output buffers for all three layouts. The FTP control (1.03x) suggests nearly all of the gain comes from skipping the regex rather than from dropping the per-row Strings. That makes the single-splitter route comphead suggested the more valuable direction: it would carry the same speedup to every scheme instead of only lowercase http:///https:// prefixes.

    viirya viirya commented on code on Oct 30, 2026 08:11 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -388,11 +449,100 @@ mod tests {
         // Unit tests for parse_url_component
         // -----------------------------------------------------------------------
     
    +    #[test]
    +    fn http_decomposition_matches_generic_parser() {
    +        for scheme in ["http", "https"] {
    +            for authority in [
    +                "example.com",
    +                "u:p@host:80",
    +                "",
    +                "[::1]:80",
    +                "[::1",
    +                "host:",
    +                "例子.com",
    +            ] {
    +                for tail in [
    +                    "",
    +                    "/",
    +                    "//a/b",
    +                    "?",
    +                    "#",
    +                    "?#",
    +                    "?x=1#f?y",
    +                    "#f?x=1",
    +                    "/é?k=值#片",
    +                    "/p?a=?b#f#x",
    +                ] {
    +                    let url = format!("{scheme}://{authority}{tail}");
    +                    assert_eq!(decompose_http(&url), decompose_generic(&url), "{url}");
    +                }
    +            }
    +        }
    +        for url in ["HTTP://host/p", "https:/p", "ftp://host/p", "mailto:a@b"] {
    +            assert!(decompose_http(url).is_none(), "{url}");
    +        }
    +    }
    +
    +    #[test]
    +    fn file_and_query_components() -> Result<()> {
    +        for (url, part, key, expected) in [
    +            ("http://h?x=1#f?y", "FILE", None, "?x=1"),
    +            ("http://h?#", "FILE", None, "?"),
    +            ("HTTP://h/p?#f", "FILE", None, "/p?"),
    +            ("ftp://h/p?x=1#f", "FILE", None, "/p?x=1"),
    +            ("https://h/é?k=值#片", "PATH", None, "/é"),
    +            // The key may introduce capture groups; both Spark and the existing
    +            // matcher return group 2 of the full pattern, not its last group.
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("v"), "2"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),
    +        ] {
    +            let result = parse_url_component(url, part, key)?.unwrap();
    +            assert_eq!(result, expected);
    +        }
    +        // Extraction must still reject an invalid component after the requested host.
    +        assert!(parse_url_component("https://host/p#invalid fragment", "HOST", None).is_err());
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn sliced_string_layouts_produce_owned_output() -> Result<()> {

    This test can't fail because of anything this PR changes. It checks that Arrow's FromIterator<Option<&str>> copies into fresh buffers, which also held before this PR, since the old code collected Option<String>. "The output remains valid after dropping all inputs" is already guaranteed by ArrayRef being 'static. The only thing it would catch is a future switch to zero-copy views of the input, which nothing here is moving toward. Unless that risk is concrete, I'd drop this test and the matching comment on process_parse_url (line 423), since slicing over the three layouts is Arrow's iterator behavior, not parse_url logic.

    viirya viirya commented on code on Oct 30, 2026 08:11 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -133,17 +194,18 @@ fn parse_url_component(value: &str, part: &str, key: Option<&str>) -> Result<Opt
             return Err(invalid_url_err(value));
         }
     
    -    let caps = match URI_REGEX.captures(value) {
    -        Some(c) => c,
    -        None => return Ok(None),
    +    let Some(UriParts {
    +        scheme,
    +        authority,
    +        path,
    +        file,
    +        query,
    +        fragment,
    +    }) = decompose_http(value).or_else(|| decompose_generic(value))

    +1. One more reason it's safe: on any input that passes has_invalid_uri_chars, URI_REGEX always matches. Every group is optional or can be empty, and the only way to fail is a \n inside the fragment (. excludes it), which is already rejected as a control character. So the let … else { return Ok(None) } arm here and the caps.get(5)? in decompose_generic are unreachable today. A total splitter would make that explicit, and URI_REGEX could move into the tests as the oracle for a parity test covering all schemes, not just http/https. I also fuzzed both decompose_http and the splitter sketched above against the regex on ~1.4M random validated inputs (biased toward :/?#@[], non-ASCII, and http:///HTTP:///// fragments) and found no mismatch.

    sunchao sunchao commented on code on Oct 30, 2026 15:09 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -133,17 +194,18 @@ fn parse_url_component(value: &str, part: &str, key: Option<&str>) -> Result<Opt
             return Err(invalid_url_err(value));
         }
     
    -    let caps = match URI_REGEX.captures(value) {
    -        Some(c) => c,
    -        None => return Ok(None),
    +    let Some(UriParts {
    +        scheme,
    +        authority,
    +        path,
    +        file,
    +        query,
    +        fragment,
    +    }) = decompose_http(value).or_else(|| decompose_generic(value))

    Replaced both decomposers with one delimiter splitter in fd76067fea. It preserves the scheme spelling, empty components and raw FILE slice. The old Appendix B regex is now only a test oracle for HTTP, FTP, opaque and relative inputs. The separate Java URI compatibility cases are tracked in #7330.

    I also compared complete native HOST calls against the previous HTTP(S) fast path on the checked-in lockfile. These are Criterion means in ms per 8,192 rows, using Utf8.

    | Input | Previous fast path | Single splitter |
    | --- | ---: | ---: |
    | FTP | 8.523 | 1.485 |
    | HTTP | 1.573 | 1.603 |
    | HTTPS | 1.549 | 1.596 |

    FTP improved 5.74×. Criterion did not detect a statistically significant change for HTTP or HTTPS. All 25 comparisons against the upstream base are in the PR benchmark table.

    sunchao sunchao commented on code on Oct 30, 2026 15:09 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -388,11 +449,100 @@ mod tests {
         // Unit tests for parse_url_component
         // -----------------------------------------------------------------------
     
    +    #[test]
    +    fn http_decomposition_matches_generic_parser() {
    +        for scheme in ["http", "https"] {
    +            for authority in [
    +                "example.com",
    +                "u:p@host:80",
    +                "",
    +                "[::1]:80",
    +                "[::1",
    +                "host:",
    +                "例子.com",
    +            ] {
    +                for tail in [
    +                    "",
    +                    "/",
    +                    "//a/b",
    +                    "?",
    +                    "#",
    +                    "?#",
    +                    "?x=1#f?y",
    +                    "#f?x=1",
    +                    "/é?k=值#片",
    +                    "/p?a=?b#f#x",
    +                ] {
    +                    let url = format!("{scheme}://{authority}{tail}");
    +                    assert_eq!(decompose_http(&url), decompose_generic(&url), "{url}");
    +                }
    +            }
    +        }
    +        for url in ["HTTP://host/p", "https:/p", "ftp://host/p", "mailto:a@b"] {
    +            assert!(decompose_http(url).is_none(), "{url}");
    +        }
    +    }
    +
    +    #[test]
    +    fn file_and_query_components() -> Result<()> {
    +        for (url, part, key, expected) in [
    +            ("http://h?x=1#f?y", "FILE", None, "?x=1"),
    +            ("http://h?#", "FILE", None, "?"),
    +            ("HTTP://h/p?#f", "FILE", None, "/p?"),
    +            ("ftp://h/p?x=1#f", "FILE", None, "/p?x=1"),
    +            ("https://h/é?k=值#片", "PATH", None, "/é"),
    +            // The key may introduce capture groups; both Spark and the existing
    +            // matcher return group 2 of the full pattern, not its last group.
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("v"), "2"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),

    Removed the repeated (abc) row in fd76067fea. The two remaining query-key cases cover capture group 2 and changing the key to v.

    sunchao sunchao commented on code on Oct 30, 2026 15:09 UTC
    Code Review
    docs/source/contributor-guide/expression-audits/url_funcs.md:1
    @@ -25,6 +25,8 @@
     
     - Performance (tuned 2026-07-11, PR [#4893](https://github.com/apache/datafusion-comet/pull/4893)): cache the compiled query regex in a thread-local single-slot cache keyed by the query key, eliminating per-row `Regex::new()` recompilation in the QUERY-with-key path (the key is constant across a batch in practice). Up to 50x faster. Benchmark: `benches/parse_url.rs`.
     
    +- Performance (tuned 2026-10-30, PR [#7329](https://github.com/apache/datafusion-comet/pull/7329)): borrow raw URL components and use delimiter decomposition for HTTP/HTTPS. Non-null HTTP(S) component microbenchmarks are 5.5–9.4x faster and query-key extraction is 3.1x faster. The PR records the alternate-lockfile measurement environment and generic-parser controls. Benchmark: `benches/parse_url.rs`.

    Removed the lockfile sentence from the audit in c342675322. The entry now records the technique, measured speedups and benchmark. The PR description has the measurement setup for the new runs on the checked-in lockfile.

    sunchao sunchao commented on code on Oct 30, 2026 15:09 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -388,11 +449,100 @@ mod tests {
         // Unit tests for parse_url_component
         // -----------------------------------------------------------------------
     
    +    #[test]
    +    fn http_decomposition_matches_generic_parser() {
    +        for scheme in ["http", "https"] {
    +            for authority in [
    +                "example.com",
    +                "u:p@host:80",
    +                "",
    +                "[::1]:80",
    +                "[::1",
    +                "host:",
    +                "例子.com",
    +            ] {
    +                for tail in [
    +                    "",
    +                    "/",
    +                    "//a/b",
    +                    "?",
    +                    "#",
    +                    "?#",
    +                    "?x=1#f?y",
    +                    "#f?x=1",
    +                    "/é?k=值#片",
    +                    "/p?a=?b#f#x",
    +                ] {
    +                    let url = format!("{scheme}://{authority}{tail}");
    +                    assert_eq!(decompose_http(&url), decompose_generic(&url), "{url}");
    +                }
    +            }
    +        }
    +        for url in ["HTTP://host/p", "https:/p", "ftp://host/p", "mailto:a@b"] {
    +            assert!(decompose_http(url).is_none(), "{url}");
    +        }
    +    }
    +
    +    #[test]
    +    fn file_and_query_components() -> Result<()> {
    +        for (url, part, key, expected) in [
    +            ("http://h?x=1#f?y", "FILE", None, "?x=1"),
    +            ("http://h?#", "FILE", None, "?"),
    +            ("HTTP://h/p?#f", "FILE", None, "/p?"),
    +            ("ftp://h/p?x=1#f", "FILE", None, "/p?x=1"),
    +            ("https://h/é?k=值#片", "PATH", None, "/é"),
    +            // The key may introduce capture groups; both Spark and the existing
    +            // matcher return group 2 of the full pattern, not its last group.
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("v"), "2"),
    +            ("https://h/?abc=1&v=2", "QUERY", Some("(abc)"), "abc"),
    +        ] {
    +            let result = parse_url_component(url, part, key)?.unwrap();
    +            assert_eq!(result, expected);
    +        }
    +        // Extraction must still reject an invalid component after the requested host.
    +        assert!(parse_url_component("https://host/p#invalid fragment", "HOST", None).is_err());
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn sliced_string_layouts_produce_owned_output() -> Result<()> {

    Removed the three-layout slicing loop, the input-drop check and the production comment in fd76067fea. I kept one Utf8View assertion for buffer retention. An owning view can remain valid while keeping the entire input allocation alive. The test checks that extracting the 16-byte host from a 128 KiB URL produces an output smaller than the input buffer.

    viirya viirya commented on code on Oct 30, 2026 16:34 UTC
    Code Review
    native/spark-expr/src/url_funcs/parse_url.rs:1
    @@ -388,11 +422,83 @@ mod tests {
         // Unit tests for parse_url_component
         // -----------------------------------------------------------------------
     
    +    #[test]
    +    fn uri_decomposition_matches_appendix_b_regex() {
    +        let regex =
    +            Regex::new(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$").unwrap();
    +        for url in [
    +            "https://u:p@host:80/p?q#f",
    +            "HTTP://host?#",
    +            "ftp://[::1]:80//a/b",
    +            "mailto:a@b",
    +            "例:é?k=值#片",
    +            "//host/p?x=1#f?y",
    +            "scheme:///p",
    +            "https:/p",
    +            "relative/path:part",
    +            ":leading",
    +            "?#",
    +            "x:/p?a=?b#f#x",

    nit: the old parity test had a fragment containing ? (#f?x=1), but every input here and in file_and_query_components has the ? before the #. Adding something like "http://h/p#f?x" would catch a future change that splits on ? before #.

    viirya viirya approved these changes on Oct 30, 2026 16:34 UTC
    Approved Reviewer

    Thanks for folding both parsers into decompose_uri. It matches the splitter I fuzzed against the Appendix B regex earlier, the unreachable Ok(None) arm is gone with it, and the FTP numbers show the speedup now carries over to non-HTTP schemes. LGTM.

    andygrove andygrove approved these changes on Oct 30, 2026 19:26 UTC
    Approved Reviewer

    Thanks for the update. The single decompose_uri splitter is a nice simplification and it carries the speedup to every scheme.

    I read the splitter against the Appendix B regex and it agrees. The scheme is taken exactly when the first of :/?# is a : at index > 0. The authority is taken when the remainder starts with //. The # split comes before the ? split, and FILE is the contiguous raw slice. I also ran a temporary fuzz test on this head, comparing decompose_uri with the regex on about 1.9M random inputs that pass has_invalid_uri_chars. The alphabet included :/?#@[], //, HTTP://, non-ASCII, \u{85}, \r and \n. I found no mismatch, and the regex always matched, so dropping the Ok(None) arm is correct. All 32 url_funcs tests pass.

    I compared the files against branch-1.2. The diff is exactly this PR, so I see no behavior change against the release. The output is copied into fresh buffers for Utf8, LargeUtf8 and Utf8View, and the retention test covers the view case. The earlier asks from comphead and viirya are all addressed.

    Reviewers
    Assignees
    sunchao sunchao
    Labels
    risk: low confidence: 88.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 42.3% (MEDIUM) · Higher = larger blast radius
    42.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.5% · Lower = rushed or shallow review
    88.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.9% · Safe to merge
    4.9%