Repository navigation
Improve SignalR hot paths and add regression benchmarks - #69189
Conversation
Optimize small targeted sends, stateful reconnect appends, reusable authorization policies, connection cancellation tracking, and multiline SSE formatting. Add focused correctness coverage and normal/adverse microbenchmarks. Co-authored-by: Copilot App <[email protected]>
|
One or more custom setup steps configured for this repository failed during this Copilot code review run: Setup steps run before each review. If the review above is missing context, or no review was posted at all, the failing step above may be the cause. See the workflow run for failure details, fix your setup steps configuration, and re-request a review. Note You can configure setup steps for Copilot code review separately from Copilot cloud agent with a |
There was a problem hiding this comment.
Copilot review overview
🔵 Needs a closer look
It changes multiple high-impact SignalR hot paths (send, reconnect buffering, authorization, SSE) and adds substantial new benchmark/test surface area that warrants careful final human validation.
Review tier: Lite
Findings: 2
New issues introduced by this change (2)
| Severity | Finding |
|---|---|
src/SignalR/perf/Microbenchmarks/HubMethodAuthorizationBenchmark.cs — Unnecessary using directive: Microsoft.Extensions.DependencyInjection.Extensions isn't referenced… |
|
src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.Authorization.cs — Unnecessary using directive: Microsoft.Extensions.DependencyInjection.Extensions isn't referenced… |
What changed in this PR
This PR optimizes several SignalR hot paths (targeted connection sends, reconnect buffering, hub-method authorization, cancellation tracking, and SSE formatting) and adds a comprehensive set of regression microbenchmarks and tests to validate correctness and performance characteristics.
Changes:
- Optimizes
DefaultHubLifetimeManager.SendConnectionsAsyncfor small target lists (≤16) with bounded duplicate suppression and single serialization per protocol. - Improves reconnect buffering by tracking the
MessageBuffertail, and reduces per-connection overhead by lazily allocating invocation-cancellation tracking. - Reworks SSE message formatting to use pooled contiguous buffers with a single output write, and adds microbenchmarks covering send/reconnect/auth/SSE and group churn scenarios.
| File | Description |
|---|---|
| src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/Internal/MessageBufferTests.cs | Adds ordering regression coverage across ACK + append cycles for buffered reconnect messages. |
| src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/Internal/HubMethodDescriptorTests.cs | Adds unit tests for composed-authorization policy caching behavior (provider identity/lifetime, failures, concurrency, GC). |
| src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.Cancellation.cs | Validates that “unknown cancellation” and typical invocations don’t allocate cancellation-source tracking. |
| src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.Authorization.cs | Adds functional tests ensuring authorization still uses per-invocation scoped services and resource data; validates no cross-provider caching for scoped/transient. |
| src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionContextTests.cs | Adds tests for lazy cancellation dictionary initialization, unknown-cancel behavior, and concurrent first-init publishing. |
| src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/DefaultHubLifetimeManagerTests.cs | Adds send-to-connections behavioral tests for dedupe/missing IDs/case sensitivity/serialization sharing/waiting for writes/cancellation interaction. |
| src/SignalR/server/Core/src/Internal/HubMethodDescriptor.cs | Introduces per-provider composed-policy caching via ConditionalWeakTable gated by AllowsCachingPolicies. |
| src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs | Uses cached policy composition path; avoids allocating cancellation tracking for unknown cancellation messages. |
| src/SignalR/server/Core/src/HubConnectionContext.cs | Lazily initializes active invocation cancellation tracking and adds a non-allocating lookup path. |
| src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs | Adds small-target indexed send fast-path with bounded dedupe and shared serialization. |
| src/SignalR/common/Shared/MessageBuffer.cs | Tracks a tail buffer to avoid traversing retained reconnect backlog on appends; adjusts ACK/resend to use head tracking. |
| src/SignalR/common/Http.Connections/src/ServerSentEventsMessageFormatter.cs | Switches multiline SSE formatting to a pooled contiguous buffer with a single write and precise written-length control. |
| src/SignalR/common/Http.Connections/test/ServerSentEventsMessageFormatterTests.cs | Adds coverage for newline/CR trimming behavior, single-write multiline behavior, sizing, buffer lifetime across async writes, and failure/cancellation cases. |
| src/SignalR/perf/Microbenchmarks/Microsoft.AspNetCore.SignalR.Microbenchmarks.csproj | Adds required reference for authorization benchmarks and links SSE formatter source into benchmarks. |
| src/SignalR/perf/Microbenchmarks/SendConnectionsBenchmark.cs | Adds baseline/regression benchmarks for small/large connection stores with targeted sends. |
| src/SignalR/perf/Microbenchmarks/SendConnectionsAdverseBenchmark.cs | Adds adverse-input microbenchmarks (dense fanout, duplicates, missing IDs, empty) and preserves original-scan control. |
| src/SignalR/perf/Microbenchmarks/MessageBufferBenchmark.cs | Adds reconnect-buffer microbenchmarks for append + ack under varying backlog sizes. |
| src/SignalR/perf/Microbenchmarks/HubMethodAuthorizationBenchmark.cs | Adds dispatcher + authorization benchmarks across provider caching + lifetime combinations. |
| src/SignalR/perf/Microbenchmarks/HubConnectionContextCreationBenchmark.cs | Adds benchmark for connection creation/cleanup with/without cancellation tracking initialization. |
| src/SignalR/perf/Microbenchmarks/HubGroupListBenchmark.cs | Adds benchmark for group churn (add/remove) under varying steady-state membership sizes. |
| src/SignalR/perf/Microbenchmarks/HubGroupListConcurrencyBenchmark.cs | Adds concurrent group churn benchmarks across worker counts and shared vs independent groups. |
| src/SignalR/perf/Microbenchmarks/ServerSentEventsFormattingBenchmark.cs | Adds SSE formatting microbenchmarks for line count/length and segmented vs contiguous inputs. |
| src/SignalR/perf/Microbenchmarks/ServerSentEventsOutputBenchmark.cs | Adds SSE output microbenchmark verifying sync vs forced-async output behavior and correctness. |
| src/SignalR/perf/Microbenchmarks/ServerSentEventsAdverseBenchmark.cs | Adds SSE adverse microbenchmarks for fragmented, dense-newline, and large-message scenarios. |
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
Adapt composed-policy caching to the expanded authorization metadata API. Preserve the no-policy path, cache only non-null results, and cover mixed metadata and uncached null policies. Co-authored-by: Copilot App <[email protected]>
|
Me waiting for a review 🥱 |
BrennanConroy
left a comment
There was a problem hiding this comment.
Looks good, testing is a bit overboard, so could pair it down a bit.
Keep boundary, lifetime, and cancellation checks while replacing randomized SSE framing with explicit examples, consolidating output checks, and reducing duplicate test paths and input permutations. Co-authored-by: Copilot App <[email protected]>
|
Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime. |
|
/azp run aspnetcore-ci |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
Keep representative targeting, cache isolation, invocation authorization, lazy tracking, reconnect ordering, and SSE ownership tests. Remove redundant scenario matrices and runtime primitive stress tests. Co-authored-by: Copilot App <[email protected]>
|
/azp run aspnetcore-ci |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/ba-g Known test issue with quic, unrelated to PR |

Improve SignalR hot paths and add regression benchmarks
Reduce SignalR send, reconnect, authorization, and SSE overhead.
Description
This changes five paths without introducing public APIs:
SendConnectionsAsyncwith at most 16 target IDs, with allocation-free duplicate suppression and shared serialization. Larger lists retain the original scan to avoid target-sized allocations and unbounded deduplication work.MessageBufferblock so appends no longer traverse the retained reconnect backlog. This is shared by the server and .NET client.AllowsCachingPoliciespermits it. AConditionalWeakTableavoids retaining scoped/transient providers. Authorization is still evaluated against the current user, resource, and scoped services on every invocation; failed/canceled combinations are not cached.ConnectionAbortedremains independent of this dictionary.Adds 10 benchmark classes covering 58 scenarios, including adverse inputs and serial/concurrent group churn. Group membership code is unchanged; those benchmarks establish controls and future optimization coverage.
The merge of
mainpreserves its expanded authorization metadata support (IAuthorizeData,AuthorizationPolicy, andIAuthorizationRequirementData). Metadata that produces no policy remains allowed; null results are not inserted into the cache.Before / after
Benchmark provenance after merging
main: These tables compare original production code atc4d061a54c669a55ca9aa18982b416e9d3ff4d2bagainst pre-merge PR commit78bfc6342eea99f4c5494ffea08ea758505e6ce0, including the simplified authorization cache and LF-count SSE sizing. They have not been rerun after mergingmainatef51aa77663661cb9162820b67e89488372dd473and adapting the cache to its expanded authorization-metadata API. They are retained as measurements of that earlier revision, not claims about the merged code or updated SDK/runtime.Tradeoffs and uncertainty
Methodology
Apple M2 Max, Arm64, 12 physical/logical cores; macOS 26.6.2 (25G83). SDK
11.0.100-preview.6.26318.108, runtime.NET 11.0.0 (11.0.26.36017), BenchmarkDotNet 0.13.0, Release builds.--config debugselects the repository's in-process benchmark toolchain; it does not mean Debug compilation.Both builds use identical new benchmark sources and dependencies. A temporary MSBuild compile-item overlay supplies the six production files from the baseline commit, including the shared buffer in both server/client and the formatter linked into the benchmark assembly. Separate output snapshots prevent loading current dependencies into the baseline. Source fingerprints, substitution manifests, and baseline/current assembly markers were checked.
Each case uses 10 warmups, 7 measured iterations, and a 200 ms target iteration time. All 58 scenarios were run before then after, sequentially with no overlapping builds. A 24-case subset was then rerun after then before. Tables below retain the complete primary results and the separate repeat, rather than selecting the fastest run. Percentages are
(after / before - 1) * 100; negative is faster.Results are mean time and managed allocation per operation, not end-to-end network throughput. Reconnect burst results are per appended message (
OperationsPerInvoke = 32). Group results are per add/remove pair (concurrent batches contain 1,024 pairs and include scheduling costs). The authorization benchmark waits for successful invocation completion, not just dispatch enqueueing. The SSE output benchmark verifies bytes written and exercises both actual synchronous and forced asynchronous sinks.OriginalScanis a copied original-algorithm control;IndexedSendinvokes the actual lifetime-manager API in each build (and takes the original-scan fallback for these >16-target adverse cases). Compare each method across builds, not the two methods as if they were the before/after pair. Small nonzero allocations in longer-running cases can include measurement/background noise. Concurrent group allocation totals also vary between runs; compare within a pair.All 58 primary before/after results (time in ns)
All 24 reverse-order confirmation results (time in ns)
Reproduction
Build once for each production revision while keeping the benchmark sources identical, then run each captured output separately with the same SDK/runtime:
The repeat filters were
*SendConnectionsBenchmark*,*HubMethodAuthorizationBenchmark.Authorized*,*ServerSentEventsAdverseBenchmark*,*ServerSentEventsOutputBenchmark*, and*HubGroupListConcurrencyBenchmark*. Use distinct artifact directories for each run. The baseline commit alone does not contain these new benchmark classes.Validation
After the final test-only reduction, the focused run covered 321 SignalR server cases (320 passed and 1 skipped) and 34 SSE formatter/transport cases (all passed). Every retained theory row executed successfully. No pre-existing tests, production code, or benchmarks were changed by the reduction.
The added test set now has 13 methods across six files. The latest trim reduced it from 28 methods and 998 added lines to 13 methods and 514 added lines (484 fewer lines, about 49%), following the earlier 97-line reduction. It consolidates targeting and serialization checks, keeps one ACK/append/replay scenario, and removes redundant authorization permutations, GC/concurrency stress scaffolding, and pool-capacity assertions.
Retained regression coverage checks duplicate/missing/case-sensitive recipients and shared serialization on both sides of the 16/17-target boundary; pending writes and existing cancellation behavior; ordered replay after partial/full ACKs and block reuse; policy-cache opt-in, provider/method isolation, mixed metadata, null/failure retries, and authorization with fresh scoped services/resources on every invocation; the handler-level no-allocation path; explicit CR/LF and Unicode framing with contiguous/fragmented input, one exact-length write, and buffer ownership until asynchronous output completes or cancels.
Before these test-only reductions, the shared .NET client multi-target build (
net11.0,netstandard2.0,netstandard2.1, andnet462), Release microbenchmark build, and authorization benchmark smoke run succeeded with the merged dependencies. Performance measurements were not rerun; all before/after tables and their pre-merge provenance remain unchanged.No linked issue.