From 8edabc882cd2fa1973ca8bb88bf30e0cd3a07db5 Mon Sep 17 00:00:00 2001 From: cesnimda Date: Thu, 3 Dec 2026 18:49:56 +0100 Subject: [PATCH] fix(ai): keep polling after wrapped database interruptions --- .../AiOperationPollingTests.cs | 145 +++++++++++++++++ JobTrackerApi.Tests/AiOperationQueueTests.cs | 149 +++++++++++++++++- JobTrackerApi/Services/AiOperationQueue.cs | 15 +- docs/direct-roadmap/GITEA_PENDING.md | 6 +- 4 files changed, 308 insertions(+), 7 deletions(-) create mode 100644 JobTrackerApi.MariaDb.Tests/AiOperationPollingTests.cs diff --git a/JobTrackerApi.MariaDb.Tests/AiOperationPollingTests.cs b/JobTrackerApi.MariaDb.Tests/AiOperationPollingTests.cs new file mode 100644 index 00000000..cecf4e67 --- /dev/null +++ b/JobTrackerApi.MariaDb.Tests/AiOperationPollingTests.cs @@ -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 + { + ["Workers:AiOperationsEnabled"] = "true", + ["AiQueue:IdleDelayMs"] = "100", + }).Build(); + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddLogging(); + services.AddHttpContextAccessor(); + services.AddScoped(); + services.AddScoped(scope => scope.GetRequiredService()); + services.AddDbContext(options => options.UseMySql(database.ConnectionString, database.ServerVersion) + .AddInterceptors(lockTimeout)); + services.AddIdentityCore().AddRoles().AddEntityFrameworkStores(); + services.AddSingleton(TimeProvider.System); + services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + await using var provider = services.BuildServiceProvider(); + await using var seed = provider.CreateAsyncScope(); + var users = seed.ServiceProvider.GetRequiredService>(); + var roles = seed.ServiceProvider.GetRequiredService>(); + 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(); + 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(), [handler], + provider.GetRequiredService(), provider.GetRequiredService(), configuration); + using var hosted = new AiOperationHostedService(worker, configuration, NullLogger.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 Failure { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public override async ValueTask> NonQueryExecutingAsync(DbCommand command, + CommandEventData eventData, InterceptionResult 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 ExecuteAsync(AiOperationExecutionContext context, + IServiceProvider services, CancellationToken cancellationToken) + { + Assert.Equal(Owner, services.GetRequiredService().UserId); + Interlocked.Increment(ref _executions); + return Task.FromResult(new AiOperationExecutionResult("native-result", "ollama", "synthetic", "local_primary", 0, 0)); + } + } +} diff --git a/JobTrackerApi.Tests/AiOperationQueueTests.cs b/JobTrackerApi.Tests/AiOperationQueueTests.cs index 0a44e38a..c08dbcf3 100644 --- a/JobTrackerApi.Tests/AiOperationQueueTests.cs +++ b/JobTrackerApi.Tests/AiOperationQueueTests.cs @@ -8,6 +8,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Xunit; namespace JobTrackerApi.Tests; @@ -71,6 +72,141 @@ public sealed class AiOperationQueueTests } } + [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(); + configuration["Workers:AiOperationsEnabled"] = "true"; + configuration["AiQueue:IdleDelayMs"] = "100"; + configuration["AiQueue:LeaseSeconds"] = "30"; + var logger = new PollingLogger(); + using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService(), 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(() => finished); + Assert.Equal(19, Assert.IsType(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(); + 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(); + var store = scope.ServiceProvider.GetRequiredService(); + 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> ReaderExecutingAsync( + DbCommand command, CommandEventData eventData, InterceptionResult 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 + { + public TaskCompletionSource TransientFailure { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => logLevel == LogLevel.Warning; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func 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() { @@ -188,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; } @@ -196,10 +335,12 @@ public sealed class AiOperationQueueTests public Task 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().UserId; PrivacyPolicy = context.EffectivePrivacyPolicy; + OnResult?.Invoke(); return Task.FromResult(new AiOperationExecutionResult( "synthetic-result", "ollama", "qwen-test", "local_primary", 120, 40)); } @@ -218,9 +359,9 @@ public sealed class AiOperationQueueTests Handler = handler; } - public static async Task CreateAsync(int perUserCapacity = 10, ClaimInterruption? interruption = null) + public static async Task 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 { @@ -238,11 +379,11 @@ public sealed class AiOperationQueueTests services.AddScoped(provider => provider.GetRequiredService()); services.AddDbContext((_, options) => { - options.UseSqlite(connection); + options.UseSqlite(connection.ConnectionString); if (interruption is not null) options.AddInterceptors(interruption); }); services.AddIdentityCore().AddRoles().AddEntityFrameworkStores(); - services.AddSingleton(TimeProvider.System); + services.AddSingleton(clock ?? TimeProvider.System); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); diff --git a/JobTrackerApi/Services/AiOperationQueue.cs b/JobTrackerApi/Services/AiOperationQueue.cs index 038a2ef5..7d7a6484 100644 --- a/JobTrackerApi/Services/AiOperationQueue.cs +++ b/JobTrackerApi/Services/AiOperationQueue.cs @@ -3,6 +3,7 @@ using JobTrackerApi.Data; using JobTrackerApi.Models; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; +using MySqlConnector; namespace JobTrackerApi.Services; @@ -272,8 +273,7 @@ public sealed class AiOperationHostedService( { if (await worker.RunOnceAsync(stoppingToken, documentImportsOnly)) continue; } - catch (DbException failure) when (failure.IsTransient || - failure is Microsoft.Data.Sqlite.SqliteException { SqliteErrorCode: 5 or 6 }) + 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."); @@ -281,4 +281,15 @@ public sealed class AiOperationHostedService( 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 }; + } } diff --git a/docs/direct-roadmap/GITEA_PENDING.md b/docs/direct-roadmap/GITEA_PENDING.md index 318442b1..70e1756f 100644 --- a/docs/direct-roadmap/GITEA_PENDING.md +++ b/docs/direct-roadmap/GITEA_PENDING.md @@ -2,7 +2,11 @@ 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 regression failed before the fix when the hosted task exited with a synthetic SQLite busy error. After the fix, 38 affected .NET Release tests passed. The hosted fixture processed the queued operation in one attempt, cleared the lease, kept ownership, emitted one terminal notification and stopped on request. This tests a transient claim failure through the real hosted loop and SQLite store. Interruption during a running operation, ambiguous commits and native MariaDB qualification remain open. +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.