From ac821b1f2d603bf7ad014c4f0f71c28cc81bd961 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:41:15 -0800 Subject: [PATCH] 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. They hide their pooling, so a query that does not call `UsePool` now always clears the used rows of those arrays before they go back, plain value rows included, and the app-wide switch cannot turn that off. `UsePool(pool, clearOnReturn)` is followed as before. Rows that hold references were always cleared. The buffers and the streams keep their rule (references, then the query, then the switch). The chunk chain and the array sink release through a new `ChunkConfig.SealCopyOut`, which reads `CopyOutClearOnReturn` (`PoolClearing.ResolveCopyOut`: what `UsePool` said, otherwise clear). A chunk of 128 KB or more is still cleared in the recycle bin, so the read path gains no inline clear for large results. The bytes per call of `ToArrayAsync` and `ToImmutableArrayAsync` on a reader (0, 1, 1,000 and 100,000 rows) are the same before and after. Tests: the rule, the chain and the array sink with no pool, `UsePool(true)` and `UsePool(false)`, in place and in the bin, a row type with references through the chain's copy-out, and the collecting terminals of a view, asynchronous and synchronous, with no pool offered, `UsePool(true)` and `UsePool(false)`. The no-pool cases fail on the old code. Docs: pooled memory remarks, the async buffers article, the pooling and clearing article, the deck notes, `UsePool`, `ChunkConfig`, and the release notes. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/ChunkChain.cs | 4 +- Source/Core/ChunkConfig.cs | 47 +++- Source/Core/Core/RowReader.cs | 6 +- Source/Core/MappedQuery.cs | 2 + Source/Core/PoolClearing.cs | 31 ++- Source/Core/PooledMemory.docs.xml | 10 +- Source/Core/RecycleBin.cs | 2 +- .../CopyOutClearingTests.cs | 210 ++++++++++++++++++ docsite/articles/async-buffers.md | 8 +- .../benchmarks/pooling-and-clearing.md | 2 +- docsite/articles/release-notes.md | 1 + docsite/presentation/index.html | 2 +- 12 files changed, 300 insertions(+), 25 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs diff --git a/Source/Core/ChunkChain.cs b/Source/Core/ChunkChain.cs index 0c40e39a..aa9fb4da 100644 --- a/Source/Core/ChunkChain.cs +++ b/Source/Core/ChunkChain.cs @@ -14,7 +14,7 @@ namespace Open.Database.Extensions.Core; /// dispose it once, with a declaration; after that it /// must not be used. /// The arrays come from, and go back to, the pool of the call's -/// ; only the rows that were written are cleared. +/// ; only the rows that were written are cleared, by . /// /// // The read runs on the caller's own flow: there is no producer task (that is @@ -305,7 +305,7 @@ public void Dispose() try { int used = i == count - 1 ? lastUsed : chunks[i].Length; - config.Seal(chunks[i], used).Release(); + config.SealCopyOut(chunks[i], used).Release(); } catch (Exception ex) { diff --git a/Source/Core/ChunkConfig.cs b/Source/Core/ChunkConfig.cs index 0340a684..6f087092 100644 --- a/Source/Core/ChunkConfig.cs +++ b/Source/Core/ChunkConfig.cs @@ -12,9 +12,11 @@ namespace Open.Database.Extensions.Core; /// The type of each row. /// The pool the arrays come from and go back to. /// -/// What was asked: for the app-wide default, -/// or for the caller's choice -/// (see ). +/// What was asked: when no pool was offered, +/// or for the caller's choice. +/// A buffer or a stream resolves it by ( +/// is the app-wide default); a collecting terminal by +/// ( always clears). /// /// The chunk sizes of the collectors, buffers and streams. /// The recycle bin that clears deferred chunks. @@ -65,10 +67,11 @@ internal sealed class ChunkConfig( /// Gets the pool the arrays come from and go back to. public ArrayPool Pool { get; } = pool; - /// Gets whether the rows are cleared before an array goes back. + /// Gets whether the rows of a buffer or a stream are cleared before an array goes back. /// /// A row type that holds references is always cleared, whatever was asked /// (see ). + /// The collecting terminals use instead. /// // Resolved once, here, from what was asked (the constructor takes the raw // intent: null is the app-wide default, true and false are what the caller @@ -76,6 +79,18 @@ internal sealed class ChunkConfig( // such rows are never given ClearMode.None. public bool ClearOnReturn { get; } = PoolClearing.Resolve(clearOnReturn); + /// + /// Gets whether the rows of a chunk that a collecting terminal rented are + /// cleared before it goes back. + /// + /// + /// A collector copies its rows out, so its chunks are never seen by the + /// caller: with no pool offered it always clears, and with + /// UsePool it follows clearOnReturn + /// (see ). + /// + public bool CopyOutClearOnReturn { get; } = PoolClearing.ResolveCopyOut(clearOnReturn); + /// Gets the chunk sizes of the collectors, buffers and streams. public ChunkSizes Sizes { get; } = sizes; @@ -118,23 +133,35 @@ public T[] Rent(int size) /// /// The lease, to be released once. public ArrayLease Seal(T[] array, int used) - => new(array, used, this, ModeFor(used)); + => new(array, used, this, ModeFor(used, ClearOnReturn)); + + /// + /// Makes the lease of a chunk of a collecting terminal that holds + /// rows: the same as , but it + /// clears by . + /// + /// The array, rented from . + /// + /// The lease, to be released once. + public ArrayLease SealCopyOut(T[] array, int used) + => new(array, used, this, ModeFor(used, CopyOutClearOnReturn)); /// The size of a row in the array (a reference is a pointer). static readonly int RowBytes = Unsafe.SizeOf(); /// Chooses what happens to the rows of a chunk on release. /// - /// : only when nothing is to be cleared (no - /// clearing asked and no references to keep alive, see the constructor), or - /// no rows were written. + /// : only when is + /// (the caller, or , + /// resolved no clearing and no references to keep alive), or no rows were written. /// : a chunk of at least /// bytes of rows, of any kind of row; /// everything else that clears does it right away. /// + /// Whether the rows are to be cleared (what the caller of the seal resolved). /// - ClearMode ModeFor(int used) - => !ClearOnReturn || used == 0 + ClearMode ModeFor(int used, bool clear) + => !clear || used == 0 ? ClearMode.None : (long)used * RowBytes >= DeferFromClearedBytes ? ClearMode.Deferred diff --git a/Source/Core/Core/RowReader.cs b/Source/Core/Core/RowReader.cs index 909478ca..f24f68fd 100644 --- a/Source/Core/Core/RowReader.cs +++ b/Source/Core/Core/RowReader.cs @@ -921,7 +921,7 @@ public Dictionary Build(ChunkChain chain) // The arrays come from the pool of the ChunkConfig (the shared array pool by default) // and are as long as the pool makes them: the sink uses all of the array it holds and // grows by renting one twice as long. A row is one array store. -// ChunkConfig.ClearOnReturn is what PoolClearing decided: the rows that were written +// ChunkConfig.CopyOutClearOnReturn is what PoolClearing decided for a collector: the rows that were written // are cleared before an array goes back, and nothing else (an array it outgrew is // released the same way, since the rows were copied out of it). internal struct ArraySink(ChunkConfig config) : IRowSink @@ -968,7 +968,7 @@ void AddSlow(T item) // The rows were copied: the old array goes back, its rows cleared // first when the rule says so (they are alive in the new one, so the // old must not keep them). - if (old is not null) config.Seal(old, rows).Release(); + if (old is not null) config.SealCopyOut(old, rows).Release(); } public readonly T[] ToArray() @@ -986,6 +986,6 @@ public void Dispose() if (items is null) return; _items = null; - config.Seal(items, Count).Release(); + config.SealCopyOut(items, Count).Release(); } } diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 91baf474..d641668d 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -1233,6 +1233,8 @@ public readonly record struct MappedQuery /// An explicit clearOnReturn: false wins over the app-wide switch for this /// query, and an explicit clearOnReturn: true clears whatever the switch /// says. + /// A query that does not call UsePool has no say, and its collecting terminals + /// (the ones that copy the rows out) clear the value rows too, whatever the switch says. /// /// /// It applies to every terminal of this query that rents pooled arrays, diff --git a/Source/Core/PoolClearing.cs b/Source/Core/PoolClearing.cs index c79dee39..8b20cd9f 100644 --- a/Source/Core/PoolClearing.cs +++ b/Source/Core/PoolClearing.cs @@ -6,8 +6,8 @@ namespace Open.Database.Extensions.Core; /// /// /// -/// One rule for every pooled array ODX rents (the collectors' chunk chain, -/// the buffers and the streams): +/// One rule for every pooled array ODX rents that the caller can hold (the +/// buffers and the streams): /// /// /// @@ -33,6 +33,13 @@ namespace Open.Database.Extensions.Core; /// /// The switch is the AppContext setting named by . /// +/// +/// The collecting terminals (ToList, ToArray, ToImmutableArray, +/// ToHashSet and the dictionaries, on a view or a reader) copy their rows out +/// and hide their pooling from the caller, so they have a rule of their own +/// (): with no pool offered they always clear, +/// whatever the switch says; with UsePool they follow clearOnReturn. +/// /// internal static class PoolClearing { @@ -89,6 +96,26 @@ public static bool Resolve(bool? clear) public static bool Resolve(bool? clear, bool all) => (clear ?? all) || Holds.References; + /// + /// Determines whether the used rows of a chunk that a collecting terminal + /// rented must be cleared: the terminal copies its rows out, so its chunks + /// are not the caller's to see. + /// + /// + /// What UsePool said wins; with no pool offered the rows are + /// cleared. The app-wide switch plays no part, so it cannot turn this off. + /// + /// + /// + /// What the query said: when it offered no pool. + /// + /// + /// if the rows must be cleared; otherwise, + /// . + /// + public static bool ResolveCopyOut(bool? clear) + => Resolve(clear, all: true); + /// /// The floor: whether a row type is, or contains, a reference. /// diff --git a/Source/Core/PooledMemory.docs.xml b/Source/Core/PooledMemory.docs.xml index 818cb6da..84a8403f 100644 --- a/Source/Core/PooledMemory.docs.xml +++ b/Source/Core/PooledMemory.docs.xml @@ -24,7 +24,15 @@ Clearing: rows that hold references (a class, a string, a struct that contains either) are always cleared before their array goes back, so a pooled array never keeps a row alive; nothing turns that off. - Rows with no references (an int, a plain struct) go back as they + Rows with no references (an int, a plain struct) depend on the + terminal. + The collecting terminals (ToList, ToArray, ToImmutableArray, + ToHashSet and the dictionaries, on a view or a reader) copy their rows out + and hide their pooling from the caller: when the query offers no pool + they always clear, whatever the app-wide setting says, and with + UsePool they follow it + (clearOnReturn: true clears, clearOnReturn: false keeps the rows as they are). + The buffers and the streams hand their arrays to the caller, so there the rows go back as they are, unless asked: UsePool(pool, clearOnReturn: true) clears them, clearOnReturn: false keeps them as they are whatever the app-wide setting diff --git a/Source/Core/RecycleBin.cs b/Source/Core/RecycleBin.cs index 44d65486..6e7df5e4 100644 --- a/Source/Core/RecycleBin.cs +++ b/Source/Core/RecycleBin.cs @@ -24,7 +24,7 @@ namespace Open.Database.Extensions.Core; /// /// /// Rows that hold references are always cleared; other rows are cleared when UsePool or -/// the app-wide switch asks for it. +/// the app-wide switch asks for it, and always by a collecting terminal that was offered no pool. /// A large chunk is cleared here; a smaller one is cleared where it is released. /// The bin is internal only: nothing outside can feed it. /// It is lazy: no loop exists until the first post. diff --git a/Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs new file mode 100644 index 00000000..f192f658 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/CopyOutClearingTests.cs @@ -0,0 +1,210 @@ +using Open.Database.Extensions.Core; +using System.Buffers; +using static Open.Database.Extensions.Tests.ChannelWait; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +/// The row of the copy-out clearing tests: plain values, nothing to keep alive. +[ExcludeFromCodeCoverage] +internal readonly record struct CopyOutRow(int Id); + +// The collecting terminals copy their rows out, so their pooling is not the +// caller's to see: with no pool offered they always clear the used rows, +// whatever the app-wide switch says; with UsePool they follow clearOnReturn. +// The pooled buffers and streams keep the other rule (PoolClearing.Resolve). +[ExcludeFromCodeCoverage] +public static class CopyOutClearingTests +{ + static CancellationToken Ct => TestContext.Current.CancellationToken; + + // A fresh array holds -1 rows, so a row with an Id above 0 is one that was + // written and not cleared. + static CountingPool NewPool() + => new() + { + RoundUp = true, + Sentinel = static () => new CopyOutRow(-1), + IsDirty = static a => a.Any(static r => r.Id > 0), + }; + + // ---- the rule ------------------------------------------------------------ + + [Theory] + [InlineData(null, true)] + [InlineData(true, true)] + [InlineData(false, false)] + public static void ResolveCopyOut_ValueRows_ClearUnlessUsePoolSaidNot(bool? clear, bool expected) + => Assert.Equal(expected, PoolClearing.ResolveCopyOut(clear)); + + [Theory] + [InlineData(null)] + [InlineData(true)] + [InlineData(false)] + public static void ResolveCopyOut_RowsThatHoldReferences_AreAlwaysCleared(bool? clear) + => Assert.True(PoolClearing.ResolveCopyOut(clear)); + + [Theory] + [InlineData(null, false)] + [InlineData(true, true)] + [InlineData(false, false)] + public static void TheBufferAndStreamRule_IsUnchanged(bool? clear, bool expected) + => Assert.Equal(expected, PoolClearing.Resolve(clear, all: false)); + + // ---- the chain (every collector) and the array sink (the synchronous ToArray) ---- + + public static TheoryData Cases => new() + { + // No pool offered: cleared, in place or by the bin. + { null, false, false }, + { null, true, false }, + // UsePool(pool, true): cleared. + { true, false, false }, + // UsePool(pool, false): left as they are. + { false, false, true }, + { false, true, true }, + }; + + // Deferred: the chunk is too big to clear where it is released, so the bin does it. + static ChunkConfig Config(CountingPool pool, bool? clear, bool deferred) + => TestConfig.Of(pool, clear, deferFromClearedBytes: deferred ? 1 : int.MaxValue); + + [Theory, MemberData(nameof(Cases))] + public static async Task AChainOfValueRows_IsClearedWhenNoPoolIsOffered_AndFollowsUsePool( + bool? clear, bool deferred, bool expectDirty) + { + CountingPool pool = NewPool(); + + using (var chain = ChunkChain.Rent(Config(pool, clear, deferred))) + { + for (int i = 1; i <= 100; i++) chain.Add(new CopyOutRow(i)); + Assert.Equal(100, chain.ToArray().Length); + } + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.True(pool.Returns > 1); + Assert.Equal(expectDirty, pool.DirtyReturns > 0); + } + + [Theory, MemberData(nameof(Cases))] + public static async Task TheArraySink_IsClearedWhenNoPoolIsOffered_AndFollowsUsePool( + bool? clear, bool deferred, bool expectDirty) + { + CountingPool pool = NewPool(); + var sink = new ArraySink(Config(pool, clear, deferred)); + try + { + // More than a first array holds, so an outgrown array is released too. + for (int i = 1; i <= 100; i++) sink.Add(new CopyOutRow(i)); + Assert.Equal(100, sink.ToArray().Length); + } + finally + { + sink.Dispose(); + } + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.True(pool.Returns > 1); + Assert.Equal(expectDirty, pool.DirtyReturns > 0); + } + + [Fact] + public static async Task ARowTypeThatHoldsReferences_IsClearedWhateverUsePoolSaid() + { + var pool = new CountingPool + { + RoundUp = true, + Sentinel = static () => new PoolRow(-1), + IsDirty = static a => a.Any(static r => r is { Id: > 0 }), + }; + + using (var chain = ChunkChain.Rent(TestConfig.Of(pool, false))) + { + for (int i = 1; i <= 100; i++) chain.Add(new PoolRow(i)); + Assert.Equal(100, chain.ToArray().Length); + } + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.True(pool.Returns > 1); + Assert.Equal(0, pool.DirtyReturns); + } + + // ---- through the terminals of a view --------------------------------------- + + // clear: null is a query with no UsePool, whose configuration asks for nothing + // (the default of an entry point), here over a pool the test can count. + static MappedCommand Rows(CountingPool pool, bool? clear) + { + MappedCommand view = new FakeDbCommand( + new FakeDbConnection(), + () => new ChannelTestReader(100)) + .Map() + .AsyncReads(); + + return clear is bool choice + ? view.UsePool(pool, choice) + : view.WithConfig(TestConfig.Of(pool, null)); + } + + 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", + ]; + + static async Task Run(string terminal, MappedCommand view) + { + switch (terminal) + { + // The synchronous collectors read through RowReader.Collect, and ToArray through the array sink. + 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 "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; + case "ToDictionaryAsync": Assert.Equal(100, (await view.ToDictionaryAsync(static r => r.Id, cancellationToken: Ct)).Count); break; + case "ToDictionaryAsync.Value": Assert.Equal(100, (await view.ToDictionaryAsync(static r => r.Id, static r => r.Id, cancellationToken: Ct)).Count); break; + default: throw new ArgumentException(terminal, nameof(terminal)); + } + } + + [Theory, MemberData(nameof(Terminals))] + public static async Task ACollector_WithNoPoolOffered_ClearsTheValueRows(string terminal) + { + CountingPool pool = NewPool(); + + await Run(terminal, Rows(pool, clear: null)); + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.True(pool.Returns > 0); + Assert.Equal(0, pool.DirtyReturns); + } + + [Theory, MemberData(nameof(Terminals))] + public static async Task ACollector_WithUsePoolTrue_ClearsTheValueRows(string terminal) + { + CountingPool pool = NewPool(); + + await Run(terminal, Rows(pool, clear: true)); + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.True(pool.Returns > 0); + Assert.Equal(0, pool.DirtyReturns); + } + + [Theory, MemberData(nameof(Terminals))] + public static async Task ACollector_WithUsePoolFalse_LeavesTheValueRows(string terminal) + { + CountingPool pool = NewPool(); + + await Run(terminal, Rows(pool, clear: false)); + + await Until(() => pool.Outstanding == 0, "the arrays back"); + Assert.True(pool.Returns > 0); + Assert.True(pool.DirtyReturns > 0); + } +} diff --git a/docsite/articles/async-buffers.md b/docsite/articles/async-buffers.md index 2f91d885..fa250840 100644 --- a/docsite/articles/async-buffers.md +++ b/docsite/articles/async-buffers.md @@ -191,11 +191,11 @@ The measurements behind these choices (which pool, how rows are cleared, and whe A pooled array that goes back with rows in it keeps them reachable while it sits in the pool, and any other code in the process can rent the same array next. So ODX decides, for every array it rents, with one rule: 1. **Rows that hold references are always cleared.** A class, a string, a struct that contains either: the used rows are cleared before the array goes back, so a pooled array never keeps a row alive. Nothing turns this off. -2. **Rows with no references are cleared when asked.** An `int` or a plain struct holds nothing to keep alive, so clearing them costs time for no gain unless the values are sensitive. The default is not to clear them. +2. **Rows with no references depend on the terminal.** An `int` or a plain struct holds nothing to keep alive, so clearing them costs time for no gain unless the values are sensitive. A collecting terminal (`ToList`, `ToArray`, `ToImmutableArray`, `ToHashSet`, the dictionaries, on a view or on a reader) copies its rows out and never shows its arrays, so it hides its pooling: with no pool offered it **always clears**, whatever the switch says, and with `UsePool(pool, clearOnReturn)` it follows `clearOnReturn`. A buffer or a stream hands its arrays to you, so it does not clear them unless asked, as follows. -Two settings raise that default for rows with no references, and the more specific one wins. +Two settings raise that default for the buffers and streams, and the more specific one wins. -**The app-wide switch** `Open.Database.Extensions.ClearPooledArrays` clears every array ODX rents, value rows included, for every query that does not say otherwise. It is off by default and is read once, so set it before the first query. The way to set it is in the application's project file, which puts it in `runtimeconfig.json`, where an operator can also change it: +**The app-wide switch** `Open.Database.Extensions.ClearPooledArrays` clears every array ODX rents for a buffer or a stream, value rows included, for every query that does not say otherwise. It is off by default and is read once, so set it before the first query. The way to set it is in the application's project file, which puts it in `runtimeconfig.json`, where an operator can also change it: ```xml @@ -209,7 +209,7 @@ Or in code, before the first query: `AppContext.SetSwitch("Open.Database.Extensi [!code-csharp[](../samples/AsyncBuffers.cs#buffers_clearing_shared)] -An explicit `clearOnReturn: true` clears value rows whatever the switch says. An explicit `clearOnReturn: false` keeps them as they are, also when the switch is on: this is the opt-out, and it is per query. It cannot lower the floor: `clear` controls rows with no references, and rows that hold references are always cleared. +An explicit `clearOnReturn: true` clears value rows whatever the switch says. An explicit `clearOnReturn: false` keeps them as they are, also when the switch is on: this is the opt-out, and it is per query, for the collecting terminals as well as for the buffers and streams. It cannot lower the floor: `clear` controls rows with no references, and rows that hold references are always cleared. The switch has no part in a collecting terminal: with no `UsePool` it clears anyway. ### Your own pool diff --git a/docsite/articles/benchmarks/pooling-and-clearing.md b/docsite/articles/benchmarks/pooling-and-clearing.md index c42634b1..3a61c2d1 100644 --- a/docsite/articles/benchmarks/pooling-and-clearing.md +++ b/docsite/articles/benchmarks/pooling-and-clearing.md @@ -17,7 +17,7 @@ A *pool* is a shop for arrays: you rent one, use it, and return it, so the memor These are what ODX does with the arrays it rents. They are written in full on [Pooled memory](../async-buffers.md#pooled-memory). 1. **Rows that hold references are always cleared.** A class, a string, a struct that contains either: the rows that were written are cleared before the array goes back, so a pooled array never keeps a row alive. Nothing turns this off. -2. **Rows with no references are cleared when asked.** An `int` or a plain struct holds nothing to keep alive, so the default is not to clear them. Ask for it for one query with `.UsePool(pool, clearOnReturn: true)`, or for the whole application with the `Open.Database.Extensions.ClearPooledArrays` switch. An explicit `clearOnReturn: false` wins over the switch. +2. **Rows with no references are cleared by a collecting terminal that was offered no pool, and otherwise when asked.** An `int` or a plain struct holds nothing to keep alive. A collecting terminal (`ToList`, `ToArray`, and the others that copy their rows out) hides its pooling, so with no `UsePool` it always clears them, and with `UsePool` it follows `clearOnReturn`. A buffer or a stream hands its arrays to the caller, so the default there is not to clear them. Ask for it for one query with `.UsePool(pool, clearOnReturn: true)`, or for the whole application with the `Open.Database.Extensions.ClearPooledArrays` switch. An explicit `clearOnReturn: false` wins over the switch. 3. **Only the part that was used is cleared.** An array can be longer than the rows written into it. ODX clears the written rows and not the rest. When every slot was written, it asks the pool to clear the array. 4. **Where the clear happens depends on the size.** A chunk that is cleared at all is cleared by the code that releases it, unless its rows add up to 128 KB or more, of any kind of row. Then it is handed to one background loop (the *recycle bin*), which clears it and returns the array to the pool, so neither the read nor the consumer waits for it. If the bin is full, the clear runs where the chunk is released. diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 94330924..0ebb74af 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -10,6 +10,7 @@ Version 11 is `11.0.0-rc.16`. For moving a 10.x codebase, read [Coming from earl - **Fixed: a cancel during `AsAsyncEnumerable(pool)`.** On a `DbDataReader`, `AsAsyncEnumerable(arrayPool)` with a pool (the form that reads every column) did not pass its token to `ReadAsync`, so a read the provider cancelled threw out of the enumeration. It now ends the enumeration quietly with the rows already yielded, as the other forms do. - **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. ### Changes since rc.15 diff --git a/docsite/presentation/index.html b/docsite/presentation/index.html index 63bde124..02131928 100644 --- a/docsite/presentation/index.html +++ b/docsite/presentation/index.html @@ -2599,7 +2599,7 @@

Clearing pooled arrays