Skip to content

Commit 4ad2baa

Browse files
github-actions[bot]mdaigleCopilot
authored
Fix nullable statistics execution timer race (#4875) (#4895)
Read the execution start timestamp once before checking and using its value. Preserve existing best-effort concurrency behavior and cover null timer release with a deterministic unit test. Co-authored-by: Malcolm Daigle <mdaigle@microsoft.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 23aed93d-7636-4021-83d9-61dfd68eeb38
1 parent b1d1bc0 commit 4ad2baa

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStatistics.cs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,11 @@ internal void RequestNetworkServerTimer()
137137

138138
internal void ReleaseAndUpdateExecutionTimer()
139139
{
140-
if (_startExecutionTimestamp.HasValue)
140+
// Use one snapshot so a concurrent release cannot invalidate the checked value.
141+
long? start = _startExecutionTimestamp;
142+
if (start.HasValue)
141143
{
142-
uint elapsed = ADP.CalculateTickCountElapsed(_startExecutionTimestamp.Value, ADP.FastTimerCurrent());
144+
uint elapsed = ADP.CalculateTickCountElapsed(start.Value, ADP.FastTimerCurrent());
143145
_executionTime += elapsed;
144146
_startExecutionTimestamp = null;
145147
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using Xunit;
6+
7+
namespace Microsoft.Data.SqlClient.UnitTests;
8+
9+
/// <summary>
10+
/// Verifies execution timer release when no timer is running.
11+
/// </summary>
12+
public sealed class SqlStatisticsTest
13+
{
14+
/// <summary>
15+
/// Releasing a null start timestamp must leave accumulated execution time unchanged.
16+
/// </summary>
17+
[Fact]
18+
public void ReleaseAndUpdateExecutionTimer_NullStart_DoesNothing()
19+
{
20+
var statistics = new SqlStatistics
21+
{
22+
_startExecutionTimestamp = null,
23+
_executionTime = 42
24+
};
25+
26+
statistics.ReleaseAndUpdateExecutionTimer();
27+
28+
Assert.Null(statistics._startExecutionTimestamp);
29+
Assert.Equal(42L, statistics._executionTime);
30+
}
31+
}

0 commit comments

Comments
 (0)