Repository navigation
perf(operators): fuse chains, share stage helpers, and fix leaks - #247
Merged
Merged
Conversation
glennawatson
force-pushed
the
perf/operator-fusions-and-teardown
branch
from
November 20, 2026 05:31
5b89c19 to
30e8e90
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #247 +/- ##
==========================================
+ Coverage 99.77% 99.98% +0.20%
==========================================
Files 785 1012 +227
Lines 24496 27139 +2643
Branches 2961 3259 +298
==========================================
+ Hits 24442 27135 +2693
+ Misses 54 4 -50 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
glennawatson
force-pushed
the
perf/operator-fusions-and-teardown
branch
6 times, most recently
from
November 20, 2026 12:27
f089150 to
acefe06
Compare
- Fuse adjacent Map, Keep, Skip, Take, KeepNotNull, KeepType, CastTo, SwitchTo, Spark, Unspark, Count, LongCount, Any, Not, WhereTrue, WhereFalse, and WhereIsNotNull chains across synchronous, Extensions, and Async signals. - Short-circuit Empty, Never, Return, and RangeSignal inputs across projection, filter, distinct, retry, recovery, and aggregate operators. Push RangeSignal and indexable FromEnumerableSignal sequences directly at subscribe time without per-stage witnesses, and subscribe TakeUntil stop triggers before empty sources. - Expose concrete operator, witness, coordinator, and sequencer stage types in the Advanced and Operators namespaces with public constructors and static factories, keeping mixin and extension members as inline forwarders. - Consolidate duplicated direct-emission, unary witness delivery, wide CombineLatest validation, binary arm coordination, SelectMany stage subscription, Async Zip queueing, stop-token linking, and terminal task execution into stateless internal static helpers with record struct state carriers. - Dispatch ImmediateSequencer and CurrentThreadSequencer work inline without wrapper allocations. Run Extensions scheduled drains directly through ScheduledDrainState as an IWorkItem. - Drive synchronous Chain, Reattempt, and FlatMap stages through iterative trampolines to prevent stack overflow on deep sequences, preserving inner subscriptions across reentrant completion and exposing concurrent callback mutations explicitly to static flow analysis. - Close concurrent outer and inner completion races across Blend, MaxConcurrentBlend, FlatMap, CombineLatest, SyncLatest, Latch, Pair, Switch, and ForkJoin coordinators, and signal the delivery gate when CombineLatest, Pair, or SyncLatest selectors fault. - Serialize Async downstream notifications through AsyncFlowGate, which tracks the holding async flow instead of the thread, across Zip, Probe, Timeout, Blend, FlatMap, RefCount, SyncLatest, TakeUntil, SwitchTo, Chain, connectable, and replay signals. Read the Async Zip counterpart completion flag under its lock. - Stop Async Timeout delivering values after its timeout completion, wait for a running OnNext before completing, and keep the deadline running after a resumed error. - Reject a null task in TaskFaultObservation.HandleCancellationAsync with ArgumentNullException at call time. - Dispose upstream, trigger, and sibling subscriptions on early completion, callback faults, and explicit disposal across synchronous, Extensions, and Async operators. - Add fusion allocation benchmarks and unit tests covering every changed line and branch, including reductions, fusions, shared internal helpers, teardown, stack safety, and completion races.
glennawatson
force-pushed
the
perf/operator-fusions-and-teardown
branch
from
November 20, 2026 12:36
acefe06 to
d09ad53
Compare
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Summary
This PR fuses common operator chains, adds short-circuit fast paths across synchronous, Extensions, and Async signals, exposes concrete operator and sequencer stages publicly behind inline forwarders, shares internal stage helpers across packages via source linking, and fixes concurrency, selector-fault, and teardown bugs.
Map,Keep,Skip,Take,KeepNotNull,KeepType,CastTo,SwitchTo,Spark,Unspark,Count,LongCount,Any,Not,WhereTrue,WhereFalse, andWhereIsNotNullcalls collapse into combined stages without intermediate observer allocations.Empty,Never,Return, andRangeSignalinputs short-circuit unary, retry, recovery, distinct, and aggregate operators.RangeSignaland indexableFromEnumerableSignalsequences push directly into downstream observers, andSwitchchecksFromEnumerableSignalrange lists atSubscribetime so list mutations after pipeline creation still apply.publicin theAdvancedandOperatorsnamespaces withpublicconstructors andpublic staticfactories. Mixin and extension methods across all packages act as inline one-expression forwarders.CombineLatestslot setup, binary coordinator arm management,SelectManyandSelectManyThenstage subscription, AsyncZipqueueing, stop-token linking, and terminal task execution share stateless internal helpers without cross-packageInternalsVisibleTo.ImmediateSequencerandCurrentThreadSequencerrun subscriptions and zero-delay work inline without wrapper allocations, and Extensions scheduled drains enqueueScheduledDrainStatedirectly as anIWorkItem.Chain,Reattempt, andFlatMapstep through synchronous inner sequences iteratively to prevent stack overflow, while keeping inner subscriptions disposable when an inner source completes duringSubscribe.Blend,MaxConcurrentBlend,FlatMap,CombineLatest,SyncLatest,Latch,Pair,Switch, andForkJoinclose concurrent outer and inner completion races, andCombineLatest,Pair, andSyncLatestsignal the delivery gate so selector exceptions on the uncontended fast path reachOnErrorand release upstream arms.Zip,Probe, andTimeoutserialize concurrent downstream notifications throughAsyncFlowGateand block late timer emissions after completion.TakeUntiltriggers (including when the main source isEmpty), callback exceptions, and explicit disposal.Why
Profiling with dotTrace, dotMemory, and BenchmarkDotNet across single operators and chained pipelines surfaced avoidable per-stage witness and disposable allocations, trampoline wrapper allocations on synchronous sequencers, and unbounded stack growth on deep synchronous
Chain,Reattempt, andFlatMaploops. Testing concurrent and fault paths also uncovered missed completions when outer and inner streams finished together across threads, droppedOnErrornotifications whenCombineLatest,Pair, orSyncLatestselectors threw on an uncontended delivery gate, stale list snapshots whenSwitchinspectedFromEnumerableSignalat build time, skippedothersubscriptions whenTakeUntilwrappedEmpty, and upstream subscriptions left open after early termination. Exposing concrete stages publicly lets callers construct stages directly, while source-linked static helpers remove duplicated delivery and teardown code without leaking internals across NuGet assemblies.Breaking changes
None
How this was verified
Unit tests cover every operator reduction, fusion stage, coordinator race, selector fault, teardown path, and shared internal helper to 100% Cobertura line coverage on Linux, alongside BenchmarkDotNet comparisons, allocation probes, dotTrace CPU captures, dotMemory retention snapshots, and benchmark smoke runs. WinUI
DispatcherQueuetests require a Windows desktop session and were not run locally on Linux.Notes for the reviewer
SignalOperatorMixins,SignalOperatorParityMixins,SignalAsyncExtensions,ReactiveExtensions,R3SignalBridge,R3AsyncBridge, and the platform sequencer extensions) contain only[MethodImpl(MethodImplOptions.AggressiveInlining)]one-expression forwarders and are safe to skim.MapSignal<TSource, TResult>,KeepSignal<T>,FusedMapSignal<TSource, TResult>,MapKeepSignal<TSource, TResult>,KeepMapSignal<TSource, TResult>,MapCastSignal<TSource, TResult>,TakeSignal<T>,SkipSignal<T>,DistinctBySignal<T, TKey>, and their Async counterparts inReactiveUI.Primitives.Async.Advanced, together with the stateless helpers (DirectSequenceEmission,UnaryWitnessDelivery,BinaryCoordinatorHelper,CombineLatestWideHelper,ZipQueueCoordinatorHelper,AsyncStopTokenHelper,AsyncTaskTerminalRunner, andSelectManyThenStageHelper).SwitchRangeOptimizer.TrySubscribeRanges(evaluated insideSubscriberather thanCreate) andTakeUntilSignal<T, TOther>.Create(subscribesothereven whensourceisEmptyso immediate trigger errors surface).CurrentThreadSequencer,Sequencer, andScheduledDrainStatenext for inline scheduling and burst draining.CombineLatestCoordinator<TLeft, TRight, TResult>,PairWitness<TLeft, TRight, TResult>, andSyncLatestWitness<TLeft, TRight, TResult>(OnError(selectorError)signalingDeliveryGate),ChainWitness<T>,ReattemptCoordinator<T>, andFlatMapCoordinator<TSource, TResult>(reentrant completion duringSubscribe), and AsyncAsyncFlowGate,ProbeWitness<T>,TimeoutWitness<T>,ZipState<T1, T2, TResult>, andAsyncSerialGate.Rangeworkloads includeDistinct(808 B to 24 B),Reattempt(368 B to 24 B),OnCleanup(464 B to 96 B),SubscribeOn(Immediate)(256 B to 56 B),Unique(104 B to 24 B),Take(128 B to 48 B), and fusedMap+Keep,Map+Map,Keep+Keep, andKeep+Mapchains (168 B to 96 B, 0 B onSubscribe), withRange -> Map -> Keepmeasured at 32.4 ns in BenchmarkDotNet and 0 B retained across dotMemory snapshots.Checklist