diff --git a/AGENTS.md b/AGENTS.md index ec4e66ea..b299e423 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,7 +87,7 @@ Structure public and internal mutation/query methods so cheap checks reject no-o The .NET 10 and later JIT can inline some methods that contain `try`/`finally`. The presence of a lock is not enough to decide whether to split a method. Use measurements to justify a split on modern targets. Keep large branches and uncommon work out of the steady-state path: - Keep hot steady-state paths (`Count`, indexer reads, `AsSpan`, observerless fast checks, lazy-initialized pipeline/channel reads) small and mark tiny wrappers `[MethodImpl(MethodImplOptions.AggressiveInlining)]`. -- Read lazy-initialized references (`_streamPipeline`, `_eventChannel`) via `Volatile.Read` on the warm path, and split lock-protected initialization (`EnsureEventProcessorStarted`, `EnsurePipelineCreated`), buffer resizing, contention fallback, and exception throwing into `[MethodImpl(MethodImplOptions.NoInlining)]` slow-path methods. +- Read lazy-initialized references (`_streamPipeline`, `_eventChannel`) via `Volatile.Read` on the warm path, and split lock-protected initialization (`EnsureEventProcessorStarted`, `CreateStreamObservable`), buffer resizing, contention fallback, and exception throwing into `[MethodImpl(MethodImplOptions.NoInlining)]` slow-path methods. ### 3. Single-Item vs Batch and Zero-Throttle Paths diff --git a/README.md b/README.md index 4da309a3..b9d88d82 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,13 @@ **Fast, thread-safe observable collections and live views for .NET.** [![Build](https://img.shields.io/github/actions/workflow/status/reactiveui/ReactiveList/ci-build.yml?branch=main&label=build&logo=githubactions&logoColor=white)](https://github.com/reactiveui/ReactiveList/actions/workflows/ci-build.yml) +[![Coverage](https://img.shields.io/codecov/c/github/reactiveui/ReactiveList?label=coverage&logo=codecov&logoColor=white)](https://codecov.io/gh/reactiveui/ReactiveList) +[![CodeQL](https://img.shields.io/github/actions/workflow/status/reactiveui/ReactiveList/codeql.yml?branch=main&label=codeql&logo=github&logoColor=white)](https://github.com/reactiveui/ReactiveList/actions/workflows/codeql.yml) +[![Quality gate](https://img.shields.io/sonar/quality_gate/reactiveui_ReactiveList?server=https%3A%2F%2Fsonarcloud.io&label=quality%20gate&logo=sonarqubecloud&logoColor=white)](https://sonarcloud.io/summary/new_code?id=reactiveui_ReactiveList) +[![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/reactiveui/ReactiveList?label=openssf%20scorecard&logo=securityscorecard&logoColor=white)](https://scorecard.dev/viewer/?uri=github.com/reactiveui/ReactiveList) [![NuGet](https://img.shields.io/nuget/v/ReactiveList?label=nuget&logo=nuget&logoColor=white&color=004880)](https://www.nuget.org/packages/ReactiveList) +[![NuGet Reactive](https://img.shields.io/nuget/v/ReactiveList.Reactive?label=nuget%20(reactive)&logo=nuget&logoColor=white&color=004880)](https://www.nuget.org/packages/ReactiveList.Reactive) [![Downloads](https://img.shields.io/nuget/dt/ReactiveList?label=downloads&logo=nuget&logoColor=white&color=004880)](https://www.nuget.org/packages/ReactiveList) -[![Coverage](https://img.shields.io/codecov/c/github/reactiveui/ReactiveList?label=coverage&logo=codecov&logoColor=white)](https://codecov.io/gh/reactiveui/ReactiveList) [![License](https://img.shields.io/github/license/reactiveui/ReactiveList?color=blue)](https://github.com/reactiveui/ReactiveList/blob/main/LICENSE) [![Discussions](https://img.shields.io/badge/discussions-ask%20a%20question-8A2BE2?logo=github&logoColor=white)](https://github.com/reactiveui/ReactiveList/discussions) @@ -25,7 +29,6 @@ Supported targets: `net10.0`, `net11.0`, `net47`, `net471`, `net472`, `net48`, a - [Install](#install) - [Package selection](#package-selection) -- [Migrating to v7.0](#migrating-to-v70) - [Quick start](#quick-start) - [Using R3](#using-r3) - [Core concepts](#core-concepts) @@ -60,6 +63,8 @@ NuGet brings in the matching runtime dependency for you: - `ReactiveList` references `ReactiveUI.Primitives`. - `ReactiveList.Reactive` references `ReactiveUI.Primitives.Reactive` and `System.Reactive`. +Upgrading from an older version? See the [migration guide](https://github.com/reactiveui/ReactiveList/blob/main/docs/migration-v6-to-v7.md). + ## Package selection Reference one package in a project, not both. Each package uses its own root namespace and scheduling type. @@ -77,6 +82,7 @@ A sequencer (`ISequencer`) decides when and on which thread work runs in `Reacti using ReactiveList; using ReactiveList.Collections; using ReactiveList.Core; +using ReactiveList.Queries; using ReactiveList.Views; using ReactiveUI.Primitives; using ReactiveUI.Primitives.Concurrency; @@ -89,29 +95,22 @@ using System.Reactive.Concurrency; using ReactiveList.Reactive; using ReactiveList.Reactive.Collections; using ReactiveList.Reactive.Core; +using ReactiveList.Reactive.Queries; using ReactiveList.Reactive.Views; using ReactiveUI.Primitives.Reactive; ``` -## Migrating to v7.0 +### What each namespace holds -Version 7.0 adopts ReactiveUI namespace standards and targets `.NET 10`, `.NET 11`, and `.NET Framework 4.7` to `4.8.1`. The NuGet package names stay `ReactiveList` and `ReactiveList.Reactive`. +The `ReactiveList.Reactive` package uses the same layout under `ReactiveList.Reactive`. -1. Update your `using` directives to the new root namespaces: - -| Package | v5 / v6 namespace | v7 namespace | -| --- | --- | --- | -| `ReactiveList` | `CP.Primitives` | `ReactiveList` | -| `ReactiveList` | `CP.Primitives.Collections` | `ReactiveList.Collections` | -| `ReactiveList` | `CP.Primitives.Core` | `ReactiveList.Core` | -| `ReactiveList` | `CP.Primitives.Views` | `ReactiveList.Views` | -| `ReactiveList.Reactive` | `CP.Reactive` | `ReactiveList.Reactive` | -| `ReactiveList.Reactive` | `CP.Reactive.Collections` | `ReactiveList.Reactive.Collections` | -| `ReactiveList.Reactive` | `CP.Reactive.Core` | `ReactiveList.Reactive.Core` | -| `ReactiveList.Reactive` | `CP.Reactive.Views` | `ReactiveList.Reactive.Views` | - -2. Rebuild your project before changing any logic. Almost every upgrade error is a namespace import. -3. Keep `ReactiveList` and `ReactiveList.Reactive` in separate assemblies when possible. Referencing both in one file puts two `Subscribe` extension methods in scope. +| Namespace | Contents | +| --- | --- | +| `ReactiveList` | The `ReactiveListExtensions` and `QuaternaryExtensions` operators, such as `CreateView`, `SortBy`, `GroupBy` and `Connect`. | +| `ReactiveList.Collections` | The collections and their interfaces: `ReactiveList`, `Reactive2DList`, `QuaternaryList`, `QuaternaryDictionary`, `IReactiveSource`, `IVersionedSnapshotSource`, `ReactiveSourceOptions` and `NotificationDeferral`. | +| `ReactiveList.Core` | Notification types and helpers: `CacheNotify`, `CacheAction`, `Change`, `ChangeSet`, `PooledBatch`, `ReactiveGroup`, `SecondaryIndex` and `CacheNotifyExtensions`. | +| `ReactiveList.Views` | The view types, such as `FilteredReactiveView`, `SortedReactiveView` and `GroupedReactiveView`. | +| `ReactiveList.Queries` | Live queries: the `Live` property, `LiveQuery`, `LiveView` and `LiveGroupView`. | ## Quick start @@ -260,9 +259,9 @@ Each `Change` carries a `ChangeReason` (`Add`, `Remove`, `Update`, `Move`, `R ### `Reactive2DList` -`Reactive2DList` extends `ReactiveList>` to store rows and cells for grids, tables, and matrices. +`Reactive2DList` is a list of `ReactiveList` rows for grids, tables, and matrices. It implements `IReactiveList>`. -It adds row and cell helpers on top of `ReactiveList`: `AddToInner`, `GetItem`, `SetItem`, `Insert`, `RemoveFromInner`, `ClearInner`, `Flatten`, and `TotalCount`. +It adds row and cell helpers to the list members: `AddToInner`, `GetItem`, `SetItem`, `Insert`, `RemoveFromInner`, `ClearInner`, `Flatten`, and `TotalCount`. ### `QuaternaryList` @@ -290,6 +289,63 @@ You can attach a secondary index to a `QuaternaryList`. A secondary index map `QuadList` and `QuadDictionary` are the single-shard storage types used inside the quaternary collections. Application code should normally use `QuaternaryList` or `QuaternaryDictionary`. +### Deferring notifications + +`DeferNotifications()` groups several writes into one notification. It is available on `ReactiveList`, `Reactive2DList`, `QuaternaryList` and `QuaternaryDictionary`. + +```csharp +using ReactiveList.Collections; + +using var prices = new ReactiveList(); + +using (prices.DeferNotifications()) +{ + prices.Add(10.5m); + prices.Add(11.0m); + prices.RemoveAt(0); +} + +// Subscribers receive one Reset whose batch holds the final items. +``` + +Reads see each write as soon as it commits. Scopes nest, and the collection publishes when the last scope closes. A scope with no changes publishes nothing. + +### Versioned snapshots + +`IVersionedSnapshotSource` lets you copy a collection and then follow its changes without missing one or applying one twice. `ReactiveList`, `Reactive2DList`, `QuaternaryList` and `QuaternaryDictionary` implement it. + +| Member | Meaning | +| --- | --- | +| `VersionedStream` | Each change as a `VersionedNotification`, which pairs the `CacheNotify` with the version that change produced. | +| `CopyVersioned(out long version)` | A copy of the items and the version that copy matches. | + +Subscribe to `VersionedStream` first, then call `CopyVersioned`. Ignore any notification whose version is at most the version of the copy, because the copy already includes it. + +```csharp +using ReactiveList.Collections; +using ReactiveUI.Primitives; + +using var source = new ReactiveList([1, 2, 3]); +long copied = long.MaxValue; + +using var subscription = source.VersionedStream.Subscribe(change => +{ + if (change.Version > Volatile.Read(ref copied)) + { + // Apply change.Notification to your own copy. + } +}); + +var items = source.CopyVersioned(out var version); +Volatile.Write(ref copied, version); +``` + +The sample drops changes that arrive before the copy is recorded. Queue them instead when writers run on other threads. + +### Source options + +If the items in a source never change in place, create it with `Options = new() { ItemsAreImmutable = true }`. Views then ignore refresh notifications. Replacing an item still updates every view. + ## Views A view is a disposable, read-only projection over a collection. It listens to the source stream, marshals updates onto your chosen sequencer or scheduler, and exposes a bindable `Items` collection (`ReadOnlyObservableCollection`) or `Groups` collection. Always dispose a view when its screen or workflow closes. @@ -330,6 +386,21 @@ list.Edit(items => > [!NOTE] > Passing `throttleMs: 0` removes the view timer, not the source's own delivery model. Quaternary collections still publish notifications through their background channel. +### Batch reset limit + +Every view has a `BatchResetLimit` property. When one applied batch changes more items than the limit, the view updates its collection and then raises a single reset, not one notification per item. The default is `int.MaxValue`, so each changed item raises its own notification. + +```csharp +using var sorted = list.SortBy(Comparer.Default, Sequencer.Default); +sorted.BatchResetLimit = 100; +``` + +A lower limit helps UI lists that redraw faster from one reset than from hundreds of single changes. + +### Filtered view order + +A filtered view lists items in the order of its source. An item that starts to match after an update takes its source position. + ### Secondary-index and dynamic search views ```csharp @@ -402,10 +473,9 @@ using var groups = byStatus.ToView(Sequencer.Default); - **Groups:** groups appear in the order their key first occurs in the query result, as `GroupBy` does in LINQ. Members keep the query order. `GroupBy(key, element)` holds a projected value in each group. A group view can be read from any thread while it changes. - **Projections:** `Select` after `OrderBy`, `Skip` or `Take` projects what the window exposes and keeps the order and window. `Where`, `Count`, `Any`, `Contains` and `GroupBy` after such a projection see the projected items. -`LiveView` and `LiveGroupView` expose `BatchResetLimit`, with the same default and meaning as the regular views. Set it to raise one reset for batches larger than the limit, or for a window move larger than the limit, instead of reporting each item separately. -If a source's items never change in place, initialize it with `Options = new() { ItemsAreImmutable = true }`. Views can then ignore refresh notifications. Replacements are still applied. +`LiveView` and `LiveGroupView` expose [`BatchResetLimit`](#batch-reset-limit), with the same default and meaning as the regular views. A window move larger than the limit also raises one reset. -Use `DeferNotifications()` on a reactive list or sharded collection to group several writes. Reads see each write as soon as it commits. When the last nested scope closes, the collection publishes one reset whose batch contains the final snapshot. Empty scopes publish nothing. +Live queries honour [source options](#source-options) and [deferred notifications](#deferring-notifications). ## Extension methods @@ -451,9 +521,12 @@ Operators on `QuaternaryList` and `QuaternaryDictionary`: | Category | Public types | | --- | --- | -| Interfaces | `IReactiveSource`, `IReactiveList`, `IQuaternaryList`, `IQuaternaryDictionary`, `IReactiveView`, `IEditableList`, `IGroupedObservable`, `ISecondaryIndex`, `IResettable`, `IQuad` | -| Core notifications | `CacheNotify`, `CacheAction`, `Change`, `ChangeReason`, `ChangeSet`, `PooledBatch` | -| Helpers and groups | `ReactiveGroup`, `SecondaryIndex`, `EditableListWrapperPool`, `PooledEditableListWrapper` | +| Interfaces | `IReactiveSource`, `IReactiveSourceWithOptions`, `IVersionedSnapshotSource`, `IReactiveList`, `IQuaternaryList`, `IQuaternaryDictionary`, `IReactiveView`, `IEditableList`, `IGroupedObservable`, `ISecondaryIndex`, `IResettable`, `IQuad` | +| Core notifications | `CacheNotify`, `CacheAction`, `Change`, `ChangeReason`, `ChangeSet`, `PooledBatch`, `VersionedNotification` | +| Live queries | `LiveQuery`, `OrderedLiveQuery`, `WindowedLiveQuery`, `GroupedLiveQuery`, `LiveView`, `LiveGroupView`, `LiveValue`, `LiveQueryExtensions` | +| Helpers and groups | `ReactiveGroup`, `SecondaryIndex`, `ReactiveSourceOptions`, `NotificationDeferral`, `EditableListWrapperPool`, `PooledEditableListWrapper` | + +Every class is sealed. Shared behaviour lives in static helpers, not in base classes. ## Thread safety @@ -462,6 +535,8 @@ Every public collection method is safe to call from multiple threads: - `ReactiveList` and `Reactive2DList` guard mutations and snapshots with a dedicated lock. - `QuaternaryList` and `QuaternaryDictionary` guard each of their four shards with an independent `ReaderWriterLockSlim` and publish notifications through an unbounded channel. - `GetEnumerator()`, `ToArray()`, `Snapshot()`, and `AsMemory()` return safe point-in-time copies. +- `Dispose` is safe to call more than once and from any thread, including from inside a notification handler. +- A view applies changes on its sequencer or scheduler. Read a view's `Items` on that same thread, as you would any `ObservableCollection`. - `AsSpan()` on `ReactiveList` reads the backing storage without copying. Call `AsSpan()` only when your code guarantees no concurrent writes can happen while the span is in use. ## Performance @@ -474,7 +549,9 @@ Choose the API that matches your workload: | Large concurrent lists | Use `QuaternaryList`. | | Concurrent key-value caches | Use `QuaternaryDictionary`. | | Repeated category or tag queries | Register a secondary index with `AddIndex` or `AddValueIndex`. | -| High-rate UI updates | Bind to a view with a UI sequencer or scheduler and keep throttling enabled. | +| Several writes that should reach subscribers as one change | Wrap them in `using (list.DeferNotifications())`. | +| Filter, sort and page in one view | Use a [live query](#live-queries), which plans the chain onto one source subscription. | +| High-rate UI updates | Bind to a view with a UI sequencer or scheduler and keep throttling enabled. Set `BatchResetLimit` for large batches. | | Low-level stream consumers | Chain `AutoDisposeBatches()` so rented arrays return to the pool. | ## Building and testing @@ -489,6 +566,8 @@ dotnet test --project tests/ReactiveList.Tests/ReactiveList.Tests.csproj -c Rele dotnet test --project tests/ReactiveList.Reactive.Tests/ReactiveList.Reactive.Tests.csproj -c Release ``` +Both suites compile the same test files, once against each package. They include CsCheck model tests, which run random operation sequences against each collection, view and live query and compare the result with a simple reference model. + The WPF showcase (`src/examples/ReactiveListTestApp`) and its UI test suite (`src/tests/ReactiveListTestApp.Tests`) compile on Linux, macOS, and Windows, and run on Windows. ## Core team diff --git a/docs/migration-v6-to-v7.md b/docs/migration-v6-to-v7.md new file mode 100644 index 00000000..fe48312c --- /dev/null +++ b/docs/migration-v6-to-v7.md @@ -0,0 +1,45 @@ +# Migrating from v5 or v6 to v7 + +Version 7 adopts ReactiveUI namespace standards and targets `.NET 10`, `.NET 11`, and `.NET Framework 4.7` to `4.8.1`. The NuGet package names stay `ReactiveList` and `ReactiveList.Reactive`. + +## Steps + +1. Update your `using` directives to the new root namespaces in the table below. +2. Rebuild your project before changing any logic. Almost every upgrade error is a namespace import. +3. Work through the breaking changes below. +4. Keep `ReactiveList` and `ReactiveList.Reactive` in separate assemblies when possible. Referencing both in one file puts two `Subscribe` extension methods in scope. + +## Namespaces + +| Package | v5 / v6 namespace | v7 namespace | +| --- | --- | --- | +| `ReactiveList` | `CP.Primitives` | `ReactiveList` | +| `ReactiveList` | `CP.Primitives.Collections` | `ReactiveList.Collections` | +| `ReactiveList` | `CP.Primitives.Core` | `ReactiveList.Core` | +| `ReactiveList` | `CP.Primitives.Views` | `ReactiveList.Views` | +| `ReactiveList.Reactive` | `CP.Reactive` | `ReactiveList.Reactive` | +| `ReactiveList.Reactive` | `CP.Reactive.Collections` | `ReactiveList.Reactive.Collections` | +| `ReactiveList.Reactive` | `CP.Reactive.Core` | `ReactiveList.Reactive.Core` | +| `ReactiveList.Reactive` | `CP.Reactive.Views` | `ReactiveList.Reactive.Views` | + +Version 7 also adds `ReactiveList.Queries` and `ReactiveList.Reactive.Queries` for live queries. + +## Breaking changes + +| Change | What to do | +| --- | --- | +| Every library class is sealed. | You cannot derive from a collection or view. Wrap one in your own type instead. | +| The abstract base class of the quaternary collections is gone. | Use `QuaternaryList`, `QuaternaryDictionary` or their interfaces. | +| `Reactive2DList` does not derive from `ReactiveList>`. | It implements `IReactiveList>`, so pass it through that interface. | +| A filtered view always lists items in source order. | An item that starts to match after an update goes to its source position, not to the end. Remove any code that relied on the old position. | +| Some parameter names changed to match their interfaces. | Update calls that use named arguments. | + +## New features + +The [README](../README.md) describes each of these: + +- Live queries, started from a collection's `Live` property. +- `DeferNotifications()`, which groups several writes into one notification. +- `IVersionedSnapshotSource`, which pairs a copy of a collection with the version it matches. +- `BatchResetLimit` on views. +- `ReactiveSourceOptions.ItemsAreImmutable`. diff --git a/src/ReactiveList/Internal/StreamProjection.cs b/src/ReactiveList/Internal/StreamProjection.cs index 11830802..b073f4eb 100644 --- a/src/ReactiveList/Internal/StreamProjection.cs +++ b/src/ReactiveList/Internal/StreamProjection.cs @@ -38,6 +38,9 @@ internal sealed class StreamProjection : IDisposable, IObserverThe comparer that finds an element by value, or for the default search. private readonly IEqualityComparer? _itemComparer; + /// The comparer that finds the exact occurrence of an element before the search by value, or . + private readonly IEqualityComparer? _occurrenceComparer; + /// The cached property-change notification. private readonly PropertyChangedEventArgs _changedArgs; @@ -138,19 +141,22 @@ internal sealed class StreamProjection : IDisposable, IObserverThe property name raised after each applied drain. /// Whether the facade reads the collection independently of the dispatcher. /// Finds an element by value for element types whose default equality allocates, or . + /// Finds the exact occurrence of an element whose identity is not its own reference, or . internal StreamProjection( IReactiveSource? source, Func select, ProjectionRules rules, string changedProperty, bool synchronizeReads = false, - IEqualityComparer? itemComparer = null) + IEqualityComparer? itemComparer = null, + IEqualityComparer? occurrenceComparer = null) { ArgumentExceptionHelper.ThrowIfNull(select); ArgumentExceptionHelper.ThrowIfNull(rules); _source = source; _itemComparer = itemComparer; + _occurrenceComparer = occurrenceComparer; _ignoreRefreshes = source is IReactiveSourceWithOptions { Options.ItemsAreImmutable: true }; _select = select; _rules = rules; @@ -1092,6 +1098,14 @@ private bool RemoveOne(T item) /// Finds an occurrence, preferring reference identity over value equality. /// The item to find. /// The index, or -1. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int IndexOf(T item) => _itemComparer is null ? Target.FindLast(item) : Target.FindLast(item, _itemComparer); + private int IndexOf(T item) + { + // Two elements can be equal by value yet stand for different source items, so the exact occurrence wins when it is present. + if (_occurrenceComparer is { } occurrence && Target.FindLast(item, occurrence) is >= 0 and var exact) + { + return exact; + } + + return _itemComparer is null ? Target.FindLast(item) : Target.FindLast(item, _itemComparer); + } } diff --git a/src/ReactiveList/Queries/LiveBinding.cs b/src/ReactiveList/Queries/LiveBinding.cs index 52323bee..b7c59be0 100644 --- a/src/ReactiveList/Queries/LiveBinding.cs +++ b/src/ReactiveList/Queries/LiveBinding.cs @@ -25,6 +25,9 @@ internal LiveBinding(LiveTryMap map, IEqualityComparer comparer, Comparer = comparer; SameRaw = sameRaw; Identity = new(comparer); + + // A value type has no instance identity, so the search by value already finds the occurrence. + Occurrence = typeof(TRaw).IsValueType ? null : new(Identity); } /// Gets the recorded filters and projections. @@ -36,6 +39,9 @@ internal LiveBinding(LiveTryMap map, IEqualityComparer comparer, /// Gets the comparer that tells whether two source items are the same occurrence: the same instance for reference types. internal LiveIdentityComparer Identity { get; } + /// Gets the comparer that finds the entry holding one source item instance, or for value types. + internal LiveEntryOccurrenceComparer? Occurrence { get; } + /// Gets the test for two source items being the same entry of a keyed source, or . internal Func? SameRaw { get; } diff --git a/src/ReactiveList/Queries/LiveEntryOccurrenceComparer.cs b/src/ReactiveList/Queries/LiveEntryOccurrenceComparer.cs new file mode 100644 index 00000000..2b9534da --- /dev/null +++ b/src/ReactiveList/Queries/LiveEntryOccurrenceComparer.cs @@ -0,0 +1,26 @@ +// Copyright (c) ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +#if REACTIVELIST_REACTIVE +namespace ReactiveList.Reactive.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Treats two entries as the same occurrence when they hold the same source item instance. +/// The source item type. +/// The item type the query exposes. +/// Tells whether two source items are the same occurrence. +internal sealed class LiveEntryOccurrenceComparer(LiveIdentityComparer identity) : IEqualityComparer> + where TRaw : notnull + where T : notnull +{ + /// + public bool Equals(LiveEntry? x, LiveEntry? y) => + ReferenceEquals(x, y) || (x is not null && y is not null && identity.Equals(x.Raw, y.Raw)); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetHashCode(LiveEntry obj) => identity.GetHashCode(obj.Raw); +} diff --git a/src/ReactiveList/Queries/LiveMergeSubscription.cs b/src/ReactiveList/Queries/LiveMergeSubscription.cs index dbef9f07..4375549c 100644 --- a/src/ReactiveList/Queries/LiveMergeSubscription.cs +++ b/src/ReactiveList/Queries/LiveMergeSubscription.cs @@ -71,7 +71,7 @@ internal LiveMergeSubscription( LiveBinding.Matches, binding.SameRaw is null ? null : binding.SameEntry, previousIsReliable: binding.SameRaw is null); - _projection = new(source, binding.CreateEntry, rules, "Count"); + _projection = new(source, binding.CreateEntry, rules, "Count", occurrenceComparer: binding.Occurrence); } /// diff --git a/src/ReactiveList/Queries/LiveSetEngine.cs b/src/ReactiveList/Queries/LiveSetEngine.cs index 496c5ba6..1932347a 100644 --- a/src/ReactiveList/Queries/LiveSetEngine.cs +++ b/src/ReactiveList/Queries/LiveSetEngine.cs @@ -49,7 +49,7 @@ internal LiveSetEngine( LiveBinding.Matches, binding.SameRaw is null ? null : binding.SameEntry, previousIsReliable: binding.SameRaw is null); - _projection = new(source, binding.CreateEntry, rules, "Count"); + _projection = new(source, binding.CreateEntry, rules, "Count", occurrenceComparer: binding.Occurrence); var skip = shape.Window.Skip; var take = shape.Window.Take; if (shape.Window.HasSources) diff --git a/src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs b/src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs index ccbe1108..cf5e079a 100644 --- a/src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs +++ b/src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs @@ -64,9 +64,11 @@ private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan thr } list.Add(ViewFuzzSupport.Sentinel); - await ViewFuzzSupport.SettleAsync(() => view.TryGetValue(ViewFuzzSupport.Sentinel % GroupCount, out var members) && members.Contains(ViewFuzzSupport.Sentinel)); + // The view changes on its scheduler thread, so wait for every group, not only the one that holds the last item written. var expected = list.ToArray().GroupBy(static item => item % GroupCount).ToDictionary(static group => group.Key, ViewFuzzSupport.Sorted); + await ViewFuzzSupport.SettleAsync(() => Matches(view, expected)); + await Assert.That(view.Count).IsEqualTo(expected.Count); foreach (var pair in expected) { @@ -76,4 +78,26 @@ private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan thr await Assert.That(view.Groups.Count).IsEqualTo(expected.Count); } + + /// Checks that the view holds exactly the expected groups and members. + /// The view. + /// The sorted members of each expected group. + /// when the view matches. + private static bool Matches(GroupedReactiveView view, Dictionary expected) + { + if (view.Count != expected.Count) + { + return false; + } + + foreach (var pair in expected) + { + if (!view.TryGetValue(pair.Key, out var members) || !ViewFuzzSupport.Sorted(members).SequenceEqual(pair.Value)) + { + return false; + } + } + + return true; + } } diff --git a/src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs b/src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs index 531fc852..6ba38f49 100644 --- a/src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs +++ b/src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs @@ -132,6 +132,31 @@ public async Task Replace_WithAnEqualCopy_SwapsTheSubscription() await Assert.That(counter.Active).IsEqualTo(1); } + /// After one of two equal items is removed, an in-place change that takes the other out of the filter releases its subscription. + /// Whether to remove the first of the two equal items, not the second. + /// A task representing the asynchronous test. + [Test] + [Arguments(true)] + [Arguments(false)] + public async Task RemoveOneOfTwoEqualItems_ThenChangeTheOther_ReleasesItsSubscription(bool removeFirst) + { + var first = new LiveQueryRow(0, 0, 0); + using var list = new ReactiveList([first, first with { }]); + var counter = new LiveQuerySubscriptionCounter(); + using var subscription = list.Live.Where(static r => r.Tag != KeptTag).SelectMany(counter.Observe).Subscribe(new LiveQueryRecorder()); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueTwo); + + list.RemoveAt(removeFirst ? 0 : 1); + var kept = list[0]; + kept.Change(KeptTag, 0); + + // Assigning an item to its own position is how a list reports that the item changed in place. + list[0] = kept; + + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == 0); + await Assert.That(counter.Unsubscribed).IsEqualTo(TestData.TestValueTwo); + } + /// An item whose observable fails synchronously while the query is rebuilt ends the merge and releases every subscription. /// A task representing the asynchronous test. [Test] diff --git a/src/tests/ReactiveList.Tests/LiveSequenceTests.cs b/src/tests/ReactiveList.Tests/LiveSequenceTests.cs index 7e79ed2e..d102f18e 100644 --- a/src/tests/ReactiveList.Tests/LiveSequenceTests.cs +++ b/src/tests/ReactiveList.Tests/LiveSequenceTests.cs @@ -25,6 +25,33 @@ public async Task Remove_EntryMissingFromTheSequence_ClearsTheMark() await Assert.That(sequence.Target.Count).IsEqualTo(0); } + /// The occurrence comparer matches entries that hold the same source item instance, not equal copies. + /// A task representing the asynchronous test. + [Test] + public async Task OccurrenceComparer_MatchesTheSameInstanceOnly() + { + var comparer = Binding.Occurrence!; + var row = new LiveQueryRow(0, 0, 0); + var entry = Binding.CreateEntry(row); + + await Assert.That(comparer.Equals(entry, entry)).IsTrue(); + await Assert.That(comparer.Equals(entry, Binding.CreateEntry(row))).IsTrue(); + await Assert.That(comparer.Equals(entry, Binding.CreateEntry(row with { }))).IsFalse(); + await Assert.That(comparer.GetHashCode(entry)).IsEqualTo(comparer.GetHashCode(Binding.CreateEntry(row))); + await Assert.That(comparer.Equals(entry, null)).IsFalse(); + await Assert.That(comparer.Equals(null, entry)).IsFalse(); + } + + /// A binding over a value type has no occurrence comparer, because the search by value already finds the occurrence. + /// A task representing the asynchronous test. + [Test] + public async Task OccurrenceComparer_ValueTypeSource_IsAbsent() + { + var binding = new LiveBinding, KeyValuePair>(PassPair, LiveKeyValueComparer.Instance, null); + + await Assert.That(binding.Occurrence).IsNull(); + } + /// Replacing an entry that is marked included but is not in the sequence inserts the replacement. /// A task representing the asynchronous test. [Test] diff --git a/src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs b/src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs index e2fe62ea..01b484a3 100644 --- a/src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs +++ b/src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs @@ -136,9 +136,11 @@ static async (initial, ops) => } list.Add(ViewFuzzSupport.Sentinel); - await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel)); + // The view changes on its scheduler thread, so wait for every item, not only the last one written. var expected = ViewFuzzSupport.Sorted(list.Where(ViewFuzzSupport.Passes)); + await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Sorted(view.Items).SequenceEqual(expected)); + await Assert.That(ViewFuzzSupport.Sorted(view.Items)).IsEquivalentTo(expected, CollectionOrdering.Matching); }, iter: ThrottledIterations, diff --git a/src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs b/src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs index 78393c23..b89f9957 100644 --- a/src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs +++ b/src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs @@ -67,10 +67,13 @@ private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan thr } list.Add(ViewFuzzSupport.Sentinel); - await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel)); + + // The view changes on its scheduler thread and the sentinel sorts ahead of other items, so it can show before the rest. Wait for every item. + var expected = ViewFuzzSupport.Sorted(list); + await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Sorted(view.Items).SequenceEqual(expected)); var items = ViewFuzzSupport.Copy(view.Items); - await Assert.That(ViewFuzzSupport.Sorted(items)).IsEquivalentTo(ViewFuzzSupport.Sorted(list), CollectionOrdering.Matching); + await Assert.That(ViewFuzzSupport.Sorted(items)).IsEquivalentTo(expected, CollectionOrdering.Matching); for (var i = 1; i < items.Length; i++) { await Assert.That(CoarseComparer.Compare(items[i - 1], items[i])).IsLessThanOrEqualTo(0); diff --git a/src/tests/ReactiveListTestApp.Tests/DynamicSecondaryIndexDictionaryReactiveViewTests.cs b/src/tests/ReactiveListTestApp.Tests/DynamicSecondaryIndexDictionaryReactiveViewTests.cs index 1c9b7ae9..27d84779 100644 --- a/src/tests/ReactiveListTestApp.Tests/DynamicSecondaryIndexDictionaryReactiveViewTests.cs +++ b/src/tests/ReactiveListTestApp.Tests/DynamicSecondaryIndexDictionaryReactiveViewTests.cs @@ -49,9 +49,10 @@ public async Task QueuedBurst_PreservesAllCurrentKeysAndValues(bool throttled, C source.AddOrUpdate(index % KeyCount, index * ParityDivisor); } - await scheduler.WorkAvailable.WaitAsync(DispatchTimeout, cancellationToken); - scheduler.RunAll(); + // The dictionary delivers the burst from a background reader, so the first queued callback may cover only part of it. + var settled = await scheduler.RunUntilAsync(() => Matches(view, source), DispatchTimeout, cancellationToken); + await Assert.That(settled).IsTrue(); await Assert.That(view.Count).IsEqualTo(KeyCount); var seen = new HashSet(); foreach (var item in view.Items) @@ -65,4 +66,26 @@ public async Task QueuedBurst_PreservesAllCurrentKeysAndValues(bool throttled, C scheduler.RunAll(); await Assert.That(view.Items).IsEmpty(); } + + /// Checks that the view holds every key with the value the source holds for it. + /// The view. + /// The source dictionary. + /// when the view matches the source. + private static bool Matches(DynamicSecondaryIndexDictionaryReactiveView view, QuaternaryDictionary source) + { + if (view.Count != KeyCount) + { + return false; + } + + foreach (var item in view.Items) + { + if (!source.TryGetValue(item.Key, out var value) || value != item.Value) + { + return false; + } + } + + return true; + } } diff --git a/src/tests/ReactiveListTestApp.Tests/QueuedViewSequencer.cs b/src/tests/ReactiveListTestApp.Tests/QueuedViewSequencer.cs index 3fdc2641..fef9d334 100644 --- a/src/tests/ReactiveListTestApp.Tests/QueuedViewSequencer.cs +++ b/src/tests/ReactiveListTestApp.Tests/QueuedViewSequencer.cs @@ -7,6 +7,9 @@ namespace ReactiveListTestApp.Tests; /// Holds projection callbacks until a test explicitly processes the dispatch queue. internal sealed class QueuedViewSequencer : ISequencer { + /// The pause between passes over the queue while waiting for a condition. + private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(1); + /// Serializes work received from timer callbacks. private readonly Lock _gate = new(); @@ -40,6 +43,31 @@ public void Schedule(IWorkItem item) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Schedule(IWorkItem item, long dueTimestamp) => Schedule(item); + /// Executes queued callbacks until a condition holds, waiting for callbacks a background source has yet to deliver. + /// The condition checked after each pass over the queue. + /// The maximum wait. + /// Cancels the wait. + /// when the condition held within the timeout. + internal async Task RunUntilAsync(Func settled, TimeSpan timeout, CancellationToken cancellationToken) + { + var started = TimeProvider.System.GetTimestamp(); + while (true) + { + RunAll(); + if (settled()) + { + return true; + } + + if (TimeProvider.System.GetElapsedTime(started) >= timeout) + { + return false; + } + + await Task.Delay(PollInterval, cancellationToken).ConfigureAwait(false); + } + } + /// Executes callbacks in their dispatch order, including callbacks they enqueue. internal void RunAll() {