Skip to content

Use cached IItemsFeature in TryGetItem (follow-up to #70161) - #70341

Closed
davidfowl wants to merge 1 commit into
mainfrom
perf/items-cached-feature
Closed

davidfowl wants to merge 1 commit into
mainfrom
perf/items-cached-feature

Conversation

@davidfowl

Copy link
Copy Markdown
Member
  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

Fixes the slowdown #70161 introduced for requests that already use HttpContext.Items.

Description

#70161 stopped hosting's RequestEnd from allocating HttpContext.Items by reading IItemsFeature straight from the feature collection. That skips DefaultHttpContext's cached feature reference, so requests where Items was already populated (authorization and CORS do this on matched endpoints) paid for an uncached Features.Get<IItemsFeature>() per lookup, twice on unmatched requests. @halter73 asked about this case in his review, and the follow-up measurement showed it was 5–15 ns slower.

This adds an internal DefaultHttpContext.ItemsFeatureIfExists:

  • If the feature cached by Items is still current (same collection revision), it returns it. This is the same check FeatureReferences.Fetch does.
  • Otherwise it returns Features.Get<IItemsFeature>(), which is what main does today.
  • It never creates or adds the feature. Fetch with a null factory isn't used because it calls IFeatureCollection.Set, which bumps Kestrel's revision.

Hosting's TryGetItem uses it for DefaultHttpContext. Microsoft.AspNetCore.Http gets an InternalsVisibleTo for Microsoft.AspNetCore.Hosting. No public API or behavior changes. A replaced or removed IItemsFeature is still picked up through the revision check.

Benchmark

The existing HostingApplicationBenchmark gets an Items parameter:

  • Unused: nothing touches Items.
  • Used: middleware writes Items, like auth and CORS do.
  • CustomFeature: the server provides its own IItemsFeature, and the pipeline doesn't touch it.

There are 3 interleaved rounds (order rotated each round). Each op is one full hosting request lifecycle. Mean ns, metrics enabled:

Endpoint Items pre-#70161 main PR Allocated (pre → main → PR)
no Unused 241.9 / 248.8 / 231.3 208.1 / 218.7 / 197.4 218.7 / 207.2 / 208.1 48 B → 0 B → 0 B
yes Unused 307.6 / 324.3 / 291.2 270.8 / 268.1 / 259.6 287.5 / 270.5 / 270.9 72 B → 24 B → 24 B
no Used 330.1 / 342.3 / 325.3 371.1 / 364.0 / 355.1 329.1 / 324.1 / 327.5 288 B (all)
yes Used 384.9 / 396.6 / 364.6 429.7 / 390.2 / 399.7 389.4 / 374.0 / 376.9 312 B (all)
no CustomFeature 238.8 / 249.9 / 229.3 256.8 / 249.8 / 244.0 265.0 / 248.6 / 247.3 0 B (all)
yes CustomFeature 312.9 / 314.4 / 301.9 297.8 / 300.7 / 298.0 327.9 / 298.2 / 301.1 24 B (all)

"pre-#70161" is main with HostingApplicationDiagnostics.cs reverted to 3ef88ec's parent. All three versions use the same benchmark code.

Machine: BenchmarkDotNet v0.13.0 (--config perflab, in-process), AMD EPYC 9V74 (2 cores), Ubuntu 24.04 container, .NET SDK 12.0.100-alpha.1.26531.102, Server GC.

Tests

  • HostingMetricsTests adds 4 tests:

    • Items already used (unhandled marker and original-endpoint route tag)
    • Server-provided IItemsFeature
    • IItemsFeature replaced after Items was used, which changes the revision
    • IItemsFeature removed after use, which must not be recreated

    All 4 pass on main and on this PR.

  • DefaultHttpContextTests adds 5 tests for ItemsFeatureIfExists:

    • Unused: returns null, adds no feature and leaves the revision unchanged
    • Used
    • Custom feature
    • Replaced or removed feature
    • Reinitialized context
  • Microsoft.AspNetCore.Hosting.Tests: 479/479 pass. Microsoft.AspNetCore.Http.Tests: 287 pass, 7 skipped.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

#70161 avoided allocating HttpContext.Items in hosting RequestEnd by reading
IItemsFeature from the feature collection directly. That bypassed
DefaultHttpContext's cached feature reference, so requests that had already
used Items paid for an uncached Features.Get on every lookup.

Add an internal DefaultHttpContext.ItemsFeatureIfExists that returns the
feature cached by Items when it is still current and otherwise reads it from
the collection, without creating or adding the feature. Extend the hosting
benchmark with Items unused/used/server-provided rows.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 6, 2026 08:01
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@github-actions github-actions Bot added area-hosting Includes Hosting area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions labels Nov 6, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The production friend-assembly dependency lets Hosting access Http internals across a prohibited assembly boundary and must be replaced with a supported contract.

1 open issue
What changed in this PR

This follow-up to #70161 reduces hosting diagnostics lookup overhead when HttpContext.Items is already populated, while preserving non-allocating lookups when it is unused.

Changes:

  • Adds a revision-aware cached items-feature accessor and uses it from hosting diagnostics.
  • Adds tests for existing, custom, replaced, removed, and reinitialized items features.
  • Extends hosting benchmarks with three items-usage scenarios.
File Description
src/​Http/​Http/​test/​DefaultHttpContextTests.cs Tests accessor behavior and feature lifecycle handling.
src/​Http/​Http/​src/​Microsoft.AspNetCore.Http.csproj Grants Hosting access to Http internals.
src/​Http/​Http/​src/​DefaultHttpContext.cs Adds the non-creating cached feature accessor.
src/​Hosting/​Hosting/​test/​HostingMetricsTests.cs Tests metric tags and feature replacement/removal behavior.
src/​Hosting/​Hosting/​src/​Internal/​HostingApplicationDiagnostics.cs Uses the cached accessor for items lookups.
src/​Hosting/​Hosting/​perf/​Microbenchmarks/​HostingApplicationBenchmark.cs Benchmarks unused, populated, and server-provided items.

Review effort: Balanced

</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Microsoft.AspNetCore.Hosting" />

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, the rule applies. .github/copilot-instructions.md ("Framework assembly boundaries", added in #68493) bans new production InternalsVisibleTo between framework assemblies and says existing uses aren't precedent. Those existing uses include Http.Abstractions → Http.Extensions/Http.Results (src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj), Authentication.Abstractions → Authentication.Core, and Kestrel.Core → Kestrel. They don't justify this edge.

I couldn't find a clean replacement that keeps the fix without public API:

  • Shared-source internal interface: this doesn't work. Each assembly gets its own copy of the type, so DefaultHttpContext can't implement Hosting's copy.
  • [UnsafeAccessor]: also banned by the same rule.
  • Public-only rewrite: I measured one Features.Get<IItemsFeature>() per RequestEnd, with reads through HttpContext.Items once the feature exists. Results below.
  • Fetch the feature once and reuse it for both lookups: this never costs more than main, but it only removes the second Get on unmatched requests. Matched endpoints with auth or CORS, the case raised in review, stay at main's cost.

The public-only rewrite, compared with main: mean ns, metrics enabled, 3 interleaved rounds, same benchmark as the PR description:

Endpoint Items main public-only this PR (IVT)*
no Used 353 / 367 / 368 346 / 357 / 355 322 / 322 / 345
yes Used 387 / 412 / 420 394 / 406 / 397 381 / 386 / 409
no server IItemsFeature 244 / 248 / 261 256 / 265 / 251 249 / 241 / 270
yes server IItemsFeature 291 / 310 / 311 320 / 331 / 312 311 / 298 / 327
no / yes Unused 198–213 / 265–280 192–195 / 262–276 199–222 / 268–299

*From a separate 3-round run against main on the same machine.

The public-only rewrite gains only about 10 ns on the unmatched Used row. It is within noise on the matched Used row and 10–20 ns slower with a server-provided feature. In that case, HttpContext.Items misses DefaultHttpContext's empty cache and calls Get again.

So restoring the cached path for matched endpoints needs one of two things: this IVT, which the rule forbids, or a small public non-allocating lookup on DefaultHttpContext, which needs API review. Otherwise this PR shouldn't go in. I'm leaving the thread open for that decision and haven't pushed changes.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@PureWeen

PureWeen commented Nov 6, 2026

Copy link
Copy Markdown
Member

/review

@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026

Copy link
Copy Markdown
Member Author

Closing this PR without merging.

  • The review is right. .github/copilot-instructions.md forbids new production InternalsVisibleTo between framework assemblies, and this PR adds one from Microsoft.AspNetCore.Hosting to Microsoft.AspNetCore.Http.
  • I found no fix that recovers the populated-Items case without an IVT or a public API change. The public-only variant (details in the review thread above) gained only ~10 ns on one row. It measured 10–20 ns slower than main when the server provides its own IItemsFeature.
  • We're accepting the small regression from Avoid allocating HttpContext.Items in hosting RequestEnd #70161. When Items is already populated, requests are 5–15 ns slower, with no allocation change. When Items is unused, Avoid allocating HttpContext.Items in hosting RequestEnd #70161 still saves 48 B and about 20 ns per request.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-hosting Includes Hosting area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants