You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow TVPs to be populated via asynchronous data sources & add a new field to SqlDbType #982
Is your feature request related to a problem? Please describe.
Currently when you use IDataReader/DbDataReader as a source for a tvp parameter, it will always call the Read() method to consume rows.
In addition, only IEnumerable<SqlDataRecord> can be used as a source, not IAsyncEnumerable<SqlDataRecord>.
I think as a solution it would be beneficial to add a new SqlDbType, StructuredAsync, which would allow using an asynchronous way of populating a structured table valued parameter.
As an alternative, we could always call ReadAsync(CancellationToken), however, this may regress scenarios where the reader is entirely synchronous and no async operations are needed.
Another approach could be add a boolean property in SqlParameter like ReadMode, but I feel like there are too many constructors and mutable properties on a SqlParameter already that is already incredibly difficult to find the options you neccessarily care about.
The problem with that is that you'd be holding the write operation on an await for the parameters which is complicated. Why would you need to send async enumerable params to a tvp? what is the discovery mechanism for the values?
Presumably, the usual reasons to use a tvp but your source doesn't have all the data immediately. You are sending a datareader from another database, or you are translating some message bus/web call into a sql data record.
The tvp would query the schema table like it does currently. For the IAsyncEnumerable, the library would read the first row for the sqlmetadata[].
The first thing a tvp does is basically insert the rows into the table type variables, and rather than streaming the records synchronously, this operation could be done async.
The way that the TVP enumerable works is to send the values as part of the request so if you don't have all the values synchrnously you will end up in a situation where the driver is trying to construct a packet containing RPC data to send to the server but it now has to do an async await meaning that the state of the connection can stay in the middle of a constructed packet for an indefinate amount of time which could be problematic. Now imagine you're doing that with a transaction open.
The obvious way to get around that would be to buffer the input but since there is no defined maximum (is there?) number of entries that'd be tricky as well. In this case you'd be better off getting the caller to buffer values until there are "enough" or source enumeration is complete and then execute the query, which leaves you in the situation you're in now.
Sounds tricky. Probably possible but given the code of the driver which isn't async friendly it's not a quick one.
Great discussion, I agree going Async way is not going to be an easy change in the driver.
We'll investigate it's possibility and come back on this one.
the state of the connection can stay in the middle of a constructed packet for an indefinate amount of time which could be problematic
Isn't the same thing happening today, just with synchronous I/O? Presumably people are already using TVPs to read from other databases, so slow network I/O is already been done - the question is only if it should be doable asynchronously (i.e. without blocking the thread).
Buffering the data (as opposed to streaming it) would increase client memory requirements, potentially in a dramatic way.
Yes, you could get into the same situation at the moment. To me an async enumerable is just more likely to be awaited since that's the intent of the interface where plain old enumerable is old synchronous world tech and is usually assumed to be always ready, at least to me. In either case if your enumeration is blocking you leave the pulling connection in a peculiar state while it waits for input.
If I understand this correctly, the point here is to stream large amounts of data into the database that's possibly coming from another database. As usual I'm not familiar with the SqlClient internals here, but having the database driver block/await on I/O while writing parameter data to the database doesn't seem any more problematic than streaming large data when fetching via DbDataReader.GetStream/GetTextReader. And as in all scenarios potentially transferring data over the network, allowing async operations as an alternative to sync is valuable.
But again, that's just an external, general point of view.
Do you have an good examples or tutorial materials on how to write dual purpose methods for sync/async purposes? The primary problem I have is that the core of the driver is synchronous and the async support is layered over it. The current async logic paths all use imperative async which is costly wasteful and hard to reason about.
@Wraith2 you're right, I think that's one of the main architectural issues you guys have, and probably the source of some bugs as well - callback-based (imperative) async is notoriously difficult to do (as you mentioned)...
It's a difficult question. I'd say the first priority would be to gradually try to transition to async/await in the driver. At least in theory, this doesn't need to be done in one go - clusters of callback-based methods returning Tasks can be gradually rewritten to use async instead (i.e. at least the method signatures don't need to change). But I don't take this lightly - it's quite a project.
If you manage to make progress here, you should end up with an async code path that closely resembles your sync code path. At this point, you may want to consider merging certain sync/async paths - though by all means not everyone does this. In Npgsql, NpgsqlCommand.ExecuteReader and ExecuteReaderAsync call into a single ExecuteReader method, which accepts a boolean async flag and itself has the async keyword. We go down the stack via similar methods, passing down the async flag, until we get to the very bottom, where I/O needs to be performed; at this point, we check the flag, and call either the sync or async method on NetworkStream (or whatever).
The end effect, is that when sync ExecuteReader is called, the code passes through async methods, but everything always completes synchronously. This implies a tiny bit of overhead for the sync path (compared to two completely separate paths), but allows you to have just one code path, which is much more maintainable. Again, not everyone does this - EF Core duplicates code for sync/async - but if you're interested I'd be happy to point you to some examples inside Npgsql.
However, this second phase of "unifying" your sync and async paths really is optional and far off in any case. I'd try to come up with a plan for modernizing and transitioning to async/await first - assuming the SqlClient team thinks that's a good direction etc.
I'd say the first priority would be to gradually try to transition to async/await in the driver.
I can't find any way to do this. The sync paths and async-by-replay mechnism in place are incompatible with trying to use language async. An example of this is what should be a simple method, BeginTransactionAsync. it's currently implemented using sync over async and because of that there are no safe suspension points, everything is written for safety through thread locks and then there are different sets of locks for cancellation, and then more for other things. Even a simple method ends up in a position where you're trying to carefully unknot the locking and verify that it's still safe. Even with the most careful review we can't tell if something is going to be safe or not.
EF Core duplicates code for sync/async - but if you're interested I'd be happy to point you to some examples inside Npgsql.
I really want to avoid duplication if at all possible. There's so much tangled logic that having two of things will make things even worse than they really are. What I'd like to try and do is move the current sync paths to an async friendly mode but I can't see how to do that. In particular the parsing should be done in one place for each token if at all possible.
Examples of single path sync/async from npgsql would be handy for study. I did have a look through the codebase but despite being way less complex than sql client I wasn't quite sure where I was going and couldn't find anything relevant. I also envy your ability to adopt new language features.
It sounds like a difficult situation. I'd love to be able to help out more, but I simply don't know enough about the internals. At the end of the day, things really shouldn't be that complicated, or involve so many set of locks - it's just a single physical connection, which needs to protect against accidental concurrent usage. I personally believe it should be a goal to modernize the driver, otherwise this will continue to hold the driver back and hamper the ability to evolve it.
it's currently implemented using sync over async
Then I'm interested in how the driver avoids the deadlocks and thread pool starvation issues which are usually associated with sync-over-async. The moment a thread synchronously blocks on an async operation (sync-over-async), that operation can very easily provoke a pseudo-deadlock as all TP threads are synchronously stuck waiting on responses, and so no TP threads are available to service the continuations for those responses. I thought
I really want to avoid duplication if at all possible.
You're definitely right about that. I'd just point out that you already have duplication in the sense that you have two paths... And the way to arrive at a single path probably has to pass through a rewriting of the current complicated async logic into a simpler async/await-based logic which would very likely resemble your current sync path.
Examples of single path sync/async from npgsql would be handy for study. I did have a look through the codebase but despite being way less complex than sql client I wasn't quite sure where I was going and couldn't find anything relevant.
If you're really interested, start at ExecuteDbDataReaderAsync and work your way down (ignoring anything related to multiplexing). I'd be happy to provide answers and points. It's all just (async) methods calling each other all the way down.
I also envy your ability to adopt new language features.
I'd really confirm that it isn't possible to take a dependency on e.g. System.ValueTuple and other similar packages which enable newer language features. After all, the latest Microsoft.Data.SqlClient takes a dependency on nugets such as Microsoft.Identity.Client and Microsoft.IdentityModel.JsonWebTokens - in the .NET Framework TFM - so I don't see why you should be limited from that either. I don't see a reason why that shouldn't be possible, but I may be missing something.
Then I'm interested in how the driver avoids the deadlocks and thread pool starvation issues which are usually associated with sync-over-async.
It doesn't. Or luck if you prefer. As we've seen with least least two bugs recently threadpool starvation is a problem with no clear solution in this library.
I'd just point out that you already have duplication in the sense that you have two paths
Not really. The async paths buffer input packets and retry the desired operation repeatedly with each new input to see if they can succeed, the retrying essentially uses the sync path with a few bits of Task and TCS throw in for confusion. The actual async is done by passing back a task from tcs to the caller and then letting them know when it finally succeeded synchronously on another thread. It's not the kind of resumable state machine you see with langauge async. This means that the core remains sync only there's just lots of stuff piled on top of it to fake async. As you've seen with strings this has clear performance issues.
For example you can look at the central parse logic in TdsParser.TryRun and you'll see that it isn't aware of async at all. That could be fine but it isn't because every single method that it calls to try and read (TryReadByte etc) input can cause an IO wait in sync mode or an outright failure (notice that the TryRun returns bool) in async mode. It can't logically suspend it just had to be re-run repeatedly over the same input until it succeeds in having enough input to reach an unknown destination.
I'll have a browse through the ExecuteDbDataReaderAsync and see if I can gain any inspiration. I've been searching for a way to approach this for a while. The problem is that the current code is so far from where I need it to be and I have to move so slowly. It's an insurmountable task incrementally.
OK, thanks for these details. I'll try to take a quick look in the coming days - out of curiosity - though I probably won't have enough time to really understand what's going on.
Just as a thought experiment... Wouldn't it be possible to start implementing a true async path based on the existing path - possibly simply by duplicating it (or via a unified path, à la npgsql)? Though I totally get how insurmountable and unapproachable this is.
In theory yes but I've no idea where to start. Any additional logic can't be truly standalone because it has to interact correctly with the existing locks to ensure they don't encounter situations they aren't designed to handle. BeginTransactionAsync is one of the places I had hoped would be amenable to writing in langauge async because it's conceptually simple but it turned out to be far more complicated than you think because it forces the entire parser into sync io mode, not even sync over async it explicitly disables that, pure sync waits.
N/A (feature request, not a bug — no environment fields required)
Area
Area\Async
Duplicates
None found
Regression
Not indicated
Analysis
This is a long-standing feature request (opened 2021) proposing a new SqlDbType.StructuredAsync to allow populating table-valued parameters (TVPs) from IAsyncEnumerable<T> or an async IDataReader, instead of forcing synchronous Read() calls during RPC parameter construction. The linked discussion (Wraith2, roji, cheenamalhotra) concluded that the core blocker is architectural: the driver's TDS parser and RPC packet writer are fundamentally synchronous with async layered on top via sync-over-async/replay mechanisms, so true streaming async TVP population would require deeper internal rework (unifying sync/async code paths, as in Npgsql) rather than a small, isolated change. No implementation has landed since. Severity: P3 (feature enhancement, not a defect; complexity is high and no active demand signal beyond the original discussion).
Next Steps
This remains an open design/architecture question rather than a ready-to-implement feature — recommend the team decide whether to prioritize investigating a unified sync/async TDS parser path (a prerequisite for this and similar async improvements) before assigning implementation work.
If pursued, recommend a design proposal covering: schema discovery for the first IAsyncEnumerable row, packet-write suspension semantics with an open transaction, and buffering strategy trade-offs, before assigning to Copilot coding agent or a contributor for implementation.
Given the multi-year inactivity and the acknowledged architectural blocker, consider re-confirming current community/maintainer interest before further investment.
Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.
Activity
Wraith2 commentedon Mar 12, 2021
The problem with that is that you'd be holding the write operation on an await for the parameters which is complicated. Why would you need to send async enumerable params to a tvp? what is the discovery mechanism for the values?
mburbea commentedon Mar 12, 2021
Presumably, the usual reasons to use a tvp but your source doesn't have all the data immediately. You are sending a datareader from another database, or you are translating some message bus/web call into a sql data record.
The tvp would query the schema table like it does currently. For the IAsyncEnumerable, the library would read the first row for the sqlmetadata[].
The first thing a tvp does is basically insert the rows into the table type variables, and rather than streaming the records synchronously, this operation could be done async.
Wraith2 commentedon Mar 12, 2021
The way that the TVP enumerable works is to send the values as part of the request so if you don't have all the values synchrnously you will end up in a situation where the driver is trying to construct a packet containing RPC data to send to the server but it now has to do an async await meaning that the state of the connection can stay in the middle of a constructed packet for an indefinate amount of time which could be problematic. Now imagine you're doing that with a transaction open.
The obvious way to get around that would be to buffer the input but since there is no defined maximum (is there?) number of entries that'd be tricky as well. In this case you'd be better off getting the caller to buffer values until there are "enough" or source enumeration is complete and then execute the query, which leaves you in the situation you're in now.
Sounds tricky. Probably possible but given the code of the driver which isn't async friendly it's not a quick one.
cheenamalhotra commentedon Mar 12, 2021
@mburbea @Wraith2
Great discussion, I agree going Async way is not going to be an easy change in the driver.
We'll investigate it's possibility and come back on this one.
roji commentedon Mar 13, 2021
Isn't the same thing happening today, just with synchronous I/O? Presumably people are already using TVPs to read from other databases, so slow network I/O is already been done - the question is only if it should be doable asynchronously (i.e. without blocking the thread).
Buffering the data (as opposed to streaming it) would increase client memory requirements, potentially in a dramatic way.
Wraith2 commentedon Mar 13, 2021
Yes, you could get into the same situation at the moment. To me an async enumerable is just more likely to be awaited since that's the intent of the interface where plain old enumerable is old synchronous world tech and is usually assumed to be always ready, at least to me. In either case if your enumeration is blocking you leave the pulling connection in a peculiar state while it waits for input.
roji commentedon Mar 15, 2021
If I understand this correctly, the point here is to stream large amounts of data into the database that's possibly coming from another database. As usual I'm not familiar with the SqlClient internals here, but having the database driver block/await on I/O while writing parameter data to the database doesn't seem any more problematic than streaming large data when fetching via DbDataReader.GetStream/GetTextReader. And as in all scenarios potentially transferring data over the network, allowing async operations as an alternative to sync is valuable.
But again, that's just an external, general point of view.
Wraith2 commentedon Mar 15, 2021
Do you have an good examples or tutorial materials on how to write dual purpose methods for sync/async purposes? The primary problem I have is that the core of the driver is synchronous and the async support is layered over it. The current async logic paths all use imperative async which is costly wasteful and hard to reason about.
roji commentedon Mar 15, 2021
@Wraith2 you're right, I think that's one of the main architectural issues you guys have, and probably the source of some bugs as well - callback-based (imperative) async is notoriously difficult to do (as you mentioned)...
It's a difficult question. I'd say the first priority would be to gradually try to transition to async/await in the driver. At least in theory, this doesn't need to be done in one go - clusters of callback-based methods returning Tasks can be gradually rewritten to use async instead (i.e. at least the method signatures don't need to change). But I don't take this lightly - it's quite a project.
If you manage to make progress here, you should end up with an async code path that closely resembles your sync code path. At this point, you may want to consider merging certain sync/async paths - though by all means not everyone does this. In Npgsql, NpgsqlCommand.ExecuteReader and ExecuteReaderAsync call into a single ExecuteReader method, which accepts a boolean
asyncflag and itself has theasynckeyword. We go down the stack via similar methods, passing down theasyncflag, until we get to the very bottom, where I/O needs to be performed; at this point, we check the flag, and call either the sync or async method on NetworkStream (or whatever).The end effect, is that when sync ExecuteReader is called, the code passes through async methods, but everything always completes synchronously. This implies a tiny bit of overhead for the sync path (compared to two completely separate paths), but allows you to have just one code path, which is much more maintainable. Again, not everyone does this - EF Core duplicates code for sync/async - but if you're interested I'd be happy to point you to some examples inside Npgsql.
However, this second phase of "unifying" your sync and async paths really is optional and far off in any case. I'd try to come up with a plan for modernizing and transitioning to async/await first - assuming the SqlClient team thinks that's a good direction etc.
Wraith2 commentedon Mar 15, 2021
I can't find any way to do this. The sync paths and async-by-replay mechnism in place are incompatible with trying to use language async. An example of this is what should be a simple method, BeginTransactionAsync. it's currently implemented using sync over async and because of that there are no safe suspension points, everything is written for safety through thread locks and then there are different sets of locks for cancellation, and then more for other things. Even a simple method ends up in a position where you're trying to carefully unknot the locking and verify that it's still safe. Even with the most careful review we can't tell if something is going to be safe or not.
I really want to avoid duplication if at all possible. There's so much tangled logic that having two of things will make things even worse than they really are. What I'd like to try and do is move the current sync paths to an async friendly mode but I can't see how to do that. In particular the parsing should be done in one place for each token if at all possible.
Examples of single path sync/async from npgsql would be handy for study. I did have a look through the codebase but despite being way less complex than sql client I wasn't quite sure where I was going and couldn't find anything relevant. I also envy your ability to adopt new language features.
roji commentedon Mar 15, 2021
It sounds like a difficult situation. I'd love to be able to help out more, but I simply don't know enough about the internals. At the end of the day, things really shouldn't be that complicated, or involve so many set of locks - it's just a single physical connection, which needs to protect against accidental concurrent usage. I personally believe it should be a goal to modernize the driver, otherwise this will continue to hold the driver back and hamper the ability to evolve it.
Then I'm interested in how the driver avoids the deadlocks and thread pool starvation issues which are usually associated with sync-over-async. The moment a thread synchronously blocks on an async operation (sync-over-async), that operation can very easily provoke a pseudo-deadlock as all TP threads are synchronously stuck waiting on responses, and so no TP threads are available to service the continuations for those responses. I thought
You're definitely right about that. I'd just point out that you already have duplication in the sense that you have two paths... And the way to arrive at a single path probably has to pass through a rewriting of the current complicated async logic into a simpler async/await-based logic which would very likely resemble your current sync path.
If you're really interested, start at ExecuteDbDataReaderAsync and work your way down (ignoring anything related to multiplexing). I'd be happy to provide answers and points. It's all just (async) methods calling each other all the way down.
I'd really confirm that it isn't possible to take a dependency on e.g. System.ValueTuple and other similar packages which enable newer language features. After all, the latest Microsoft.Data.SqlClient takes a dependency on nugets such as Microsoft.Identity.Client and Microsoft.IdentityModel.JsonWebTokens - in the .NET Framework TFM - so I don't see why you should be limited from that either. I don't see a reason why that shouldn't be possible, but I may be missing something.
Wraith2 commentedon Mar 15, 2021
It doesn't. Or luck if you prefer. As we've seen with least least two bugs recently threadpool starvation is a problem with no clear solution in this library.
Not really. The async paths buffer input packets and retry the desired operation repeatedly with each new input to see if they can succeed, the retrying essentially uses the sync path with a few bits of Task and TCS throw in for confusion. The actual async is done by passing back a task from tcs to the caller and then letting them know when it finally succeeded synchronously on another thread. It's not the kind of resumable state machine you see with langauge async. This means that the core remains sync only there's just lots of stuff piled on top of it to fake async. As you've seen with strings this has clear performance issues.
For example you can look at the central parse logic in TdsParser.TryRun and you'll see that it isn't aware of async at all. That could be fine but it isn't because every single method that it calls to try and read (TryReadByte etc) input can cause an IO wait in sync mode or an outright failure (notice that the TryRun returns bool) in async mode. It can't logically suspend it just had to be re-run repeatedly over the same input until it succeeds in having enough input to reach an unknown destination.
I'll have a browse through the ExecuteDbDataReaderAsync and see if I can gain any inspiration. I've been searching for a way to approach this for a while. The problem is that the current code is so far from where I need it to be and I have to move so slowly. It's an insurmountable task incrementally.
roji commentedon Mar 15, 2021
OK, thanks for these details. I'll try to take a quick look in the coming days - out of curiosity - though I probably won't have enough time to really understand what's going on.
Just as a thought experiment... Wouldn't it be possible to start implementing a true async path based on the existing path - possibly simply by duplicating it (or via a unified path, à la npgsql)? Though I totally get how insurmountable and unapproachable this is.
Wraith2 commentedon Mar 15, 2021
In theory yes but I've no idea where to start. Any additional logic can't be truly standalone because it has to interact correctly with the existing locks to ensure they don't encounter situations they aren't designed to handle. BeginTransactionAsync is one of the places I had hoped would be amenable to writing in langauge async because it's conceptually simple but it turned out to be far more complicated than you think because it forces the entire parser into sync io mode, not even sync over async it explicitly disables that, pure sync waits.
roji commentedon Mar 15, 2021
That's... very unfortunate.
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Area\AsyncAnalysis
This is a long-standing feature request (opened 2021) proposing a new
SqlDbType.StructuredAsyncto allow populating table-valued parameters (TVPs) fromIAsyncEnumerable<T>or an asyncIDataReader, instead of forcing synchronousRead()calls during RPC parameter construction. The linked discussion (Wraith2, roji, cheenamalhotra) concluded that the core blocker is architectural: the driver's TDS parser and RPC packet writer are fundamentally synchronous with async layered on top via sync-over-async/replay mechanisms, so true streaming async TVP population would require deeper internal rework (unifying sync/async code paths, as in Npgsql) rather than a small, isolated change. No implementation has landed since. Severity: P3 (feature enhancement, not a defect; complexity is high and no active demand signal beyond the original discussion).Next Steps
IAsyncEnumerablerow, packet-write suspension semantics with an open transaction, and buffering strategy trade-offs, before assigning to Copilot coding agent or a contributor for implementation.