Compare commits

..

2 Commits

Author SHA1 Message Date
cesnimda 8edabc882c fix(ai): keep polling after wrapped database interruptions
CI and Deploy / test (pull_request) Failing after 4m15s
CI and Deploy / deploy (pull_request) Has been skipped
2026-12-03 18:49:56 +01:00
cesnimda 562b66c962 Keep the hosted AI queue polling after transient database failures 2026-12-02 18:48:47 +01:00
7 changed files with 395 additions and 152 deletions
@@ -0,0 +1,145 @@
using System.Data.Common;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging.Abstractions;
using MySqlConnector;
using Xunit;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class AiOperationPollingTests
{
private const string Owner = "queue-owner";
[Fact]
public async Task Hosted_worker_recovers_from_a_native_claim_lock_timeout()
{
await using var database = await MariaDbDatabase.CreateAsync();
var lockTimeout = new ClaimLockTimeout();
var handler = new SyntheticHandler();
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Workers:AiOperationsEnabled"] = "true",
["AiQueue:IdleDelayMs"] = "100",
}).Build();
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(configuration);
services.AddLogging();
services.AddHttpContextAccessor();
services.AddScoped<CurrentUserService>();
services.AddScoped<ICurrentUserService>(scope => scope.GetRequiredService<CurrentUserService>());
services.AddDbContext<JobTrackerContext>(options => options.UseMySql(database.ConnectionString, database.ServerVersion)
.AddInterceptors(lockTimeout));
services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
services.AddSingleton(TimeProvider.System);
services.AddScoped<UserOperationStore>();
services.AddSingleton<AiPrivacyPolicy>();
services.AddSingleton<AiOperationExecutionScope>();
await using var provider = services.BuildServiceProvider();
await using var seed = provider.CreateAsyncScope();
var users = seed.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roles = seed.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var user = new ApplicationUser { Id = Owner, UserName = "native-queue@example.test", AiEnabled = true };
Assert.True((await roles.CreateAsync(new IdentityRole("Premium"))).Succeeded);
Assert.True((await users.CreateAsync(user)).Succeeded);
Assert.True((await users.AddToRoleAsync(user, "Premium")).Succeeded);
var now = DateTime.UtcNow;
var operation = new UserOperation
{
OwnerUserId = Owner, TaskType = handler.TaskType, IdempotencyKey = "native-lock",
CreatedAtUtc = now, AvailableAtUtc = now, EntitlementDecision = "allowed", PrivacyPolicy = "local_only",
};
var db = seed.ServiceProvider.GetRequiredService<JobTrackerContext>();
db.UserOperations.Add(operation);
await db.SaveChangesAsync();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
await using var lockContext = database.Context(Owner);
await using var held = await lockContext.Database.BeginTransactionAsync(timeout.Token);
Assert.Equal(1, await lockContext.UserOperations.Where(row => row.Id == operation.Id)
.ExecuteUpdateAsync(set => set.SetProperty(row => row.Priority, 1), timeout.Token));
var worker = new AiOperationWorker(provider.GetRequiredService<IServiceScopeFactory>(), [handler],
provider.GetRequiredService<AiPrivacyPolicy>(), provider.GetRequiredService<AiOperationExecutionScope>(), configuration);
using var hosted = new AiOperationHostedService(worker, configuration, NullLogger<AiOperationHostedService>.Instance);
try
{
await hosted.StartAsync(timeout.Token);
var finished = await Task.WhenAny(hosted.ExecuteTask!, lockTimeout.Failure.Task).WaitAsync(timeout.Token);
if (finished == hosted.ExecuteTask) await finished;
var failure = await lockTimeout.Failure.Task;
Assert.Equal(1205, failure.Number);
Assert.True(failure.IsTransient);
var queued = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync(timeout.Token);
Assert.Equal(OperationStatuses.Queued, queued.Status);
Assert.Null(queued.LeaseToken);
Assert.Equal(0, queued.AttemptCount);
await held.RollbackAsync(timeout.Token);
UserOperation completed;
do
{
await Task.Delay(50, timeout.Token);
if (hosted.ExecuteTask!.IsCompleted) await hosted.ExecuteTask;
completed = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync(timeout.Token);
} while (completed.Status != OperationStatuses.Succeeded);
Assert.Equal(1, completed.AttemptCount);
Assert.Null(completed.LeaseToken);
Assert.Equal(Owner, completed.OwnerUserId);
Assert.Equal(1, handler.Executions);
Assert.Equal(Owner, (await db.UserNotifications.IgnoreQueryFilters().SingleAsync(timeout.Token)).OwnerUserId);
Assert.False(hosted.ExecuteTask!.IsCompleted);
}
finally
{
await hosted.StopAsync(timeout.Token);
}
}
private sealed class ClaimLockTimeout : DbCommandInterceptor
{
public TaskCompletionSource<MySqlException> Failure { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command,
CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (command.CommandText.StartsWith("UPDATE", StringComparison.Ordinal) &&
command.CommandText.Contains("`UserOperations`", StringComparison.Ordinal))
{
await using var setup = command.Connection!.CreateCommand();
setup.Transaction = command.Transaction;
setup.CommandText = "SET SESSION innodb_lock_wait_timeout = 1";
await setup.ExecuteNonQueryAsync(cancellationToken);
}
return result;
}
public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData,
CancellationToken cancellationToken = default)
{
if (eventData.Exception is MySqlException failure)
Failure.TrySetResult(failure);
return Task.CompletedTask;
}
}
private sealed class SyntheticHandler : IAiOperationHandler
{
private int _executions;
public int Executions => Volatile.Read(ref _executions);
public string TaskType => "synthetic.ai.mariadb";
public Task<AiOperationExecutionResult> ExecuteAsync(AiOperationExecutionContext context,
IServiceProvider services, CancellationToken cancellationToken)
{
Assert.Equal(Owner, services.GetRequiredService<ICurrentUserService>().UserId);
Interlocked.Increment(ref _executions);
return Task.FromResult(new AiOperationExecutionResult("native-result", "ollama", "synthetic", "local_primary", 0, 0));
}
}
}
@@ -1,134 +0,0 @@
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);
}
}
}
+208 -4
View File
@@ -1,17 +1,212 @@
using System.Data.Common;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
namespace JobTrackerApi.Tests;
public sealed class AiOperationQueueTests
{
[Fact]
public async Task Hosted_worker_survives_transient_claim_failure_and_completes_once()
{
var interruption = new ClaimInterruption();
await using var fixture = await Fixture.CreateAsync(interruption: interruption);
await fixture.SeedUserAsync("pro-1", pro: true);
await fixture.EnqueueAsync("pro-1", "recover");
var configuration = fixture.Provider.GetRequiredService<IConfiguration>();
configuration["Workers:AiOperationsEnabled"] = "true";
configuration["AiQueue:IdleDelayMs"] = "100";
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration,
Microsoft.Extensions.Logging.Abstractions.NullLogger<AiOperationHostedService>.Instance);
interruption.Armed = true;
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
await hosted.StartAsync(timeout.Token);
var finished = await Task.WhenAny(hosted.ExecuteTask!, interruption.PolledAfterRecovery.Task).WaitAsync(timeout.Token);
if (finished == hosted.ExecuteTask) await finished;
Assert.Same(interruption.PolledAfterRecovery.Task, finished);
}
finally
{
await hosted.StopAsync(timeout.Token);
}
await using var scope = fixture.Provider.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<JobTrackerContext>();
var operation = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync();
Assert.Equal(OperationStatuses.Succeeded, operation.Status);
Assert.Equal(1, operation.AttemptCount);
Assert.Null(operation.LeaseToken);
Assert.Equal("pro-1", fixture.Handler.OwnerUserId);
Assert.Single(await db.UserNotifications.IgnoreQueryFilters().ToListAsync());
}
private sealed class ClaimInterruption : DbCommandInterceptor
{
private int _polls;
public bool Armed { get; set; }
public TaskCompletionSource PolledAfterRecovery { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
if (Armed && command.CommandText.Contains("UserOperations", StringComparison.Ordinal) &&
command.CommandText.Contains("ORDER BY", StringComparison.Ordinal))
{
var poll = Interlocked.Increment(ref _polls);
if (poll == 1) throw new SqliteException("Synthetic busy claim", 5);
if (poll == 3) PolledAfterRecovery.TrySetResult();
}
return new(result);
}
}
[Theory]
[InlineData("retry")]
[InlineData("cancel")]
[InlineData("committed")]
[InlineData("permanent")]
public async Task Hosted_worker_recovers_a_terminal_database_interruption(string scenario)
{
var cancel = scenario == "cancel";
var committed = scenario == "committed";
var permanent = scenario == "permanent";
var commitInterruption = new TerminalCommitInterruption();
var clock = new AdjustableClock();
await using var fixture = await Fixture.CreateAsync(
interruption: committed ? commitInterruption : new TerminalSaveInterruption(permanent ? 19 : 5), clock: clock);
if (committed) fixture.Handler.OnResult = commitInterruption.Arm;
await fixture.SeedUserAsync("pro-1", pro: true);
await fixture.EnqueueAsync("pro-1", "recover-terminal");
var configuration = fixture.Provider.GetRequiredService<IConfiguration>();
configuration["Workers:AiOperationsEnabled"] = "true";
configuration["AiQueue:IdleDelayMs"] = "100";
configuration["AiQueue:LeaseSeconds"] = "30";
var logger = new PollingLogger();
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration, logger);
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(12));
try
{
await hosted.StartAsync(timeout.Token);
var finished = await Task.WhenAny(hosted.ExecuteTask!, logger.TransientFailure.Task).WaitAsync(timeout.Token);
if (permanent)
{
Assert.Same(hosted.ExecuteTask, finished);
var failure = await Assert.ThrowsAsync<DbUpdateException>(() => finished);
Assert.Equal(19, Assert.IsType<SqliteException>(failure.InnerException).SqliteErrorCode);
Assert.False(logger.TransientFailure.Task.IsCompleted);
return;
}
if (finished == hosted.ExecuteTask) await finished;
Assert.Same(logger.TransientFailure.Task, finished);
await using var scope = fixture.Provider.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<JobTrackerContext>();
var operation = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync(timeout.Token);
Assert.Equal(committed ? OperationStatuses.Succeeded : OperationStatuses.Running, operation.Status);
Assert.Equal(1, operation.AttemptCount);
if (committed) Assert.Null(operation.LeaseToken);
else Assert.NotNull(operation.LeaseToken);
Assert.Equal("pro-1", operation.OwnerUserId);
Assert.Equal(committed ? 1 : 0, await db.UserNotifications.IgnoreQueryFilters().CountAsync(timeout.Token));
if (cancel)
{
var currentUser = scope.ServiceProvider.GetRequiredService<CurrentUserService>();
var store = scope.ServiceProvider.GetRequiredService<UserOperationStore>();
using (currentUser.UseBackgroundUser("other-tenant"))
Assert.False(await store.RequestCancellationAsync(operation.Id, timeout.Token));
using (currentUser.UseBackgroundUser("pro-1"))
Assert.True(await store.RequestCancellationAsync(operation.Id, timeout.Token));
}
clock.Advance(TimeSpan.FromSeconds(31));
if (committed) await fixture.EnqueueAsync("pro-1", "after-ambiguous-commit");
var expected = cancel ? OperationStatuses.Cancelled : OperationStatuses.Succeeded;
var operationId = operation.Id;
bool subsequentWorkCompleted;
do
{
await Task.Delay(40, timeout.Token);
if (hosted.ExecuteTask!.IsCompleted) await hosted.ExecuteTask;
var rows = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().ToListAsync(timeout.Token);
operation = rows.Single(row => row.Id == operationId);
subsequentWorkCompleted = !committed || rows.Single(row => row.Id != operationId).Status == OperationStatuses.Succeeded;
} while (operation.Status != expected || !subsequentWorkCompleted);
Assert.Equal(cancel || committed ? 1 : 2, operation.AttemptCount);
Assert.Equal(cancel ? 1 : 2, fixture.Handler.Executions);
Assert.Null(operation.LeaseToken);
Assert.Equal(cancel ? null : "synthetic-result", operation.ResultReference);
var notifications = await db.UserNotifications.IgnoreQueryFilters().ToListAsync(timeout.Token);
Assert.Equal(committed ? 2 : 1, notifications.Count);
Assert.All(notifications, notification => Assert.Equal("pro-1", notification.OwnerUserId));
Assert.False(hosted.ExecuteTask!.IsCompleted);
}
finally
{
await hosted.StopAsync(timeout.Token);
}
}
private sealed class TerminalSaveInterruption(int errorCode) : DbCommandInterceptor
{
private int _interrupted;
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
if (command.CommandText.Contains("INSERT INTO \"UserNotifications\"", StringComparison.Ordinal)
&& Interlocked.Exchange(ref _interrupted, 1) == 0)
throw new SqliteException("Synthetic terminal save failure", errorCode);
return new(result);
}
}
private sealed class TerminalCommitInterruption : DbTransactionInterceptor
{
private int _state;
public void Arm() => Interlocked.CompareExchange(ref _state, 1, 0);
public override Task TransactionCommittedAsync(DbTransaction transaction, TransactionEndEventData eventData,
CancellationToken cancellationToken = default)
{
if (Interlocked.CompareExchange(ref _state, 2, 1) == 1)
throw new SqliteException("Synthetic lost reply after terminal commit", 5);
return Task.CompletedTask;
}
}
private sealed class PollingLogger : ILogger<AiOperationHostedService>
{
public TaskCompletionSource TransientFailure { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel == LogLevel.Warning;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
if (IsEnabled(logLevel)) TransientFailure.TrySetResult();
}
}
private sealed class AdjustableClock : TimeProvider
{
private long _ticks = DateTimeOffset.UtcNow.UtcTicks;
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
public void Advance(TimeSpan duration) => Interlocked.Add(ref _ticks, duration.Ticks);
}
[Fact]
public async Task Admission_is_pro_only_idempotent_bounded_and_contains_no_raw_payload()
{
@@ -129,6 +324,9 @@ public sealed class AiOperationQueueTests
private sealed class SyntheticHandler : IAiOperationHandler
{
private int _executions;
public int Executions => Volatile.Read(ref _executions);
public Action? OnResult { get; set; }
public string TaskType => "synthetic.ai";
public string? OwnerUserId { get; private set; }
public string? PrivacyPolicy { get; private set; }
@@ -137,10 +335,12 @@ public sealed class AiOperationQueueTests
public Task<AiOperationExecutionResult> ExecuteAsync(AiOperationExecutionContext context, IServiceProvider services, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _executions);
if (Failure is not null) throw Failure;
if (GenerationFailure is not null) throw GenerationFailure;
OwnerUserId = services.GetRequiredService<ICurrentUserService>().UserId;
PrivacyPolicy = context.EffectivePrivacyPolicy;
OnResult?.Invoke();
return Task.FromResult(new AiOperationExecutionResult(
"synthetic-result", "ollama", "qwen-test", "local_primary", 120, 40));
}
@@ -159,9 +359,9 @@ public sealed class AiOperationQueueTests
Handler = handler;
}
public static async Task<Fixture> CreateAsync(int perUserCapacity = 10)
public static async Task<Fixture> CreateAsync(int perUserCapacity = 10, IInterceptor? interruption = null, TimeProvider? clock = null)
{
var connection = new SqliteConnection("Data Source=:memory:");
var connection = new SqliteConnection($"Data Source=ai-queue-{Guid.NewGuid():N};Mode=Memory;Cache=Shared");
await connection.OpenAsync();
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
@@ -177,9 +377,13 @@ public sealed class AiOperationQueueTests
services.AddHttpContextAccessor();
services.AddScoped<CurrentUserService>();
services.AddScoped<ICurrentUserService>(provider => provider.GetRequiredService<CurrentUserService>());
services.AddDbContext<JobTrackerContext>((_, options) => options.UseSqlite(connection));
services.AddDbContext<JobTrackerContext>((_, options) =>
{
options.UseSqlite(connection.ConnectionString);
if (interruption is not null) options.AddInterceptors(interruption);
});
services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
services.AddSingleton(TimeProvider.System);
services.AddSingleton(clock ?? TimeProvider.System);
services.AddScoped<UserOperationStore>();
services.AddSingleton<AiPrivacyPolicy>();
services.AddSingleton<AiOperationExecutionScope>();
@@ -34,7 +34,8 @@ public sealed class CvProcessingOperationTests
var configuration = fixture.Provider.GetRequiredService<IConfiguration>();
configuration["Workers:AiOperationsEnabled"] = "false";
configuration["Workers:CvDocumentImportsEnabled"] = "true";
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration);
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration,
Microsoft.Extensions.Logging.Abstractions.NullLogger<AiOperationHostedService>.Instance);
await hosted.StartAsync(default);
try
{
+25 -3
View File
@@ -1,7 +1,9 @@
using System.Data.Common;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MySqlConnector;
namespace JobTrackerApi.Services;
@@ -251,7 +253,8 @@ public sealed class AiOperationWorker(
private static TimeSpan RetryDelay(int attempt) => TimeSpan.FromSeconds(Math.Min(60, (1 << Math.Min(attempt, 5)) + Random.Shared.Next(0, 4)));
}
public sealed class AiOperationHostedService(AiOperationWorker worker, IConfiguration configuration) : BackgroundService
public sealed class AiOperationHostedService(
AiOperationWorker worker, IConfiguration configuration, ILogger<AiOperationHostedService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
@@ -266,8 +269,27 @@ public sealed class AiOperationHostedService(AiOperationWorker worker, IConfigur
var idleDelayMs = Math.Clamp(configuration.GetValue("AiQueue:IdleDelayMs", 1000), 100, 10_000);
while (!stoppingToken.IsCancellationRequested)
{
if (!await worker.RunOnceAsync(stoppingToken, documentImportsOnly))
await Task.Delay(idleDelayMs, stoppingToken);
try
{
if (await worker.RunOnceAsync(stoppingToken, documentImportsOnly)) continue;
}
catch (Exception failure) when (IsTransientDatabaseFailure(failure))
{
// The store owns recovery of any persisted lease when polling resumes.
logger.LogWarning("AI operation polling paused after a transient database error.");
}
await Task.Delay(idleDelayMs, stoppingToken);
}
}
private static bool IsTransientDatabaseFailure(Exception failure)
{
// Pomelo's non-retrying execution strategy wraps transient provider errors.
if (failure is InvalidOperationException { InnerException: { } inner } &&
inner is MySqlException or DbUpdateException { InnerException: MySqlException })
failure = inner;
var providerError = failure is DbUpdateException update ? update.InnerException : failure;
return providerError is DbException { IsTransient: true }
or Microsoft.Data.Sqlite.SqliteException { SqliteErrorCode: 5 or 6 };
}
}
+15
View File
@@ -0,0 +1,15 @@
# Gitea continuation
The live Project 1 read on 2 December 2026 returned 101 open items. There were 32 Ready, 50 Blocked, 17 Backlog and two Testing. PR #130 was open and unmerged at `c05d6f89`. The backlog tool was run from the existing isolated migration checkout.
Issue #120 has a verified candidate on `codex/issue-120-ai-queue`, based on `ac64d2ee`. The original claim regression established SQLite polling recovery. The follow-up reproduced a polling exit on an EF-wrapped SQLite busy error during the terminal save and on Pomelo's wrapper around native MariaDB lock timeout 1205.
After the follow-up fix, 42 affected .NET Release tests passed. The SQLite fixtures prove that a rolled-back terminal save keeps the active lease until expiry, then allows one bounded retry or finalizes owner cancellation. Another tenant cannot cancel the operation. A lost reply after a successful commit preserves the original result and its single notification, and the worker polls a subsequent operation. The permanent SQLite error still faults the hosted task. MariaDB 12.2.2 passed the native claim-lock fixture. After rollback released the blocking transaction, the worker completed in one attempt with the correct owner, a cleared lease and one notification.
The injected terminal faults occur after the synthetic handler returns. Provider interruption during its execution and native MariaDB terminal-commit ambiguity were outside these fixtures. Publish the candidate and update the open issue with this evidence. Integration and production acceptance remain separate.
The live board move to Code Review and issue evidence note await authentication. The scoped credential file did not exist, the session had no `GITEA_TOKEN`, and the Playwright CLI reported no signed-in browser. The repository project REST endpoint returned 404. The public read through the existing board parser succeeded.
To resume board writes, sign in to the isolated Playwright session from the backlog tooling checkout using `playwright-cli.cmd -s=jobjakt-board open https://git.cesnimda.uk/cesnimda/jobtrackingapp/projects/1 --headed --browser=chrome`. Run `scripts/gitea-board.ps1 -Number 120 -Column 'Code Review'` without `-Apply` for a readback first. Apply only the current evidence-backed stage, then reload and verify. For issue notes use the scoped credential setup in the tooling README. Keep the token out of chat and files tracked by Git. Preserve the issue as open until its full criteria are met.
Next independent item is #121. Existing source still formats Companies dates in the viewer timezone and seeds editor inputs from the stored date prefix. The previous picker work covers user-selected dates. Reuse that evidence, define the legacy read/display contract and test display/edit/save in Los Angeles, Oslo and Kiritimati.
-10
View File
@@ -7,13 +7,3 @@ 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`.