Skip to content

perf: faster, safer collections and views, with live queries and model tests - #421

Merged
glennawatson merged 160 commits into
mainfrom
perf-reliability-pass
Dec 2, 2026
Merged

glennawatson merged 160 commits into
mainfrom
perf-reliability-pass

Conversation

@glennawatson

@glennawatson glennawatson commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

What this does

A performance and reliability pass over the collections, views and notification paths. It also adds a live query API and CsCheck model tests.

Reliability and thread safety

  • Views: fixed a lost wake-up in the dispatcher, a stale order after a same-instance replace in sorted views, leftovers after batch removal, a leak when a view constructor throws, and a gap between subscribing and copying the source.
  • Collections: a silent clear now reaches versioned subscribers, state stays consistent when user equality or selectors throw, subscribing after disposal completes at once, and the lock-free sharded dictionary Count can no longer go negative.
  • Disposal is idempotent and does not wait on the thread that raised the event. A new internal DisposalGate stops work on other threads before Dispose returns.
  • No blocking waits and no iterator state machines remain on the notification paths.

New API (additive, except where noted)

  • Live queries with LINQ names (Where, Select, OrderBy, GroupBy, SelectMany, Skip, Take, Count, Any) and query syntax support.
  • IVersionedSnapshotSource<T> (CopyVersioned, VersionedStream), implemented by ReactiveList<T>, Reactive2DList<T> and the sharded collections.
  • DeferNotifications() on the list, the 2D list and the sharded collections. Scopes nest, and the last release publishes one reset.
  • BatchResetLimit on views.
  • Behaviour change: a filtered view now always lists items in source order. An item that gains membership through an update goes to its source position instead of the end, which matches what a refresh already produced.
  • Breaking: the abstract quaternary base class is gone. Every library class is sealed and shared behaviour moved to static helpers and internal state records. Some parameter names changed to match their interfaces.

Tests

  • 2,480 tests in ReactiveList.Tests and 2,510 in ReactiveList.Reactive.Tests pass on .NET 10 and .NET 11, on Linux, macOS and Windows.
  • Line coverage of the library is 100%, up from 98.58%. Hard-to-reach branches moved into internal static helpers that are tested directly, and unreachable code was removed. Nothing is excluded from coverage.
  • New CsCheck model tests compare each collection, view and live query with a simple reference model under random operation sequences.
  • New race tests cover the dictionary count, first subscription against disposal, and live enumeration during writes.

Timings

BenchmarkDotNet, A-B-B-A against 4463701, .NET 11, pinned cores, one run per area. Base and New are the first pass of each. Allocation is bytes per operation. .NET 10 moved the same way. Some runs shared the machine with builds, so treat differences under about 1.3x as noise.

Core list

Benchmark Base New Ratio Alloc base -> new
Add_Remove_Single (no observers) 94.2 ns 32.2 ns 0.35 192 -> 0
Indexer_Write 49.0 ns 15.8 ns 0.32 144 -> 0
Enumerate_Single 17.5 ns 0.9 ns 0.05 32 -> 0
Contains_Single 13.6 ns 3.0 ns 0.22 0 -> 0
Create_Dispose 113.3 ns 44.8 ns 0.40 824 -> 376
AddRange_NoObservers (10,000) 58,016 ns 3,803 ns 0.07 200,944 -> 80,424
RemoveMany_Predicate (10,000) 296,014 ns 15,901 ns 0.06 181,082 -> 60,426
Remove_Enumerable (10,000) 893,801 ns 95,079 ns 0.10 246,808 -> 197,583
Enumerate (10,000) 6,848 ns 2,652 ns 0.39 40,024 -> 0
Add_Remove_Observed (128) 142.4 ns 84.8 ns 0.68 480 -> 288
Edit_NetZero_Observed (128) 3,179 ns 79 ns 0.03 6,072 -> 32
ReplaceAll_Mirror (1,000) 5,814 ns 464 ns 0.08 6,048 -> 6,048
RemoveRange_InsertRange_Mirror (1,000) 19,982 ns 373 ns 0.02 2,024 -> 4,048
Reactive2DList.TotalCount (128 rows) 334.3 ns 36.2 ns 0.11 0 -> 0
Reactive2DList.Add_Remove_Row (16 rows) 122.3 ns 35.4 ns 0.30 144 -> 0

Views

Benchmark Base New Ratio Alloc base -> new
CreateDispose sorted (4,096) 81,767 ns 9,511 ns 0.12 443,776 -> 82,800
CreateDispose grouped (4,096) 86,657 ns 20,289 ns 0.23 451,648 -> 74,472
CreateDispose filtered (64) 789.9 ns 409.1 ns 0.48 4,584 -> 1,616
SingleAddRemove source (4,096) 2,529 ns 190 ns 0.08 616 -> 288
SingleAddRemove sorted (4,096) 290.0 ns 200.5 ns 0.68 576 -> 288
BatchAddRemove source (4,096) 86,389 ns 699 ns 0.01 4,720 -> 1,960
BatchAddRemove sorted (4,096) 3,198 ns 1,212 ns 0.38 4,976 -> 3,456
BatchAddRemoveByValue grouped 253,479 ns 123,324 ns 0.48 303,704 -> 261,808
Sharded FilteredViewCreateDispose (4,096) 33,281 ns 5,053 ns 0.15 230,632 -> 41,944

Sharded collections under contention

Benchmark Base New Ratio
List_ParallelAdd_Clear (1,000) 268.5 us 61.2 us 0.22
List_ParallelAdd_Clear (10,000) 2,787 us 936 us 0.32
List_ParallelMixed_Clear (10,000) 5,436 us 3,013 us 0.55
Dictionary_ParallelAdd_Clear (1,000) 266.8 us 80.9 us 0.30
Dictionary_ParallelAdd_Clear (10,000) 2,530 us 1,102 us 0.42

A sharded ToArray of 10,000 int values also dropped from about 1.9 us to 1.15 us.

Known regressions

Benchmark Base New Note
RemoveRange_InsertRange_Mirror allocation 2,024 B 4,048 B Deliberate. The list copies the caller's array, so the caller cannot corrupt the notification by changing that array. Time is 0.02x.
ReactiveList Indexer_Read 0.8 ns 1.0 ns Seen in the combined run only. Run on its own, both trees measure 0.6 ns.
Sharded list Count 0.6 ns 0.8 ns The count is now a lock-free sum of four shard counts. That is what makes the contended rows faster.
View SingleAddRemove at 1 and 64 items (filtered, sorted, grouped) 159 to 274 ns 188 to 319 ns 1.07x to 1.20x, about 15 to 20 ns from the disposal gate. Allocation fell from 576-1,384 B to 288-1,168 B.
BatchAddRemove grouped (1 item) 1,907 ns 2,003 ns 1.07x, with allocation down from 10,632 B to 9,616 B.

- add CsCheck fuzz harness and filtered, sorted, grouped and dynamic fuzz tests
- ViewChangeBuffer retains raw notifications with version coverage and head verification
- filtered view tracks membership so inserts, moves and updates keep source order
- sorted view uses binary search and stable rebuild, grouped view re-keys items
- ViewDispatcher dispatches zero throttle directly and coalesces windows
…nnot be applied exactly

- add StreamProjection with count verification and resync, used by ReactiveView
- retry source copies that fail under concurrent mutation
- add quaternary ReactiveView fuzz tests, immediate and throttled
…ry collections

- Model-based tests compare QuaternaryList, QuaternaryDictionary and SecondaryIndex with simple reference models.
- Concurrency tests cover linearizability, mixed workloads, notification order, AddIndex races and Clear races.
- Lifecycle tests cover dispose, observer faults, enumeration snapshots and argument validation.
…d lazy mirrors

- Raise events, streams and PropertyChanged outside the list lock through a single-drainer queue
- Make Dispose atomic and idempotent and complete the streams once
- Create the Items, history and CurrentItems mirrors on first use
- Share one immutable snapshot between enumeration, AsSpan and AsMemory
- Validate Move, RemoveRange, CopyTo and IList arguments under the lock
- Remove many items in one pass instead of quadratic removal
- Keep Reactive2DList rows consistent when row creation fails
- Record the AggressiveInlining attribute on Clear in the public API baselines
- Compare ReactiveList with a List model over random operation sequences, with and without observers
- Check linearizability, cross-thread callbacks, reentrancy, handler exceptions and concurrent Dispose
- Update the coverage test for wrong-type IList.Add and IList.Insert
…correct

- Dispose is atomic and idempotent; operations after disposal throw ObjectDisposedException and the stream completes.
- Notifications are queued under the shard lock so they keep mutation order; PropertyChanged is raised once per batch after unlocking.
- AddIndex builds and registers under all write locks; Clear resets indexes under the lock.
- SecondaryIndex keeps duplicates as a multiset, removes stale mutable keys and avoids boxing.
- Enumeration, ToArray and Snapshot use point-in-time copies; RemoveMany runs its predicate outside the locks.
- RemoveRange and dictionary RemoveKeys/RemoveMany publish BatchRemoved with the removed items.
- CollectionChanged add/remove use compare-exchange; observer and handler faults are isolated.
…d harden fuzz reads

- number unversioned notifications so a source copy discards changes it already contains
- take one confirming copy after racing notifications settle
- quarantine the ReactiveList.Edit reorder defect and avoid it in shared generators
- read view collections defensively while a scheduler thread updates them
… quaternary benchmarks

- SecondaryIndex keeps a per-key bucket with a running total so lookups copy in one pass.
- ToArray and Snapshot return the shared empty array without taking locks when the collection is empty.
- RemoveRange sizes its per-shard count dictionaries up front.
- Add MemoryDiagnoser benchmarks for the zero-item floor, 16 to 128 items with an observer, contended 1,000 to 10,000 items and the secondary index.
- Make benchmark classes unsealed so the in-process toolchain can run them.
- Replace placeholder XML docs in QuadList and fix the RemoveRange remark.
…rojection and route public factories to it

- DynamicReactiveView and the three secondary index views resync from their source and follow key and filter changes
- ReactiveListExtensions and QuaternaryExtensions factories build ReactiveView from the source instead of a stream and snapshot
- projection discards copied-in notifications, waits for an in-flight drain on dispose and survives source copy races
- add dynamic, secondary index and public factory fuzz tests
…benchmarks

- Serve indexer, ToArray, AsSpan and AsMemory from the immutable snapshot when one exists
- Build the snapshot after repeated reads with no mutation, never on a write-then-read loop
- Add floor, interactive and bulk MemoryDiagnoser benchmarks for ReactiveList
…namic notifications

- Watch items from add until remove, replace, clear, source end or dispose, with duplicate items counted once
- Serialize AutoRefresh output and complete or fail it when the source ends
- Subscribe to the stream once in FilterDynamic so a predicate change no longer opens a gap that drops notifications
- Translate updates, keep batch actions and run the predicate once per batch item
- Correct the AutoRefresh expression overload docs
- Add lifecycle, FilterDynamic, AutoRefresh and operator model fuzz tests
…t concurrent mutation

- cover dispose during a mutation storm, double dispose, concurrent handler add and remove, and pooled batches queued at dispose
- read the source through the bounded retry copy when a list view resets or verifies its mirror
- publish count changes without throwing when a view is disposed mid-drain
- expose a resync counter on ReactiveView for tests
- cover single and batch changes over reactive and quaternary lists
…lk regimes

- measure single and batch notifications and view creation for each view type
- measure view creation over a populated quaternary list
- Skip the remaining delivery stages and drop queued changes once the list is disposed
- Test synchronous delivery, mutation order under writers, reentrant mutation, throwing handlers and dispose from a handler
- Split the Edit benchmark into a net-zero and a net-change case so the cancelling edit is not mistaken for a speedup
…s and snapshot

- Check concurrent writers on a deserialized list
- Check a list serialized after Dispose comes back usable
- Check mirrors and the lock-free snapshot after deserialization
- Say plainly that the result is a point-in-time view that mutations never change
- Test mutation, shared snapshots, dispose and concurrent writers
…-pass

# Conflicts:
#	src/tests/ReactiveList.Reactive.Tests/ReactiveList.Reactive.Tests.csproj
#	src/tests/ReactiveList.Tests/ReactiveList.Tests.csproj
- Move every actions-common workflow pin to e07297f.
- Read the list through one enumerator in the reader stress test, because a spread reads Count and then enumerates.
- Add ArgumentExceptionHelper, ArgumentOutOfRangeExceptionHelper and ObjectDisposedExceptionHelper polyfills, compiled only for .NET Framework.
- Alias the same names to the base class library types on modern targets.
- Move the compiler attribute polyfills to src/Polyfills and drop their placeholder types.
- Remove the hand-written guard fallbacks in ReactiveListExtensions and ReactiveList.
…ify batches without a copy

- remove each batch item from the mirror instead of rebuilding it from the source
- check size and the inserted range against the source, copying only when they disagree or equal items make the order ambiguous
- drop unused view helpers
…-pass

# Conflicts:
#	src/tests/ReactiveList.Reactive.Tests/ReactiveList.Reactive.Tests.csproj
#	src/tests/ReactiveList.Tests/ReactiveList.Tests.csproj
- Rename every ThrowHelper.ThrowIfNull call to ArgumentExceptionHelper.ThrowIfNull.
- Delete Internal/ThrowHelper.cs.
…ror ops

- Gather added/removed/changed history items only when a mirror exists
- Contains, IndexOf and GetEnumerator read the shared snapshot without the lock
- RangeObservableCollection uses List.InsertRange and geometric growth via ListCompat
- ChangeSet(Change[]) copies on every target
- GetEnumerator gains AggressiveInlining (PublicAPI baselines updated)
… replaced dictionary entries

- CopyVersioned copies every shard under all read locks and returns the exact version
- the reader exposes the version of the notification it is delivering (NotificationVersion)
- AddOrUpdate publishes the replaced entry as Previous
- race tests cover every read path against concurrent writers
… replaced dictionary entries

- CopyVersioned copies every shard under all read locks and returns the exact version
- the reader exposes the version of the notification it is delivering (NotificationVersion)
- AddOrUpdate publishes the replaced entry as Previous
- race tests cover every read path against concurrent writers
- Read, write and reject a negative batch reset limit on each view type
- Add and remove collection and property change handlers on each view type
- Exercise every forwarding member, event detach and constructor failure
- Cover reference, equatable and boxed struct searches in ItemComparison
- Extract queue-behind and take-next into a static helper with state passed in
- Cover observer failures and dispose during delivery
- a count over a list now rebuilds when an item replaces itself, since its earlier test result is unknown
- the live query model tests change items in place and announce the change
- remove query members that nothing reads
- drop a disposal check the serialized output already makes
…and quaternary events

- Return the mutation-rejected exception instead of calling a throwing helper
- Accept any observable in QuaternaryEvents.Attach so a failing pipeline can be tested
- Check the disposed flag after starting the event processor
…yers

- drive tallies and merges with a scripted source
- move group change checks into a static helper and test it
- check window rebuilds and large inserts
…onary interfaces

- Remove an unreachable empty-input guard from QuaternaryList.AddCore
- Expose the secondary index key matchers to tests
- request a drain through a static helper that is tested directly
- refresh an item in an engine and check its new position
…etry and reset filtering

- Move the source copy retry loop into a state-passing helper
- Expose dispatcher window and run callbacks to tests
- Add a scripted source whose copies and index reads can change or fail mid-read
- Cover null items, positional and unpositioned removals, and verification at the head
…and test them

- Share the property change publication and signal creation of the pump and the projection
- Take retained notifications through a static queue helper
- Make the dispatcher callbacks internal so their disposed paths can be driven
- Populate a batch collection through its list storage
- Cover the pump, projection, engines, relays, gate and source rules
- Populate the batch collection's default list directly instead of a dead enumeration branch
…deterministic

- Hold replayed notifications until the snapshot is applied so a late older change cannot overwrite it
- Drain without a null sink check, since Start always sets the sink first
- Split lock-protected creation paths into internal helpers so each guard can be tested
- Move the disposal-tolerant subscribe into a shared static helper
…n quiet batch end

- Move the handler compare-and-swap into helpers that report a stale read
- Keep the view pump, projection and batch collection with their shared static helpers
- Keep the dispatcher callbacks and the subscription terminal methods as internal
- Combine the relay, pump and source rules tests of both branches
…isposal

- Drive the disposed pipeline path of the event attach directly
- Create the current items signal from a disposed list
- Pick the handler or a rethrow helper in one expression, so the handler field is read once and no null check repeats.
- Eleven views repeated the same guarded setter. Each now assigns through ReactiveViewHelpers.CheckedResetLimit.
@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

@glennawatson
glennawatson merged commit e3cfe0e into main Dec 2, 2026
18 checks passed
@glennawatson
glennawatson deleted the perf-reliability-pass branch December 2, 2026 05:41
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