Skip to content
This repository was archived by the owner on Jul 7, 2024. It is now read-only.
This repository was archived by the owner on Jul 7, 2024. It is now read-only.

SqlServer.Core: Performance-oriented SQL Server .NET driver #6

Closed as not planned

Description

@roji

An experiment in collaboration with the community to determine what potential there is modern .NET features in a highly performant SQL Server driver.

Activity

  1. changed the title [-]Experiment [/-] [+]SqlServer.Core[/+] on Feb 10, 2021
  2. changed the title [-]SqlServer.Core[/-] [+]SqlClient.Core[/+] on Feb 12, 2021
  3. transferred this issue fromdotnet/efcoreon Feb 12, 2021
  4. added
    User Story
    on Feb 12, 2021
  5. changed the title [-]SqlClient.Core[/-] [+]SqlServer.Core[/+] on Apr 22, 2021
  6. ajcvickers commented on Apr 23, 2021

    @ajcvickers
    Contributor

    @ErikEJ @Wraith2 @NickCraver @mgravell @Drawaes: Let's get this party started!

    @smitpatel, @roji, and I discussed how to get started with Woodstar, and we have created some initial issues for the ideas we came up with. We want this to be collaborative, so please add your ideas, either by commenting on issues or in new issues as appropriate.

    Initial ideas:

    /cc @davidfowl

  7. NickCraver commented on May 2, 2021

    @NickCraver
    Member

    Would it be useful to list current pain points, especially w.r.t. performance in the current driver structure? Discussing connection pooling and what we are/aren't able to see or get metrics on today due to what's exposed and what's internal is something that doesn't hurt so much per connection but is a pain at scale in various ways. Today, we're wrapping connections to make best-guess workarounds for how pooling is behaving, which commands are in flight when a stall happens, etc.

    I know out goal is performance, but I think it's worth considering the driver/implementation surface area along these lines as we go, and maybe current pain points is the good thing to have as a starting point on that front?

  8. Wraith2 commented on May 2, 2021

    @Wraith2
    • Async strings and blobs. The current internal structure makes their performance non-linear. It is a long project to fix it but it's complicated and there is no mitigation other than using SequentialAccess mode and constructing the string yourself.
    • Task based internal architecture uses almost entirely imperative task classes rather than langauge supported and this generates a lot of garbage in Tasks, TaskCompletionSources, ContinueWith closures etc. This could all be langauge and valuetask based and perform faster and cleaner
    • The codebases mixes sync and async paths liberally and confusingly. Along with lots of locking this makes making logical deductions about safety hard. Atomic state changes would be a lot easier to work with
    • The code is complex and hard to follow with very little explanation for internal choices. e.g., why when connecting to a named address does it choose the last ip4 address returned from the dns to try first? If we change it do we break someone?
    • Parameters being non-generic forces the use of boxing object containers and leads to reflection based runtime type discovery and conversion.
    • Connection pool keys being canonicalized and stored as strings incurs overhead because every connection because the string has to be generated each time. A dedicated immutable type would be better.
    • The SNI (Sql Network Interface) layer) and Tds Layer are disconnected loops and every packet received is copied at least twice, at least half of the byte arrays used are dropped to GC because the lifetime isn't tracked so they aren't known to be safe to re-use.

    Plus a whole load of other random bits and pieces that when/if we encounter the same problem in a new implementation I will hopefully spot and warn about so we can avoid the same implementation choice. In general it's about what you expect from a 20 year old codebase at this point. Decisions which were correct at the time are now outdated but the weight of the codebase is so high that changing direction carries unacceptably high risk. Writing from a high level async-first perspective will get us an easier codebase to work with.

  9. NickCraver commented on May 2, 2021

    @NickCraver
    Member

    Should async-only be a design goal here, like HttpClient in .NET Core before...the happening?

  10. Wraith2 commented on May 2, 2021

    @Wraith2

    I'd prefer to support as much of the existing external surface area as possible because it will enable widest adoption if we get to production stages. I'd say async first but not async only if that's possible, I think it is possible because postgres manages it afaik.

  11. davidfowl commented on May 2, 2021

    @davidfowl
    Member

    I'd hope we'd build the core engine with a different API shape than what ADO.NET wants. We can write a slow adapter for that layer but the new APIs shouldn't be bound by it. Also take a look at this issue dotnet/runtime#28882 as a way to avoid boxing for DbParameters.

  12. Wraith2 commented on May 2, 2021

    @Wraith2

    The problem with using another shape is knowing what it is, there can be no consumers until we write one so we don't know what shape is required without a specific and well defined set of consumer requirements, who's the first consumer?

  13. Drawaes commented on May 2, 2021

    @Drawaes

    Well you have SO people commenting right here. The point I thought is to push the boundaries of performance and not support the widest number of use cases. As David has said slower compatibility could be built on top. In reality though in the case of sync you are just hiding what is really going on as all db operations are async in nature if there is network or any disk access involved.

  14. Wraith2 commented on May 2, 2021

    @Wraith2

    Ok, pure perf it is and then we'll see. That'll allow ignoring all the existing public surface area defined in terms of Task and using ValueTask throughout which will be lovely.

    You say that all db operations are async. All IO operations are async and if you meant that then I agree. However because TDS is packetized there can be multiple columns and even rows in a single packet so a single data fetch may not be async it could just be fetched from memory. At the moment in SqlClient you either have to allocate a task every time or you have to use sync and live with the thread blocking sometimes. ValueTask<T> GetFieldValueAsync(int index) will make that problem go away.

    We may also want to think about being clever with pre-dispatching packet requests. Currently you run through the packet until you run out of data and then request more and wait for the response. If you can guess based on reading, a string for example, that you won't have enough data you could pre dispatch the next packet request and then it might be ready when you need it. A fundamental limitation of any library like this is network latency and we might be able to hide some of that.

  15. 70 remaining items

  16. roji commented on Oct 6, 2021

    @roji
    MemberAuthor

    OK, thanks for the details @Wraith2. I plan to work on a proposal to basically allow users to directly reference a "DbDataSource" (naming temporary!), which typically would represent a pool; this would allow applications to resolve the pool from the connection string exactly once at startup, and then request connections from that. However, if you really want to check the system username on every open (because of impersonation), this may not help so much.

  17. KalleOlaviNiemitalo commented on Oct 6, 2021

    @KalleOlaviNiemitalo

    Can you first check whether the thread is impersonating, and if it is not, then use the previously allocated strings (or no strings at all)? Something with GetCurrentThreadToken and GetTokenInformation, perhaps. Whether that would help depends on how common impersonation is, I guess. And this would still involve "direct pinvokes into windows security related apis".

  18. Wraith2 commented on Oct 6, 2021

    @Wraith2

    Impersonation and Mars are things that could be left out of the Core implementation quite easily. They'll still have to be supported in SqlClient but if you're looking for a fast minimal sql implementation I don't think you want them.

  19. IanRingrose commented on Dec 31, 2022

    @IanRingrose
    public IAsyncEnumerable<Fortune> GetFortunes()
    {
    	await using (var connection = GetSqlCoreConnection())
    	{
    		using (var command = GetSqlCoreCommand(connection, command properties ?))
    		{
    			using (var reader = await command.GetReader(reader properties))
    			{
    				while (await reader.GetNextRow())
    				{
    					yield return new Fortune { Id = await reader.GetValue<int>(0), Message = await reader.GetValue<string>(1) };
    				}
    			}
    		}
    	}
    }

    We know that a single row is nearly always small enough to hold in memory and that the user often knows their rows are small. I would normally rather not have await reader.GetNextRow() complete until all fields are in memory ready to read. This can then totally advoid the overhead of having GetValue() returning a task that then needs checking to see of it is completed. (Think of what these unnecessary conditions checks do to the CPU instruction pipeline)

  20. Wraith2 commented on Dec 31, 2022

    @Wraith2

    We know that a single row is nearly always small enough to hold in memory

    How do we know this? I know that mine often are but working with the sqlclient driver has shown me bug replications where people do things I would never consider.

    the user often knows their rows are small.

    Yes. However through maintenance this has a habit of changing. If a small row is 3 items and the driver optimizes for that what happens when 2 years later someone adds 3 more fields. Do we see a slowdown? Is that consequence going to be obvious from the code?

    This can then totally avoid the overhead of having GetValue() returning a task that then needs checking to see of it is completed

    I'm almost certain we would use ValueTask as the return type. If for some reaon we could not then a custom poolable awaitable would likely be used. Any non-null valued data type including a single byte in the tds stream can span multiple packets (because there is always a header so all records are multibyte). That means that every read can cause a network delay to be observable, the faster you can consume the data the more likely you are to hit an io wait. This needs to be a task like return type.

  21. roji commented on Jan 1, 2023

    @roji
    MemberAuthor

    I agree that the majority use case is small rows which can be easily buffered in memory, and that this scenario should be optimized for (of course while keeping good support for large rows). This is also the reasoning for ADO.NET's CommandBehavior.SequentialAccess, which is an opt-in behavior for large rows.

    I would normally rather not have await reader.GetNextRow() complete until all fields are in memory ready to read. This can then totally advoid the overhead of having GetValue() returning a task that then needs checking to see of it is completed.

    I'm a bit confused... If GetNextRow (ADO.NET's DbDataReader.Read) doesn't wait to buffer all columns, then the subsequent GetValue calls (ADO.NET's DbDataReader.GetFieldValue) do potentially have to do I/O (since the row hasn't been completely read and buffered yet). So either you (possibly) wait longer up-front in GetNextRow - and then yuo're guaranteed that subsequent GetValue calls just accessed buffered results - or GetNextRow returns early without buffering, and then subsequent GetValue calls may need to wait.

    Stepping back... I think the low-level approach here would be to not do (implicit) row buffering. Crucially, this means it's the user's responsibility to read column values in the order in which they get delivered from the database; you can't read value 3 and then read value 1 (since we're just streaming columns). You also can't read the same value twice. This corresponds pretty much exactly to how CommandBehavior.SequentialAccess works today in ADO.NET.

    Row buffering can be considered a "convenience" feature layered on top of this, allowing users to seek back in the row and read the same value multiple times. I agree it's still not necessary to pre-buffer the entire row in GetNextRow: I/O can simply be performed later - as needed - from GetValue, which would return ValueTask (so calls to values which happen to be already buffered are very cheap).

    the user often knows their rows are small.

    Yes. However through maintenance this has a habit of changing. If a small row is 3 items and the driver optimizes for that what happens when 2 years later someone adds 3 more fields. Do we see a slowdown? Is that consequence going to be obvious from the code?

    I do think that programmers can be expected to know the general shape of their data (does a certain table contain huge rows or not), and that it's reasonable to expect stability here. If you don't want to make any assumptions (e.g. a dynamic data scenario), you can always use "sequential access" and stream columns - I don't think there's any downside to doing so, aside from a more difficult API to work with. Otherwise, if you use an API which does buffering (the ADO.NET default), and you encounter a huge row, your memory requirements will increase accordingly.

  22. IanRingrose commented on Jan 4, 2023

    @IanRingrose

    We know that a single row is nearly always small enough to hold in memory

    How do we know this? I know that mine often are but working with the sqlclient driver has shown me bug replications where people do things I would never consider.

    the user often knows their rows are small.

    Yes. However through maintenance this has a habit of changing. If a small row is 3 items and the driver optimizes for that what happens when 2 years later someone adds 3 more fields. Do we see a slowdown? Is that consequence going to be obvious from the code?

    I am thinking of a mode of operation when the user states upfront the rows are small and an exception is throw if the rows are large.

    "Small row" being defined as under the size of a network packet so it is known that a row will never need more then two networks pockets being buffered in a "zero copy" implementation.

    =======
    Another option would be for ReadRowAndAllValue() generic method that returns a triplet of all the values. I don't know if this is practical to implement.

  23. IanRingrose commented on Jan 4, 2023

    @IanRingrose

    Should an optional callback based interface be provided so the user implementation OnNextRow() and OnNextStringValue(id, span) etc?

    This would make it cheaper to read into an array(s) of structs for code that needs fast bulk loading. At present it can be faster to get SQLServer to write to a file and then read the file from .net, this should never be the case with a database access API.

  24. roji commented on Jan 4, 2023

    @roji
    MemberAuthor

    I am thinking of a mode of operation when the user states upfront the rows are small and an exception is throw if the rows are large.

    "Small row" being defined as under the size of a network packet so it is known that a row will never need more then two networks pockets being buffered in a "zero copy" implementation.

    I think it's a good idea to stop and think exactly what kind of special optimizations we're thinking about for small rows vs. large rows. I think that the existing ADO.NET model isn't too bad here: an opt-in mode (SequentialAccess) for streaming the row and a default mode for, basically, buffering it. I don't know what "zero copy" means in this context: the driver needs to read raw bytes in any case, and decode them to a user-readable value (int, string); there shouldn't be any extra copying beyond that going on regardless of whether the row is small or not. The only impact that should have is whether we keep earlier columns in memory so the user can access them after later ones.

    Another option would be for ReadRowAndAllValue() generic method that returns a triplet of all the values. I don't know if this is practical to implement.

    That sounds like a very allocate-y API to get the row.

    Should an optional callback based interface be provided so the user implementation OnNextRow() and OnNextStringValue(id, span) etc?
    This would make it cheaper to read into an array(s) of structs for code that needs fast bulk loading. [...]

    Not sure exactly why this is inherently faster than an API where application code calls ReadRow (it's basically just push vs. pull).

  25. IanRingrose commented on Jan 4, 2023

    @IanRingrose

    Should an optional callback based interface be provided so the user implementation OnNextRow() and OnNextStringValue(id, span) etc?
    This would make it cheaper to read into an array(s) of structs for code that needs fast bulk loading. [...]

    Not sure exactly why this is inherently faster than an API where application code calls ReadRow (it's basically just push vs. pull).

    It advoids C# having to feed as many returned tasks into the generated state machine.

  26. Wraith2 commented on Jan 4, 2023

    @Wraith2

    "Small row" being defined as under the size of a network packet so it is known that a row will never need more then two networks packets being buffered in a "zero copy" implementation.

    The number of row values in a single packet depends on the data values, not even the types. The ability to identify if you had a specific set of data which did not span a packet is prohibitively difficult to calculate. You can also change the packet size in the connection string.

    I agree with @roji that the current high level way of accessing the data is reasonable and covers most scenarios that we need. All other methods considered have clear downsides like requiring sequential access at all times of large upfront investment of developer time to ensure they avoid packet boundaries which should be handled by the driver transparently.

  27. roji commented on Jan 4, 2023

    @roji
    MemberAuthor

    "Small row" being defined as under the size of a network packet so it is known that a row will never need more then two networks packets being buffered in a "zero copy" implementation.

    The number of row values in a single packet depends on the data values, not even the types. The ability to identify if you had a specific set of data which did not span a packet is prohibitively difficult to calculate. You can also change the packet size in the connection string.

    @Wraith2 at least from my perspective, the idea here wouldn't be to automatically calculate anything, but rather for the developer to use one API or another based on whether they want to stream the row or not, based on their knowledge of their data domain. In other words, pretty much what CommandBehavior.SequentialAccess already means in ADO.NET.

    I definitely do think we need to provide a row sequential/streaming mode, which avoids having to buffer entire rows in memory; otherwise huge rows must require huge amounts of memory, which isn't feasible. This is already supposed to be done in all major ADO.NET drivers (via CommandBehavior.SequentialAccess).

    Should an optional callback based interface be provided so the user implementation OnNextRow() and OnNextStringValue(id, span) etc?
    This would make it cheaper to read into an array(s) of structs for code that needs fast bulk loading. [...]

    Not sure exactly why this is inherently faster than an API where application code calls ReadRow (it's basically just push vs. pull).

    It advoids C# having to feed as many returned tasks into the generated state machine.

    I'm not sure we should shape the entire row-reading API around saving on the async state machine box for when ReadRow needs to complete asynchronously (note that at least in reasonable scenarios, many/most invocations of ReadRow return synchronously since (small) rows are already buffered in memory).

  28. roji commented on Jul 1, 2024

    @roji
    MemberAuthor

    See #22 for a summary of the Woodstar experiment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

User Storyproject-woodstar

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions