Repository navigation
perf: refactor SqlBulkCopy async loops to async/await and eliminate per-row task allocations - #4685
PauloHMattos wants to merge 6 commits into
Conversation
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
Replaces the hand-rolled TaskCompletionSource + AsyncHelper.ContinueTaskWithState state machine in the innermost column-copy loop with async/await. CopyColumnsAsync now runs a straight-line loop over the row's columns and returns null while every WriteBulkCopyValue completes synchronously (the existing Task-or-null contract its caller relies on). The first time a write pends it hands the remainder of the row to a new async helper, CopyColumnsAsyncContinued, which awaits only the writes that actually pend. This removes the per-column TaskCompletionSource, the CopyColumnsAsyncSetupContinuation closure, and the recursive re-entry. The unused 'source' parameter on CopyColumnsAsync is dropped: the only caller (CopyRowsAsync) always called CopyColumnsAsync(0) with no source, so the source-completion branch was dead code. Behavior is unchanged: the synchronous fast path never awaits (no sync-over-async), and exceptions propagate to the caller (sync) or via the returned Task (async) exactly as before.
This is the change that resolves the bulk of issue dotnet#716. The async regression was concentrated in the SqlDataReader (true-async-read) source path, which scheduled roughly two ThreadPool work items per row. Two hotspots are rewritten: 1. ReadFromRowSourceAsync: the async branch previously did ReadAsync(cts).ContinueWith(...).Unwrap(), allocating a continuation and a wrapper Task for every row. It now checks for synchronous completion (return null, the Task-or-null fast path) and otherwise awaits the read via a small async helper, updating _hasMoreRowToCopy inline. 2. CopyRowsAsync: the hand-rolled TaskCompletionSource + AsyncHelper.ContinueTaskWithState re-entry (one continuation per pending row write and per pending read) is replaced by a synchronous fast-path loop that delegates to an async batch loop (CopyRowsLoopAsync) on the first pend. Writes and reads are awaited only when they actually pend, so the synchronous path never awaits (no sync-over-async) and stays allocation-free. CheckForCancellation is removed; cancellation is now a cts.ThrowIfCancellationRequested() inside the async loop and a Task.FromCanceled() on the synchronous entry, preserving the prior behavior of only observing cancellation in async mode. The unused 'source' parameter on CopyRowsAsync is dropped (its only caller passes none). Per-row semantics are preserved exactly: WriteByte(SQLROW), CheckAndRaiseNotification after each row, and the _parserLock release/reacquire around synchronous reads.
770f154 to
f8c0031
Compare
|
@dotnet-policy-service agree company="Inoa" |
|
@dotnet-policy-service agree |
|
/azp run |
|
Azure Pipelines: Successfully started running 2 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #4685 +/- ##
==========================================
- Coverage 66.27% 65.39% -0.88%
==========================================
Files 290 286 -4
Lines 45062 68567 +23505
==========================================
+ Hits 29865 44840 +14975
- Misses 15197 23727 +8530
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Copilot review overview
🔵 Needs a closer look
The core asynchronous state machine changed substantially and warrants human validation despite the localized scope.
Review effort: Balanced
Findings: 1
Open (1)
What changed in this PR
Refactors SqlBulkCopy async row and column loops to reduce allocations and ThreadPool work.
Changes:
- Adds synchronous fast paths for completed reads and writes.
- Replaces continuation-based loops with
async/awaithelpers. - Preserves cancellation and batching behavior.
| File | Description |
|---|---|
SqlBulkCopy.cs |
Optimizes asynchronous bulk-copy processing. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| state: this, | ||
| scheduler: TaskScheduler.Default | ||
| ).Unwrap(); | ||
| Task<bool> readTask = _dbDataReaderRowSource.ReadAsync(cts); |
cheenamalhotra
left a comment
There was a problem hiding this comment.
Request changes for two reproduced regressions: reader faults can commit partial data, and synchronous EOF can report success despite cancellation. Confirmed against base f2310e9 and head f8c0031 on SQL Server with .NET 8, using native and managed SNI. Please preserve the existing behavior and add regression coverage.
| // remain. Only reached when the read did not complete synchronously. | ||
| private async Task AwaitReadFromDbDataReaderAsync(Task<bool> readTask) | ||
| { | ||
| _hasMoreRowToCopy = await readTask.ConfigureAwait(false); |
There was a problem hiding this comment.
[P1] Reader faults can now commit partial data
Awaiting a faulted task containing OperationCanceledException changes the helper's status to Canceled. That selects cleanupParser: true, sending BulkCopyDone instead of aborting the batch.
Repro: read two rows, then return Task.FromException<bool>(new OperationCanceledException()), with default options and an uncanceled caller token. Base: Faulted, 0 rows committed. PR: Canceled, 2 rows committed.
Preserve fault-versus-cancellation status across the rewritten helpers, and cover task status and destination row count.
There was a problem hiding this comment.
AwaitReadFromDbDataReaderAsync still decides fault versus cancellation from cts.IsCancellationRequested, not readTask.IsFaulted/IsCanceled: a reader that cancels the caller token and then returns a faulted OCE task bypasses the marker and still selects cleanupParser: true, finalizing the partial batch. Conversely, a genuinely canceled reader task with an uncanceled caller token is now wrapped as a fault; synchronous reader OCEs after the row loop has pended also bypass this guard. Preserve antecedent status and synchronous-fault semantics across the new await boundaries, and add task-status/destination-row regressions for those cases.
Auto-replied by the GitHub Copilot app
| { | ||
| _hasMoreRowToCopy = readTask.Result; | ||
| return null; | ||
| } |
There was a problem hiding this comment.
[P2] Synchronous EOF bypasses the final cancellation check
Returning null can reach the unconditional source.SetResult(null) branch in WriteToServerInternalRestContinuedAsync, bypassing its async completion branch's cancellation check.
Repro: use the default DbDataReader.ReadAsync; the final Read() cancels the caller token and returns false. With no pending writes, base returns Canceled; PR returns RanToCompletion.
Apply the same final cancellation check to synchronous completion of async bulk copies and add an EOF regression case.
|
@cheenamalhotra just pushed the regression tests and fix for P1 (typo in the commit name) and P2. Once the review process is finished, if I'm home, I can rerun the benchmark to see where we ended up. |
|
/azp run |
|
Azure Pipelines: Successfully started running 2 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
apoorvdeshmukh
left a comment
There was a problem hiding this comment.
Requesting changes on head 9ba026cb220d015e48e962f223e0e7f600397997 compared with base f2310e93f14c2589718551339b7fc7c33a72ca66.
The existing P1 status-preservation fix remains incomplete: faulted reader OCEs can still select partial-batch finalization, while genuine reader cancellation can be converted to a fault. Details and required regression cases are in the follow-up on the existing P1 thread.
The new inline finding identifies unreachable exception unwrapping: the private BulkCopyAbortException escapes instead of the original reader exception. Preserve Faulted status while unwrapping at the actual fault-completion boundary, including initial-read failures.
The synchronous-EOF cancellation source fix is present. Please extend regression coverage for task status, original exception fidelity, destination rows, and post-failure connection behavior. Current-head CI still has a failed aggregate and a canceled job; the author has not rerun performance measurements after the fixes.
This is an AI-assisted, source-inspection review; no local PR builds, SQL reproductions, or benchmarks were executed. CI failure attribution and controlled current-head performance remain verification gaps, not additional proven implementation defects.
| Exception inner = task.Exception.InnerException; | ||
| if (inner is BulkCopyAbortException abort && abort.InnerException != null) | ||
| { | ||
| inner = abort.InnerException; | ||
| } | ||
| source.SetException(inner); |
There was a problem hiding this comment.
AsyncHelper.ContinueTaskWithState handles faulted tasks itself and never invokes this onSuccess callback, so the new BulkCopyAbortException unwrapping is unreachable. The existing faulted-OCE regression therefore exposes BulkCopyAbortException instead of the original OperationCanceledException, and an initial-read fault never reaches this method. Unwrap at the actual fault-propagation/public-completion boundary while keeping the task Faulted, and extend the regression to assert the original exception type.
|
/azp run |
|
Azure Pipelines: Successfully started running 2 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
There was a problem hiding this comment.
🟡 Changes recommended
Some column/write OperationCanceledException faults are incorrectly converted to cancellation, and added tests violate documented test conventions.
5 open findings
Preserve fault status for canceled exceptions in pending writes · New Preserve fault status for synchronous reader conversion cancellations · New Add required XML documentation to new tests and helpers · New Use DatabaseObjects.Table fixture for transient table lifecycle · New Correct async reader contract for non-generic task result
🧠 Review effort: Balanced
| private async Task CopyColumnsAsyncContinued(Task pendingWrite, int i) | ||
| { | ||
| AsyncHelper.ContinueTaskWithState( | ||
| task, | ||
| source, | ||
| state: this, | ||
| onSuccess: (object state) => | ||
| await pendingWrite.ConfigureAwait(false); |
|
|
||
| _stateObj.WriteByte(TdsEnums.SQLROW); | ||
|
|
||
| Task writeTask = CopyColumnsAsync(0); // Copy 1 row |
| // Regression test: a reader whose ReadAsync returns a *faulted* task carrying | ||
| // an OperationCanceledException must surface WriteToServerAsync as Faulted | ||
| // (not Canceled) and must not commit the rows already written. A Canceled | ||
| // task would select cleanupParser (send BulkCopyDone) and commit partial | ||
| // data; a faulted task aborts the batch. |
| private static void CreateSingleIntColumnTable(SqlConnection connection, string tableName) | ||
| { | ||
| DataTestUtility.DropTable(connection, tableName); | ||
| using SqlCommand command = connection.CreateCommand(); | ||
| Helpers.TryExecute(command, $"create table {tableName} (col1 int)"); |
|
@PauloHMattos This pull request has been marked as Author attention needed. When you have addressed the reviewer feedback and are ready for another review, please post a comment with |
apoorvdeshmukh
left a comment
There was a problem hiding this comment.
@PauloHMattos Can you address the review comments?
|
It's worth noting that #4687 merged earlier this evening, which ported the initial setup phase to use async/await. There'll be some genuine merge conflicts, but it might be easier to address the review feedback now that there's less need to bridge between the per-row native async/await and the outer layers' TaskCompletionSource-based approach. |
@edwardneal There was just 2 conflicts that were easily resolved. @cheenamalhotra @apoorvdeshmukh @edwardneal but before I can restart working on this. I need a decision on one behavior question. Since #4687 made the outer layers of SqlBulkCopy native async/await, an OperationCanceledException that is a fault now makes WriteToServerAsync return a Canceled task with no exception. Examples: a reader returning Task.FromException(new OperationCanceledException()), or ReadAsync/GetValue throwing one synchronously. Before #4687 (f2310e9) the task was Faulted with the original exception. I checked main against SQL Server: the batch is still correctly aborted (0 rows committed), so only the status callers see changed. It wasn't one of the three behavior changes flagged in #4687. Independently of that, this PR has to keep these errors from being treated as cancellations inside the per-row/per-column loops. Otherwise its new async loops would finalize and commit the partial batch (the P1 repro). That part isn't in question. What I'd like you to decide is the public contract:
I lean towards A, since the P1 review asked for Faulted with the original exception, and a Canceled status makes reader errors look like user cancellation. I'm happy to go either way. |
|
Thanks @PauloHMattos, hope the merge helped. I only expected the three noted behaviour changes from #4687, so the change in the returned Task's state comes as a surprise. Thanks for picking up on this and apologies @cheenamalhotra for missing it earlier. The conversations around cancellation/exceptions are slightly awkward. I'd draw a distinction between the sources of the exception though:
This results in a situation I dislike, but which I think would be too large to change. Assuming a non-signalled CancellationToken, these three ReadAsync implementations would behave differently: // Returns a Faulted task.
public override Task<bool> ReadAsync(CancellationToken cancellationToken) =>
Task.FromException<bool>(new OperationCanceledException());
// Throws an exception synchronously.
public override Task<bool> ReadAsync(CancellationToken cancellationToken) =>
throw new OperationCanceledException();
// Returns a Canceled task.
public override async Task<bool> ReadAsync(CancellationToken cancellationToken) =>
throw new OperationCanceledException();The first and second implementations will result in a batch being aborted and all of the previous rows in the batch being discarded. The third will result in the batch being cancelled and all previous rows in the batch being committed. I don't like this distinction, because it means that a client which rewrites their DbDataReader to use modern async/await can find that they've silently changed the commit semantics of the bulk copies which use it. For compatibility purposes, I'd suggest that we should check the CancellationToken prior to any user-supplied method calls, then wrap any OperationCanceledExceptions received from those method calls in an InvalidOperationException, unless those method calls return tasks which are in the Canceled state. The same principle would apply to both sync and async variations of those methods. We can then simply allow that translated exception to propagate naturally to the caller without requiring the rest of SqlBulkCopy and all of its upstream callers to think about how the async state machines handle OperationCanceledException. This preserves the batch-handling distinction between faulted reader operations and cancelled reader tasks, and ensures that caller-supplied CancellationTokens are respected. We'd need to document the new scenario which can generate this exception, but I personally think it'd be a fairly minor change. |


Description
This PR fixes a long-standing performance and memory allocation bottleneck in
SqlBulkCopywhen streaming rows asynchronously from aDbDataReaderorSqlDataReadersource.While troubleshooting heavy GC pressure during large async bulk copies, we traced the issue back to how
SqlBulkCopyhandled per-row and per-column continuations. For every single row read,ReadFromRowSourceAsyncwas wrappingReadAsyncin aContinueWith(...).Unwrap()delegate chain—even when the underlying socket buffer already had the data ready. On top of that,CopyColumnsAsyncandCopyRowsAsyncrelied on a hand-rolled state machine built aroundTaskCompletionSource<object>andAsyncHelper.ContinueTaskWithState. For a 100,000-row ingestion, this churned through over 200,000 ThreadPool work items and generated tens of megabytes of short-lived heap allocations.What Changed
ReadFromRowSourceAsyncto checkreadTask.Status == TaskStatus.RanToCompletioninline. If data is already buffered, it updates_hasMoreRowToCopydirectly and returnsnullwithout spinning up a task continuation wrapper.async/await: Replaced the legacyTaskCompletionSourcesetup with direct C#async/awaitcontinuation helpers (CopyColumnsAsyncContinuedandCopyRowsLoopAsync).task != null). If all writes for a row complete synchronously, no async state machine is ever allocated.Benchmark Summary (100,000 Rows)
Note on Outliers: The time regressions in Numeric (Batch 10000) and Wide (Batch 0) reflect environmental noise (CPU/GC contention during execution on a local laptop with parallel processes running), as memory allocations consistently dropped by 70–80% across all async scenarios.
Full benchmark code is available here: https://github.com/PauloHMattos/SqlClientBulkCopyBenchmark
Issues
Fixes #716