using AttendanceHub.Sync.Persistence; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace AttendanceHub.Sync.Host; /// /// Independent delivery watchdog: "is the backlog growing?" asked on its own clock, NOT from inside /// the upload loop. /// /// It has to be independent for a specific reason. The failure on 2026-10-11 was that a config copy /// set upload.enabled=false, so the upload loop never ran at all: no UPLOAD_CYCLE lines, no errors, /// nothing to observe from inside that loop. A detector placed there could not have fired, because /// the code it lives in was not executing. Meanwhile the host stayed connected to all five devices, /// validated every window, wrote every punch to the ledger and emitted healthy health lines, while /// 530 punches (508 people) accrued as Pending with upload_attempts=0 for ten hours. /// /// So this watches the ledger rather than the uploader, which makes it blind to nothing: it behaves /// the same whether delivery is disabled, failing, hung, or absent. /// /// Predicate is GROWTH, not occupancy. Pending occupancy cannot distinguish a stall from a healthy /// host, because the ledger legitimately holds rows that will never leave it — device-clock garbage /// dated 2033 sits Pending forever and is correctly withheld. Any test of the form "pending > 0" /// would therefore alarm permanently on a perfectly healthy service. Pending that climbs across /// consecutive samples has no benign explanation: a working uploader drains it every 15s poll. /// /// The metric is Pending + Sending + Retry, NOT Pending alone. The outbox state machine is /// PENDING -> SENDING -> SENT | RETRY -> SENDING..., so a delivery that is actually broken does not /// leave rows sitting in Pending: every cycle CLAIMS them into SENDING and, on failure, parks them /// in RETRY. Pending is then drained every 15s and stays near zero while Retry grows without bound. /// A watchdog counting only Pending would be blind to precisely the failure it exists to catch — /// an unreachable endpoint or a revoked token — and would report a healthy, shrinking backlog while /// attendance piled up undelivered. Dlq and PermanentFailure are excluded on purpose: those are /// terminal verdicts on the data, not work still owed. /// /// Residual gap, covered elsewhere: if delivery is disabled AND no punches arrive, pending is flat /// and this stays quiet. That case is caught by the UPLOAD_INACTIVE warning at startup, which states /// the consequence rather than naming a mode. /// public sealed class DeliveryWatchdog : IAsyncDisposable { private readonly ISyncStore _store; private readonly Func> _deviceIds; private readonly ILogger _log; /// How often the backlog is sampled. public static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(30); /// /// Consecutive growing samples required before UPLOAD_STALL is raised. With the 30s poll this /// alarms after five minutes of unbroken growth — short enough to be noticed inside one working /// morning, long enough that a working uploader (15s per device, batch 200, local endpoint) /// cannot plausibly alias into it. /// public const int StallThreshold = 10; /// Emit a compact per-device status line every N polls, so routine health is visible /// without a flood: 5 devices at 5-minute intervals is ~600 lines a day. private const int StatusEveryNPolls = 10; private readonly Dictionary _watches = new(StringComparer.Ordinal); private Task? _loop; private int _polls; public DeliveryWatchdog(ISyncStore store, Func> deviceIds, ILogger? log = null) { _store = store; _deviceIds = deviceIds; _log = log ?? NullLogger.Instance; } private sealed class Watch { public long LastOwed = -1; public int GrowthStreak; public bool Alarmed; public DateTimeOffset FirstGrowthAt; } public void Start(CancellationToken ct) => _loop = Task.Run(() => RunAsync(ct), CancellationToken.None); public async Task RunAsync(CancellationToken ct) { _log.LogInformation( "DELIVERY_WATCHDOG_START pollMs={P} stallThresholdSamples={T} — independent of the upload loop; " + "watches ledger backlog growth, not uploader activity", (int)PollInterval.TotalMilliseconds, StallThreshold); using var timer = new PeriodicTimer(PollInterval); try { while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) { await SampleAsync(ct).ConfigureAwait(false); } } catch (OperationCanceledException) { // normal shutdown } _log.LogInformation("DELIVERY_WATCHDOG_STOP"); } /// One sampling pass. Public for tests, which drive it directly instead of waiting on a timer. public async Task SampleAsync(CancellationToken ct = default) { try { var deviceIds = _deviceIds()?.ToArray() ?? Array.Empty(); var status = new List(deviceIds.Length); foreach (var deviceId in deviceIds) { UploadOutboxStats stats; try { stats = await _store.GetUploadStatsAsync(deviceId, ct).ConfigureAwait(false); } catch (Exception ex) { _log.LogWarning(ex, "DELIVERY_WATCH_SAMPLE_FAILED device={Device} — cannot judge delivery", deviceId); continue; } if (!_watches.TryGetValue(deviceId, out var w)) { w = new Watch(); _watches[deviceId] = w; } // Undelivered work still owed. See the class comment for why this is Pending+Sending+Retry // and not Pending alone: a broken delivery CLAIMS Pending into Sending and parks it in // Retry every cycle, so Pending alone would read as a draining backlog. var owed = stats.Pending + stats.Sending + stats.Retry; Evaluate(deviceId, owed, stats.Pending, stats.Sending, stats.Retry, stats.Sent, stats.LastSuccessAt, w); status.Add($"{deviceId}:owed={owed},pending={stats.Pending},retry={stats.Retry},sent={stats.Sent}"); } _polls++; if (_polls % StatusEveryNPolls == 0 && status.Count > 0) { _log.LogInformation("DELIVERY_METRICS {Status} samples={Samples}", string.Join(" ", status), _polls); } } catch (Exception ex) { // A watchdog must never take the host down with it. _log.LogWarning(ex, "DELIVERY_WATCHDOG_ERROR — sample skipped"); } } /// Pending + Sending + Retry — the work the host still owes the API. private void Evaluate(string deviceId, long owed, long pending, long sending, long retry, long sent, DateTimeOffset? lastSuccessAt, Watch w) { var growing = owed > 0 && owed > w.LastOwed; if (!growing) { if (w.Alarmed) { _log.LogInformation( "UPLOAD_STALL_CLEARED device={Device} owed={O} pending={P} sending={Sn} retry={R} sent={Se} " + "stalledForSamples={N} — the backlog is no longer growing. Punches captured while stalled are " + "still in the ledger and are NOT lost; a later cycle claims them.", deviceId, owed, pending, sending, retry, sent, w.GrowthStreak); } w.GrowthStreak = 0; w.Alarmed = false; w.LastOwed = owed; return; } w.GrowthStreak++; if (w.GrowthStreak == 1) w.FirstGrowthAt = DateTimeOffset.UtcNow; w.LastOwed = owed; var firstAlarm = !w.Alarmed && w.GrowthStreak >= StallThreshold; var repeatAlarm = w.Alarmed && w.GrowthStreak % StallThreshold == 0; if (!firstAlarm && !repeatAlarm) return; w.Alarmed = true; // The split is the diagnosis, so it goes in the alarm. retry-dominated means the endpoint // answered and refused (bad token, rejected payload); pending-dominated means nothing ever // tried, which is the disabled-uploader shape. Two different causes, one alarm, told apart // from a single line without opening the database. var shape = retry > pending ? "RETRY_DOMINATED — the endpoint is reachable but refusing; check the API token and any server-side rejection." : "PENDING_DOMINATED — nothing is being attempted; check upload.enabled in the config this process actually loaded."; _log.LogWarning( "UPLOAD_STALL device={Device} owed={O} pending={P} sending={Sn} retry={R} consecutiveGrowingSamples={N} " + "stalledForSec={Sec} sent={Se} lastSuccessAt={Ls} — the backlog is growing and nothing has drained it for " + "{N} consecutive samples. This is DELIVERY, not acquisition. Punches are still being captured to the " + "ledger and are NOT lost, but they are NOT reaching the API either. " + shape, deviceId, owed, pending, sending, retry, w.GrowthStreak, (int)(DateTimeOffset.UtcNow - w.FirstGrowthAt).TotalSeconds, sent, lastSuccessAt?.ToString("o") ?? "(never)", w.GrowthStreak); } public ValueTask DisposeAsync() { _log.LogInformation( "DELIVERY_WATCHDOG_FINAL_STATE {State}", string.Join(" ", _watches.Select(kv => $"{kv.Key}:owed={kv.Value.LastOwed},streak={kv.Value.GrowthStreak},alarmed={kv.Value.Alarmed}"))); return ValueTask.CompletedTask; } }