From aafc8fa78771d4708e74889e951c1d5d277b95fb Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:34:08 -0800 Subject: [PATCH 1/5] ToChannel: read the read task's fault so a failed read is not also reported as unobserved A failure in the read reaches the channel through Complete, as documented. The task that ran the read was dropped by every form that does not return the count (ToChannelReader, ToChannel, and ToChannel with an ignored out argument), so when the task was collected, TaskScheduler.UnobservedTaskException fired with the same failure. Produce now attaches an OnlyOnFaulted continuation that reads the task's Exception, as the Dataflow pump does, and still returns the original task: a caller who awaits the count sees the fault. Cost: one continuation per ToChannel call, nothing per row. Test: a failing read through the three forms that drop the count, then GC.Collect and WaitForPendingFinalizers, asserts that no unobserved exception names the read's failure. It fails before the change (three unobserved exceptions) and passes after. Release notes: one Fixed line under Changes since rc.16. Co-Authored-By: Claude Sonnet 5.5 --- Source/Channel/ToChannel.Produce.cs | 12 +++- .../ToChannelProduceTests.cs | 63 +++++++++++++++++++ docsite/articles/release-notes.md | 1 + 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/Source/Channel/ToChannel.Produce.cs b/Source/Channel/ToChannel.Produce.cs index d2a3cd8f..9e51dab3 100644 --- a/Source/Channel/ToChannel.Produce.cs +++ b/Source/Channel/ToChannel.Produce.cs @@ -223,8 +223,9 @@ IAsyncEnumerable> chunks AllowSynchronousContinuations = false, }); - // A failure reaches the channel through Complete; the task - // is dropped unobserved unless the caller asked for the count. + // A failure reaches the channel through Complete: the task's own + // fault is read so that a caller who drops the count never has it + // reported as unobserved. A caller who awaits it still sees it. readCount = ChannelPump .Run>( new(chunks), @@ -233,6 +234,13 @@ IAsyncEnumerable> chunks cancellationToken) .AsTask(); + _ = readCount.ContinueWith( + static task => task.Exception, + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted + | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + return channel; } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs index 50511d35..21fa1bc2 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs @@ -135,6 +135,69 @@ await Assert.ThrowsAsync( Assert.Equal(ConnectionState.Closed, tally.Connections[0].State); } + [Fact] + public static async Task ARowFailure_WhenNobodyAsksForTheCount_IsNotReportedUnobserved() + { + // The fault reaches the channel; the task nobody holds must not + // raise it a second time when it is collected. + List unobserved = []; + void OnUnobserved(object? s, UnobservedTaskExceptionEventArgs e) + { + if (!e.Exception.ToString().Contains( + "failed while reading", StringComparison.Ordinal)) + { + return; + } + + lock (unobserved) + { + unobserved.Add(e.Exception); + } + } + + TaskScheduler.UnobservedTaskException += OnUnobserved; + try + { + // The three forms that drop the count. + DbTally[] tallies = [Tally(20, 9), Tally(20, 9), Tally(20, 9)]; + ChannelReader[] readers = + [ + Read(tallies[0]).ToChannelReader(Ct), + Read(tallies[1]).ToChannel(Ct).Reader, + Read(tallies[2]).ToChannel(out _, Ct).Reader, + ]; + + foreach (ChannelReader reader in readers) + { + (List _, Exception? error) = await ChannelWait.Collect(reader); + Assert.NotNull(error); + } + + foreach (DbTally tally in tallies) + { + await ChannelWait.Until( + () => tally.Connections[0].ClosedAfterOpen, + "the connection to close"); + } + + await Task.Delay(100, Ct); + for (int i = 0; i < 3; ++i) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + lock (unobserved) + { + Assert.Empty(unobserved); + } + } + finally + { + TaskScheduler.UnobservedTaskException -= OnUnobserved; + } + } + [Fact] public static async Task ACancel_CompletesTheChannelWithIt_NotACleanEnd() { diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 58ee72c2..da19c7e8 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 - **New: output parameters are checked against the procedure's metadata before the run.** When the database reports a procedure's parameters (the ADO.NET `ProcedureParameters` schema collection, which SQL Server answers), a call that reads output parameters throws `InvalidOperationException` before the command runs if a member reads a parameter whose mode is `IN` (an input parameter), or if a `decimal` member declares a scale lower than the parameter's (the value would be rounded); a higher scale passes, and no precision is checked. The metadata is read once per procedure, only for such a call, and only checks: it never fills a value, a type or a scale. Without it the call runs as before and the provider's own error applies (SQL Server: 8162 for an output on an `IN` parameter). See [Output parameters](expressive-commands.md#output-parameters). - **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. +- **Fixed: a failed read through `ToChannel` or `ToChannelReader` was also raised as an unobserved task exception.** The failure reached the channel, as documented, but the read's task was dropped by the forms that do not return the count, so `TaskScheduler.UnobservedTaskException` fired when the task was collected. The task's fault is now read, so nothing is raised; the count you ask for with `ToChannel(out Task readCount)` still throws when awaited. - **Removed: parameter directions on the fluent chain.** `AddParam` and `AddParamIf` no longer take a `ParameterDirection`; `AddReturnParam` is gone, and `AddParam(name, direction)`, `AddParamIf(condition, name, direction)`, `AddParam(name, type)` and `AddParamIf(condition, name, type)` are now compile errors that say what to do instead. The forms that took a direction after the value, `AddParam(name, value, ParameterDirection)` and `AddParam(name, value, type, direction)` (the SQL Server forms with a database type and a direction too), fail to compile with the compiler's own argument error, without a message of their own: use the raw `AddParameter` inside `ExecuteAsync(command => ...)`, or read the output with `ExecuteOutputAsync`. A parameter on the chain is an input. To set a direction, use `ExecuteAsync(command => ...)` with the raw `AddParameter`, `AddParameterType` and `AddReturnParameter` extensions. Calls that never passed a direction compile unchanged, with one exception: a constant zero of type `byte` on the SQL Server command, `AddParam(name, (byte)0)`, used to bind silently to the direction overload and is now an ambiguous-call error (CS0121); pass a variable, or give the database type, `AddParam(name, value, SqlDbType.TinyInt)`. `Param` has no `direction` constructor parameter and no `Direction` property. - **Read output parameters: `ExecuteOutputAsync()`.** It maps a command's output parameters and return code into a model by name, with the `Map()` rules; `ExecuteOutputAsync(name)` reads one value, and `CaptureOutput(out DbCapture value, name)` captures one; a name finds its parameter the way `AddParam`'s name does (exactly, else ignoring case, else ignoring case and underscores, else without a common prefix such as `p_`), so `"totalCount"` finds `@total_count`. A `decimal` declares its SQL type: `[Column(TypeName = "decimal(p,s)")]` on a member, or `ExecuteOutputAsync(name, precision, scale)` (`ExecuteOutputDecimalAsync`) for one value. See [Output parameters](expressive-commands.md#output-parameters). - **New: captures, output parameters beside rows.** `CaptureOutput` (a model, one value, or a `decimal` with its precision and scale), `CaptureOutputDecimal` and `CaptureReturn` on an expressive command, a mapped query and its `Skip` and `Take` views give a `DbCapture` as an `out` argument; the async terminal fills it, and a stream fills it when its loop ends, a `break` included. A capture runs once and needs an async terminal; a query's run fills the captures its command has when the run starts, including one added after `Map`. Misuse throws at the call, except that the return code of a command that is not a stored procedure is refused when the run starts: `NotSupportedException` on a query that does not read from an expressive command, `InvalidOperationException` otherwise. A command whose type re-implements `IExecuteReader` is refused too, as `NotSupportedException` on a query capture and `InvalidOperationException` when a command capture runs. See [Output parameters beside rows](expressive-commands.md#output-parameters-beside-rows). From c76080d719c75b2caa9cc3aff69a0d0e3a9ad7ca Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:34:08 -0800 Subject: [PATCH 2/5] Simplify: remove forwarding overloads, local copies and one closure per call Each change keeps the behavior; no public or protected signature changes. - The row reader's guard builds the wrapper exception with its constructor (a row-reading loop catches it) or calls the four-argument RowErrors.Create with row -1, so the three-argument Create and RowMappingFailure.Defer, which only existed to be found by reflection, are deleted. - The reader refusal of a captured run puts only the call that can throw inside the try. - The name check of a parameter list is three `case ... when` arms instead of three nested ifs, and the three-argument ResolveDerived, which had one caller, is deleted: that caller asks the four-argument one with `out _`. - GenericPool no longer repeats Take as an explicit interface member: the public Take already implements both interfaces. - The asynchronous void ExecuteTransactionAsync calls the conditional core directly instead of going through the generic overload, which wrapped the action a second time. The generic overload's async state machine and one wrapping lambda are gone per transaction. - ExecuteReaderAsync on an IDbCommand that is a DbCommand passes the handler with a delegate variance cast instead of a wrapping lambda. The cast makes the DbCommand overload the only applicable one, so it cannot pick itself. One closure and one delegate fewer per call. - DirectStream disposal sets the state with one Interlocked.Exchange instead of a compare-exchange loop; the timestamp the loop kept is only read while the state is Idle. Cost: nothing is added on any path; the two overload changes remove an allocation per call. Tests: ExecuteReaderAsync on a DbCommand held as IDbCommand calls the handler once for both return shapes (a wrong overload pick would recurse forever). Core tests and generator tests pass in Release; whole solution builds with 0 warnings. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/Core/RowErrors.cs | 20 ---------- Source/Core/Core/RowMap.cs | 23 ++++++----- Source/Core/DbQueryBinding.cs | 14 ------- Source/Core/DbQueryParams.cs | 31 +++++++-------- Source/Core/DirectStream.cs | 14 ++----- Source/Core/Extensions/Command._.cs | 12 +++++- Source/Core/Extensions/Transaction.cs | 10 +++-- Source/Core/IDbConnectionPool.cs | 3 -- Source/Core/MappedQuery.cs | 15 ++++--- .../CommandExtensionsTests.cs | 39 +++++++++++++++++++ 10 files changed, 93 insertions(+), 88 deletions(-) diff --git a/Source/Core/Core/RowErrors.cs b/Source/Core/Core/RowErrors.cs index 0080630f..4eac87b4 100644 --- a/Source/Core/Core/RowErrors.cs +++ b/Source/Core/Core/RowErrors.cs @@ -12,16 +12,6 @@ namespace Open.Database.Extensions; /// static class RowErrors { - /// - /// Creates the exception for a failure mapping a row whose number is not known (a reader whose caller owns the read loop). - /// - /// The error the read or the conversion raised. - /// The model type, or the type of the single value. - /// for a single value; otherwise, for a model. - /// The exception to throw. - public static ValueMappingException Create(Exception inner, Type target, bool singleValue) - => Create(inner, target, singleValue, -1); - /// /// Creates the exception for a failure mapping a row. /// @@ -151,16 +141,6 @@ public ValueMappingException Create(Type model, int row) #pragma warning restore IDE0079 // Remove unnecessary suppression sealed class RowMappingFailure(Exception inner, Type target, bool singleValue) : Exception(null, inner) { - /// - /// Creates the wrapper; called by the compiled row readers. - /// - /// The error the read or the conversion raised. - /// The model type, or the type of the single value. - /// for a single value; otherwise, for a model. - /// The wrapper to throw. - public static RowMappingFailure Defer(Exception inner, Type target, bool singleValue) - => new(inner, target, singleValue); - /// /// Returns the exception the read loop throws, naming the row. /// diff --git a/Source/Core/Core/RowMap.cs b/Source/Core/Core/RowMap.cs index b711bd7b..bdc16ca9 100644 --- a/Source/Core/Core/RowMap.cs +++ b/Source/Core/Core/RowMap.cs @@ -1807,9 +1807,18 @@ static Expression OnNull(CellRead read, Slot slot, string column) static BlockExpression Guard(Expression body, List variables, bool singleValue, bool rowKnown) { ParameterExpression ex = Expression.Parameter(typeof(Exception), "ex"); - MethodInfo fail = rowKnown - ? typeof(RowMappingFailure).GetMethod(nameof(RowMappingFailure.Defer))! - : typeof(RowErrors).GetMethod(nameof(RowErrors.Create), [typeof(Exception), typeof(Type), typeof(bool)])!; + Expression type = Expression.Constant(typeof(T)); + Expression single = Expression.Constant(singleValue); + Expression fail = rowKnown + ? Expression.New( + typeof(RowMappingFailure).GetConstructor( + [typeof(Exception), typeof(Type), typeof(bool)])!, + ex, type, single) + : Expression.Call( + typeof(RowErrors).GetMethod( + nameof(RowErrors.Create), + [typeof(Exception), typeof(Type), typeof(bool), typeof(int)])!, + ex, type, single, Expression.Constant(-1)); return Expression.Block( typeof(T), @@ -1823,13 +1832,7 @@ static BlockExpression Guard(Expression body, List variable Expression.TypeIs(ex, typeof(DbException)), Expression.TypeIs(ex, typeof(OperationCanceledException))), Expression.Rethrow(typeof(T)), - Expression.Throw( - Expression.Call( - fail, - ex, - Expression.Constant(typeof(T)), - Expression.Constant(singleValue)), - typeof(T)))))); + Expression.Throw(fail, typeof(T)))))); } /// diff --git a/Source/Core/DbQueryBinding.cs b/Source/Core/DbQueryBinding.cs index bcf5afb5..f9b580cf 100644 --- a/Source/Core/DbQueryBinding.cs +++ b/Source/Core/DbQueryBinding.cs @@ -19,20 +19,6 @@ static class DbQueryBinding public static bool Known(NameSet? names) => names is { Names.Length: > 0 }; - /// - /// Gets the real name an argument of AddParam(value) stands for. - /// - /// The facts of the argument's text. - /// The remembered names, or when they are not known. - /// The query definition. - /// The real name; the last member as written when the names are not known. - /// The expression matches none of the names, or more than one equally well. - public static string ResolveDerived( - ParameterNames.DerivedExpression derived, - NameSet? names, - DbQuery definition) - => ResolveDerived(derived, names, definition, out _); - /// /// Gets the real name an argument of AddParam(value) stands for, and its place in the names. /// diff --git a/Source/Core/DbQueryParams.cs b/Source/Core/DbQueryParams.cs index c58ff7f0..e31ea6ff 100644 --- a/Source/Core/DbQueryParams.cs +++ b/Source/Core/DbQueryParams.cs @@ -197,23 +197,20 @@ public bool Claims(string name, NameSet? names, DbQuery definition) Get(i, out object key, out _); switch (key) { - case string written: - if (DbQueryBinding.SameName(written, name)) return true; - break; - - case NameSet.Entry entry: - if (DbQueryBinding.SameName(entry.Real, name)) return true; - break; - - case ParameterNames.DerivedExpression derived: - if (DbQueryBinding.SameName( - DbQueryBinding.ResolveDerived(derived, names, definition), - name)) - { - return true; - } - - break; + case string written + when DbQueryBinding.SameName(written, name): + return true; + + case NameSet.Entry entry + when DbQueryBinding.SameName(entry.Real, name): + return true; + + case ParameterNames.DerivedExpression derived + when DbQueryBinding.SameName( + DbQueryBinding.ResolveDerived( + derived, names, definition, out _), + name): + return true; } } diff --git a/Source/Core/DirectStream.cs b/Source/Core/DirectStream.cs index 82006a6a..fe5e544e 100644 --- a/Source/Core/DirectStream.cs +++ b/Source/Core/DirectStream.cs @@ -146,16 +146,6 @@ bool TryMove(int from, int to) } } - // Sets the state whatever it was, and returns what it was. - int Exchange(int to) - { - while (true) - { - long word = Volatile.Read(ref _word); - if (Interlocked.CompareExchange(ref _word, (word & ~StateMask) | (uint)to, word) == word) - return (int)(word & StateMask); - } - } #endregion @@ -331,7 +321,9 @@ void Tick() async ValueTask DisposeCoreAsync() { - int was = Exchange(Disposed); + // The timestamp is only read while the state is Idle, so a disposed + // stream does not keep it. + int was = (int)(Interlocked.Exchange(ref _word, Disposed) & StateMask); if (was is NotStarted or Disposed) return; StopTimer(); diff --git a/Source/Core/Extensions/Command._.cs b/Source/Core/Extensions/Command._.cs index 479363ad..48edfcc1 100644 --- a/Source/Core/Extensions/Command._.cs +++ b/Source/Core/Extensions/Command._.cs @@ -237,7 +237,11 @@ public static async ValueTask ExecuteReaderAsync(this IDbCommand command, if (command is DbCommand c) { - await c.ExecuteReaderAsync(reader => handler(reader), behavior, cancellationToken).ConfigureAwait(false); + await c.ExecuteReaderAsync( + (Func)handler, + behavior, + cancellationToken) + .ConfigureAwait(false); return; } @@ -322,7 +326,11 @@ public static ValueTask ExecuteReaderAsync(this IDbCommand command, Contract.EndContractBlock(); return command is DbCommand c - ? ExecuteReaderAsync(c, reader => transform(reader), behavior, cancellationToken) + ? ExecuteReaderAsync( + c, + (Func>)transform, + behavior, + cancellationToken) : ExecuteReaderAsyncCore(command, transform, behavior); static async ValueTask ExecuteReaderAsyncCore(IDbCommand command, Func> transform, CommandBehavior behavior) diff --git a/Source/Core/Extensions/Transaction.cs b/Source/Core/Extensions/Transaction.cs index fdffebee..e468ac40 100644 --- a/Source/Core/Extensions/Transaction.cs +++ b/Source/Core/Extensions/Transaction.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; [SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] public static partial class TransactionExtensions @@ -242,8 +242,12 @@ public static async ValueTask ExecuteTransactionAsync( Contract.EndContractBlock(); await connection - .ExecuteTransactionAsync( - async c => { await action(c).ConfigureAwait(false); return true; }, + .ExecuteTransactionConditionalAsync( + async t => + { + await action(t).ConfigureAwait(false); + return (true, true); + }, isolationLevel, cancellationToken) .ConfigureAwait(false); } diff --git a/Source/Core/IDbConnectionPool.cs b/Source/Core/IDbConnectionPool.cs index a408f615..cae3dd32 100644 --- a/Source/Core/IDbConnectionPool.cs +++ b/Source/Core/IDbConnectionPool.cs @@ -80,9 +80,6 @@ private readonly IDbConnectionPool _source public IDbConnection Take() => _source.Take(); - IDbConnection IDbConnectionPool.Take() - => _source.Take(); - /// public void Give(IDbConnection connection) => _source.Give(connection); diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index 9220cd04..c7c967cf 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -528,25 +528,24 @@ ValueTask ExecuteReaderAsync(TState state, Func diff --git a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs index fc609648..dcf8a2f8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs @@ -146,4 +146,43 @@ public static async Task ExecuteReaderAsync_ClosedConnection_RequestsCloseConnec } #endregion + + #region An IDbCommand that is a DbCommand + + // The IDbCommand overloads hand a DbCommand to the DbCommand overloads; + // a wrong pick would call itself forever. + [Fact] + public static async Task ExecuteReaderAsync_OnADbCommandBehindIDbCommand_CallsTheHandlerOnce() + { + CancellationToken token = TestContext.Current.CancellationToken; + FakeDbConnection connection = new(); + connection.SetState(ConnectionState.Open); + IDbCommand command = new FakeDbCommand( + connection, () => new CountingReader(3)); + int handled = 0; + + await command.ExecuteReaderAsync( + reader => + { + Assert.IsAssignableFrom(reader); + handled++; + return default; + }, + CommandBehavior.Default, + token); + int fields = await command.ExecuteReaderAsync( + reader => + { + Assert.IsAssignableFrom(reader); + handled++; + return new ValueTask(reader.FieldCount); + }, + CommandBehavior.Default, + token); + + Assert.Equal(2, handled); + Assert.Equal(1, fields); + } + + #endregion } From 02b768bd699cedc504b31841d1122b8ef4ca39f1 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:34:09 -0800 Subject: [PATCH 3/5] Generator: read model attributes with Any and look at properties only DeclaresNullPolicy no longer looks at fields: NullPolicy and NullValue cannot be put on a field, so a field never carried one in code that compiles. HasAttribute is one Any call. The generated text is byte-identical: the output of the generator tests (counters on and off) and of the generated benchmarks (net10.0 and net11.0) was compared before and after, file against file. Cost: none at run time; the generator runs at build time. Co-Authored-By: Claude Sonnet 5.5 --- Source/Generator/ModelReader.cs | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index bf4f4bdc..0c2e0c28 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -310,15 +310,10 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t) { if (HasAttribute(c.GetAttributes(), NullPolicyAttribute)) return true; + // Neither attribute can be put on a field. foreach (ISymbol m in c.GetMembers()) { - ImmutableArray attributes = m switch - { - IPropertySymbol p => p.GetAttributes(), - IFieldSymbol f => f.GetAttributes(), - _ => [], - }; - if (HasNullAttribute(attributes)) return true; + if (m is IPropertySymbol p && HasNullAttribute(p.GetAttributes())) return true; } } @@ -463,12 +458,7 @@ static bool IsRetired(ISymbol? member) && a.ConstructorArguments.Length == 2 && a.ConstructorArguments[1].Value is true) == true; static bool HasAttribute(ImmutableArray attributes, string fullName) - { - foreach (AttributeData a in attributes) - if (a.AttributeClass is { } c && FullName(c) == fullName) return true; - - return false; - } + => attributes.Any(a => a.AttributeClass is { } c && FullName(c) == fullName); // The metadata full name (namespace + nested types + arity), as reflection's Type.FullName gives it for a non-generic or definition type. public static string FullName(ITypeSymbol t) From 724afe5e0ec27f027558192db02e8bb538da071d Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:41:12 -0800 Subject: [PATCH 4/5] Review fixes: serialize and guard the unobserved-task test, keep the refusal's try as it was - The unobserved-task test for ToChannel is its own class in the heap-measurement collection, which runs alone, so no parallel test raises the same text into its handler. It cannot pass vacuously: a faulted task it drops itself must be reported unobserved after the collection loop, and the task of the third form (held only through a weak reference) must be dead, before the list of the read's failures is asserted empty. Without the fix it still fails on that last assertion, with three unobserved exceptions. - ReaderRefusal builds the refusal's exception inside the try again, as before the simplification, so the set of exceptions turned into a refusal is unchanged. - Transaction.cs keeps its UTF-8 byte order mark, which the earlier commit dropped. - The ExecuteReaderAsync test is named for what it checks (one call per call), its comment says what the cast does, and the cast has a one-line comment; the two arguments behavior and cancellationToken are grouped on one line. - ModelReader lines are wrapped; a double blank line in DirectStream is removed. No behavior change; the generated text is still byte-identical to the base. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DirectStream.cs | 1 - Source/Core/Extensions/Command._.cs | 8 +- Source/Core/Extensions/Transaction.cs | 2 +- Source/Core/MappedQuery.cs | 15 +-- Source/Generator/ModelReader.cs | 9 +- .../CommandExtensionsTests.cs | 6 +- .../ToChannelProduceTests.cs | 63 ---------- .../ToChannelUnobservedTests.cs | 115 ++++++++++++++++++ 8 files changed, 138 insertions(+), 81 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/ToChannelUnobservedTests.cs diff --git a/Source/Core/DirectStream.cs b/Source/Core/DirectStream.cs index fe5e544e..775bb472 100644 --- a/Source/Core/DirectStream.cs +++ b/Source/Core/DirectStream.cs @@ -146,7 +146,6 @@ bool TryMove(int from, int to) } } - #endregion #region The consumer's side diff --git a/Source/Core/Extensions/Command._.cs b/Source/Core/Extensions/Command._.cs index 48edfcc1..704cb8e8 100644 --- a/Source/Core/Extensions/Command._.cs +++ b/Source/Core/Extensions/Command._.cs @@ -237,10 +237,10 @@ public static async ValueTask ExecuteReaderAsync(this IDbCommand command, if (command is DbCommand c) { + // The cast selects the DbCommand overload without allocating a closure. await c.ExecuteReaderAsync( (Func)handler, - behavior, - cancellationToken) + behavior, cancellationToken) .ConfigureAwait(false); return; } @@ -326,11 +326,11 @@ public static ValueTask ExecuteReaderAsync(this IDbCommand command, Contract.EndContractBlock(); return command is DbCommand c + // The cast selects the DbCommand overload without allocating a closure. ? ExecuteReaderAsync( c, (Func>)transform, - behavior, - cancellationToken) + behavior, cancellationToken) : ExecuteReaderAsyncCore(command, transform, behavior); static async ValueTask ExecuteReaderAsyncCore(IDbCommand command, Func> transform, CommandBehavior behavior) diff --git a/Source/Core/Extensions/Transaction.cs b/Source/Core/Extensions/Transaction.cs index e468ac40..9bf87346 100644 --- a/Source/Core/Extensions/Transaction.cs +++ b/Source/Core/Extensions/Transaction.cs @@ -1,4 +1,4 @@ -namespace Open.Database.Extensions; +namespace Open.Database.Extensions; [SuppressMessage("Design", "CA1068:CancellationToken parameters must come last", Justification = "Overload for easier consumption.")] public static partial class TransactionExtensions diff --git a/Source/Core/MappedQuery.cs b/Source/Core/MappedQuery.cs index c7c967cf..9220cd04 100644 --- a/Source/Core/MappedQuery.cs +++ b/Source/Core/MappedQuery.cs @@ -528,24 +528,25 @@ ValueTask ExecuteReaderAsync(TState state, Func diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index 0c2e0c28..d5f64e1f 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -313,7 +313,11 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t) // Neither attribute can be put on a field. foreach (ISymbol m in c.GetMembers()) { - if (m is IPropertySymbol p && HasNullAttribute(p.GetAttributes())) return true; + if (m is IPropertySymbol p + && HasNullAttribute(p.GetAttributes())) + { + return true; + } } } @@ -458,7 +462,8 @@ static bool IsRetired(ISymbol? member) && a.ConstructorArguments.Length == 2 && a.ConstructorArguments[1].Value is true) == true; static bool HasAttribute(ImmutableArray attributes, string fullName) - => attributes.Any(a => a.AttributeClass is { } c && FullName(c) == fullName); + => attributes.Any( + a => a.AttributeClass is { } c && FullName(c) == fullName); // The metadata full name (namespace + nested types + arity), as reflection's Type.FullName gives it for a non-generic or definition type. public static string FullName(ITypeSymbol t) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs index dcf8a2f8..816d4f96 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs @@ -149,10 +149,10 @@ public static async Task ExecuteReaderAsync_ClosedConnection_RequestsCloseConnec #region An IDbCommand that is a DbCommand - // The IDbCommand overloads hand a DbCommand to the DbCommand overloads; - // a wrong pick would call itself forever. + // The IDbCommand overloads hand a DbCommand to the DbCommand overloads + // with a delegate cast, which picks them without a closure. [Fact] - public static async Task ExecuteReaderAsync_OnADbCommandBehindIDbCommand_CallsTheHandlerOnce() + public static async Task ExecuteReaderAsync_OnADbCommandBehindIDbCommand_CallsTheHandlerOncePerCall() { CancellationToken token = TestContext.Current.CancellationToken; FakeDbConnection connection = new(); diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs index 21fa1bc2..50511d35 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/ToChannelProduceTests.cs @@ -135,69 +135,6 @@ await Assert.ThrowsAsync( Assert.Equal(ConnectionState.Closed, tally.Connections[0].State); } - [Fact] - public static async Task ARowFailure_WhenNobodyAsksForTheCount_IsNotReportedUnobserved() - { - // The fault reaches the channel; the task nobody holds must not - // raise it a second time when it is collected. - List unobserved = []; - void OnUnobserved(object? s, UnobservedTaskExceptionEventArgs e) - { - if (!e.Exception.ToString().Contains( - "failed while reading", StringComparison.Ordinal)) - { - return; - } - - lock (unobserved) - { - unobserved.Add(e.Exception); - } - } - - TaskScheduler.UnobservedTaskException += OnUnobserved; - try - { - // The three forms that drop the count. - DbTally[] tallies = [Tally(20, 9), Tally(20, 9), Tally(20, 9)]; - ChannelReader[] readers = - [ - Read(tallies[0]).ToChannelReader(Ct), - Read(tallies[1]).ToChannel(Ct).Reader, - Read(tallies[2]).ToChannel(out _, Ct).Reader, - ]; - - foreach (ChannelReader reader in readers) - { - (List _, Exception? error) = await ChannelWait.Collect(reader); - Assert.NotNull(error); - } - - foreach (DbTally tally in tallies) - { - await ChannelWait.Until( - () => tally.Connections[0].ClosedAfterOpen, - "the connection to close"); - } - - await Task.Delay(100, Ct); - for (int i = 0; i < 3; ++i) - { - GC.Collect(); - GC.WaitForPendingFinalizers(); - } - - lock (unobserved) - { - Assert.Empty(unobserved); - } - } - finally - { - TaskScheduler.UnobservedTaskException -= OnUnobserved; - } - } - [Fact] public static async Task ACancel_CompletesTheChannelWithIt_NotACleanEnd() { diff --git a/Tests/Open.Database.Extensions.Core.Tests/ToChannelUnobservedTests.cs b/Tests/Open.Database.Extensions.Core.Tests/ToChannelUnobservedTests.cs new file mode 100644 index 00000000..a44ab990 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/ToChannelUnobservedTests.cs @@ -0,0 +1,115 @@ +using System.Runtime.CompilerServices; +using static Open.Database.Extensions.Tests.ChannelFixtures; + +namespace Open.Database.Extensions.Tests; + +// A failed read reaches the channel; the read's task, which nobody holds, +// must not report the same failure as unobserved when it is collected. +// The collection runs alone: no other test raises an unobserved task +// into the handler while it listens. +[Collection("Heap measurements")] +[ExcludeFromCodeCoverage] +public static class ToChannelUnobservedTests +{ + const string Failure = "failed while reading"; + const string Sentinel = "sentinel of the unobserved-task test"; + + static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public static async Task ARowFailure_WhenNobodyAsksForTheCount_IsNotReportedUnobserved() + { + List unobserved = []; + List sentinels = []; + void OnUnobserved(object? s, UnobservedTaskExceptionEventArgs e) + { + string text = e.Exception.ToString(); + List? list = text.Contains( + Sentinel, StringComparison.Ordinal) + ? sentinels + : text.Contains(Failure, StringComparison.Ordinal) + ? unobserved + : null; + if (list is null) + { + return; + } + + lock (list) + { + list.Add(e.Exception); + } + } + + TaskScheduler.UnobservedTaskException += OnUnobserved; + try + { + // The three forms that drop the count; the last one hands the + // task out so that its collection can be checked. + DbTally[] tallies = [Tally(20, 9), Tally(20, 9), Tally(20, 9)]; + WeakReference countTask = Start( + tallies, out ChannelReader[] readers); + DropFaultedTask(); + + foreach (ChannelReader reader in readers) + { + (List _, Exception? error) = await ChannelWait.Collect(reader); + Assert.NotNull(error); + } + + foreach (DbTally tally in tallies) + { + await ChannelWait.Until( + () => tally.Connections[0].ClosedAfterOpen, + "the connection to close"); + } + + await Task.Delay(100, Ct); + for (int i = 0; i < 3; ++i) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + // The test can fail only if it could have seen the report: + // a faulted task nobody observes does raise it here, and the + // task of the read has been collected. + lock (sentinels) + { + Assert.NotEmpty(sentinels); + } + + Assert.False(countTask.IsAlive, "the read's task is still alive"); + lock (unobserved) + { + Assert.Empty(unobserved); + } + } + finally + { + TaskScheduler.UnobservedTaskException -= OnUnobserved; + } + } + + // Not inlined, so that no local of the test keeps a task alive. + [MethodImpl(MethodImplOptions.NoInlining)] + static WeakReference Start( + DbTally[] tallies, + out ChannelReader[] readers) + { + ChannelReader third = Read(tallies[2]) + .ToChannel(out Task count, Ct) + .Reader; + readers = + [ + Read(tallies[0]).ToChannelReader(Ct), + Read(tallies[1]).ToChannel(Ct).Reader, + third, + ]; + return new(count); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void DropFaultedTask() + => _ = Task.FromException(new InvalidOperationException(Sentinel)); +} \ No newline at end of file From 12ba7dbe97e5ffeede99527330c26bbfbd414d4c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:50:43 -0800 Subject: [PATCH 5/5] Tests: the reader checks use Assert.IsType with exactMatch false The two new assertions named Assert.IsAssignableFrom, which the xUnit analyzer reports (info); Assert.IsType with exactMatch false says the same. Co-Authored-By: Claude Sonnet 5.5 --- .../CommandExtensionsTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs index 816d4f96..786afd5a 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/CommandExtensionsTests.cs @@ -164,7 +164,7 @@ public static async Task ExecuteReaderAsync_OnADbCommandBehindIDbCommand_CallsTh await command.ExecuteReaderAsync( reader => { - Assert.IsAssignableFrom(reader); + Assert.IsType(reader, exactMatch: false); handled++; return default; }, @@ -173,7 +173,7 @@ await command.ExecuteReaderAsync( int fields = await command.ExecuteReaderAsync( reader => { - Assert.IsAssignableFrom(reader); + Assert.IsType(reader, exactMatch: false); handled++; return new ValueTask(reader.FieldCount); },