Skip to content

Regression since 6.1.4 / 5.1.9: "Nullable object must have a value" from SqlStatistics.ReleaseAndUpdateExecutionTimer with concurrent commands on a MARS connection #4778

Done
3 of 3 issues completed

Description

@PspInsFws

Describe the bug

Since the statistics execution timer was changed from long to long? (#3609, backported as #3830 in 6.1.4 and as #3831 in 5.1.9), several commands that run at the same time on one MARS connection can fail with:

System.InvalidOperationException: Nullable object must have a value.
   at System.Nullable`1.get_Value()
   at Microsoft.Data.SqlClient.SqlStatistics.ReleaseAndUpdateExecutionTimer()
   at Microsoft.Data.SqlClient.SqlStatistics.StopTimer(SqlStatistics statistics)
   at Microsoft.Data.SqlClient.SqlDataReader.GetValue(Int32 i)
   at SqlRace.ReadAllAsync(SqlConnection conn, Int32 rows, Int32 payload)

The exception is thrown from the finally block that stops the statistics timer (SqlStatistics.StopTimer), so it fails the caller's GetValue() / Read() although the query itself worked. In all my runs the commands that did not throw returned exactly the rows a sequential read returns, so the exception is the only symptom.

The timer is active when SqlConnection.StatisticsEnabled is true or when a DiagnosticListener has SqlClientCommandAfter enabled (SqlCommand.Statistics). The second case means no application code has to touch statistics: in a separate test, OpenTelemetry.Instrumentation.SqlClient 1.19.0 (OpenTelemetry 1.19.1, no StatisticsEnabled) triggers the same failure with 7.0.2 and none with 6.1.3 or 5.2.3.

That is how I found it: after OpenTelemetry (.NET automatic instrumentation) was switched on for an ASP.NET Core service (.NET 10, Linux container) that runs several queries in parallel with Task.WhenAll over one MARS connection, it started failing intermittently, surfacing in Dapper as Error parsing column N (...).

I am aware that the documentation says MARS operations are not thread-safe and that true parallelism needs separate connections. I am reporting it anyway because:

  • this pattern did not throw with statistics on up to 6.1.3 and in 5.2.3, so it is a behavior regression;
  • the failure comes from diagnostics bookkeeping, not from the command that was executing;
  • the old code had the same unsynchronized check-then-act, but losing the race could only make ExecutionTime inaccurate, it could not throw.

Where it comes from (as far as I can tell from reading the code)

There is one SqlStatistics per SqlConnection (SqlConnection._statistics) and SqlCommand.Statistics hands it to every command and reader on that connection, so with MARS several readers share it. Each reader call is wrapped in StartTimer / StopTimer (SqlDataReader.GetValue); a caller whose StartTimer returns null (timer already running) makes its StopTimer a no-op, so only the "owner" runs the code below.

SqlStatistics.cs at v7.1.1 (identical on main) compared with v6.1.3:

// SqlStatistics.cs, 6.1.4 - 7.1.1 and main
// (6.1.3 and 5.2.3: `long _startExecutionTimestamp` with `== 0` / `> 0` checks, same structure)
internal bool RequestExecutionTimer()
{
    if (!_startExecutionTimestamp.HasValue)                  // check ...
    {
        _startExecutionTimestamp = ADP.FastTimerCurrent();   // ... then set: not atomic, so two callers can both become the "owner"
        return true;
    }
    return false;
}

internal void ReleaseAndUpdateExecutionTimer()
{
    if (_startExecutionTimestamp.HasValue)                   // owner A passes this check
    {
        uint elapsed = ADP.CalculateTickCountElapsed(
            _startExecutionTimestamp.Value,                  // owner B set the field to null in between -> InvalidOperationException
            ADP.FastTimerCurrent());
        _executionTime += elapsed;
        _startExecutionTimestamp = null;
    }
}

To reproduce

One project, no schema needed (it only reads sys.all_columns). Repro.csproj and Program.cs are at the end of this issue.

  • dotnet run -p:SqlClientVersion=7.1.1 -- timer needs no SQL Server: it calls SqlStatistics.StartTimer / StopTimer (what GetValue() / Read() do) on one shared instance from several threads, through reflection.
  • dotnet run -p:SqlClientVersion=7.1.1 -- sql "<connection string>" is the end-to-end version: 6 readers in flight at once on one MARS connection with StatisticsEnabled = true. Add --mode listener to leave statistics off and only subscribe a DiagnosticListener to SqlClientDiagnosticListener (what OpenTelemetry's instrumentation does), or --mode none for the control without either.

Results (laptop, Windows 11, .NET 8, Azure SQL Database; the failure rate in the end-to-end run depends on timing, so it will differ on other setups, and --rows / --payload change how much the readers overlap):

Microsoft.Data.SqlClient -- timer (no server): exceptions in 3 s -- sql (6 concurrent readers, StatisticsEnabled = true): iterations with an exception
5.1.9 1,270,910 51 / 100
5.2.3 0 0 / 100
6.0.5 0 0 / 100
6.1.0 0 0 / 100
6.1.1 0 0 / 100
6.1.2 0 0 / 100
6.1.3 0 0 / 100
6.1.4 1,579,578 50 / 100
6.1.5 1,549,324 50 / 100
6.1.6 1,486,024 60 / 100
6.1.7 1,465,277 56 / 100
7.0.0 1,427,512 73 / 100
7.0.1 1,244,571 72 / 100
7.0.2 1,230,059 74 / 100
7.0.3 1,345,339 60 / 100
7.1.0 1,240,272 69 / 100
7.1.1 1,378,117 66 / 100
Microsoft.Data.SqlClient --mode listener (statistics off, only a DiagnosticListener) --mode none (control) --commands 1 (no concurrency, statistics on)
6.1.3 0 / 100 0 / 100 0 / 100
6.1.4 70 / 100 0 / 100 0 / 100
7.1.1 42 / 100 0 / 100 0 / 100

Pre-releases (same programs). 7.0.0-preview1 was published the day before #3609 was merged to main and is fine; 7.0.0-preview2, the next pre-release, is the first one that fails, which matches the PR:

Pre-release -- timer (no server): exceptions in 3 s -- sql (6 concurrent readers, StatisticsEnabled = true): iterations with an exception
7.0.0-preview1.25257.1 0 0 / 100
7.0.0-preview2.25289.6 1,359,304 61 / 100
7.0.0-preview3.25342.7 1,270,838 not run
7.0.0-preview4.26063.3 1,419,929 not run
7.0.0-preview4.26064.3 1,498,987 not run
7.1.0-preview1.26124.5 1,422,663 not run
7.1.0-preview2.26190.3 1,220,887 not run
7.1.0-preview2.26190.5 990,307 not run
7.1.0-preview3.26238.4 961,482 73 / 100

Expected behavior

Collecting statistics, or having a diagnostic listener attached, should not make SqlDataReader calls throw. Concurrent use may make the timing numbers imprecise, as it could in 6.1.3 and 5.2.3, but it should not fail the command.

Suggested change

The smallest change that removes the exception is to read the field once in ReleaseAndUpdateExecutionTimer:

internal void ReleaseAndUpdateExecutionTimer()
{
    long? start = _startExecutionTimestamp;   // single read: HasValue and Value can no longer disagree
    if (start.HasValue)
    {
        _executionTime += ADP.CalculateTickCountElapsed(start.Value, ADP.FastTimerCurrent());
        _startExecutionTimestamp = null;
    }
}

If the timer should also have exactly one owner at a time, RequestExecutionTimer / ReleaseAndUpdateExecutionTimer could claim and take the value with Interlocked.CompareExchange / Interlocked.Exchange on a long with a "not started" sentinel (Environment.TickCount is an int, so long.MinValue cannot collide). The other counters in this class (SafeAdd, SafeIncrement) are plain unsynchronized read-modify-write operations, so the statistics were never exact under concurrency; the problem is only that the nullable timer turns "inaccurate" into "throws".

I checked both variants in an isolated copy of this logic (no SqlClient reference, 16 threads on one instance, 3 s per variant): the current logic threw 591,661 times, the local-copy variant 0 times, and the Interlocked variant 0 times with every claimed timer released exactly once (7,637,401 claims, 7,637,401 releases). I have not run a patched build of the library itself. I am happy to open a PR if you agree on the direction.

Further technical details

Microsoft.Data.SqlClient version: affected 5.1.9, 6.1.4 - 6.1.7, 7.0.0 - 7.0.3, 7.1.0, 7.1.1 and every pre-release from 7.0.0-preview2 to 7.1.0-preview3; not affected 5.2.3, 6.0.5, 6.1.0 - 6.1.3, 7.0.0-preview1 (tables above; other versions not tested)
.NET target: net8.0 (repro); first seen on .NET 10
SQL Server version: Azure SQL Database
Operating system: Windows 11 (repro); first seen in a Linux (Alpine) container

Additional context

  • Workarounds until this is fixed: do not run commands concurrently on one connection (a connection per concurrent command, or one command with several result sets), or keep statistics off (StatisticsEnabled = false and no SqlClientDiagnosticListener subscriber such as OpenTelemetry's SqlClient instrumentation), or stay on 6.1.3 or 5.2.3.
  • Without MARS the same concurrent pattern is rejected up front (The connection does not support MultipleActiveResultSets), and running the commands one after another on a MARS connection never failed in my tests, so it needs both MARS and real concurrency.
  • SqlStatistics.cs on main is identical to v7.1.1 (the last change to it is Optimization: Use Environment.TickCount for SqlStatistics execution timing #3609), so builds from main should be affected as well; I have not run one because no 8.0 package is published yet.
  • Labels (the contributing guide asks reporters to say which ones apply, since contributors cannot add them): this looks like Regression 💥 (introduced by Optimization: Use Environment.TickCount for SqlStatistics execution timing #3609) and has a repro available ✔️ (-- timer needs no SQL Server).
  • Disclosure: the analysis and the repro were prepared with the help of an AI assistant; every number in the tables above comes from running the programs below.
Repro.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <!-- pick the package version on the command line: dotnet run -p:SqlClientVersion=6.1.3 -->
    <SqlClientVersion Condition="'$(SqlClientVersion)' == ''">7.1.1</SqlClientVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="$(SqlClientVersion)" />
  </ItemGroup>

</Project>
Program.cs
// Repro: InvalidOperationException "Nullable object must have a value." thrown from
// SqlStatistics.ReleaseAndUpdateExecutionTimer() (called from the finally block of SqlDataReader.GetValue()/Read())
// when several commands run at the same time on ONE MARS connection while statistics are on.
// Works with Microsoft.Data.SqlClient <= 6.1.3, fails with >= 6.1.4 (SqlStatistics._startExecutionTimestamp: long -> long?).
//
//   dotnet run -- timer
//       No SQL Server needed. Calls SqlStatistics.StartTimer/StopTimer (what GetValue()/Read() do) on one shared
//       SqlStatistics instance from several threads, via reflection.
//   dotnet run -- sql "<connection string>"  [--mode stats|listener|none] [--iterations 100] [--commands 6] [--rows 100] [--payload 500]
//       End to end. <commands> readers in flight at once on one MARS connection. The connection string can also come
//       from the MSSQL_CONNECTION_STRING environment variable. Only reads sys.all_columns.
//         stats    (default) SqlConnection.StatisticsEnabled = true
//         listener           statistics stay off, but a DiagnosticListener subscribes to "SqlClientDiagnosticListener"
//                            (this is what OpenTelemetry's SqlClient instrumentation does; SqlCommand.Statistics turns
//                            statistics on when SqlClientCommandAfter is enabled)
//         none               control: statistics off, nothing subscribed
//
//   Choose the SqlClient version with:  dotnet run -p:SqlClientVersion=6.1.3 -- timer
using System.Diagnostics;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Data.SqlClient;

var version = typeof(SqlConnection).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "?";
Console.WriteLine($"Microsoft.Data.SqlClient {version.Split('+')[0]} | {RuntimeInformation.FrameworkDescription}");

if (args.Length >= 1 && args[0] == "timer")
{
    return TimerRace.Run();
}
if (args.Length >= 1 && args[0] == "sql")
{
    return await SqlRace.RunAsync(args);
}
Console.WriteLine("usage: dotnet run -- timer");
Console.WriteLine("       dotnet run -- sql \"<connection string>\" [--mode stats|listener|none] [--iterations 100] [--commands 6] [--rows 100] [--payload 500]");
return 2;

static class Util
{
    // first lines of an exception, without the local source paths (keeps the output pasteable)
    public static string Frames(string exceptionText, int take = 8) =>
        string.Join(Environment.NewLine, exceptionText.Split('\n').Take(take)
            .Select(l => "  " + System.Text.RegularExpressions.Regex.Replace(l.TrimEnd(), @" in .*:line \d+$", "")));
}

static class TimerRace
{
    public static int Run()
    {
        const BindingFlags Flags = BindingFlags.Static | BindingFlags.NonPublic;
        var statsType = typeof(SqlConnection).Assembly.GetType("Microsoft.Data.SqlClient.SqlStatistics", throwOnError: true)!;
        var arg = Expression.Parameter(typeof(object));
        var stats = Expression.Convert(arg, statsType);
        // SqlStatistics.StartTimer(statistics) / StopTimer(statistics): the calls SqlDataReader.GetValue() and Read() wrap their work in
        var startTimer = Expression.Lambda<Func<object, object?>>(
            Expression.Convert(Expression.Call(statsType.GetMethod("StartTimer", Flags)!, stats), typeof(object)), arg).Compile();
        var stopTimer = Expression.Lambda<Action<object?>>(
            Expression.Call(statsType.GetMethod("StopTimer", Flags)!, stats), arg).Compile();

        var shared = Activator.CreateInstance(statsType, nonPublic: true)!; // one SqlStatistics, like one SqlConnection owns
        int threads = Math.Max(4, Environment.ProcessorCount);
        const int Seconds = 3;
        long exceptions = 0, pairs = 0, firstAtMs = -1;
        string? first = null;
        var sw = Stopwatch.StartNew();
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(Seconds));
        using var barrier = new Barrier(threads);
        var workers = new Thread[threads];
        for (int t = 0; t < threads; t++)
        {
            workers[t] = new Thread(() =>
            {
                barrier.SignalAndWait();
                long n = 0;
                while (!cts.IsCancellationRequested)
                {
                    try
                    {
                        object? owner = startTimer(shared); // statistics = StartTimer(Statistics)
                        try
                        {
                            n++; // the reader's real work goes here
                        }
                        finally
                        {
                            stopTimer(owner); // StopTimer(statistics) in the finally block
                        }
                    }
                    catch (InvalidOperationException ex)
                    {
                        if (Interlocked.Increment(ref exceptions) == 1)
                        {
                            first = ex.ToString();
                            firstAtMs = sw.ElapsedMilliseconds;
                        }
                    }
                }
                Interlocked.Add(ref pairs, n);
            });
            workers[t].Start();
        }
        foreach (var w in workers)
        {
            w.Join();
        }

        Console.WriteLine($"timer: {threads} threads, {pairs:N0} StartTimer/StopTimer pairs in {Seconds}s -> {exceptions:N0} InvalidOperationException");
        if (first is not null)
        {
            Console.WriteLine($"first one after {firstAtMs} ms:");
            Console.WriteLine(Util.Frames(first));
        }
        return exceptions == 0 ? 0 : 1;
    }
}

static class SqlRace
{
    private sealed class Listener : IObserver<DiagnosticListener>, IObserver<KeyValuePair<string, object?>>
    {
        public void OnNext(DiagnosticListener listener)
        {
            if (listener.Name == "SqlClientDiagnosticListener")
            {
                listener.Subscribe(this);
            }
        }

        public void OnNext(KeyValuePair<string, object?> value) { }
        public void OnCompleted() { }
        public void OnError(Exception error) { }
    }

    private static string Opt(string[] args, string name, string fallback)
    {
        int i = Array.IndexOf(args, name);
        return i >= 0 && i + 1 < args.Length ? args[i + 1] : fallback;
    }

    // one command, one reader, every column of every row read with GetValue() and consumed (hashed), like an ORM materializing the row
    private static async Task<(int Rows, ulong Hash)> ReadAllAsync(SqlConnection conn, int rows, int payload)
    {
        await using var cmd = conn.CreateCommand();
        cmd.CommandText = $"SELECT TOP ({rows}) *, REPLICATE(CAST(N'x' AS nvarchar(max)), {payload}) AS payload FROM sys.all_columns ORDER BY object_id, column_id";
        await using var reader = await cmd.ExecuteReaderAsync();
        int count = 0;
        ulong hash = 14695981039346656037UL;
        while (await reader.ReadAsync())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                foreach (char ch in Convert.ToString(reader.GetValue(i), CultureInfo.InvariantCulture) ?? "")
                {
                    hash = (hash ^ ch) * 1099511628211UL;
                }
            }
            count++;
        }
        return (count, hash);
    }

    public static async Task<int> RunAsync(string[] args)
    {
        string? connectionString = args.Length > 1 && !args[1].StartsWith("--") ? args[1] : Environment.GetEnvironmentVariable("MSSQL_CONNECTION_STRING");
        if (string.IsNullOrEmpty(connectionString))
        {
            Console.WriteLine("no connection string (argument 2 or MSSQL_CONNECTION_STRING)");
            return 2;
        }
        string mode = Opt(args, "--mode", "stats");
        int iterations = int.Parse(Opt(args, "--iterations", "100"));
        int commands = int.Parse(Opt(args, "--commands", "6"));
        int rows = int.Parse(Opt(args, "--rows", "100"));
        int payload = int.Parse(Opt(args, "--payload", "500")); // characters of padding per row, makes the rows span several network packets

        var csb = new SqlConnectionStringBuilder(connectionString) { MultipleActiveResultSets = true };
        if (mode == "listener")
        {
            DiagnosticListener.AllListeners.Subscribe(new Listener());
        }

        // reference result: the same query read once, sequentially, on its own connection
        (int Rows, ulong Hash) expected;
        await using (var refConn = new SqlConnection(csb.ConnectionString))
        {
            await refConn.OpenAsync();
            expected = await ReadAllAsync(refConn, rows, payload);
        }

        int failedIterations = 0, failedCommands = 0, wrongResults = 0;
        var kinds = new Dictionary<string, int>();
        string? first = null;
        var sw = Stopwatch.StartNew();
        for (int it = 0; it < iterations; it++)
        {
            await using var conn = new SqlConnection(csb.ConnectionString);
            await conn.OpenAsync();
            if (mode == "stats")
            {
                conn.StatisticsEnabled = true;
            }

            // <commands> commands in flight at the same time on the SAME connection (MARS)
            var tasks = Enumerable.Range(0, commands).Select(_ => ReadAllAsync(conn, rows, payload)).ToArray();
            try
            {
                await Task.WhenAll(tasks).WaitAsync(TimeSpan.FromSeconds(30));
            }
            catch (TimeoutException)
            {
                Console.WriteLine($"HANG: commands did not finish within 30 s (iteration {it + 1})");
                Environment.Exit(1);
            }
            catch
            {
                // WhenAll rethrows only the first failure; every task is inspected below
            }

            bool failed = false;
            foreach (var t in tasks)
            {
                if (t.IsFaulted)
                {
                    failed = true;
                    failedCommands++;
                    var ex = t.Exception!.GetBaseException();
                    string kind = $"{ex.GetType().Name}: {ex.Message}";
                    kinds[kind] = kinds.GetValueOrDefault(kind) + 1;
                    first ??= ex.ToString();
                }
                else if (t.IsCompletedSuccessfully && t.Result != expected)
                {
                    failed = true;
                    wrongResults++;
                }
            }
            if (failed)
            {
                failedIterations++;
            }
        }
        sw.Stop();

        Console.WriteLine($"sql: mode={mode} MARS=True, {commands} concurrent commands x {rows} rows (+{payload} chars each), {iterations} iterations in {sw.Elapsed.TotalSeconds:0.0}s");
        Console.WriteLine($"     iterations with a failure: {failedIterations}/{iterations} ({100.0 * failedIterations / iterations:0}%), failed commands: {failedCommands}, results that differ from a sequential read: {wrongResults}");
        foreach (var kv in kinds.OrderByDescending(k => k.Value))
        {
            Console.WriteLine($"     {kv.Value,5} x {kv.Key}");
        }
        if (first is not null)
        {
            Console.WriteLine("first failure:");
            Console.WriteLine(Util.Frames(first));
        }
        return failedIterations == 0 && wrongResults == 0 ? 0 : 1;
    }
}

Sub-issues

Sub-issues

3 of 3 Issues completed
Loading 3 sub-issues

Activity

  1. github-actions commented on Oct 2, 2026

    @github-actions

    🔍 Triage Summary

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Async
    Duplicates None found
    Regression Likely regression from v6.1.3 / v5.2.3 (first failing: 6.1.4, 5.1.9, 7.0.0-preview2; introduced by #3609)

    Analysis

    SqlStatistics.RequestExecutionTimer / ReleaseAndUpdateExecutionTimer use a non-atomic check-then-act on a long? shared per connection. With concurrent readers on a MARS connection (statistics enabled, or a DiagnosticListener such as OpenTelemetry), .Value can be read after another owner nulls it, throwing InvalidOperationException from StopTimer. MARS concurrency is not officially thread-safe, but diagnostics bookkeeping should not fail a successful command. Severity: P2.

    Next Steps

    • Assign this issue to Copilot coding agent to investigate SqlStatistics.cs (RequestExecutionTimer, ReleaseAndUpdateExecutionTimer, StartTimer/StopTimer). Apply a single read of _startExecutionTimestamp into a local, or use Interlocked operations with a sentinel long. Add unit tests for concurrent timer use and consider backports to 6.1 and 5.1.
    • Bisection is not needed: the reporter already pinned the boundary to Optimization: Use Environment.TickCount for SqlStatistics execution timing #3609.

    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.

    Generated by SqlClient Issue Auto-Triage for #4778 · copilot · auto · 26.4 AIC · ⌖ 11.4 AIC · ⊞ 13.3K · ◷

  2. added
    Regression 💥
    on Oct 2, 2026
  3. added theissue type on Oct 2, 2026
  4. mdaigle commented on Oct 2, 2026

    @mdaigle
    Contributor

    Thanks @PspInsFws. Even if concurrency isn't supported, it's best to proactively guard the state of our objects to keep them consistent, so I think this is worth fixing.

  5. moved this from Backlog to In progress in SqlClient Boardon Oct 20, 2026
  6. added this to the 8.0.0-preview1 milestone on Oct 20, 2026
  7. moved this from In progress to Done in SqlClient Boardon Oct 21, 2026
  8. moved this from Done to In progress in SqlClient Boardon Nov 24, 2026
  9. moved this from In progress to Done in SqlClient Boardon Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Regression 💥

Type

Projects

Relationships

None yet

Development

No branches or pull requests

Issue actions