Skip to content

perf(operators): fuse chains, share stage helpers, and fix leaks - #247

Merged
glennawatson merged 1 commit into
mainfrom
perf/operator-fusions-and-teardown
Nov 20, 2026
Merged

glennawatson merged 1 commit into
mainfrom
perf/operator-fusions-and-teardown

Conversation

@glennawatson

@glennawatson glennawatson commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Adjacent Map, Keep, Skip, Take, KeepNotNull, KeepType, CastTo, SwitchTo, Spark, Unspark, Count, LongCount, Any, Not, WhereTrue, WhereFalse, and WhereIsNotNull calls collapse into combined stages without intermediate observer allocations.
  • Empty, Never, Return, and RangeSignal inputs short-circuit unary, retry, recovery, distinct, and aggregate operators. RangeSignal and indexable FromEnumerableSignal sequences push directly into downstream observers, and Switch checks FromEnumerableSignal range lists at Subscribe time so list mutations after pipeline creation still apply.
  • Every operator, witness, coordinator, and scheduled work-item type is public in the Advanced and Operators namespaces with public constructors and public static factories. Mixin and extension methods across all packages act as inline one-expression forwarders.
  • Shared direct-emission, unary witness delivery, wide CombineLatest slot setup, binary coordinator arm management, SelectMany and SelectManyThen stage subscription, Async Zip queueing, stop-token linking, and terminal task execution share stateless internal helpers without cross-package InternalsVisibleTo.
  • ImmediateSequencer and CurrentThreadSequencer run subscriptions and zero-delay work inline without wrapper allocations, and Extensions scheduled drains enqueue ScheduledDrainState directly as an IWorkItem.
  • Chain, Reattempt, and FlatMap step through synchronous inner sequences iteratively to prevent stack overflow, while keeping inner subscriptions disposable when an inner source completes during Subscribe.
  • Blend, MaxConcurrentBlend, FlatMap, CombineLatest, SyncLatest, Latch, Pair, Switch, and ForkJoin close concurrent outer and inner completion races, and CombineLatest, Pair, and SyncLatest signal the delivery gate so selector exceptions on the uncontended fast path reach OnError and release upstream arms.
  • Async Zip, Probe, and Timeout serialize concurrent downstream notifications through AsyncFlowGate and block late timer emissions after completion.
  • Synchronous, Extensions, and Async operators dispose upstream, trigger, and sibling subscriptions on early completion, pre-completed or pre-faulted TakeUntil triggers (including when the main source is Empty), 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, and FlatMap loops. Testing concurrent and fault paths also uncovered missed completions when outer and inner streams finished together across threads, dropped OnError notifications when CombineLatest, Pair, or SyncLatest selectors threw on an uncontended delivery gate, stale list snapshots when Switch inspected FromEnumerableSignal at build time, skipped other subscriptions when TakeUntil wrapped Empty, 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 DispatcherQueue tests require a Windows desktop session and were not run locally on Linux.

Notes for the reviewer

  • Mixin and extension classes (SignalOperatorMixins, SignalOperatorParityMixins, SignalAsyncExtensions, ReactiveExtensions, R3SignalBridge, R3AsyncBridge, and the platform sequencer extensions) contain only [MethodImpl(MethodImplOptions.AggressiveInlining)] one-expression forwarders and are safe to skim.
  • Start with the fusion and short-circuit factories on 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 in ReactiveUI.Primitives.Async.Advanced, together with the stateless helpers (DirectSequenceEmission, UnaryWitnessDelivery, BinaryCoordinatorHelper, CombineLatestWideHelper, ZipQueueCoordinatorHelper, AsyncStopTokenHelper, AsyncTaskTerminalRunner, and SelectManyThenStageHelper).
  • Check SwitchRangeOptimizer.TrySubscribeRanges (evaluated inside Subscribe rather than Create) and TakeUntilSignal<T, TOther>.Create (subscribes other even when source is Empty so immediate trigger errors surface).
  • Review CurrentThreadSequencer, Sequencer, and ScheduledDrainState next for inline scheduling and burst draining.
  • Focus on the concurrency and fault paths in CombineLatestCoordinator<TLeft, TRight, TResult>, PairWitness<TLeft, TRight, TResult>, and SyncLatestWitness<TLeft, TRight, TResult> (OnError(selectorError) signaling DeliveryGate), ChainWitness<T>, ReattemptCoordinator<T>, and FlatMapCoordinator<TSource, TResult> (reentrant completion during Subscribe), and Async AsyncFlowGate, ProbeWitness<T>, TimeoutWitness<T>, ZipState<T1, T2, TResult>, and AsyncSerialGate.
  • Observed per-invocation allocation drops on Range workloads include Distinct (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 fused Map+Keep, Map+Map, Keep+Keep, and Keep+Map chains (168 B to 96 B, 0 B on Subscribe), with Range -> Map -> Keep measured at 32.4 ns in BenchmarkDotNet and 0 B retained across dotMemory snapshots.

Checklist

  • I have read the Contribute guide
  • The PR title follows Conventional Commits
  • Tests cover this change, or the summary says why they do not
  • New or changed public API has XML documentation

@glennawatson
glennawatson force-pushed the perf/operator-fusions-and-teardown branch from 5b89c19 to 30e8e90 Compare November 20, 2026 05:31
@glennawatson glennawatson changed the title perf(operators): fuse operator chains and fix subscription leaks perf(operators): fuse chains, expose Advanced stages, and fix leaks Nov 20, 2026
@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.98%. Comparing base (1eb5b3b) to head (d09ad53).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@glennawatson glennawatson changed the title perf(operators): fuse chains, expose Advanced stages, and fix leaks perf(operators): fuse chains, share stage helpers, and fix leaks Nov 20, 2026
@glennawatson
glennawatson force-pushed the perf/operator-fusions-and-teardown branch 6 times, most recently from f089150 to acefe06 Compare November 20, 2026 12:27
- 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
glennawatson force-pushed the perf/operator-fusions-and-teardown branch from acefe06 to d09ad53 Compare November 20, 2026 12:36
@sonarqubecloud

Copy link
Copy Markdown

@glennawatson
glennawatson merged commit 246a924 into main Nov 20, 2026
16 checks passed
@glennawatson
glennawatson deleted the perf/operator-fusions-and-teardown branch November 20, 2026 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant