Compare commits

..

1 Commits

Author SHA1 Message Date
cesnimda 562b66c962 Keep the hosted AI queue polling after transient database failures 2026-12-02 18:48:47 +01:00
4 changed files with 92 additions and 6 deletions
+65 -2
View File
@@ -1,9 +1,11 @@
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 Xunit;
@@ -12,6 +14,63 @@ 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);
}
}
[Fact]
public async Task Admission_is_pro_only_idempotent_bounded_and_contains_no_raw_payload()
{
@@ -159,7 +218,7 @@ public sealed class AiOperationQueueTests
Handler = handler;
}
public static async Task<Fixture> CreateAsync(int perUserCapacity = 10)
public static async Task<Fixture> CreateAsync(int perUserCapacity = 10, ClaimInterruption? interruption = null)
{
var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
@@ -177,7 +236,11 @@ 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);
if (interruption is not null) options.AddInterceptors(interruption);
});
services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
services.AddSingleton(TimeProvider.System);
services.AddScoped<UserOperationStore>();
@@ -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
{
+14 -3
View File
@@ -1,3 +1,4 @@
using System.Data.Common;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.AspNetCore.Identity;
@@ -251,7 +252,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 +268,17 @@ 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 (DbException failure) when (failure.IsTransient ||
failure is Microsoft.Data.Sqlite.SqliteException { SqliteErrorCode: 5 or 6 })
{
// 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);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
# 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 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.
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.