From 2a41122a3936828a676e698f180bbb47bc1f23e6 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:23:13 -0500 Subject: [PATCH] fix(kpi): rollup backfill plans from its own persisted watermark, not the periodic fold's MAX (KPI-1, WP4 task 4.10) --- docs/requirements/Component-KpiHistory.md | 2 +- .../Entities/Kpi/KpiRollupBackfillState.cs | 29 +++ .../Repositories/IKpiHistoryRepository.cs | 39 +++- ...lupBackfillStateEntityTypeConfiguration.cs | 28 +++ .../Repositories/KpiHistoryRepository.cs | 62 +++++++ .../ScadaBridgeDbContext.cs | 3 + .../KpiHistoryRecorderActor.cs | 92 ++++++++-- .../Repositories/KpiHistoryRepositoryTests.cs | 34 ++++ .../KpiHistoryRecorderActorTests.cs | 172 +++++++++++++++++- 9 files changed, 438 insertions(+), 23 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Kpi/KpiRollupBackfillState.cs create mode 100644 src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/KpiRollupBackfillStateEntityTypeConfiguration.cs diff --git a/docs/requirements/Component-KpiHistory.md b/docs/requirements/Component-KpiHistory.md index 3f6251e8..3acc7999 100644 --- a/docs/requirements/Component-KpiHistory.md +++ b/docs/requirements/Component-KpiHistory.md @@ -92,7 +92,7 @@ Each source has a `SourceTimeout` (default 10 seconds) bounding the actual wait **Hourly rollup tick.** A third timer (`kpi-rollup`) fires every `RollupInterval` (default 1h). On each tick the recorder opens a per-tick DI scope and calls `IKpiHistoryRepository.FoldHourlyRollupsAsync` over the window `[TruncateToHour(now) − RollupLookbackHours, TruncateToHour(now))` — an **exclusive** upper bound at the current hour start, so the in-progress hour is never folded. The fold groups raw `KpiSample` rows by `(series, hour)`, applies the per-metric aggregation intent (sum for rate metrics, last-value for gauges — see Query), and **idempotently upserts** each `(Source, Metric, Scope, ScopeKey, HourStartUtc)` row. Re-folding the trailing lookback window (default 3h) rather than only the last hour is the self-heal for a **singleton-failover-missed tick**: because the upsert overwrites the aggregate in place, re-running the same window produces identical values (no double-count), so any complete hour a missed tick skipped is refilled on the next fold. A `_rollupInFlight` guard (mirroring `_sampleInFlight`) skips a tick while a prior fold is still running so two idempotent upserts never race on overlapping rows. During a **failover overlap** — the old singleton incarnation's in-flight fold and the new node's first fold both `Add`-ing the same `(series, hour)` row — the loser of the unique `IX_KpiRollupHourly_Series` upsert race discards its **whole fold pass** (a single `SaveChanges`), logged at Information and repaired by the next idempotent fold; when reading fold logs after a failover, the failure grain is the **pass, not the row** (arch-review 04 round 2, R5). Only a unique-key violation (SQL Server 2601/2627; the SQLite `UNIQUE constraint failed` fault on the test provider) is classified as that benign race — any other save failure propagates and the recorder logs it at Error, so a fold that faults for a real reason is no longer invisible. -**One-shot backfill.** So the 30 d / 90 d charts are not blank until enough wall-clock passes, the recorder runs a backfill on start (`kpi-rollup-backfill` timer) that folds the retention window, reusing the same `FoldHourlyRollupsAsync` path. The `FoldHourlyRollupsAsync` repository call reads raw samples **one hour at a time** (an untracked projection of a single hour, grouped in memory by series), so resident memory is bounded by one hour of samples regardless of the window; the backfill still folds the window in **≤24 h slices, oldest-first** — one bounded slice per fold — rather than handing the fold the full 90-day window at once (which at fleet volume is tens of millions of rows in one tracked pass). Between slices it lowers its in-flight guard so periodic folds **interleave** instead of stalling behind the historical pass; a periodic fold and a backfill slice strictly alternate through the single `_rollupInFlight`/`_backfillInFlight` gate pair, so the two idempotent upserts never race on overlapping rows. On a **failover restart** the plan first consults the `IKpiHistoryRepository.GetLatestRollupHourAsync` watermark: if the newest folded hour is already within `RollupLookbackHours` of now (the common case) the whole historical pass is **skipped** — the periodic fold's lookback covers the tail — otherwise the window is **shrunk to the un-rolled tail** `[watermark, TruncateToHour(now))` (re-folding the watermark hour itself as an idempotent safety margin) instead of the full `RetentionDays` floor. A `_backfillDone` latch makes the whole pass at-most-once per actor lifetime, and it defers (re-arms) while a periodic fold is in flight. Being an idempotent upsert, it is safe (idempotent) to re-run on a later failover restart; the watermark fast-path makes the failover re-run cheap as well. +**One-shot backfill.** So the 30 d / 90 d charts are not blank until enough wall-clock passes, the recorder runs a backfill on start (`kpi-rollup-backfill` timer) that folds the retention window, reusing the same `FoldHourlyRollupsAsync` path. The `FoldHourlyRollupsAsync` repository call reads raw samples **one hour at a time** (an untracked projection of a single hour, grouped in memory by series), so resident memory is bounded by one hour of samples regardless of the window; the backfill still folds the window in **≤24 h slices, oldest-first** — one bounded slice per fold — rather than handing the fold the full 90-day window at once (which at fleet volume is tens of millions of rows in one tracked pass). Between slices it lowers its in-flight guard so periodic folds **interleave** instead of stalling behind the historical pass; a periodic fold and a backfill slice strictly alternate through the single `_rollupInFlight`/`_backfillInFlight` gate pair, so the two idempotent upserts never race on overlapping rows. The plan reads the backfill's **own persisted watermark** — the single-row `KpiRollupBackfillState` table (`IKpiHistoryRepository.GetRollupBackfillWatermarkAsync`; migration `AddKpiRollupBackfillState`), the exclusive hour boundary its completed slices have folded through — never the periodic fold's `MAX(KpiRollupHourly.HourStartUtc)` (KPI-1, 2026-12: the periodic fold writes the last `RollupLookbackHours` seconds before the plan ran, so whenever samples existed in that window the backfill latched itself "current" and folded nothing — an upgrade onto 90 days of raw samples never got its 30 d/90 d history, and an interrupted backfill was never resumed). If the watermark is already within `RollupLookbackHours` of now the historical pass is **skipped**; otherwise the window is `[max(watermark, retention floor), TruncateToHour(now))` — the full retention window on a fresh install or after the upgrade. Each slice advances the watermark only after it folds; a failed slice drops the remaining queue and re-plans from the watermark after 5 min (three consecutive failures give up until the next singleton start), so the marker never jumps a gap. Once the backfill has completed, each periodic fold advances the marker too, but only when it already reaches that fold's lower bound (`onlyIfReachedUtc`) — contiguous, never created by the periodic fold — so a later restart plans only the short tail. A `_backfillDone` latch makes the whole pass at-most-once per actor lifetime, and it defers (re-arms) while a periodic fold is in flight. Being an idempotent upsert, it is safe (idempotent) to re-run on a later failover restart; the watermark fast-path makes the failover re-run cheap as well. **Retention.** A daily purge timer (`PurgeInterval`, default 24h) now runs **both** purges: raw `KpiSample` rows older than `RetentionDays` (default 90) via `IKpiHistoryRepository.PurgeOlderThanAsync`, **and** hourly rollup rows older than `RollupRetentionDays` (default 365) via `IKpiHistoryRepository.PurgeRollupsOlderThanAsync` (a one-hour-sliced batched DELETE mirroring the raw purge). Rollups deliberately **outlive** raw samples so long-range trend charts have data after the raw rows are purged; the options validator enforces `RollupRetentionDays >= RetentionDays` so a window never falls into a hole where raw is purged but no rollup exists. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Kpi/KpiRollupBackfillState.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Kpi/KpiRollupBackfillState.cs new file mode 100644 index 00000000..3bd83201 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Kpi/KpiRollupBackfillState.cs @@ -0,0 +1,29 @@ +namespace ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi; + +/// +/// The KPI rollup backfill's own persisted progress marker (KPI-1, 2026-12): a single row +/// ( = ) recording that every whole hour before +/// has been folded by the one-shot backfill. +/// +/// +/// The backfill used to plan from MAX(KpiRollupHourly.HourStartUtc), which the periodic +/// lookback fold advances seconds before the backfill reads it — so the backfill was skipped +/// whenever samples existed in the last few hours, and an interrupted backfill was never resumed. +/// This marker moves only when a backfill slice folds successfully, so it says exactly how far +/// the backfill got. Persistence-ignorant POCO; the EF mapping lives in the Configuration +/// Database component. +/// +public sealed class KpiRollupBackfillState +{ + /// The id of the one and only row. + public const int SingletonId = 1; + + /// Always . + public int Id { get; set; } + + /// Exclusive upper hour boundary (UTC) the backfill has folded through. + public DateTime BackfilledThroughUtc { get; set; } + + /// When the marker last moved (UTC). + public DateTime UpdatedAtUtc { get; set; } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs index 774f9a11..b3759858 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IKpiHistoryRepository.cs @@ -111,14 +111,47 @@ public interface IKpiHistoryRepository /// /// Returns the newest KpiRollupHourly.HourStartUtc across all series, or - /// null when no rollups exist. The recorder's one-shot backfill consults - /// this watermark to skip (or shrink to) the un-rolled tail instead of re-folding - /// the whole raw-retention window on every failover (arch-review 04 round 2, R1). + /// null when no rollups exist. No longer used to plan the backfill (KPI-1): the + /// periodic lookback fold advances this MAX seconds before the backfill reads it and it + /// says nothing about gaps below it — see . /// /// Cancellation token. /// A task resolving to the newest folded hour start, or null when empty. Task GetLatestRollupHourAsync(CancellationToken cancellationToken = default); + /// + /// Returns the rollup backfill's OWN persisted progress marker (KPI-1): the exclusive hour + /// boundary every whole hour before which the backfill has folded, or null when the + /// backfill has never completed a slice. The recorder plans the backfill from this — never + /// from the periodic fold's — so an upgrade with raw + /// history and an interrupted backfill are both folded. The default implementation (test + /// doubles) reports no progress. + /// + /// Cancellation token. + /// The backfilled-through hour, or null. + Task GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default) + => Task.FromResult(null); + + /// + /// Advances the backfill's persisted progress marker to + /// — monotonically: a value at or below the stored one is a no-op. Called after each backfill + /// slice folds successfully, and after each periodic fold with + /// = the fold's lower bound, so a COMPLETED backfill's + /// marker keeps pace with the periodic fold without ever jumping a gap (the marker moves only + /// when it already reaches the fold window; it is never created that way). The default + /// implementation (test doubles) does nothing. + /// + /// The exclusive hour boundary now folded through. + /// + /// When set, advance only if the stored marker is already at or past this instant (contiguity); + /// never inserts the marker. + /// + /// Cancellation token. + /// A task that represents the asynchronous operation. + Task AdvanceRollupBackfillWatermarkAsync( + DateTime backfilledThroughUtc, DateTime? onlyIfReachedUtc = null, CancellationToken cancellationToken = default) + => Task.CompletedTask; + /// /// Bulk-deletes hourly rollup rows whose /// is diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/KpiRollupBackfillStateEntityTypeConfiguration.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/KpiRollupBackfillStateEntityTypeConfiguration.cs new file mode 100644 index 00000000..1eed463b --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/KpiRollupBackfillStateEntityTypeConfiguration.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi; + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Configurations; + +/// +/// Maps the single-row to the central +/// KpiRollupBackfillState table — the rollup backfill's own progress marker (KPI-1). +/// +public class KpiRollupBackfillStateEntityTypeConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the EF Core entity type mapping for . + /// + /// The entity type builder to configure. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("KpiRollupBackfillState"); + + // A fixed singleton key, never store-generated. + builder.HasKey(s => s.Id); + builder.Property(s => s.Id).ValueGeneratedNever(); + + builder.Property(s => s.BackfilledThroughUtc).IsRequired(); + builder.Property(s => s.UpdatedAtUtc).IsRequired(); + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs index a0692df4..0521e9b2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs @@ -293,6 +293,68 @@ public sealed class KpiHistoryRepository : IKpiHistoryRepository .MaxAsync(r => (DateTime?)r.HourStartUtc, cancellationToken); } + /// + public async Task GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default) + { + return await _context.KpiRollupBackfillState + .AsNoTracking() + .Where(s => s.Id == KpiRollupBackfillState.SingletonId) + .Select(s => (DateTime?)s.BackfilledThroughUtc) + .FirstOrDefaultAsync(cancellationToken); + } + + /// + public async Task AdvanceRollupBackfillWatermarkAsync( + DateTime backfilledThroughUtc, DateTime? onlyIfReachedUtc = null, CancellationToken cancellationToken = default) + { + var now = DateTime.UtcNow; + var reached = onlyIfReachedUtc ?? DateTime.MinValue; + // Monotonic (only ever moves forward) and, when asked, contiguous (only when the marker + // already reaches the folded window). One statement, so a concurrent writer (a failover + // overlap) cannot move it back. + var moved = await _context.KpiRollupBackfillState + .Where(s => s.Id == KpiRollupBackfillState.SingletonId + && s.BackfilledThroughUtc < backfilledThroughUtc + && s.BackfilledThroughUtc >= reached) + .ExecuteUpdateAsync(set => set + .SetProperty(s => s.BackfilledThroughUtc, backfilledThroughUtc) + .SetProperty(s => s.UpdatedAtUtc, now), cancellationToken); + if (moved > 0 || onlyIfReachedUtc is not null) + { + // A contiguity-guarded advance never creates the marker: only the backfill does. + return; + } + + var exists = await _context.KpiRollupBackfillState + .AnyAsync(s => s.Id == KpiRollupBackfillState.SingletonId, cancellationToken); + if (exists) + { + return; // already at or past this boundary + } + + _context.KpiRollupBackfillState.Add(new KpiRollupBackfillState + { + Id = KpiRollupBackfillState.SingletonId, + BackfilledThroughUtc = backfilledThroughUtc, + UpdatedAtUtc = now, + }); + try + { + await _context.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Lost a first-insert race — the winner's row stands; re-apply the monotonic update. + _context.ChangeTracker.Clear(); + await _context.KpiRollupBackfillState + .Where(s => s.Id == KpiRollupBackfillState.SingletonId + && s.BackfilledThroughUtc < backfilledThroughUtc) + .ExecuteUpdateAsync(set => set + .SetProperty(s => s.BackfilledThroughUtc, backfilledThroughUtc) + .SetProperty(s => s.UpdatedAtUtc, now), cancellationToken); + } + } + /// public async Task PurgeRollupsOlderThanAsync(DateTime before, CancellationToken cancellationToken = default) { diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs index d72c4b04..01cacdff 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs @@ -153,6 +153,9 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext /// Gets the set of hourly KPI rollups (pre-aggregated long-range trend backbone). public DbSet KpiRollupHourly => Set(); + /// Gets the single-row KPI rollup backfill progress marker (KPI-1). + public DbSet KpiRollupBackfillState => Set(); + // Transport (bundle export/import) /// Gets the set of recorded bundle-unlock attempts — the fleet-wide sliding window behind the per-client unlock throttle (register row 52). public DbSet BundleUnlockAttempts => Set(); diff --git a/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs b/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs index d0af3d48..af35e623 100644 --- a/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs @@ -164,6 +164,18 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers /// private bool _backfillDone; + /// Consecutive failed backfill slices in this actor lifetime (KPI-1). + private int _backfillFailures; + + /// Consecutive failed slices after which the backfill gives up for this lifetime. + private const int MaxConsecutiveBackfillFailures = 3; + + /// + /// Delay before re-planning (from the persisted watermark) after a failed backfill slice. + /// Settable for tests. + /// + internal static TimeSpan BackfillRetryDelay { get; set; } = TimeSpan.FromMinutes(5); + /// Akka timer scheduler, assigned by the actor system via . public ITimerScheduler Timers { get; set; } = null!; @@ -191,9 +203,34 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers Receive(_ => _rollupInFlight = false); // lower the in-flight guard (success or fault) Receive(_ => HandleBackfillTick()); Receive(HandleBackfillPlan); - Receive(_ => + Receive(complete => { _backfillInFlight = false; // release the fold path BETWEEN slices (R1) + + if (!complete.Succeeded) + { + // KPI-1: the persisted watermark stops at the last slice that folded, so the + // remaining queue is dropped and the backfill re-plans from that watermark after a + // delay — a later slice must never advance the marker past a gap. A few + // consecutive failures give up for this actor lifetime; the next singleton start + // resumes from the watermark. + _backfillSlices.Clear(); + _backfillFailures++; + if (_backfillFailures >= MaxConsecutiveBackfillFailures) + { + _backfillDone = true; + _logger.LogWarning( + "KPI rollup backfill stopped after {Failures} consecutive failed slices; it resumes " + + "from its persisted watermark on the next singleton start.", + _backfillFailures); + return; + } + + Timers.StartSingleTimer(BackfillTimerKey, BackfillTick.Instance, BackfillRetryDelay); + return; + } + + _backfillFailures = 0; if (_backfillSlices.Count == 0) { _backfillDone = true; // latch: at most once per actor lifetime (unchanged semantics) @@ -536,6 +573,11 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers await using var scope = _serviceProvider.CreateAsyncScope(); var repository = scope.ServiceProvider.GetRequiredService(); await repository.FoldHourlyRollupsAsync(fromHourUtc, toHourUtc, cancellationToken); + + // KPI-1: keep a COMPLETED backfill's marker current — it moves only when it already + // reaches this fold's window, so it can never jump a gap the backfill has not folded. + await repository.AdvanceRollupBackfillWatermarkAsync( + toHourUtc, onlyIfReachedUtc: fromHourUtc, cancellationToken: cancellationToken); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -602,11 +644,11 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers RunBackfillPass(slice.FromHourUtc, slice.ToHourUtc, cancellationToken).PipeTo( Self, - success: () => BackfillSliceComplete.Instance, + success: ok => ok ? BackfillSliceComplete.Success : BackfillSliceComplete.Failure, failure: ex => { _logger.LogError(ex, "KPI rollup backfill slice faulted unexpectedly."); - return BackfillSliceComplete.Instance; + return BackfillSliceComplete.Failure; }); } @@ -658,7 +700,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers _backfillInFlight = false; _backfillDone = true; _logger.LogInformation( - "KPI rollup backfill skipped — rollups current through {Watermark:o}.", plan.Watermark); + "KPI rollup backfill skipped — the backfill has already folded through {Watermark:o}.", plan.Watermark); return; } @@ -682,10 +724,13 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers } /// - /// Resolves the newest folded rollup hour (the backfill watermark) off the actor thread in a - /// fresh DI scope. Never faults — on cancellation or error it returns null, which the - /// plan treats as "no rollups", keeping the full retention window (best-effort, mirrors the - /// other passes). + /// Resolves the backfill's OWN persisted watermark (KPI-1 — the hour boundary its completed + /// slices have folded through) off the actor thread in a fresh DI scope. Deliberately NOT + /// MAX(KpiRollupHourly.HourStartUtc): the periodic lookback fold advances that seconds + /// before this runs, so it used to latch the backfill "current" on every start that had + /// recent samples, and it says nothing about gaps below it. Never faults — on cancellation or + /// error it returns null, which the plan treats as "nothing backfilled", keeping the + /// full retention window (idempotent; best-effort, mirrors the other passes). /// private async Task RunBackfillPlanPass(CancellationToken cancellationToken) { @@ -693,7 +738,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers { await using var scope = _serviceProvider.CreateAsyncScope(); var repository = scope.ServiceProvider.GetRequiredService(); - return await repository.GetLatestRollupHourAsync(cancellationToken); + return await repository.GetRollupBackfillWatermarkAsync(cancellationToken); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -715,7 +760,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers /// disrupt startup. The fold method returns no count, so each slice is logged at Debug with its /// window and elapsed wall time (the queue-drained completion is logged at Information). /// - private async Task RunBackfillPass( + private async Task RunBackfillPass( DateTime fromHourUtc, DateTime toHourUtc, CancellationToken cancellationToken) { var startedAt = DateTime.UtcNow; @@ -725,17 +770,25 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers var repository = scope.ServiceProvider.GetRequiredService(); await repository.FoldHourlyRollupsAsync(fromHourUtc, toHourUtc, cancellationToken); + // KPI-1: record the backfill's own progress only once the slice has folded, so the + // marker means exactly "every hour before this is rolled up". + await repository.AdvanceRollupBackfillWatermarkAsync(toHourUtc, cancellationToken: cancellationToken); + _logger.LogDebug( "KPI rollup backfill slice folded [{FromHour:o}, {ToHour:o}) in {ElapsedMs:F0} ms.", fromHourUtc, toHourUtc, (DateTime.UtcNow - startedAt).TotalMilliseconds); + return true; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { - // Shutdown interrupted the backfill; a failover re-runs it (idempotent). Not a failure. + // Shutdown interrupted the backfill; the next singleton resumes from the persisted + // watermark (idempotent). Not a failure worth retrying in this lifetime. + return true; } catch (Exception ex) { - _logger.LogError(ex, "KPI rollup backfill failed unexpectedly."); + _logger.LogError(ex, "KPI rollup backfill slice [{FromHour:o}, {ToHour:o}) failed.", fromHourUtc, toHourUtc); + return false; } } @@ -823,7 +876,18 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers /// internal sealed class BackfillSliceComplete { - public static readonly BackfillSliceComplete Instance = new(); - private BackfillSliceComplete() { } + /// The slice folded and the persisted watermark advanced. + public static readonly BackfillSliceComplete Success = new(true); + + /// The slice failed; the backfill re-plans from the persisted watermark (KPI-1). + public static readonly BackfillSliceComplete Failure = new(false); + + /// Backwards-compatible alias for . + public static BackfillSliceComplete Instance => Success; + + private BackfillSliceComplete(bool succeeded) => Succeeded = succeeded; + + /// Whether the slice folded successfully. + public bool Succeeded { get; } } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs index 39c1aa97..0cf950be 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/KpiHistoryRepositoryTests.cs @@ -487,6 +487,40 @@ public class KpiHistoryRepositoryTests Assert.Empty(ctx.ChangeTracker.Entries()); } + /// + /// KPI-1: the backfill's own watermark is absent until a slice advances it, then moves only + /// forward, and a contiguity-guarded advance neither creates it nor jumps a gap. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RollupBackfillWatermark_IsMonotonic_AndContiguityGuarded() + { + await using var ctx = NewContext(); + var repo = new KpiHistoryRepository(ctx); + + Assert.Null(await repo.GetRollupBackfillWatermarkAsync()); + + // A contiguity-guarded advance (the periodic fold's) never creates the marker. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(5), onlyIfReachedUtc: Base.AddHours(2)); + Assert.Null(await repo.GetRollupBackfillWatermarkAsync()); + + // A backfill slice creates and advances it. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(24)); + Assert.Equal(Base.AddHours(24), await repo.GetRollupBackfillWatermarkAsync()); + + // Never backwards. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(10)); + Assert.Equal(Base.AddHours(24), await repo.GetRollupBackfillWatermarkAsync()); + + // A periodic fold whose window starts past the marker (a gap) does not move it… + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(30), onlyIfReachedUtc: Base.AddHours(27)); + Assert.Equal(Base.AddHours(24), await repo.GetRollupBackfillWatermarkAsync()); + + // …one that the marker reaches does. + await repo.AdvanceRollupBackfillWatermarkAsync(Base.AddHours(26), onlyIfReachedUtc: Base.AddHours(23)); + Assert.Equal(Base.AddHours(26), await repo.GetRollupBackfillWatermarkAsync()); + } + /// Verifies that the latest rollup hour is null when no rollups exist. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs index 83a81274..3a2e8905 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.KpiHistory.Tests/KpiHistoryRecorderActorTests.cs @@ -239,6 +239,57 @@ public class KpiHistoryRecorderActorTests : TestKit return Task.FromResult(_latestRollupHour); } } + + private DateTime? _backfillWatermark; + private int _backfillWatermarkQueryCount; + private readonly List<(DateTime Through, DateTime? OnlyIfReached)> _advances = new(); + + /// The backfill's own persisted watermark the fake reports (settable; KPI-1). + public DateTime? BackfillWatermark + { + get { lock (_gate) { return _backfillWatermark; } } + set { lock (_gate) { _backfillWatermark = value; } } + } + + /// Number of times the backfill plan pass read the backfill watermark. + public int BackfillWatermarkQueryCount + { + get { lock (_gate) { return _backfillWatermarkQueryCount; } } + } + + /// Every watermark advance requested, in call order. + public IReadOnlyList<(DateTime Through, DateTime? OnlyIfReached)> Advances + { + get { lock (_gate) { return _advances.ToArray(); } } + } + + /// + public Task GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default) + { + lock (_gate) + { + _backfillWatermarkQueryCount++; + return Task.FromResult(_backfillWatermark); + } + } + + /// + public Task AdvanceRollupBackfillWatermarkAsync( + DateTime backfilledThroughUtc, DateTime? onlyIfReachedUtc = null, CancellationToken cancellationToken = default) + { + lock (_gate) + { + _advances.Add((backfilledThroughUtc, onlyIfReachedUtc)); + var reached = onlyIfReachedUtc is null + || (_backfillWatermark is { } w && w >= onlyIfReachedUtc.Value); + if (reached && (onlyIfReachedUtc is null || _backfillWatermark is not null) + && (_backfillWatermark is null || _backfillWatermark < backfilledThroughUtc)) + { + _backfillWatermark = backfilledThroughUtc; + } + } + return Task.CompletedTask; + } } /// @@ -1168,7 +1219,7 @@ public class KpiHistoryRecorderActorTests : TestKit interval: TimeSpan.FromMilliseconds(50)); } - /// Verifies that the backfill is skipped when rollups are already current. + /// Verifies that the backfill is skipped when its own watermark is already current. [Fact] public void Backfill_Skips_WhenRollupsAlreadyCurrent() { @@ -1187,17 +1238,18 @@ public class KpiHistoryRecorderActorTests : TestKit RollupLookbackHours = 3, }); - // Rollups current through one hour ago — well inside the 3 h lookback tail. + // The BACKFILL's own watermark is current through one hour ago (KPI-1: the plan reads its + // own persisted marker, never the periodic fold's MAX(HourStartUtc)). var nowHour = new DateTime( DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); - repository.LatestRollupHour = nowHour - TimeSpan.FromHours(1); + repository.BackfillWatermark = nowHour - TimeSpan.FromHours(1); actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); // The plan pass must consult the watermark… AwaitAssert( - () => Assert.True(repository.LatestRollupHourQueryCount >= 1), + () => Assert.True(repository.BackfillWatermarkQueryCount >= 1), duration: TimeSpan.FromSeconds(3), interval: TimeSpan.FromMilliseconds(50)); @@ -1234,7 +1286,7 @@ public class KpiHistoryRecorderActorTests : TestKit DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); var watermark = nowHour - TimeSpan.FromDays(2); - repository.LatestRollupHour = watermark; + repository.BackfillWatermark = watermark; actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); @@ -1250,4 +1302,114 @@ public class KpiHistoryRecorderActorTests : TestKit duration: TimeSpan.FromSeconds(5), interval: TimeSpan.FromMilliseconds(50)); } + + /// + /// KPI-1 regression: the periodic fold has just written the last few hours (so + /// MAX(HourStartUtc) is an hour ago) but the backfill has never run — e.g. an upgrade onto 90 + /// days of raw samples. The backfill must fold the whole retention window, not latch itself + /// "current" from the periodic fold's MAX. + /// + [Fact] + public void Backfill_IgnoresThePeriodicFoldsMax_AndFoldsTheWholeWindow() + { + var repository = new RecordingRepository(); + var sp = BuildServiceProvider(repository, new HealthySource()); + var actor = CreateActor(sp, new KpiHistoryOptions + { + SampleInterval = TimeSpan.FromHours(1), + PurgeInterval = TimeSpan.FromHours(1), + RollupInterval = TimeSpan.FromHours(1), + RetentionDays = 5, + RollupLookbackHours = 3, + }); + + var nowHour = new DateTime( + DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, + DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); + repository.LatestRollupHour = nowHour - TimeSpan.FromHours(1); // periodic fold's MAX + repository.BackfillWatermark = null; // backfill never ran + + actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); + + AwaitAssert( + () => + { + var windows = repository.FoldWindows; + Assert.Equal(5, windows.Count); + Assert.Equal(nowHour - TimeSpan.FromDays(5), windows[0].FromHourUtc); + // Each folded slice advanced the backfill's own marker, ending at the plan's end. + Assert.Equal(nowHour, repository.BackfillWatermark); + }, + duration: TimeSpan.FromSeconds(5), + interval: TimeSpan.FromMilliseconds(50)); + } + + /// + /// KPI-1: an interrupted backfill resumes from its own watermark (the next singleton plans from + /// where the completed slices got to), not from the rollup table's MAX. + /// + [Fact] + public void Backfill_ResumesFromItsOwnWatermark() + { + var repository = new RecordingRepository(); + var sp = BuildServiceProvider(repository, new HealthySource()); + var actor = CreateActor(sp, new KpiHistoryOptions + { + SampleInterval = TimeSpan.FromHours(1), + PurgeInterval = TimeSpan.FromHours(1), + RollupInterval = TimeSpan.FromHours(1), + RetentionDays = 90, + RollupLookbackHours = 3, + }); + + var nowHour = new DateTime( + DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, + DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc); + repository.LatestRollupHour = nowHour - TimeSpan.FromHours(1); + repository.BackfillWatermark = nowHour - TimeSpan.FromDays(40); + + actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance); + + AwaitAssert( + () => + { + var windows = repository.FoldWindows; + Assert.NotEmpty(windows); + Assert.Equal(nowHour - TimeSpan.FromDays(40), windows[0].FromHourUtc); + }, + duration: TimeSpan.FromSeconds(5), + interval: TimeSpan.FromMilliseconds(50)); + } + + /// + /// KPI-1: the periodic fold extends a completed backfill's marker only with the contiguity + /// guard (only-if-reached = the fold's lower bound), so it can never jump a gap. + /// + [Fact] + public void PeriodicFold_AdvancesTheBackfillMarker_OnlyContiguously() + { + var repository = new RecordingRepository(); + var sp = BuildServiceProvider(repository, new HealthySource()); + var actor = CreateActor(sp, new KpiHistoryOptions + { + SampleInterval = TimeSpan.FromHours(1), + PurgeInterval = TimeSpan.FromHours(1), + RollupInterval = TimeSpan.FromHours(1), + RetentionDays = 90, + RollupLookbackHours = 3, + }); + + actor.Tell(KpiHistoryRecorderActor.RollupTick.Instance); + + AwaitAssert( + () => + { + var advance = Assert.Single(repository.Advances); + Assert.Equal(repository.FoldFromHourUtc, advance.OnlyIfReached); + Assert.Equal(repository.FoldToHourUtc, advance.Through); + Assert.Null(repository.BackfillWatermark); // never created by the periodic fold + }, + duration: TimeSpan.FromSeconds(5), + interval: TimeSpan.FromMilliseconds(50)); + } }