Repository navigation
Conversation
Skip narrowing the :path value to bytes and running PathDecoder when the path has no percent-encoding and no dot segments. Inputs that don't match the fast path, including all invalid ones, use the existing code. Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
There are no active review issues for the HTTP/2 and HTTP/3 path-validation changes.
No open issues 🎉
What changed in this PR
Optimizes Kestrel’s HTTP/2 and HTTP/3 :path validation by skipping byte conversion and decoding for common paths without percent encoding or dot segments, while retaining the existing fallback.
Changes:
- Adds matching fast paths for HTTP/2 and HTTP/3, with separate validation for paths with and without queries.
- Extends functional tests for plain paths, normalization, encoding, and invalid characters.
- Adds a pooled HTTP/2 stream benchmark covering header processing and request validation.
| File | Description |
|---|---|
| src/Servers/Kestrel/test/InMemory.FunctionalTests/Http3/Http3StreamTests.cs | Adds plain-path and query-bearing decoding and normalization cases. |
| src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2StreamTests.cs | Adds path cases and invalid-character rejection coverage with a query. |
| src/Servers/Kestrel/perf/Microbenchmarks/Http2/Http2StreamHeadersBenchmark.cs | Benchmarks HTTP/2 header processing across three request targets. |
| src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs | Adds the HTTP/3 path-validation fast path. |
| src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs | Adds the equivalent HTTP/2 path-validation fast path. |
Review effort: Balanced
Co-authored-by: Copilot <[email protected]>
|
Retriggered CI with an empty commit (873e2af). The failures on 5e625ab look unrelated to this change:
🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
/review |
|
Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime. |
|
Nov 25 refresh: PR head Merge assessmentVerdict: Hold. This branch conflicts with main; halter73's Nov 25 review specifically requests an updated query assertion and extraction of the duplicated fast path into
Reasons to merge
Reasons not to merge yet
What would change this verdict: Rebase, update #70578 query assertions, extract the common helper as requested, resolve both threads, then rerun the affected tests, H2/H3 performance comparisons and CI on the revised head and seek Kestrel approval. 🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
| [InlineData("/a/b/c", "/a/b/c")] | ||
| [InlineData("/a/.b", "/a/.b")] // Not a dot segment | ||
| [InlineData("/a/b?q=1", "/a/b")] | ||
| [InlineData("/a/./b?q=1", "/a/b")] // Navigation processed with query | ||
| [InlineData("/a%5E?q=1", "/a^")] // Decoded with query |
There was a problem hiding this comment.
This needs a rebase. #70578 added an expectedQuery = "" parameter to this theory, and it now asserts Request.QueryString, so the rows with a query need a third argument.
| // Fast path: when the path isn't percent-encoded and has no dot segments, PathDecoder.DecodePath doesn't modify it, | ||
| // so the path can be validated without narrowing it to bytes first. Requests that don't match this fast path, | ||
| // including invalid ones, use the slower path below. | ||
| if (!pathEncoded && !pathSegment.Contains("/.", StringComparison.Ordinal)) | ||
| { | ||
| if (QueryString!.Length == 0) | ||
| { | ||
| // DecodePath returns the raw target when there's no query. Every char must still fit in a byte. | ||
| if (!pathSegment.ContainsAnyExceptInRange((char)0, (char)byte.MaxValue)) | ||
| { | ||
| Path = RawTarget!; | ||
| return true; | ||
| } | ||
| } | ||
| else if (Ascii.IsValid(pathSegment)) | ||
| { | ||
| // DecodePath creates an ASCII string from the path when there's a query. | ||
| Path = pathSegment.ToString(); | ||
| return true; | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
I traced this against PathDecoder.DecodePath, and the results match: no % skips UrlDecoder, and no /. makes RemoveDotSegments return src.Length. Without a query, the <= 0xFF check matches the narrowing loop and returns RawTarget. With a query, Ascii.IsValid accepts the same inputs as GetAsciiString, and everything else still falls through.
This block is identical in Http3Stream.TryValidatePath and has no protocol-specific abort logic. Can we move it into PathDecoder, next to the code it shortcuts, so the equivalence argument lives in one place?
// PathDecoder.cs
// Returns the same result as DecodePath for paths that need no percent-decoding or dot-segment removal.
// Returns false for every other path, including invalid ones, so the caller falls back to DecodePath.
public static bool TryGetUnmodifiedPath(ReadOnlySpan<char> path, string rawTarget, int queryLength, [NotNullWhen(true)] out string? result)
{
if (!path.Contains("/.", StringComparison.Ordinal))
{
if (queryLength == 0)
{
if (!path.ContainsAnyExceptInRange((char)0, (char)byte.MaxValue))
{
result = rawTarget;
return true;
}
}
else if (Ascii.IsValid(path))
{
result = path.ToString();
return true;
}
}
result = null;
return false;
}// Http2Stream / Http3Stream
var pathEncoded = pathSegment.Contains('%');
if (!pathEncoded && PathDecoder.TryGetUnmodifiedPath(pathSegment, RawTarget!, QueryString!.Length, out var path))
{
Path = path;
return true;
}
Fast path for HTTP/2 and HTTP/3 :path validation
Add a fast path for clean
:pathvalues in HTTP/2 and HTTP/3 validation.Description
Skip narrowing
:pathto bytes and runningPathDecoderfor the common clean paths in HTTP/2 and HTTP/3.For every request,
Http2Stream.TryValidatePathandHttp3Stream.TryValidatePathcopy the:pathchars into a byte buffer one char at a time. They then callPathDecoder.DecodePath, which scans for dot segments and either returnsRawTargetor creates an ASCII string from the bytes.Most request paths have no
%and no/.. For those paths,DecodePathreturns one of two values:RawTarget. Each char must still be<= 0xFF; the narrowing loop already enforces that.GetAsciiString(path). That call throws for non-ASCII input, and the stream is then reset.The new fast path returns the same results directly.
ContainsAnyExceptInRange(0, 0xFF)covers the case with no query, andAscii.IsValidplusToString()covers the case with a query. Any input outside these cases falls through to the existing code, which is unchanged. That includes percent-encoded paths, dot segments and anything the old code would reject. Rejection behavior and error messages therefore stay the same.This adds no new unsafe code, no new stackalloc and no API changes.
Benchmark
This PR adds
Http2StreamHeadersBenchmark. It drives a pooledHttp2Streamthrough Reset, theOnHeadercallbacks for a typical 8-header browser GET,OnHeadersCompleteandTryParseRequest. The table shows results from BenchmarkDotNet (short job) over three interleaved A/B rounds://api/products/12345/shop/category/electronics/laptops/item-12345?ref=homepage&utm_source=newsletterAllocations are unchanged.
In isolation, narrowing costs 5 / 18 / 41 ns for 12 / 48 / 120-char paths. The fast path costs a few ns at any length.
Tests
New cases in
Path_DecodedAndNormalizedfor both H2 and H3:/.bthat isn't a dot segmentH2 also gets a new
CharacterLargerThanByte_Resetcase with a query. H3 already covers that case.The
Http2andHttp3tests in InMemory.FunctionalTests pass (786), as do the related Kestrel Core tests.🤖 Posted by ASP.NET Core Perf 2 (AI Agent)