diff --git a/JobTrackerApi.MariaDb.Tests/RulesFreshnessMariaDbTests.cs b/JobTrackerApi.MariaDb.Tests/RulesFreshnessMariaDbTests.cs new file mode 100644 index 00000000..12a97c51 --- /dev/null +++ b/JobTrackerApi.MariaDb.Tests/RulesFreshnessMariaDbTests.cs @@ -0,0 +1,134 @@ +using System.Data.Common; +using System.Diagnostics; +using JobTrackerApi.Controllers; +using JobTrackerApi.Data; +using JobTrackerApi.Models; +using JobTrackerApi.Services; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using MySqlConnector; +using Xunit; +using Xunit.Abstractions; + +namespace JobTrackerApi.MariaDb.Tests; + +[CollectionDefinition("Rules MariaDB measurements", DisableParallelization = true)] +public sealed class RulesMariaDbMeasurementCollection; + +[Collection("Rules MariaDB measurements")] +public sealed class RulesFreshnessMariaDbTests(ITestOutputHelper output) +{ + private const string Owner = "rules-owner"; + private const string Other = "rules-other"; + private const string Fallback = "rules-fallback"; + private const int Repetitions = 100; + + [Fact] + public async Task Timed_out_save_preserves_committed_rules_and_retry_reaches_existing_readers() + { + await using var database = await MariaDbDatabase.CreateAsync(); + await Seed(database); + await using var ownerReader = database.Context(Owner); + await using var otherReader = database.Context(Other); + Assert.Equal(30, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays); + Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays); + + await using var lockOwner = database.Context(Owner); + await using var transaction = await lockOwner.Database.BeginTransactionAsync(); + var locked = await lockOwner.UserRuleSettings.SingleAsync(); + locked.AppliedFollowUpDays = 31; + await lockOwner.SaveChangesAsync(); + + await using var failedWriter = database.Context(Owner); + await failedWriter.Database.OpenConnectionAsync(); + await failedWriter.Database.ExecuteSqlRawAsync("SET SESSION innodb_lock_wait_timeout = 1"); + var started = Stopwatch.GetTimestamp(); + var error = await Assert.ThrowsAsync( + () => new RulesController(failedWriter).Update(new RuleSettings { AppliedFollowUpDays = 1 }, default)); + var update = Assert.IsType(error.InnerException); + Assert.Equal(1205, Assert.IsType(update.InnerException).Number); + var timeout = Stopwatch.GetElapsedTime(started); + + Assert.Equal(1, failedWriter.UserRuleSettings.Local.Single().AppliedFollowUpDays); + Assert.Equal(30, (await RulesEngine.GetSettings(failedWriter, default)).AppliedFollowUpDays); + Assert.Equal(30, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays); + Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays); + await transaction.RollbackAsync(); + + await using var retry = database.Context(Owner); + started = Stopwatch.GetTimestamp(); + Assert.IsType( + await new RulesController(retry).Update(new RuleSettings { AppliedFollowUpDays = 1 }, default)); + var retryDuration = Stopwatch.GetElapsedTime(started); + Assert.Equal(1, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays); + Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays); + output.WriteLine($"MariaDB {database.ActualVersion} lock timeout {timeout.TotalMilliseconds:F1} ms; retry {retryDuration.TotalMilliseconds:F1} ms."); + } + + [Fact] + public async Task Committed_owner_and_fallback_reads_measure_queries_and_latency_with_same_workload() + { + await using var database = await MariaDbDatabase.CreateAsync(); + await Seed(database); + var ownerQueries = new QueryCounter(); + var fallbackQueries = new QueryCounter(); + await using var owner = database.Context(Owner, ownerQueries); + await using var fallback = database.Context(Fallback, fallbackQueries); + + Assert.Equal(30, (await RulesEngine.GetSettings(owner, default)).AppliedFollowUpDays); + Assert.Equal(60, (await RulesEngine.GetSettings(fallback, default)).AppliedFollowUpDays); + ownerQueries.Count = fallbackQueries.Count = 0; + double[] ownerTimes = new double[Repetitions]; + double[] fallbackTimes = new double[Repetitions]; + + for (var index = 0; index < Repetitions; index++) + { + ownerTimes[index] = await MeasureRead(owner, 30); + fallbackTimes[index] = await MeasureRead(fallback, 60); + } + + Assert.Equal(Repetitions, ownerQueries.Count); + Assert.Equal(Repetitions * 2, fallbackQueries.Count); + Array.Sort(ownerTimes); + Array.Sort(fallbackTimes); + output.WriteLine(FormattableString.Invariant( + $"MariaDB {database.ActualVersion}; {Repetitions} reads per path. Owner {ownerQueries.Count} commands, p50/p95 {ownerTimes[Repetitions / 2 - 1]:F3}/{ownerTimes[Repetitions * 95 / 100 - 1]:F3} ms. Fallback {fallbackQueries.Count} commands, p50/p95 {fallbackTimes[Repetitions / 2 - 1]:F3}/{fallbackTimes[Repetitions * 95 / 100 - 1]:F3} ms.")); + } + + private static async Task MeasureRead(JobTrackerContext db, int expected) + { + var start = Stopwatch.GetTimestamp(); + var settings = await RulesEngine.GetSettings(db, default); + var elapsed = Stopwatch.GetElapsedTime(start).TotalMilliseconds; + Assert.Equal(expected, settings.AppliedFollowUpDays); + return elapsed; + } + + private static async Task Seed(MariaDbDatabase database) + { + await using var db = database.Context(); + db.Users.AddRange( + new ApplicationUser { Id = Owner, UserName = Owner }, + new ApplicationUser { Id = Other, UserName = Other }, + new ApplicationUser { Id = Fallback, UserName = Fallback }); + (await db.RuleSettings.SingleAsync()).AppliedFollowUpDays = 60; + db.UserRuleSettings.AddRange( + new UserRuleSettings { OwnerUserId = Owner, AppliedFollowUpDays = 30 }, + new UserRuleSettings { OwnerUserId = Other, AppliedFollowUpDays = 45 }); + await db.SaveChangesAsync(); + } + + private sealed class QueryCounter : DbCommandInterceptor + { + public int Count { get; set; } + + public override ValueTask> ReaderExecutingAsync( + DbCommand command, CommandEventData eventData, InterceptionResult result, + CancellationToken cancellationToken = default) + { + Count++; + return base.ReaderExecutingAsync(command, eventData, result, cancellationToken); + } + } +} diff --git a/docs/performance/RULES_FAILED_SAVE.md b/docs/performance/RULES_FAILED_SAVE.md index 52ac9dcc..99b459b1 100644 --- a/docs/performance/RULES_FAILED_SAVE.md +++ b/docs/performance/RULES_FAILED_SAVE.md @@ -7,3 +7,13 @@ The additional real-SQLite case warms owner A/B application decisions, then inje All nine RuleSettingsFreshnessTests passed with zero failures/skips. Eight existing cases overlap the previous 35-case regression and are not added to that total. The native TRX, compressed/raw hashes and command log are retained under `evidence/rules-failed-save/`. Dependency restore used only the existing local NuGet cache. No application or dependency source changed. The injected exception occurs before database save. This verifies committed-read behaviour after that failure and subsequent successful retry. Mid-transaction connection loss, MariaDB, multi-process load, latency, operational restore and release qualification remain separate. + +## MariaDB committed reads after a native lock timeout + +4 December 2026. Published A3 base `ac64d2ee221859c481dfd62e8fe83084af4c6764`. The native lane used disposable MariaDB 12.2.2 on Docker Desktop’s Linux engine with loopback TCP and .NET SDK 9.0.317. + +A second connection held an uncommitted update of owner A’s rule row. The actual Rules controller save received MariaDB error 1205 through EF and Pomelo after 1,007.5 ms with the fixture session’s one-second lock timeout. Owner A’s committed threshold remained 30, including when read through the failed writer with its proposed value still tracked. Owner B remained at 45. After the lock holder rolled back, a fresh explicit save took 5.3 ms and the existing readers observed A at 1 and B still at 45. + +With the same serialized workload and 100 warm reads of each path, the explicit-owner path issued 100 SQL commands and measured p50/p95 of 2.584/3.197 ms. The fallback path issued 200 commands and measured 5.068/6.095 ms. Every read returned its expected setting. These are local service-method measurements for a three-user fixture. Concurrent traffic, HTTP latency, production load and historical P2-O01’s missing server exception remain outside this run. + +The first full run passed 101 of 102 cases. The test expected an unwrapped EF failure while Pomelo wrapped the same native server error. The final test checks both wrappers and error 1205. The second run passed **102 of 102**, zero skipped. Both disposable containers were removed. Run `python scripts/mariadb-integration.py` with the pinned SDK. Local native logs and TRX are in `.artifacts/issue-98-mariadb` and `.artifacts/issue-98-mariadb-final`. Final TRX SHA-256 `efdec2891da9e877273e0c9ab8273bc5b4fd516be326d0ad77bb2dd2496cf8ca`.