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
8 changed files with 148 additions and 213 deletions
@@ -1,38 +0,0 @@
using System.Text;
using System.Text.Json;
using JobTrackerApi.Controllers;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class CalendarPrecisionTests
{
[Theory]
[InlineData("2026-10-25T02:30:00+02:00", "20261025T003000Z")]
[InlineData("2026-10-25T02:30:00+01:00", "20261025T013000Z")]
public async Task Explicit_follow_up_offset_survives_mariadb_round_trip_to_ics(string source, string expected)
{
const string owner = "calendar-owner";
var json = JsonSerializer.Serialize(new { followUpAt = source });
var request = JsonSerializer.Deserialize<FollowUpRequest>(json, new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
await using var database = await MariaDbDatabase.CreateAsync();
await using var db = database.Context(owner);
var job = new JobApplication
{
OwnerUserId = owner, Company = new Company { OwnerUserId = owner, Name = "Synthetic calendar" },
JobTitle = "Synthetic role", Status = "Interview", FollowUpAt = request.FollowUpAt,
};
db.JobApplications.Add(job);
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
var controller = new ApplicationCalendarController(db, Mock.Of<ICurrentUserService>(user => user.UserId == owner),
new Mock<IGmailOAuthService>(MockBehavior.Strict).Object, new Mock<IMicrosoftGraphOAuthService>(MockBehavior.Strict).Object);
var file = Assert.IsType<FileContentResult>(await controller.DownloadEvent(job.Id, "follow-up", default));
Assert.Contains($"DTSTART:{expected}\r\n", Encoding.UTF8.GetString(file.FileContents), StringComparison.Ordinal);
}
}
@@ -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);
}
}
}
@@ -6,41 +6,12 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.Sqlite;
using Moq;
using System.Globalization;
using System.Text.Json;
using Xunit;
namespace JobTrackerApi.Tests;
public sealed class ApplicationCalendarControllerTests
{
[Theory]
[InlineData("2026-10-25T02:30:00+02:00", "2026-10-25T00:30:00", DateTimeKind.Utc)]
[InlineData("2026-10-25T02:30:00+01:00", "2026-10-25T01:30:00", DateTimeKind.Utc)]
[InlineData("2026-10-25T00:15:00Z", "2026-10-25T00:15:00", DateTimeKind.Utc)]
[InlineData("2026-10-25T02:30:00", "2026-10-25T02:30:00", DateTimeKind.Unspecified)]
[InlineData("2026-10-25", "2026-10-25T00:00:00", DateTimeKind.Unspecified)]
[InlineData(null, null, null)]
public void Follow_up_write_contracts_preserve_explicit_instants_and_legacy_values(
string? input, string? expected, DateTimeKind? kind)
{
var json = JsonSerializer.Serialize(new { followUpAt = input });
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var dates = new[]
{
JsonSerializer.Deserialize<CreateJobApplicationRequest>(json, options)!.FollowUpAt,
JsonSerializer.Deserialize<UpdateJobApplicationRequest>(json, options)!.FollowUpAt,
JsonSerializer.Deserialize<FollowUpRequest>(json, options)!.FollowUpAt,
JsonSerializer.Deserialize<InterviewPrepController.SetFollowUpRequest>(json, options)!.FollowUpAt,
};
Assert.All(dates, value =>
{
Assert.Equal(expected, value?.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture));
Assert.Equal(kind, value?.Kind);
});
}
[Fact]
public async Task Agenda_date_window_translates_on_sqlite_and_keeps_legacy_wall_clock_date()
{
@@ -1,22 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace JobTrackerApi.Controllers;
public sealed class FollowUpDateTimeConverter : JsonConverter<DateTime?>
{
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (!reader.TryGetDateTime(out var value))
throw new JsonException("Follow-up date must be an ISO 8601 date or timestamp.");
// An explicit offset becomes server-local DateTime before storage discards its Kind.
return value.Kind == DateTimeKind.Local ? reader.GetDateTimeOffset().UtcDateTime : value;
}
public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
{
if (value is { } date) writer.WriteStringValue(date);
else writer.WriteNullValue();
}
}
@@ -3,7 +3,6 @@ using JobTrackerApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;
namespace JobTrackerApi.Controllers;
@@ -18,8 +17,7 @@ namespace JobTrackerApi.Controllers;
[Authorize(AuthenticationSchemes = "local")]
public sealed class InterviewPrepController : ControllerBase
{
public sealed record SetFollowUpRequest(
[property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt, string? NextAction);
public sealed record SetFollowUpRequest(DateTime? FollowUpAt, string? NextAction);
private readonly UserManager<ApplicationUser> _users;
private readonly IInterviewPrepService _prep;
@@ -1,6 +1,5 @@
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using System.Text.Json.Serialization;
namespace JobTrackerApi.Controllers
{
@@ -95,7 +94,7 @@ namespace JobTrackerApi.Controllers
string? SalaryCurrency,
string? SalaryPeriod,
string? NextAction,
[property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt,
DateTime? FollowUpAt,
string? Notes,
string? Description,
string? TranslatedDescription,
@@ -123,7 +122,7 @@ namespace JobTrackerApi.Controllers
string? SalaryCurrency,
string? SalaryPeriod,
string? NextAction,
[property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt,
DateTime? FollowUpAt,
string? Notes,
string? Description,
string? TranslatedDescription,
@@ -154,7 +153,7 @@ namespace JobTrackerApi.Controllers
DateTime? MessageDate,
string? MessageSubject);
public sealed record FollowUpRequest([property: JsonConverter(typeof(FollowUpDateTimeConverter))] DateTime? FollowUpAt);
public sealed record FollowUpRequest(DateTime? FollowUpAt);
public sealed record JobEventDto(int Id, string Type, string? OldValue, string? NewValue, string? Note, DateTime At);
+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`.
@@ -1,117 +0,0 @@
import { readFile, writeFile } from 'node:fs/promises';
import { expect, test, type APIRequestContext } from '@playwright/test';
import { translations } from '../src/i18n/translations';
const apiUrl = 'http://localhost:5302/api';
const password = 'E2ePassword123!';
const fixtures = [
{ title: 'Date-only deadline', field: 'deadline', value: '2026-10-25', kind: 'deadline',
start: 'DTSTART;VALUE=DATE:20261025', end: 'DTEND;VALUE=DATE:20261026' },
{ title: 'UTC follow-up', field: 'followUpAt', value: '2026-10-25T00:15:00Z', kind: 'follow-up',
start: 'DTSTART:20261025T001500Z', end: 'DTEND:20261025T004500Z' },
{ title: 'First repeated hour', field: 'followUpAt', value: '2026-10-25T02:30:00+02:00', kind: 'follow-up',
start: 'DTSTART:20261025T003000Z', end: 'DTEND:20261025T010000Z' },
{ title: 'Second repeated hour', field: 'followUpAt', value: '2026-10-25T02:30:00+01:00', kind: 'follow-up',
start: 'DTSTART:20261025T013000Z', end: 'DTEND:20261025T020000Z' },
{ title: 'Legacy wall-clock follow-up', field: 'followUpAt', value: '2026-10-25T02:30:00', kind: 'follow-up',
start: 'DTSTART:20261025T023000Z', end: 'DTEND:20261025T030000Z' },
] as const;
async function login(api: APIRequestContext, email: string) {
expect((await api.post(`${apiUrl}/auth/login`, { data: { email, password } })).status()).toBe(200);
const me = await api.get(`${apiUrl}/auth/me`);
expect(me.status()).toBe(200);
const csrf = (await api.storageState()).cookies.find(cookie => cookie.name === 'XSRF-TOKEN');
expect(csrf).toBeDefined();
return { 'X-CSRF-TOKEN': csrf!.value, 'X-Session-Context': (await me.json()).sessionContext as string };
}
for (const variant of [
{ language: 'en', locale: 'en-GB', mode: 'light', timezoneId: 'Europe/Oslo', viewport: { width: 1440, height: 900 } },
{ language: 'nb', locale: 'nb-NO', mode: 'dark', timezoneId: 'America/Los_Angeles', viewport: { width: 390, height: 844 } },
] as const) {
test.describe(`calendar precision ${variant.language}`, () => {
test.use({ timezoneId: variant.timezoneId, viewport: variant.viewport });
test('recorded dates and ICS retain precision through the autumn DST transition', async ({ page, context, playwright }, info) => {
test.setTimeout(120_000);
expect(process.env.PLAYWRIGHT_REUSE_SERVERS).not.toBe('true');
expect(info.config.metadata.isolatedDataRoot).toEqual(expect.any(String));
await context.route('**/*', route => {
const url = new URL(route.request().url());
return ['localhost', '127.0.0.1'].includes(url.hostname) || ['blob:', 'data:', 'about:'].includes(url.protocol)
? route.continue() : route.abort();
});
const admin = await playwright.request.newContext();
let headers: Record<string, string>;
try {
const adminHeaders = await login(admin, 'e2e@example.test');
const email = `calendar-dst-${Date.now()}-${variant.language}@example.test`;
expect((await admin.post(`${apiUrl}/users`, { headers: adminHeaders, data: { email, password, roles: [] } })).status()).toBe(200);
headers = await login(page.request, email);
} finally {
await admin.dispose();
}
expect((await page.request.put(`${apiUrl}/auth/preferences/language`, {
headers, data: { language: variant.language === 'nb' ? 'nb-NO' : 'en' },
})).status()).toBe(204);
await page.addInitScript(({ language, mode }) => {
localStorage.setItem('uiLanguage', language);
localStorage.setItem('jobtracker.themeMode', mode);
}, { language: variant.language, mode: variant.mode });
const company = await page.request.post(`${apiUrl}/companies`, { headers, data: { name: 'Synthetic calendar company' } });
expect(company.status()).toBe(201);
const companyId = (await company.json()).id as number;
const jobs = [];
for (const fixture of fixtures) {
const response = await page.request.post(`${apiUrl}/jobapplications`, {
headers, data: { companyId, jobTitle: fixture.title, status: 'Interview', [fixture.field]: fixture.value },
});
expect(response.status()).toBe(201);
jobs.push({ ...fixture, id: (await response.json()).id as number });
}
await page.clock.setFixedTime(new Date('2026-10-25T12:00:00Z'));
await page.goto('/reminders');
const t = translations[variant.language];
const calendar = page.getByRole('region', { name: t.calendarAgendaTitle, exact: true });
const dateLabel = new Intl.DateTimeFormat(variant.locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(new Date('2026-10-25T12:00:00Z'));
const dateSection = calendar.getByRole('region', { name: dateLabel, exact: true });
await expect(dateSection.getByRole('link')).toHaveCount(jobs.length);
await expect(page.locator('html')).toHaveAttribute('data-color-scheme', variant.mode);
const observed = [];
for (const job of jobs) {
const row = dateSection.getByRole('article').filter({ hasText: job.title });
await expect(row.getByRole('link')).toHaveAttribute('href', `/jobs/${job.id}`);
const time = row.locator('time');
await expect(time).toHaveText(dateLabel);
observed.push({ ...job, recordedAt: await time.getAttribute('datetime') });
}
await page.getByRole('button', { name: t.calendarMonth, exact: true }).click();
const day = calendar.getByRole('table', { name: t.calendarMonth }).getByText('25', { exact: true, selector: 'button' });
await day.focus();
await page.keyboard.press('Enter');
await expect(day).toBeFocused();
await expect(day).toHaveAttribute('aria-pressed', 'true');
await expect(dateSection.getByRole('link')).toHaveCount(jobs.length);
const downloaded = [];
for (const job of jobs) {
await page.goto(`/jobs/${job.id}?section=tasks`);
const [file] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: t.calendarDownload, exact: true }).click(),
]);
expect(file.suggestedFilename()).toBe(`jobjakt-${job.id}-${job.kind}.ics`);
const content = await readFile(await file.path(), 'utf8');
const timestamps = content.split('\r\n').filter(line => /^(DTSTART|DTEND)/.test(line));
downloaded.push({ title: job.title, timestamps });
expect.soft(timestamps, job.title).toEqual([job.start, job.end]);
}
const evidence = info.outputPath('calendar-dst-matrix.json');
await writeFile(evidence, JSON.stringify({ variant, source: 'native API and Chromium downloads', observed, downloaded }, null, 2));
await info.attach('calendar-dst-matrix', { path: evidence, contentType: 'application/json' });
});
});
}