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:
@@ -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.
|
**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.
|
**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.
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
/// <summary>
|
||||||
/// Returns the newest <c>KpiRollupHourly.HourStartUtc</c> across all series, or
|
/// 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
|
/// <c>null</c> when no rollups exist. No longer used to plan the backfill (KPI-1): the
|
||||||
/// this watermark to skip (or shrink to) the un-rolled tail instead of re-folding
|
/// periodic lookback fold advances this <c>MAX</c> seconds before the backfill reads it and it
|
||||||
/// the whole raw-retention window on every failover (arch-review 04 round 2, R1).
|
/// says nothing about gaps below it — see <see cref="GetRollupBackfillWatermarkAsync"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="cancellationToken">Cancellation token.</param>
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
/// <returns>A task resolving to the newest folded hour start, or <c>null</c> when empty.</returns>
|
/// <returns>A task resolving to the newest folded hour start, or <c>null</c> when empty.</returns>
|
||||||
Task<DateTime?> GetLatestRollupHourAsync(CancellationToken cancellationToken = default);
|
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>
|
/// <summary>
|
||||||
/// Bulk-deletes hourly rollup rows whose
|
/// Bulk-deletes hourly rollup rows whose
|
||||||
/// <see cref="ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupHourly.HourStartUtc"/> is
|
/// <see cref="ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupHourly.HourStartUtc"/> is
|
||||||
|
|||||||
+28
@@ -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);
|
.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 />
|
/// <inheritdoc />
|
||||||
public async Task PurgeRollupsOlderThanAsync(DateTime before, CancellationToken cancellationToken = default)
|
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>
|
/// <summary>Gets the set of hourly KPI rollups (pre-aggregated long-range trend backbone).</summary>
|
||||||
public DbSet<KpiRollupHourly> KpiRollupHourly => Set<KpiRollupHourly>();
|
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)
|
// 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>
|
/// <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>();
|
public DbSet<BundleUnlockAttempt> BundleUnlockAttempts => Set<BundleUnlockAttempt>();
|
||||||
|
|||||||
@@ -164,6 +164,18 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private bool _backfillDone;
|
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>
|
/// <summary>Akka timer scheduler, assigned by the actor system via <see cref="IWithTimers"/>.</summary>
|
||||||
public ITimerScheduler Timers { get; set; } = null!;
|
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<RollupComplete>(_ => _rollupInFlight = false); // lower the in-flight guard (success or fault)
|
||||||
Receive<BackfillTick>(_ => HandleBackfillTick());
|
Receive<BackfillTick>(_ => HandleBackfillTick());
|
||||||
Receive<BackfillPlan>(HandleBackfillPlan);
|
Receive<BackfillPlan>(HandleBackfillPlan);
|
||||||
Receive<BackfillSliceComplete>(_ =>
|
Receive<BackfillSliceComplete>(complete =>
|
||||||
{
|
{
|
||||||
_backfillInFlight = false; // release the fold path BETWEEN slices (R1)
|
_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)
|
if (_backfillSlices.Count == 0)
|
||||||
{
|
{
|
||||||
_backfillDone = true; // latch: at most once per actor lifetime (unchanged semantics)
|
_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();
|
await using var scope = _serviceProvider.CreateAsyncScope();
|
||||||
var repository = scope.ServiceProvider.GetRequiredService<IKpiHistoryRepository>();
|
var repository = scope.ServiceProvider.GetRequiredService<IKpiHistoryRepository>();
|
||||||
await repository.FoldHourlyRollupsAsync(fromHourUtc, toHourUtc, cancellationToken);
|
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)
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
@@ -602,11 +644,11 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
|
|||||||
|
|
||||||
RunBackfillPass(slice.FromHourUtc, slice.ToHourUtc, cancellationToken).PipeTo(
|
RunBackfillPass(slice.FromHourUtc, slice.ToHourUtc, cancellationToken).PipeTo(
|
||||||
Self,
|
Self,
|
||||||
success: () => BackfillSliceComplete.Instance,
|
success: ok => ok ? BackfillSliceComplete.Success : BackfillSliceComplete.Failure,
|
||||||
failure: ex =>
|
failure: ex =>
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "KPI rollup backfill slice faulted unexpectedly.");
|
_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;
|
_backfillInFlight = false;
|
||||||
_backfillDone = true;
|
_backfillDone = true;
|
||||||
_logger.LogInformation(
|
_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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -682,10 +724,13 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Resolves the newest folded rollup hour (the backfill watermark) off the actor thread in a
|
/// Resolves the backfill's OWN persisted watermark (KPI-1 — the hour boundary its completed
|
||||||
/// fresh DI scope. Never faults — on cancellation or error it returns <c>null</c>, which the
|
/// slices have folded through) off the actor thread in a fresh DI scope. Deliberately NOT
|
||||||
/// plan treats as "no rollups", keeping the full retention window (best-effort, mirrors the
|
/// <c>MAX(KpiRollupHourly.HourStartUtc)</c>: the periodic lookback fold advances that seconds
|
||||||
/// other passes).
|
/// 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>
|
/// </summary>
|
||||||
private async Task<DateTime?> RunBackfillPlanPass(CancellationToken cancellationToken)
|
private async Task<DateTime?> RunBackfillPlanPass(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
@@ -693,7 +738,7 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
|
|||||||
{
|
{
|
||||||
await using var scope = _serviceProvider.CreateAsyncScope();
|
await using var scope = _serviceProvider.CreateAsyncScope();
|
||||||
var repository = scope.ServiceProvider.GetRequiredService<IKpiHistoryRepository>();
|
var repository = scope.ServiceProvider.GetRequiredService<IKpiHistoryRepository>();
|
||||||
return await repository.GetLatestRollupHourAsync(cancellationToken);
|
return await repository.GetRollupBackfillWatermarkAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
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
|
/// 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).
|
/// window and elapsed wall time (the queue-drained completion is logged at Information).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task RunBackfillPass(
|
private async Task<bool> RunBackfillPass(
|
||||||
DateTime fromHourUtc, DateTime toHourUtc, CancellationToken cancellationToken)
|
DateTime fromHourUtc, DateTime toHourUtc, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var startedAt = DateTime.UtcNow;
|
var startedAt = DateTime.UtcNow;
|
||||||
@@ -725,17 +770,25 @@ public class KpiHistoryRecorderActor : ReceiveActor, IWithTimers
|
|||||||
var repository = scope.ServiceProvider.GetRequiredService<IKpiHistoryRepository>();
|
var repository = scope.ServiceProvider.GetRequiredService<IKpiHistoryRepository>();
|
||||||
await repository.FoldHourlyRollupsAsync(fromHourUtc, toHourUtc, cancellationToken);
|
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(
|
_logger.LogDebug(
|
||||||
"KPI rollup backfill slice folded [{FromHour:o}, {ToHour:o}) in {ElapsedMs:F0} ms.",
|
"KPI rollup backfill slice folded [{FromHour:o}, {ToHour:o}) in {ElapsedMs:F0} ms.",
|
||||||
fromHourUtc, toHourUtc, (DateTime.UtcNow - startedAt).TotalMilliseconds);
|
fromHourUtc, toHourUtc, (DateTime.UtcNow - startedAt).TotalMilliseconds);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
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)
|
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>
|
/// </summary>
|
||||||
internal sealed class BackfillSliceComplete
|
internal sealed class BackfillSliceComplete
|
||||||
{
|
{
|
||||||
public static readonly BackfillSliceComplete Instance = new();
|
/// <summary>The slice folded and the persisted watermark advanced.</summary>
|
||||||
private BackfillSliceComplete() { }
|
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; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+34
@@ -487,6 +487,40 @@ public class KpiHistoryRepositoryTests
|
|||||||
Assert.Empty(ctx.ChangeTracker.Entries<KpiSample>());
|
Assert.Empty(ctx.ChangeTracker.Entries<KpiSample>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[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());
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that the latest rollup hour is null when no rollups exist.</summary>
|
/// <summary>Verifies that the latest rollup hour is null when no rollups exist.</summary>
|
||||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -239,6 +239,57 @@ public class KpiHistoryRecorderActorTests : TestKit
|
|||||||
return Task.FromResult(_latestRollupHour);
|
return Task.FromResult(_latestRollupHour);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private DateTime? _backfillWatermark;
|
||||||
|
private int _backfillWatermarkQueryCount;
|
||||||
|
private readonly List<(DateTime Through, DateTime? OnlyIfReached)> _advances = new();
|
||||||
|
|
||||||
|
/// <summary>The backfill's own persisted watermark the fake reports (settable; KPI-1).</summary>
|
||||||
|
public DateTime? BackfillWatermark
|
||||||
|
{
|
||||||
|
get { lock (_gate) { return _backfillWatermark; } }
|
||||||
|
set { lock (_gate) { _backfillWatermark = value; } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Number of times the backfill plan pass read the backfill watermark.</summary>
|
||||||
|
public int BackfillWatermarkQueryCount
|
||||||
|
{
|
||||||
|
get { lock (_gate) { return _backfillWatermarkQueryCount; } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Every watermark advance requested, in call order.</summary>
|
||||||
|
public IReadOnlyList<(DateTime Through, DateTime? OnlyIfReached)> Advances
|
||||||
|
{
|
||||||
|
get { lock (_gate) { return _advances.ToArray(); } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<DateTime?> GetRollupBackfillWatermarkAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_backfillWatermarkQueryCount++;
|
||||||
|
return Task.FromResult(_backfillWatermark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -1168,7 +1219,7 @@ public class KpiHistoryRecorderActorTests : TestKit
|
|||||||
interval: TimeSpan.FromMilliseconds(50));
|
interval: TimeSpan.FromMilliseconds(50));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that the backfill is skipped when rollups are already current.</summary>
|
/// <summary>Verifies that the backfill is skipped when its own watermark is already current.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Backfill_Skips_WhenRollupsAlreadyCurrent()
|
public void Backfill_Skips_WhenRollupsAlreadyCurrent()
|
||||||
{
|
{
|
||||||
@@ -1187,17 +1238,18 @@ public class KpiHistoryRecorderActorTests : TestKit
|
|||||||
RollupLookbackHours = 3,
|
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(
|
var nowHour = new DateTime(
|
||||||
DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
|
DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
|
||||||
DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc);
|
DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc);
|
||||||
repository.LatestRollupHour = nowHour - TimeSpan.FromHours(1);
|
repository.BackfillWatermark = nowHour - TimeSpan.FromHours(1);
|
||||||
|
|
||||||
actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance);
|
actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance);
|
||||||
|
|
||||||
// The plan pass must consult the watermark…
|
// The plan pass must consult the watermark…
|
||||||
AwaitAssert(
|
AwaitAssert(
|
||||||
() => Assert.True(repository.LatestRollupHourQueryCount >= 1),
|
() => Assert.True(repository.BackfillWatermarkQueryCount >= 1),
|
||||||
duration: TimeSpan.FromSeconds(3),
|
duration: TimeSpan.FromSeconds(3),
|
||||||
interval: TimeSpan.FromMilliseconds(50));
|
interval: TimeSpan.FromMilliseconds(50));
|
||||||
|
|
||||||
@@ -1234,7 +1286,7 @@ public class KpiHistoryRecorderActorTests : TestKit
|
|||||||
DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
|
DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
|
||||||
DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc);
|
DateTime.UtcNow.Hour, 0, 0, DateTimeKind.Utc);
|
||||||
var watermark = nowHour - TimeSpan.FromDays(2);
|
var watermark = nowHour - TimeSpan.FromDays(2);
|
||||||
repository.LatestRollupHour = watermark;
|
repository.BackfillWatermark = watermark;
|
||||||
|
|
||||||
actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance);
|
actor.Tell(KpiHistoryRecorderActor.BackfillTick.Instance);
|
||||||
|
|
||||||
@@ -1250,4 +1302,114 @@ public class KpiHistoryRecorderActorTests : TestKit
|
|||||||
duration: TimeSpan.FromSeconds(5),
|
duration: TimeSpan.FromSeconds(5),
|
||||||
interval: TimeSpan.FromMilliseconds(50));
|
interval: TimeSpan.FromMilliseconds(50));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
[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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
[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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
[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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user