From 188a9ad2d407c18fef6270a3806a829e00a8b349 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois <1+arnaud.dartois@noreply.localhost> Date: Sat, 7 Nov 2026 17:35:50 +0100 Subject: [PATCH] fix(web): retry Hangfire startup lock contention (#278) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #214 ## Résumé - Réessaie l’enregistrement complet et idempotent des jobs Hangfire après une `PostgreSqlDistributedLockException`, avec nouveau scope par tentative, délais bornés et annulation à l’arrêt. - Ajoute un test ciblé de contention transitoire et la skill projet `hangfire-startup-lock`. ## Vérifications - `dotnet test tests/Heimdall.Api.Tests/Heimdall.Api.Tests.csproj --no-restore --filter FullyQualifiedName~RecurringJobStartupRetryTests` — 1 passé. - `dotnet build src/Heimdall.Web/Heimdall.Web.csproj --no-restore` — réussi, 0 avertissement. - Compose disposable depuis la source: projet `heimdall214-261107080901-ae486b`, sans ports hôtes publiés; Central healthy et `hangfire.hash` confirme `recurring-job:agent-failover` avec cron `*/1 * * * *`. - Trap de nettoyage: aucun conteneur/volume/réseau du projet et tag `heimdall:heimdall214-261107080901-ae486b-acceptance` absent. Bases PostgreSQL/.NET conservées. Le critère de télémétrie après déploiement reste ouvert dans #214. Aucun déploiement réel n’est déclaré validé. Reviewed-on: https://sources.tordais.cc/arnaud.dartois/Heimdall/pulls/278 --- skills/hangfire-startup-lock/SKILL.md | 23 +++++++++++++ src/Heimdall.Web/Program.cs | 33 ++++++++++++++++--- .../RecurringJobStartupRetryTests.cs | 32 ++++++++++++++++++ 3 files changed, 83 insertions(+), 5 deletions(-) create mode 100644 skills/hangfire-startup-lock/SKILL.md create mode 100644 tests/Heimdall.Api.Tests/RecurringJobStartupRetryTests.cs diff --git a/skills/hangfire-startup-lock/SKILL.md b/skills/hangfire-startup-lock/SKILL.md new file mode 100644 index 0000000..8404add --- /dev/null +++ b/skills/hangfire-startup-lock/SKILL.md @@ -0,0 +1,23 @@ +--- +name: hangfire-startup-lock +description: Diagnose and recover Heimdall startup from transient Hangfire PostgreSQL recurring-job lock contention. +--- + +# Hangfire startup lock recovery + +Heimdall registers all recurring jobs synchronously after database migrations in `src/Heimdall.Web/Program.cs`. Hangfire's PostgreSQL storage acquires a distributed lock per recurring-job id during `AddOrUpdate`; `agent-failover` is currently the first registration after removing the legacy `heartbeat-monitor` id. + +## Implementation and diagnosis + +- Inspect the GlitchTip event stack, app start time, event timestamps, and `Program.cs`/`JobSetup.cs` line references. A timeout names the contended job key; it proves lock contention, not the number or identity of competing processes. +- Because registration is on the startup path, an unhandled provider lock timeout terminates startup even when caused by another instance. Retry only `Hangfire.PostgreSql.PostgreSqlDistributedLockException`; do not retry arbitrary registration/configuration failures. +- Retry the complete idempotent `ConfigureRecurringJobs` sequence with a new DI scope per attempt. Keep delay bounded, observe application shutdown cancellation, log attempts without connection details, and propagate the final exception so missing recurring schedules are not reported as successful startup. +- Cover transient recovery with a focused test that injects the provider exception and verifies a subsequent full registration attempt. + +## Acceptance + +1. Run `dotnet test tests/Heimdall.Api.Tests/Heimdall.Api.Tests.csproj --no-restore --filter FullyQualifiedName~RecurringJobStartupRetryTests` and build the Web project using the SDK pinned in `global.json`. +2. Run a disposable Compose project from the changed source with unique project name, generated credentials, loopback port, volume names, and a unique Heimdall image tag. Confirm the Web service becomes healthy and recurring Hangfire jobs are available in the isolated PostgreSQL storage. +3. Use an EXIT trap to tear down only that Compose project, verify its containers, volumes, and networks are absent, remove and verify absence of its exact locally built image tag, and remove temporary files. Preserve the original status and report cleanup failures. + +The Compose check demonstrates isolated startup and Hangfire storage integration; the synthetic unit test demonstrates contention recovery. Neither establishes that a particular production deployment had one or multiple replicas. Record deployed telemetry separately in Gitea issue #214. diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 82037bd..f5ce381 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -61,11 +61,7 @@ var isTesting = app.Environment.IsEnvironment(TestingEnvironment); var pgConnStr = Environment.GetEnvironmentVariable("DATABASE_URL") ?? app.Configuration.GetConnectionString("Default"); if (!isTesting && !string.IsNullOrEmpty(pgConnStr)) { - using (var scope = app.Services.CreateScope()) - { - var manager = scope.ServiceProvider.GetRequiredService(); - Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager); - } + await Program.ConfigureRecurringJobsAsync(app.Services, app.Lifetime.ApplicationStopping); } // ── Seed Identity roles (required in ALL environments, including Testing) ─ @@ -85,10 +81,37 @@ internal sealed record SignInRequest( public partial class Program { private const string TestingEnvironment = "Testing"; + private const int RecurringJobRegistrationAttempts = 5; // SonarQube S1118: partial class used by WebApplicationFactory needs a constructor. protected Program() { } + internal static async Task ConfigureRecurringJobsAsync(IServiceProvider services, CancellationToken cancellationToken) + { + var retryDelay = TimeSpan.FromSeconds(2); + var logger = services.GetRequiredService>(); + for (var attempt = 1; attempt <= RecurringJobRegistrationAttempts; attempt++) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + using var scope = services.CreateScope(); + var manager = scope.ServiceProvider.GetRequiredService(); + Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager); + return; + } + catch (Hangfire.PostgreSql.PostgreSqlDistributedLockException ex) + when (attempt < RecurringJobRegistrationAttempts) + { + logger.LogWarning(ex, + "Recurring Hangfire job registration hit a distributed lock (attempt {Attempt}/{MaxAttempts}); retrying in {DelaySeconds}s.", + attempt, RecurringJobRegistrationAttempts, retryDelay.TotalSeconds); + await Task.Delay(retryDelay, cancellationToken); + retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 16)); + } + } + } + private static string ResolveCategory(string key) { if (key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal)) diff --git a/tests/Heimdall.Api.Tests/RecurringJobStartupRetryTests.cs b/tests/Heimdall.Api.Tests/RecurringJobStartupRetryTests.cs new file mode 100644 index 0000000..f104005 --- /dev/null +++ b/tests/Heimdall.Api.Tests/RecurringJobStartupRetryTests.cs @@ -0,0 +1,32 @@ +using Hangfire; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Api.Tests; + +public sealed class RecurringJobStartupRetryTests +{ + [Fact] + public async Task ConfigureRecurringJobs_RetriesDistributedLockContention() + { + var manager = Substitute.For(); + var calls = 0; + manager.When(x => x.RemoveIfExists(Arg.Any())).Do(_ => + { + if (Interlocked.Increment(ref calls) == 1) + throw new Hangfire.PostgreSql.PostgreSqlDistributedLockException("synthetic lock contention"); + }); + + using var services = new ServiceCollection() + .AddLogging() + .AddSingleton(manager) + .BuildServiceProvider(); + + await Program.ConfigureRecurringJobsAsync(services, CancellationToken.None); + + calls.ShouldBe(2); + manager.Received(2).RemoveIfExists("heartbeat-monitor"); + } +}