fix(checklist): recover only system-key duplicate races
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
using System.Data.Common;
|
||||
using System.Text.Json;
|
||||
using JobTrackerApi.Models;
|
||||
using JobTrackerApi.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace JobTrackerApi.MariaDb.Tests;
|
||||
|
||||
public sealed class AnalyticsStatsPersistenceTests(ITestOutputHelper output)
|
||||
{
|
||||
private const string Owner = "rd21-owner";
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(250)]
|
||||
[InlineData(2500)]
|
||||
public async Task Stats_keep_owned_results_with_bounded_native_roundtrips(int size)
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
var recorder = new Reads();
|
||||
await using var db = database.Context(interceptor: recorder);
|
||||
var company = new Company { Name = "Synthetic analytics", OwnerUserId = Owner };
|
||||
db.Companies.Add(company);
|
||||
await db.SaveChangesAsync();
|
||||
var date = DateTime.Now.AddDays(-10);
|
||||
db.JobApplications.AddRange(Enumerable.Range(0, size).Select(_ => Job(company.Id, Owner, "Applied", date)));
|
||||
db.JobApplications.Add(Job(company.Id, "foreign-owner", "Private", date));
|
||||
db.JobApplications.Add(Job(company.Id, null, "Unowned", date));
|
||||
await db.SaveChangesAsync();
|
||||
db.ChangeTracker.Clear();
|
||||
recorder.Sql.Clear();
|
||||
|
||||
var stats = await new AnalyticsService(db).GetStatsAsync(default);
|
||||
Assert.Equal(size, stats.Total);
|
||||
Assert.Equal(size, stats.Active);
|
||||
Assert.Equal(0, stats.Deleted);
|
||||
Assert.Equal(size, stats.AppliedLast30Days);
|
||||
Assert.Equal(size == 0 ? 0 : 10, stats.AverageDaysSinceApplied);
|
||||
Assert.Equal(size == 0 ? 0 : 1, stats.ByStatus.Count);
|
||||
if (size > 0) Assert.Equal(size, stats.ByStatus["Applied"]);
|
||||
Assert.Empty(db.ChangeTracker.Entries());
|
||||
Assert.All(recorder.Sql, sql =>
|
||||
{
|
||||
Assert.DoesNotContain("Description", sql);
|
||||
Assert.DoesNotContain("CoverLetterText", sql);
|
||||
});
|
||||
output.WriteLine(JsonSerializer.Serialize(new { database.ActualVersion, OwnedRows = size,
|
||||
Commands = recorder.Sql.Count, Sql = recorder.Sql }));
|
||||
Assert.Equal(size == 0 ? 2 : 3, recorder.Sql.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Stats_preserve_native_nullable_dates_deletion_ownership_and_mutation()
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
await using var db = database.Context();
|
||||
var company = new Company { Name = "Synthetic semantics", OwnerUserId = Owner };
|
||||
db.Add(company);
|
||||
await db.SaveChangesAsync();
|
||||
var now = DateTime.Now;
|
||||
db.JobApplications.AddRange(
|
||||
Job(company.Id, Owner, "Applied", now.AddDays(-29)),
|
||||
Job(company.Id, Owner, "Interview", now.AddDays(-31)),
|
||||
Job(company.Id, Owner, "", null),
|
||||
Job(company.Id, Owner, " ", now.AddDays(2)),
|
||||
Job(company.Id, Owner, "Unknown", null),
|
||||
Job(company.Id, Owner, "Deleted", now, deleted: true),
|
||||
Job(company.Id, "foreign-owner", "Private", now),
|
||||
Job(company.Id, null, "Unowned", now));
|
||||
await db.SaveChangesAsync();
|
||||
var service = new AnalyticsService(db);
|
||||
var stats = await service.GetStatsAsync(default);
|
||||
Assert.Equal(6, stats.Total);
|
||||
Assert.Equal(5, stats.Active);
|
||||
Assert.Equal(1, stats.Deleted);
|
||||
Assert.Equal(2, stats.AppliedLast30Days);
|
||||
Assert.Equal(20, stats.AverageDaysSinceApplied);
|
||||
Assert.Equal(3, stats.ByStatus["Unknown"]);
|
||||
Assert.Equal(1, stats.ByStatus["Applied"]);
|
||||
Assert.Equal(1, stats.ByStatus["Interview"]);
|
||||
await using var other = database.Context("foreign-owner");
|
||||
Assert.Equal(1, (await new AnalyticsService(other).GetStatsAsync(default)).Total);
|
||||
await using var anonymous = database.Context(null!);
|
||||
var denied = await new AnalyticsService(anonymous).GetStatsAsync(default);
|
||||
Assert.Equal(0, denied.Total);
|
||||
Assert.Empty(denied.ByStatus);
|
||||
db.JobApplications.Add(Job(company.Id, Owner, "Saved", null));
|
||||
await db.SaveChangesAsync();
|
||||
Assert.Equal(7, (await service.GetStatsAsync(default)).Total);
|
||||
output.WriteLine(database.ActualVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cancellation_at_native_command_boundary_prevents_later_stats_reads()
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var recorder = new Reads { BeforeRead = cancellation.Cancel };
|
||||
await using var db = database.Context(interceptor: recorder);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
new AnalyticsService(db).GetStatsAsync(cancellation.Token));
|
||||
Assert.Single(recorder.Sql);
|
||||
output.WriteLine(database.ActualVersion);
|
||||
}
|
||||
|
||||
private static JobApplication Job(int companyId, string? owner, string status, DateTime? date, bool deleted = false) => new()
|
||||
{
|
||||
CompanyId = companyId, OwnerUserId = owner, JobTitle = "Synthetic analyst", Status = status,
|
||||
DateApplied = date, IsDeleted = deleted, Description = "Synthetic wide data must not be selected",
|
||||
CoverLetterText = "Synthetic private letter must not be selected",
|
||||
};
|
||||
|
||||
private sealed class Reads : DbCommandInterceptor
|
||||
{
|
||||
public List<string> Sql { get; } = [];
|
||||
public Action? BeforeRead { get; init; }
|
||||
|
||||
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command,
|
||||
CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Sql.Add(command.CommandText);
|
||||
BeforeRead?.Invoke();
|
||||
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using JobTrackerApi.Models;
|
||||
using JobTrackerApi.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using MySqlConnector;
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace JobTrackerApi.MariaDb.Tests;
|
||||
|
||||
public sealed class ApplicationChecklistPersistenceTests(ITestOutputHelper output)
|
||||
{
|
||||
private const string Owner = "rd21-owner";
|
||||
|
||||
[Theory]
|
||||
[InlineData("system-key")]
|
||||
[InlineData("foreign-key")]
|
||||
[InlineData("unrelated-unique")]
|
||||
public async Task Seed_recovers_only_its_actual_unique_constraint(string scenario)
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
int jobId;
|
||||
const string spoof = "IX_ApplicationChecklistItems_JobApplicationId_SystemKey";
|
||||
await using (var seed = database.Context())
|
||||
{
|
||||
seed.Users.Add(new ApplicationUser { Id = Owner, UserName = spoof, NormalizedUserName = spoof });
|
||||
var job = new JobApplication { OwnerUserId = Owner, Company = new Company { OwnerUserId = Owner, Name = "Synthetic checklist" }, Status = "Interview", Version = 7 };
|
||||
seed.JobApplications.Add(job);
|
||||
await seed.SaveChangesAsync();
|
||||
jobId = job.Id;
|
||||
seed.ApplicationChecklistItems.AddRange(
|
||||
new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = jobId, SystemKey = "prepare-cv", AutoSignal = ChecklistSignalKeys.Cv,
|
||||
IsSystemGenerated = true, Title = "Prepare CV", Category = ChecklistCategories.Preparation, Status = ChecklistStatuses.Dismissed },
|
||||
new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = jobId, Title = "Manual decision", Category = ChecklistCategories.Custom,
|
||||
Status = ChecklistStatuses.Done, SortOrder = 90 });
|
||||
await seed.SaveChangesAsync();
|
||||
}
|
||||
var race = new Race();
|
||||
await using var winner = database.Context(interceptor: new Gate(race, winner: true));
|
||||
var losingGate = new Gate(race, winner: false, saveOtherFirst: scenario == "unrelated-unique");
|
||||
await using var loser = database.Context(interceptor: losingGate);
|
||||
if (scenario == "foreign-key")
|
||||
loser.ApplicationChecklistItems.Add(new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = int.MaxValue,
|
||||
Title = "Invalid parent must fail", Status = ChecklistStatuses.Done });
|
||||
if (scenario == "unrelated-unique")
|
||||
loser.Users.Add(new ApplicationUser { Id = "other-user", UserName = spoof, NormalizedUserName = spoof });
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
var winningRead = new ApplicationChecklistService(winner).GetAsync(Owner, jobId, timeout.Token);
|
||||
var losingRead = new ApplicationChecklistService(loser).GetAsync(Owner, jobId, timeout.Token);
|
||||
Assert.NotNull(await winningRead);
|
||||
var observed = await Record.ExceptionAsync(async () => await losingRead);
|
||||
var saveError = Assert.IsType<DbUpdateException>(losingGate.Failure);
|
||||
var native = Assert.IsType<MySqlException>(saveError.InnerException);
|
||||
output.WriteLine($"Server={database.ActualVersion}; scenario={scenario}; native={native.Number}; message={native.Message}; service={observed?.GetType().Name ?? "none"}");
|
||||
if (scenario == "system-key")
|
||||
{
|
||||
Assert.Equal(1062, native.Number);
|
||||
Assert.Null(observed);
|
||||
var first = (await winningRead)!;
|
||||
var second = (await losingRead)!;
|
||||
Assert.Equal(first.Items.Select(item => item.Id).Order(), second.Items.Select(item => item.Id).Order());
|
||||
Assert.Equal(ChecklistStatuses.Dismissed, second.Items.Single(item => item.SystemKey == "prepare-cv").Status);
|
||||
Assert.Equal(ChecklistStatuses.Done, second.Items.Single(item => item.SystemKey == null).Status);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (scenario == "unrelated-unique")
|
||||
{
|
||||
Assert.EndsWith("for key 'UserNameIndex'", native.Message);
|
||||
Assert.Contains(spoof, native.Message, StringComparison.Ordinal);
|
||||
}
|
||||
Assert.IsType<DbUpdateException>(observed);
|
||||
Assert.Equal(scenario == "foreign-key" ? 1452 : 1062, native.Number);
|
||||
Assert.True(loser.ChangeTracker.Entries().Any(entry => entry.State == EntityState.Added));
|
||||
}
|
||||
await using var verify = database.Context();
|
||||
Assert.Equal(15, await verify.ApplicationChecklistItems.CountAsync());
|
||||
Assert.Equal(7, (await verify.JobApplications.SingleAsync()).Version);
|
||||
Assert.Equal(1, await verify.Users.CountAsync());
|
||||
}
|
||||
|
||||
private sealed class Race
|
||||
{
|
||||
private int _arrivals;
|
||||
public TaskCompletionSource BothReady { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Committed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public void Arrive() { if (Interlocked.Increment(ref _arrivals) == 2) BothReady.TrySetResult(); }
|
||||
}
|
||||
|
||||
private sealed class Gate(Race race, bool winner, bool saveOtherFirst = false) : SaveChangesInterceptor
|
||||
{
|
||||
private bool _used;
|
||||
public Exception? Failure { get; private set; }
|
||||
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData data, InterceptionResult<int> result, CancellationToken ct = default)
|
||||
{
|
||||
if (_used) return result;
|
||||
_used = true;
|
||||
race.Arrive();
|
||||
await race.BothReady.Task.WaitAsync(ct);
|
||||
if (!winner) await race.Committed.Task.WaitAsync(ct);
|
||||
if (saveOtherFirst)
|
||||
{
|
||||
// Force the unrelated tracked write first; normal batch ordering hits checklist duplicates first.
|
||||
var context = data.Context!;
|
||||
var seeds = context.ChangeTracker.Entries<ApplicationChecklistItem>()
|
||||
.Where(entry => entry.State == EntityState.Added).ToList();
|
||||
foreach (var seed in seeds) seed.State = EntityState.Detached;
|
||||
try { await context.SaveChangesAsync(ct); }
|
||||
finally { foreach (var seed in seeds) context.Add(seed.Entity); }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public override ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData data, int result, CancellationToken ct = default)
|
||||
{
|
||||
if (winner) race.Committed.TrySetResult();
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
public override Task SaveChangesFailedAsync(DbContextErrorEventData data, CancellationToken ct = default)
|
||||
{
|
||||
Failure = data.Exception;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user