Compare commits

..

1 Commits

Author SHA1 Message Date
cesnimda 6f6ba9402a Verify Rules freshness and retry on native MariaDB
CI and Deploy / test (pull_request) Failing after 5m0s
CI and Deploy / deploy (pull_request) Has been skipped
2026-12-04 18:13:23 +01:00
5 changed files with 144 additions and 219 deletions
@@ -88,7 +88,6 @@ internal sealed class MariaDbDatabase : IAsyncDisposable
builder.Services.AddSingleton<IStartupReadiness, StartupReadiness>();
builder.Services.AddDbContext<JobTrackerContext>(options => database.Configure(options));
builder.Services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
builder.Services.AddControllers();
database.App = builder.Build();
await database.App.InitializeJobTrackerAsync();
return database;
@@ -1,111 +0,0 @@
using System.Security.Claims;
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
using Xunit.Abstractions;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class PreferenceConcurrencyTests(ITestOutputHelper output)
{
[Fact]
public async Task Concurrent_language_and_notification_writes_preserve_the_winner_and_allow_a_fresh_retry()
{
await using var database = await MariaDbDatabase.CreateAsync();
await using (var seed = database.Context())
{
seed.Users.AddRange(
new ApplicationUser { Id = "preference-owner", UserName = "owner@example.test", UiLanguage = "en", EmailFollowUpRemindersEnabled = true },
new ApplicationUser { Id = "preference-other", UserName = "other@example.test", UiLanguage = "nb-NO", EmailFollowUpRemindersEnabled = false });
await seed.SaveChangesAsync();
}
await using var languageScope = database.App.Services.CreateAsyncScope();
await using var notificationScope = database.App.Services.CreateAsyncScope();
await using var otherScope = database.App.Services.CreateAsyncScope();
var language = LanguageController(languageScope.ServiceProvider, "preference-owner");
var notification = NotificationController(notificationScope.ServiceProvider, "preference-owner");
var otherLanguage = LanguageController(otherScope.ServiceProvider, "preference-other");
var otherNotification = NotificationController(otherScope.ServiceProvider, "preference-other");
// Model two requests that have read the same Identity version before either writes.
var languageSnapshot = await languageScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>().GetUserAsync(language.User);
var notificationSnapshot = await notificationScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>().GetUserAsync(notification.User);
Assert.NotNull(languageSnapshot);
Assert.NotNull(notificationSnapshot);
Assert.NotSame(languageSnapshot, notificationSnapshot);
var originalStamp = languageSnapshot.ConcurrencyStamp;
Assert.Equal(originalStamp, notificationSnapshot.ConcurrencyStamp);
var languageWrite = language.UpdateLanguagePreference(new("nb-NO"));
var notificationWrite = notification.Put(new(false));
var otherWrite = otherLanguage.UpdateLanguagePreference(new("en"));
await Task.WhenAll(languageWrite, notificationWrite, otherWrite);
Assert.IsType<NoContentResult>(await otherWrite);
Assert.IsType<BadRequestObjectResult>(await otherLanguage.UpdateLanguagePreference(new("fr-FR")));
Assert.IsType<OkObjectResult>((await otherNotification.Put(new(true))).Result);
var languageWon = await languageWrite is NoContentResult;
if (languageWon)
{
var error = Assert.IsType<ObjectResult>((await notificationWrite).Result);
Assert.Equal(StatusCodes.Status500InternalServerError, error.StatusCode);
}
else
{
var error = Assert.IsType<BadRequestObjectResult>(await languageWrite);
Assert.Contains(new IdentityErrorDescriber().ConcurrencyFailure().Description, Assert.IsType<string>(error.Value));
Assert.IsType<OkObjectResult>((await notificationWrite).Result);
}
await using (var read = database.Context())
{
var owner = await read.Users.AsNoTracking().SingleAsync(user => user.Id == "preference-owner");
Assert.Equal(languageWon ? "nb-NO" : "en", owner.UiLanguage);
Assert.Equal(languageWon, owner.EmailFollowUpRemindersEnabled);
Assert.NotEqual(originalStamp, owner.ConcurrencyStamp);
}
await using var retryScope = database.App.Services.CreateAsyncScope();
if (languageWon)
Assert.IsType<OkObjectResult>((await NotificationController(retryScope.ServiceProvider, "preference-owner").Put(new(false))).Result);
else
Assert.IsType<NoContentResult>(await LanguageController(retryScope.ServiceProvider, "preference-owner").UpdateLanguagePreference(new("nb-NO")));
await using var reload = database.Context();
var users = await reload.Users.AsNoTracking().Where(user => user.Id.StartsWith("preference-")).OrderBy(user => user.Id).ToListAsync();
Assert.Collection(users,
other => { Assert.Equal("preference-other", other.Id); Assert.Equal("en", other.UiLanguage); Assert.True(other.EmailFollowUpRemindersEnabled); },
owner => { Assert.Equal("preference-owner", owner.Id); Assert.Equal("nb-NO", owner.UiLanguage); Assert.False(owner.EmailFollowUpRemindersEnabled); });
output.WriteLine($"MariaDB {database.ActualVersion}: {(languageWon ? "language" : "notification")} won the overlapping writes; fresh retry preserved both preferences and the other owner's independent writes.");
}
private static AuthController LanguageController(IServiceProvider services, string owner) => new(
services.GetRequiredService<IConfiguration>(), services.GetRequiredService<UserManager<ApplicationUser>>(),
Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(),
NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), services.GetRequiredService<JobTrackerContext>(),
externalOrigin: ExternalOrigin.Parse("http://localhost:3300", production: false))
{ ControllerContext = Principal(services, owner) };
private static NotificationSettingsController NotificationController(IServiceProvider services, string owner) => new(
services.GetRequiredService<UserManager<ApplicationUser>>()) { ControllerContext = Principal(services, owner) };
private static ControllerContext Principal(IServiceProvider services, string owner) => new()
{
HttpContext = new DefaultHttpContext
{
RequestServices = services,
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, owner)], "test")),
},
};
}
@@ -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<InvalidOperationException>(
() => new RulesController(failedWriter).Update(new RuleSettings { AppliedFollowUpDays = 1 }, default));
var update = Assert.IsType<DbUpdateException>(error.InnerException);
Assert.Equal(1205, Assert.IsType<MySqlException>(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<NoContentResult>(
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<double> 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<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
Count++;
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
}
}
}
+10
View File
@@ -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`.
@@ -93,110 +93,3 @@ test('MariaDB native Career conflict and network failure retain drafts; reviewed
limits:'Native browser/API and independent read-only MariaDB connections; controlled request abort; no production or power-loss durability claim.' }), contentType:'application/json' });
} finally { await admin.dispose(); await second.dispose(); await fresh.dispose(); }
});
test('MariaDB preference writes overlap across owners and rejected language changes do not survive reload', async ({ page, browser, playwright, baseURL }, info) => {
expect(info.config.metadata.mariaDbDatabase).toMatch(/^jt_it_[a-f0-9]{32}$/);
const admin = await playwright.request.newContext();
const phoneContext = await browser.newContext({ viewport: { width: 390, height: 844 } });
const phone = await phoneContext.newPage();
const suffix = Date.now();
const emails = [`preferences-desktop-${suffix}@example.test`, `preferences-phone-${suffix}@example.test`];
const languageUrl = `${api}/auth/preferences/language`;
const notificationUrl = `${api}/notification-settings`;
const en = translations.en;
const nb = translations.nb;
let releaseRequests!: () => void;
const held = new Promise<void>(resolve => { releaseRequests = resolve; });
try {
const fixtureOrigins = new Set([new URL(api).origin, new URL(baseURL!).origin]);
for (const context of [page.context(), phoneContext]) {
await context.route('**/*', route => fixtureOrigins.has(new URL(route.request().url()).origin) ? route.continue() : route.abort());
}
const administrator = await login(admin, 'e2e@example.test');
for (const email of emails) {
expect((await admin.post(`${api}/users`, { headers: administrator.headers, data: { email, password, roles: [] } })).status()).toBe(200);
}
const desktop = await login(page.request, emails[0]);
const mobile = await login(phone.request, emails[1]);
expect(desktop.id).not.toBe(mobile.id);
for (const [request, headers] of [[page.request, desktop.headers], [phone.request, mobile.headers]] as const) {
expect((await request.put(languageUrl, { headers, data: { language: 'nb-NO' } })).status()).toBe(204);
}
await page.setViewportSize({ width: 1440, height: 900 });
await page.addInitScript(() => localStorage.setItem('jobtracker.themeMode', 'light'));
await phone.addInitScript(() => localStorage.setItem('jobtracker.themeMode', 'dark'));
await Promise.all([page.goto('/settings'), phone.goto('/settings')]);
await expect(page.locator('html')).toHaveAttribute('lang', 'nb-NO');
await expect(phone.locator('html')).toHaveAttribute('lang', 'nb-NO');
const openNotifications = async () => {
const navigation = phone.getByRole('combobox', { name: nb.settingsNavigation });
await navigation.press('Enter');
await phone.getByRole('option', { name: nb.settingsTabNotifications, exact: true }).press('Enter');
await expect(navigation).toBeFocused();
};
const chooseLanguage = async (label: string, option: string) => {
const select = page.getByRole('combobox', { name: label });
await select.press('Enter');
await page.getByRole('option', { name: option, exact: true }).press('Enter');
};
const reminders = phone.getByRole('switch', { name: nb.settingsNotificationsFollowUpReminders, exact: true });
await openNotifications();
await expect(reminders).toBeChecked();
await reminders.uncheck();
const save = phone.getByRole('button', { name: nb.settingsNotificationsSave, exact: true });
await save.focus();
await expect(save).toBeFocused();
const arrived: string[] = [];
await page.route(languageUrl, async route => {
if (route.request().method() === 'PUT') { arrived.push('language'); await held; }
await route.continue();
});
await phone.route(notificationUrl, async route => {
if (route.request().method() === 'PUT') { arrived.push('notification'); await held; }
await route.continue();
});
const languageAccepted = page.waitForResponse(response => response.url() === languageUrl && response.request().method() === 'PUT');
const notificationAccepted = phone.waitForResponse(response => response.url() === notificationUrl && response.request().method() === 'PUT');
await Promise.all([chooseLanguage(nb.settingsPreferredLanguage, nb.settingsEnglish), save.press('Enter')]);
await expect.poll(() => [...arrived].sort()).toEqual(['language', 'notification']);
releaseRequests();
const accepted = await Promise.all([languageAccepted, notificationAccepted]);
expect(accepted.map(response => response.status())).toEqual([204, 200]);
await page.unroute(languageUrl);
await phone.unroute(notificationUrl);
await expect(page.locator('html')).toHaveAttribute('lang', 'en');
// Send one invalid value to the real server through the native language control.
await page.route(languageUrl, route => route.continue({ postData: JSON.stringify({ language: 'fr-FR' }) }), { times: 1 });
const rejection = page.waitForResponse(response => response.url() === languageUrl && response.request().method() === 'PUT');
await chooseLanguage(en.settingsPreferredLanguage, en.settingsNorwegian);
expect((await rejection).status()).toBe(400);
await expect(page.getByText(nb.settingsLanguageSaveFailed, { exact: true })).toBeVisible();
await Promise.all([page.reload(), phone.reload()]);
await expect(page.locator('html')).toHaveAttribute('lang', 'en');
await expect(page.locator('html')).toHaveAttribute('data-color-scheme', 'light');
await expect(phone.locator('html')).toHaveAttribute('lang', 'nb-NO');
await expect(phone.locator('html')).toHaveAttribute('data-color-scheme', 'dark');
await openNotifications();
await expect(reminders).not.toBeChecked();
const observed = [];
for (const email of emails) {
const fresh = await playwright.request.newContext();
try {
await login(fresh, email);
const user = await fresh.get(`${api}/auth/me`);
const notifications = await fresh.get(notificationUrl);
expect(user.status()).toBe(200);
expect(notifications.status()).toBe(200);
observed.push({ language: (await user.json()).uiLanguage, reminders: (await notifications.json()).emailFollowUpRemindersEnabled });
} finally { await fresh.dispose(); }
}
expect(observed).toEqual([{ language: 'en', reminders: true }, { language: 'nb-NO', reminders: false }]);
await info.attach('mariadb-preference-readback', { body: JSON.stringify({ accepted: [204, 200], rejected: 400, observed,
desktop: { width: 1440, height: 900, theme: 'light' }, phone: { width: 390, height: 844, theme: 'dark' } }), contentType: 'application/json' });
} finally { releaseRequests(); await phoneContext.close(); await admin.dispose(); }
});