Skip to content

Commit a37330f

Browse files
authored
[5.0.3] Fix event counter issues and add test patterns for event source testing (#23826)
* [5.0.3] Fix event counter issues and add test patterns for event source testing Fixes #23630 **Description** Three event counters don't get updated when the async API is used (as opposed to the sync one). An additional event counter is incorrectly updated, and so show wrong results. **Customer Impact** Our newly-introduced event counters show incorrect data which does not take into account async calls. **How found** Customer reported an issue on 5.0.0 with one counter, the rest discovered via due diligence. **Test coverage** Test coverage added after investigation and discussion of the best way to do it. We settled on using reflection to access the counters and then configuring the tests to not run in parallel. These tests are both for detecting regressions, and so that going forward we can test new event counters to avoid mistakes like this in the future. **Regression?** No, event counters are new in 5.0.0. **Risk** Very low, add missing counter updates which are already in place and working for the sync versions, and move the location of another counter update. Only affects the new event counters feature. * Review feedback
1 parent 8e7ac85 commit a37330f

File tree

6 files changed

+308
-3
lines changed

6 files changed

+308
-3
lines changed

src/EFCore/ChangeTracking/Internal/StateManager.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1114,6 +1114,8 @@ protected virtual async Task<int> SaveChangesAsync(
11141114
{
11151115
using (_concurrencyDetector.EnterCriticalSection())
11161116
{
1117+
EntityFrameworkEventSource.Log.SavingChanges();
1118+
11171119
return await _database.SaveChangesAsync(entriesToSave, cancellationToken)
11181120
.ConfigureAwait(false);
11191121
}

src/EFCore/DbContext.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,8 @@ public DbContext([NotNull] DbContextOptions options)
112112
ServiceProviderCache.Instance.GetOrAdd(options, providerRequired: false)
113113
.GetRequiredService<IDbSetInitializer>()
114114
.InitializeSets(this);
115+
116+
EntityFrameworkEventSource.Log.DbContextInitializing();
115117
}
116118

117119
/// <summary>
@@ -347,8 +349,6 @@ private IServiceProvider InternalServiceProvider
347349
{
348350
_initializing = true;
349351

350-
EntityFrameworkEventSource.Log.DbContextInitializing();
351-
352352
var optionsBuilder = new DbContextOptionsBuilder(_options);
353353

354354
OnConfiguring(optionsBuilder);
@@ -642,6 +642,8 @@ public virtual async Task<int> SaveChangesAsync(
642642
}
643643
catch (DbUpdateConcurrencyException exception)
644644
{
645+
EntityFrameworkEventSource.Log.OptimisticConcurrencyFailure();
646+
645647
await DbContextDependencies.UpdateLogger.OptimisticConcurrencyExceptionAsync(this, exception, cancellationToken)
646648
.ConfigureAwait(false);
647649

src/EFCore/Infrastructure/EntityFrameworkEventSource.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Diagnostics.Tracing;
66
using System.Runtime.InteropServices;
77
using System.Threading;
8+
using JetBrains.Annotations;
89
using Microsoft.EntityFrameworkCore.Storage;
910

1011
namespace Microsoft.EntityFrameworkCore.Infrastructure
@@ -156,6 +157,10 @@ protected override void OnEventCommand(EventCommandEventArgs command)
156157
}
157158
}
158159

160+
[UsedImplicitly]
161+
private void ResetCacheInfo()
162+
=> _compiledQueryCacheInfo = new CacheInfo();
163+
159164
[StructLayout(LayoutKind.Explicit)]
160165
private struct CacheInfo
161166
{

src/EFCore/Storage/ExecutionStrategy.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,9 @@ private async Task<TResult> ExecuteImplementationAsync<TState, TResult>(
273273
catch (Exception ex)
274274
{
275275
Suspended = false;
276+
277+
EntityFrameworkEventSource.Log.ExecutionStrategyOperationFailure();
278+
276279
if (verifySucceeded != null
277280
&& CallOnWrappedException(ex, ShouldVerifySuccessOn))
278281
{
Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Linq;
7+
using System.Reflection;
8+
using System.Threading.Tasks;
9+
using Microsoft.EntityFrameworkCore.Infrastructure;
10+
using Microsoft.EntityFrameworkCore.Storage;
11+
using Xunit;
12+
13+
namespace Microsoft.EntityFrameworkCore
14+
{
15+
[Collection("EventSourceTest")]
16+
public class EventSourceTest
17+
{
18+
private static readonly BindingFlags _bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
19+
20+
[ConditionalTheory]
21+
[InlineData(false)]
22+
[InlineData(true)]
23+
public async Task Counts_when_query_is_executed(bool async)
24+
{
25+
TotalQueries = 0;
26+
27+
for (var i = 1; i <= 3; i++)
28+
{
29+
using var context = new SomeDbContext();
30+
31+
_ = async ? await context.Foos.ToListAsync() : context.Foos.ToList();
32+
33+
Assert.Equal(i, TotalQueries);
34+
}
35+
}
36+
37+
[ConditionalTheory]
38+
[InlineData(false)]
39+
[InlineData(true)]
40+
public async Task Counts_when_SaveChanges_is_called(bool async)
41+
{
42+
TotalSaveChanges = 0;
43+
44+
for (var i = 1; i <= 3; i++)
45+
{
46+
using var context = new SomeDbContext();
47+
48+
context.Add(new Foo());
49+
50+
_ = async ? await context.SaveChangesAsync() : context.SaveChanges();
51+
52+
Assert.Equal(i, TotalSaveChanges);
53+
}
54+
}
55+
56+
[ConditionalTheory]
57+
[InlineData(false)]
58+
[InlineData(true)]
59+
public async Task Counts_when_context_is_constructed_and_disposed(bool async)
60+
{
61+
ActiveDbContexts = 0;
62+
var contexts = new List<DbContext>();
63+
64+
for (var i = 1; i <= 3; i++)
65+
{
66+
contexts.Add(new SomeDbContext());
67+
68+
Assert.Equal(i, ActiveDbContexts);
69+
}
70+
71+
for (var i = 2; i >= 0; i--)
72+
{
73+
if (async)
74+
{
75+
await ((IAsyncDisposable)contexts[i]).DisposeAsync();
76+
}
77+
else
78+
{
79+
contexts[i].Dispose();
80+
}
81+
82+
Assert.Equal(i, ActiveDbContexts);
83+
}
84+
}
85+
86+
[ConditionalTheory]
87+
[InlineData(false)]
88+
[InlineData(true)]
89+
public async Task Counts_query_cache_hits_and_misses(bool async)
90+
{
91+
ResetCacheInfo();
92+
93+
for (var i = 1; i <= 3; i++)
94+
{
95+
using var context = new SomeDbContext();
96+
97+
var query = context.Foos.Where(e => e.Id == new Guid("6898CFFC-3DCC-45A6-A472-A23057462EE6"));
98+
99+
_ = async ? await query.ToListAsync() : query.ToList();
100+
101+
Assert.Equal(1, CompiledQueryCacheInfoMisses);
102+
Assert.Equal(i - 1, CompiledQueryCacheInfoHits);
103+
}
104+
}
105+
106+
[ConditionalTheory]
107+
[InlineData(false)]
108+
[InlineData(true)]
109+
public async Task Counts_when_DbUpdateConcurrencyException_is_thrown(bool async)
110+
{
111+
TotalOptimisticConcurrencyFailures = 0;
112+
113+
for (var i = 1; i <= 3; i++)
114+
{
115+
using var context = new SomeDbContext();
116+
117+
var entity = new Foo();
118+
context.Add(entity);
119+
context.SaveChanges();
120+
121+
using (var innerContext = new SomeDbContext())
122+
{
123+
innerContext.Foos.Find(entity.Id).Token = 1;
124+
innerContext.SaveChanges();
125+
}
126+
127+
entity.Token = 2;
128+
129+
if (async)
130+
{
131+
await Assert.ThrowsAsync<DbUpdateConcurrencyException>(async () => await context.SaveChangesAsync());
132+
}
133+
else
134+
{
135+
Assert.Throws<DbUpdateConcurrencyException>(() => context.SaveChanges());
136+
}
137+
138+
Assert.Equal(i, TotalOptimisticConcurrencyFailures);
139+
}
140+
}
141+
142+
[ConditionalTheory]
143+
[InlineData(false)]
144+
[InlineData(true)]
145+
public async Task Counts_when_execution_strategy_retries(bool async)
146+
{
147+
TotalExecutionStrategyOperationFailures = 0;
148+
149+
for (var i = 1; i <= 3; i++)
150+
{
151+
using var context = new SomeDbContext();
152+
153+
var executionCount = 0;
154+
var executionStrategyMock = new ExecutionStrategyTest.TestExecutionStrategy(
155+
context,
156+
retryCount: 2,
157+
shouldRetryOn: e => e is ArgumentOutOfRangeException,
158+
getNextDelay: e => TimeSpan.FromTicks(0));
159+
160+
if (async)
161+
{
162+
Assert.IsType<ArgumentOutOfRangeException>(
163+
(await Assert.ThrowsAsync<RetryLimitExceededException>(
164+
() =>
165+
executionStrategyMock.ExecuteAsync(
166+
() =>
167+
{
168+
if (executionCount++ < 3)
169+
{
170+
throw new ArgumentOutOfRangeException();
171+
}
172+
173+
Assert.True(false);
174+
return Task.FromResult(1);
175+
}))).InnerException);
176+
}
177+
else
178+
{
179+
Assert.IsType<ArgumentOutOfRangeException>(
180+
Assert.Throws<RetryLimitExceededException>(
181+
() =>
182+
executionStrategyMock.Execute(
183+
() =>
184+
{
185+
if (executionCount++ < 3)
186+
{
187+
throw new ArgumentOutOfRangeException();
188+
}
189+
190+
Assert.True(false);
191+
return 0;
192+
})).InnerException);
193+
}
194+
195+
Assert.Equal(3, executionCount);
196+
Assert.Equal(i * 3, TotalExecutionStrategyOperationFailures);
197+
}
198+
}
199+
200+
private static readonly FieldInfo _activeDbContexts
201+
= typeof(EntityFrameworkEventSource).GetField("_activeDbContexts", _bindingFlags);
202+
203+
private static long ActiveDbContexts
204+
{
205+
get => (long)_activeDbContexts.GetValue(EntityFrameworkEventSource.Log);
206+
set => _activeDbContexts.SetValue(EntityFrameworkEventSource.Log, value);
207+
}
208+
209+
private static readonly FieldInfo _totalQueries
210+
= typeof(EntityFrameworkEventSource).GetField(nameof(_totalQueries), _bindingFlags);
211+
212+
private static long TotalQueries
213+
{
214+
get => (long)_totalQueries.GetValue(EntityFrameworkEventSource.Log);
215+
set => _totalQueries.SetValue(EntityFrameworkEventSource.Log, value);
216+
}
217+
218+
private static readonly FieldInfo _totalSaveChanges
219+
= typeof(EntityFrameworkEventSource).GetField(nameof(_totalSaveChanges), _bindingFlags);
220+
221+
private static long TotalSaveChanges
222+
{
223+
get => (long)_totalSaveChanges.GetValue(EntityFrameworkEventSource.Log);
224+
set => _totalSaveChanges.SetValue(EntityFrameworkEventSource.Log, value);
225+
}
226+
227+
private static readonly FieldInfo _totalExecutionStrategyOperationFailures
228+
= typeof(EntityFrameworkEventSource).GetField(nameof(_totalExecutionStrategyOperationFailures), _bindingFlags);
229+
230+
private static long TotalExecutionStrategyOperationFailures
231+
{
232+
get => (long)_totalExecutionStrategyOperationFailures.GetValue(EntityFrameworkEventSource.Log);
233+
set => _totalExecutionStrategyOperationFailures.SetValue(EntityFrameworkEventSource.Log, value);
234+
}
235+
236+
private static readonly FieldInfo _totalOptimisticConcurrencyFailures
237+
= typeof(EntityFrameworkEventSource).GetField(nameof(_totalOptimisticConcurrencyFailures), _bindingFlags);
238+
239+
private static long TotalOptimisticConcurrencyFailures
240+
{
241+
get => (long)_totalOptimisticConcurrencyFailures.GetValue(EntityFrameworkEventSource.Log);
242+
set => _totalOptimisticConcurrencyFailures.SetValue(EntityFrameworkEventSource.Log, value);
243+
}
244+
245+
private static readonly FieldInfo _compiledQueryCacheInfo
246+
= typeof(EntityFrameworkEventSource).GetField(nameof(_compiledQueryCacheInfo), _bindingFlags);
247+
248+
private static readonly MethodInfo _resetCacheInfo
249+
= typeof(EntityFrameworkEventSource).GetMethod("ResetCacheInfo", _bindingFlags);
250+
251+
private static readonly FieldInfo _compiledQueryCacheInfoHits
252+
= _compiledQueryCacheInfo.FieldType.GetField("Hits", _bindingFlags);
253+
254+
private static int CompiledQueryCacheInfoHits
255+
{
256+
get => (int)_compiledQueryCacheInfoHits.GetValue(_compiledQueryCacheInfo.GetValue(EntityFrameworkEventSource.Log));
257+
}
258+
259+
private static readonly FieldInfo _compiledQueryCacheInfoMisses
260+
= _compiledQueryCacheInfo.FieldType.GetField("Misses", _bindingFlags);
261+
262+
private static int CompiledQueryCacheInfoMisses
263+
{
264+
get => (int)_compiledQueryCacheInfoMisses.GetValue(_compiledQueryCacheInfo.GetValue(EntityFrameworkEventSource.Log));
265+
}
266+
267+
private static void ResetCacheInfo()
268+
=> _resetCacheInfo.Invoke(EntityFrameworkEventSource.Log, null);
269+
270+
private class SomeDbContext : DbContext
271+
{
272+
public DbSet<Foo> Foos { get; set; }
273+
274+
protected internal override void OnModelCreating(ModelBuilder modelBuilder)
275+
=> modelBuilder.Entity<Foo>().Property(e => e.Token).IsConcurrencyToken();
276+
277+
protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
278+
=> optionsBuilder
279+
.UseInMemoryDatabase(nameof(EventSourceTest));
280+
}
281+
282+
private class Foo
283+
{
284+
public Guid Id { get; set; }
285+
public int Token { get; set; }
286+
}
287+
}
288+
289+
[CollectionDefinition("EventSourceTest", DisableParallelization = true)]
290+
public class EventSourceTestCollection
291+
{
292+
}
293+
}

test/EFCore.Tests/Storage/ExecutionStrategyTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -649,7 +649,7 @@ protected DbContext CreateContext()
649649
.AddScoped<IDbContextTransactionManager, TestInMemoryTransactionManager>()),
650650
InMemoryTestHelpers.Instance.CreateOptions());
651651

652-
private class TestExecutionStrategy : ExecutionStrategy
652+
public class TestExecutionStrategy : ExecutionStrategy
653653
{
654654
private readonly Func<Exception, bool> _shouldRetryOn;
655655
private readonly Func<Exception, TimeSpan?> _getNextDelay;

0 commit comments

Comments
 (0)