fix(kpi): rollup backfill plans from its own persisted watermark, not the periodic fold's MAX (KPI-1, WP4 task 4.10)

This commit is contained in:
Joseph Doherty
2026-12-03 10:23:13 -05:00
parent 5c67559a25
commit 2a41122a39
9 changed files with 438 additions and 23 deletions
@@ -0,0 +1,29 @@
namespace ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi;
/// <summary>
/// The KPI rollup backfill's own persisted progress marker (KPI-1, 2026-12): a single row
/// (<see cref="Id"/> = <see cref="SingletonId"/>) recording that every whole hour before
/// <see cref="BackfilledThroughUtc"/> has been folded by the one-shot backfill.
/// </summary>
/// <remarks>
/// The backfill used to plan from <c>MAX(KpiRollupHourly.HourStartUtc)</c>, 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.
/// </remarks>
public sealed class KpiRollupBackfillState
{
/// <summary>The id of the one and only row.</summary>
public const int SingletonId = 1;
/// <summary>Always <see cref="SingletonId"/>.</summary>
public int Id { get; set; }
/// <summary>Exclusive upper hour boundary (UTC) the backfill has folded through.</summary>
public DateTime BackfilledThroughUtc { get; set; }
/// <summary>When the marker last moved (UTC).</summary>
public DateTime UpdatedAtUtc { get; set; }
}
@@ -111,14 +111,47 @@ public interface IKpiHistoryRepository
/// <summary>
/// Returns the newest <c>KpiRollupHourly.HourStartUtc</c> across all series, or
/// <c>null</c> 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).
/// <c>null</c> when no rollups exist. No longer used to plan the backfill (KPI-1): the
/// periodic lookback fold advances this <c>MAX</c> seconds before the backfill reads it and it
/// says nothing about gaps below it — see <see cref="GetRollupBackfillWatermarkAsync"/>.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task resolving to the newest folded hour start, or <c>null</c> when empty.</returns>
Task<DateTime?> GetLatestRollupHourAsync(CancellationToken cancellationToken = default);
/// <summary>
/// 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 <c>null</c> when the
/// backfill has never completed a slice. The recorder plans the backfill from this — never
/// from the periodic fold's <see cref="GetLatestRollupHourAsync"/> — so an upgrade with raw
/// history and an interrupted backfill are both folded. The default implementation (test
/// doubles) reports no progress.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The backfilled-through hour, or <c>null</c>.</returns>
Task<DateTime?> GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default)
=> Task.FromResult<DateTime?>(null);
/// <summary>
/// Advances the backfill's persisted progress marker to <paramref name="backfilledThroughUtc"/>
/// — 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
/// <paramref name="onlyIfReachedUtc"/> = 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.
/// </summary>
/// <param name="backfilledThroughUtc">The exclusive hour boundary now folded through.</param>
/// <param name="onlyIfReachedUtc">
/// When set, advance only if the stored marker is already at or past this instant (contiguity);
/// never inserts the marker.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task AdvanceRollupBackfillWatermarkAsync(
DateTime backfilledThroughUtc, DateTime? onlyIfReachedUtc = null, CancellationToken cancellationToken = default)
=> Task.CompletedTask;
/// <summary>
/// Bulk-deletes hourly rollup rows whose
/// <see cref="ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupHourly.HourStartUtc"/> is
@@ -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;
/// <summary>
/// Maps the single-row <see cref="KpiRollupBackfillState"/> to the central
/// <c>KpiRollupBackfillState</c> table — the rollup backfill's own progress marker (KPI-1).
/// </summary>
public class KpiRollupBackfillStateEntityTypeConfiguration : IEntityTypeConfiguration<KpiRollupBackfillState>
{
/// <summary>
/// Configures the EF Core entity type mapping for <see cref="KpiRollupBackfillState"/>.
/// </summary>
/// <param name="builder">The entity type builder to configure.</param>
public void Configure(EntityTypeBuilder<KpiRollupBackfillState> 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();
}
}
@@ -293,6 +293,68 @@ public sealed class KpiHistoryRepository : IKpiHistoryRepository
.MaxAsync(r => (DateTime?)r.HourStartUtc, cancellationToken);
}
/// <inheritdoc />
public async Task<DateTime?> GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default)
{
return await _context.KpiRollupBackfillState
.AsNoTracking()
.Where(s => s.Id == KpiRollupBackfillState.SingletonId)
.Select(s => (DateTime?)s.BackfilledThroughUtc)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
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);
}
}
/// <inheritdoc />
public async Task PurgeRollupsOlderThanAsync(DateTime before, CancellationToken cancellationToken = default)
{
@@ -153,6 +153,9 @@ public class ScadaBridgeDbContext : DbContext, IDataProtectionKeyContext
/// <summary>Gets the set of hourly KPI rollups (pre-aggregated long-range trend backbone).</summary>
public DbSet<KpiRollupHourly> KpiRollupHourly => Set<KpiRollupHourly>();
/// <summary>Gets the single-row KPI rollup backfill progress marker (KPI-1).</summary>
public DbSet<KpiRollupBackfillState> KpiRollupBackfillState => Set<KpiRollupBackfillState>();
// Transport (bundle export/import)
/// <summary>Gets the set of recorded bundle-unlock attempts — the fleet-wide sliding window behind the per-client unlock throttle (register row 52).</summary>
public DbSet<BundleUnlockAttempt> BundleUnlockAttempts => Set<BundleUnlockAttempt>();
@@ -164,6 +164,18 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
/// </summary>
private bool _backfillDone;
/// <summary>Consecutive failed backfill slices in this actor lifetime (KPI-1).</summary>
private int _backfillFailures;
/// <summary>Consecutive failed slices after which the backfill gives up for this lifetime.</summary>
private const int MaxConsecutiveBackfillFailures = 3;
/// <summary>
/// Delay before re-planning (from the persisted watermark) after a failed backfill slice.
/// Settable for tests.
/// </summary>
internal static TimeSpan BackfillRetryDelay { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>Akka timer scheduler, assigned by the actor system via <see cref="IWithTimers"/>.</summary>
public ITimerScheduler Timers { get; set; } = null!;
@@ -191,9 +203,34 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
Receive<RollupComplete>(_ => _rollupInFlight = false); // lower the in-flight guard (success or fault)
Receive<BackfillTick>(_ => HandleBackfillTick());
Receive<BackfillPlan>(HandleBackfillPlan);
Receive<BackfillSliceComplete>(_ =>
Receive<BackfillSliceComplete>(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<IKpiHistoryRepository>();
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
}
/// <summary>
/// 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 <c>null</c>, 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
/// <c>MAX(KpiRollupHourly.HourStartUtc)</c>: 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 <c>null</c>, which the plan treats as "nothing backfilled", keeping the
/// full retention window (idempotent; best-effort, mirrors the other passes).
/// </summary>
private async Task<DateTime?> RunBackfillPlanPass(CancellationToken cancellationToken)
{
@@ -693,7 +738,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
{
await using var scope = _serviceProvider.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<IKpiHistoryRepository>();
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).
/// </summary>
private async Task RunBackfillPass(
private async Task<bool> 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<IKpiHistoryRepository>();
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
/// </summary>
internal sealed class BackfillSliceComplete
{
public static readonly BackfillSliceComplete Instance = new();
private BackfillSliceComplete() { }
/// <summary>The slice folded and the persisted watermark advanced.</summary>
public static readonly BackfillSliceComplete Success = new(true);
/// <summary>The slice failed; the backfill re-plans from the persisted watermark (KPI-1).</summary>
public static readonly BackfillSliceComplete Failure = new(false);
/// <summary>Backwards-compatible alias for <see cref="Success"/>.</summary>
public static BackfillSliceComplete Instance => Success;
private BackfillSliceComplete(bool succeeded) => Succeeded = succeeded;
/// <summary>Whether the slice folded successfully.</summary>
public bool Succeeded { get; }
}
}