diff --git a/Source/Core/Core/RowReader.cs b/Source/Core/Core/RowReader.cs index f24f68fd..7751bbdb 100644 --- a/Source/Core/Core/RowReader.cs +++ b/Source/Core/Core/RowReader.cs @@ -134,23 +134,31 @@ public static void Fill(IRowSource source, IDataReader reader, int /// The reader positioned on a result set. /// The number of rows to skip. /// The number of rows to read; 0 reads none. + /// The pool and the clearing rule of the chain. /// Cancels the command at an early stop, or . /// The token that cancels the read; only a reader that is not a observes it. - /// The rows, in a new list. + /// The rows, in a new list of exactly their number. // The two hottest terminals (this one and ToArray) keep their own loops: // the sink indirection of Fill is measurable with a tiny projection - // (benchmarked), so the list and the array are written out directly. - public static List ToList(IRowSource source, IDataReader reader, int skip, int take, ReaderAbandon? abandon = null, CancellationToken token = default) + // (benchmarked), so the rows are written out directly, into the chain of pooled arrays + // (as ToListAsync does) and copied once into the list. + // A bare IDataReader has no DbDataReader fast path: Fill reads it through Stream into the same chain. + public static List ToList(IRowSource source, IDataReader reader, int skip, int take, ChunkConfig config, ReaderAbandon? abandon = null, CancellationToken token = default) { if (reader is not DbDataReader db) - return [.. Stream(source, reader, skip, take, false, abandon, token)]; + { + using var viaStream = ChunkChain.Rent(config); + var sink = new ChainSink(viaStream); + Fill(source, reader, skip, take, ref sink, abandon, token); + return viaStream.ToList(); + } - var list = new List(); - if (TakesNone(take, abandon, db)) return list; + if (TakesNone(take, abandon, db)) return []; - if (!SkipRows(db, skip) || !db.Read()) return list; + if (!SkipRows(db, skip) || !db.Read()) return []; Func map = source.Mapper(db); + using var chain = ChunkChain.Rent(config); int n = 0; do { @@ -161,11 +169,11 @@ public static List ToList(IRowSource source, IDataReader reader, int sk } catch (Exception ex) when (RowErrors.IsRowFailure(source, ex)) { - // The list's count, not n (see Fill). - throw RowErrors.Report(ex, skip + list.Count); + // The chain's count, not n (see Fill). + throw RowErrors.Report(ex, skip + chain.Count); } - list.Add(item); + chain.Add(item); if (++n == take) { abandon?.CancelIfMore(db); @@ -174,7 +182,7 @@ public static List ToList(IRowSource source, IDataReader reader, int sk } while (db.Read()); - return list; + return chain.ToList(); } /// diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index d641668d..ad191eb8 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -583,8 +583,8 @@ static IAsyncEnumerable StreamAsync(IRowSource source, IDataReader reader, public List ToList() { ReaderAbandon? abandon = NewAbandon(); - return Run((_source, _skip, _take, abandon), static (reader, s) - => RowReader.ToList(s._source, reader, s._skip, s._take, s.abandon), Behavior, abandon); + return Run((_source, _skip, _take, Config, abandon), static (reader, s) + => RowReader.ToList(s._source, reader, s._skip, s._take, s.Config, s.abandon), Behavior, abandon); } public T[] ToArray() diff --git a/Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs index f192f658..56096b86 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs @@ -150,19 +150,19 @@ static MappedCommand Rows(CountingPool pool, bool? clear public static TheoryData Terminals => [ "ToListAsync", "ToArrayAsync", "ToImmutableArrayAsync", "ToHashSetAsync", "ToDictionaryAsync", "ToDictionaryAsync.Value", - // The synchronous ToList grows a list of its own and rents nothing, so there is nothing to clear. - "ToArray", "ToImmutableArray", "ToDictionary", + "ToList", "ToArray", "ToImmutableArray", "ToDictionary", ]; static async Task Run(string terminal, MappedCommand view) { switch (terminal) { - // The synchronous collectors read through RowReader.Collect, and ToArray through the array sink. + // The synchronous collectors read through RowReader.Collect, and ToList and ToArray through the chain and the array sink they write out themselves. + case "ToList": Assert.Equal(100, view.ToList().Count); break; case "ToArray": Assert.Equal(100, view.ToArray().Length); break; case "ToImmutableArray": Assert.Equal(100, view.ToImmutableArray().Length); break; case "ToDictionary": Assert.Equal(100, view.ToDictionary(static r => r.Id).Count); break; - case "ToListAsync":Assert.Equal(100, (await view.ToListAsync(Ct)).Count); break; + case "ToListAsync": Assert.Equal(100, (await view.ToListAsync(Ct)).Count); break; case "ToArrayAsync": Assert.Equal(100, (await view.ToArrayAsync(Ct)).Length); break; case "ToImmutableArrayAsync": Assert.Equal(100, (await view.ToImmutableArrayAsync(Ct)).Length); break; case "ToHashSetAsync": Assert.Equal(100, (await view.ToHashSetAsync(cancellationToken: Ct)).Count); break; diff --git a/Tests/Open.Database.Extensions.Core.Tests/SyncToListAllocationProbe.cs b/Tests/Open.Database.Extensions.Core.Tests/SyncToListAllocationProbe.cs new file mode 100644 index 00000000..1a43449b --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/SyncToListAllocationProbe.cs @@ -0,0 +1,84 @@ +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// Bytes per call of the synchronous ToList of a mapped view, over an in-memory DataTable, +// against a List that grows (the old shape, written by hand over a DataTableReader). +// A count of bytes, not a time; the thread-local counter sees everything because nothing suspends. +// Run it by itself, in Release, with the test executable and -explicit only. +[ExcludeFromCodeCoverage] +[Collection("Heap measurements")] +public sealed class SyncToListAllocationProbe(ITestOutputHelper output) +{ + const int Rounds = 15; + + static DataTable Table(int rows) + { + var table = new DataTable(); + table.Columns.Add("Id", typeof(int)); + for (int i = 0; i < rows; i++) table.Rows.Add(i); + return table; + } + + // The smallest of several runs, after a warm-up. + static long Measure(Action call) + { + for (int i = 0; i < 20; i++) call(); + + long best = long.MaxValue; + for (int i = 0; i < Rounds; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + long before = GC.GetAllocatedBytesForCurrentThread(); + call(); + best = Math.Min(best, GC.GetAllocatedBytesForCurrentThread() - before); + } + + return best; + } + +#if !DEBUG + // The rows go into pooled chunks and are copied once, so a call allocates the list and not the growth of one. + [Theory] + [InlineData(1000)] + [InlineData(100_000)] + public void ToList_AllocatesLessThanAListThatGrows(int rows) + { + DataTable table = Table(rows); + + long chain = Measure(() => GC.KeepAlive(table.Map().ToList())); + long grows = Measure(() => + { + using DataTableReader r = table.CreateDataReader(); + var l = new List(); + while (r.Read()) l.Add(r.GetInt32(0)); + GC.KeepAlive(l); + }); + + Assert.True(chain < grows, $"{rows} rows: chain {chain} B, list that grows {grows} B."); + } +#endif + + [Fact(Explicit = true)] + public void Probe_BytesPerCall() + { + output.WriteLine("rows | view.ToList() | List that grows (by hand) | view.ToArray() (bytes per call)"); + foreach (int rows in new[] { 0, 1, 1000, 100_000 }) + { + DataTable table = Table(rows); + + long list = Measure(() => GC.KeepAlive(table.Map().ToList())); + long grows = Measure(() => + { + using DataTableReader r = table.CreateDataReader(); + var l = new List(); + while (r.Read()) l.Add(r.GetInt32(0)); + GC.KeepAlive(l); + }); + long array = Measure(() => GC.KeepAlive(table.Map().ToArray())); + + output.WriteLine($"{rows,7} | {list,12} | {grows,12} | {array,12}"); + } + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/SyncToListTests.cs b/Tests/Open.Database.Extensions.Core.Tests/SyncToListTests.cs new file mode 100644 index 00000000..d479761e --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/SyncToListTests.cs @@ -0,0 +1,148 @@ +using Open.Database.Extensions.Core; +using System.Buffers; +using static Open.Database.Extensions.Tests.ChannelWait; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The synchronous ToList reads into the chain of pooled arrays and copies once, as ToListAsync does, +// so a list is exactly as long as its rows, the arrays go back however the call ends, and the +// copy-out clearing applies to it (CopyOutClearingTests). +[ExcludeFromCodeCoverage] +public static class SyncToListTests +{ + static CountingPool NewPool() + => new() + { + RoundUp = true, + Sentinel = static () => new CopyOutRow(-1), + IsDirty = static a => a.Any(static r => r.Id > 0), + }; + + static MappedCommand Rows(int n, int? failAtRow = null, ArrayPool? pool = null) + { + MappedCommand view = new FakeDbCommand( + new FakeDbConnection(), + () => new ChannelTestReader(n, failAtRow: failAtRow)) + .Map(); + + return pool is null ? view : view.UsePool(pool, clearOnReturn: true); + } + + public static TheoryData Sizes + => [0, 1, 15, 16, 17, 48, 49, 100, 8191, 8192, 8193, 20_000]; + + [Theory, MemberData(nameof(Sizes))] + public static void ToList_ReturnsEveryRowInOrder_ExactlySized(int n) + { + List rows = Rows(n).ToList(); + + Assert.Equal(n, rows.Count); + Assert.Equal(n, rows.Capacity); + for (int i = 0; i < n; i++) Assert.Equal(i + 1, rows[i].Id); + } + + [Fact] + public static void WithSkipAndTake_OnlyThoseRowsArrive() + { + List list = Rows(100).Skip(10).Take(30).ToList(); + + Assert.Equal(30, list.Count); + Assert.Equal(11, list[0].Id); + Assert.Equal(40, list[^1].Id); + } + + [Fact] + public static void ATakeOfZero_RentsNothingAndReturnsEmpty() + { + CountingPool pool = NewPool(); + + Assert.Empty(Rows(50, pool: pool).Take(0).ToList()); + Assert.Equal(0, pool.Rents); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(100)] + [InlineData(9000)] + public static async Task EveryArray_GoesBack_AndIsCleanWhenItDoes(int n) + { + CountingPool pool = NewPool(); + + Assert.Equal(n, Rows(n, pool: pool).ToList().Count); + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.Equal(pool.Rents, pool.Returns); + Assert.Equal(0, pool.DirtyReturns); + Assert.Equal(n == 0, pool.Rents == 0); + } + + [Fact] + public static async Task AFailureMidRead_ReturnsEveryArray_AndThrows() + { + CountingPool pool = NewPool(); + + Assert.Throws( + () => Rows(100, failAtRow: 40, pool: pool).ToList()); + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.True(pool.Rents > 0); + Assert.Equal(pool.Rents, pool.Returns); + Assert.Equal(0, pool.DirtyReturns); + } + + // A bare IDataReader has no DbDataReader fast path: it is read through the same chain. + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(100)] + [InlineData(5000)] + public static void ABareIDataReader_ReadsIntoTheSameChain(int n) + { + IDataReader reader = FakeReader.Create(["Id"], [.. Enumerable.Range(1, n).Select(static i => (object?[])[i])]); + + List list = reader.Map().ToList(); + + Assert.Equal(Enumerable.Range(1, n), list); + Assert.Equal(n, list.Capacity); + } + + // A row type of its own, so no other test rents or parks its chain. + sealed record FailRow(int Id); + + static object? ParkedChain() + => typeof(ChunkChain) + .GetField("_spare", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)! + .GetValue(null); + + static InvalidOperationException ThirdRowFails(IDataReader reader) + { + int seen = 0; + MappedReader view = reader.Map(r + => ++seen == 3 + ? throw new InvalidOperationException("mapper failed") + : new FailRow((int)r.GetValue(0))); + + return Assert.Throws(() => view.ToList()); + } + + [Fact] + public static void AFailureMidRead_OfAReader_GivesTheChainBack_AndThrowsTheMappersOwnFailure() + { + object?[][] rows = [.. Enumerable.Range(1, 20).Select(static i => (object?[])[i])]; + Assert.Null(ParkedChain()); + + // The fast path of a DbDataReader, then a bare IDataReader: the chain is parked again after each. + InvalidOperationException db = ThirdRowFails(FakeReader.CreateDb(["Id"], rows)); + Assert.NotNull(ParkedChain()); + InvalidOperationException bare = ThirdRowFails(FakeReader.Create(["Id"], rows)); + // It took the parked chain and gave it back: a chain not disposed would leave none. + Assert.NotNull(ParkedChain()); + + // The caller's own mapper failure comes out as it was thrown, on both paths. + Assert.Equal("mapper failed", db.Message); + Assert.Equal("mapper failed", bare.Message); + } +} diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 0ebb74af..32caac8f 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -11,6 +11,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Fixed: `CreateCommand` on a `SqlTransaction` that has no connection throws `InvalidOperationException`.** The SQL Server package threw `ArgumentNullException` named `connection`; it now reports "Transaction has no connection.", as the core package does. `CreateTextCommand` and `CreateStoredProcedureCommand` follow. - **New: `ToArrayAsync` and `ToImmutableArrayAsync` on a `DbDataReader`.** Like `ToListAsync(transform)`, they read the remaining rows of the current result set through an asynchronous transform into pooled chunks and copy them once, into an array of exactly their number; on .NET 8 and later the immutable array wraps that array and does not copy it again (on .NET Standard it is a copy). - **Changed: the collecting terminals clear their value rows when no pool is offered.** `ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet` and the dictionaries, asynchronous and synchronous, on a view or on a `DbDataReader`, copy their rows out and never show their pooled arrays, so they hide their pooling: a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, whatever the `Open.Database.Extensions.ClearPooledArrays` switch says. `UsePool(pool, clearOnReturn)` is followed as before, so `clearOnReturn: false` still keeps the rows. Rows that hold references were always cleared. The buffers and streams are unchanged: their default is still not to clear value rows. A chunk of 128 KB or more is cleared in the background, as before, and the allocation of a call is the same. +- **Changed: the synchronous `ToList()` reads into pooled chunks, as `ToListAsync` does.** On a view or a reader it grew a list of its own, and so allocated the growth as well as the result and rented no pooled array; it now reads into the chain of pooled arrays and copies the rows once into a list of exactly their number, so the copy-out clearing above applies to it too. The growth is gone: 100,000 `int` rows allocate about 400 KB instead of about 1.05 MB, and 1,000 rows about 28.8 KB instead of 33.2 KB. ### Changes since rc.15