using AttendanceHub.Sync.Domain; using AttendanceHub.Sync.Ingestion; using AttendanceHub.Sync.Persistence; using AttendanceHub.Sync.Persistence.Sqlite; using AttendanceHub.Sync.Upload; using Xunit; namespace AttendanceHub.Sync.Tests; /// /// Ingest retention (the half that keeps the ledger bounded WITHOUT a re-upload loop): /// - ClassifyTime marks punch_time older than the retention window as Expired. /// - UpsertBatchAsync never persists (or returns as a normal reject) an Expired row. /// - ReconciliationPersistence drops Expired rows at ingest and does not let them move the watermark. /// - THE regression this exists for: a full-buffer device read re-delivers ~12 months of history on /// every pass, so a row deleted by the daily prune would otherwise come back as "new", be re-uploaded, /// re-Sent, re-pruned... forever. With the ingest filter the pruned row stays gone. /// public class IngestRetentionTests : IAsyncLifetime { private string _dbPath = null!; private SQLiteSyncStore _store = null!; public async Task InitializeAsync() { _dbPath = Path.Combine(Path.GetTempPath(), "ahub-ingest-retention", Guid.NewGuid().ToString("N") + ".db"); Directory.CreateDirectory(Path.GetDirectoryName(_dbPath)!); _store = new SQLiteSyncStore(_dbPath); await _store.InitializeAsync(); } public async Task DisposeAsync() { await _store.DisposeAsync(); try { Directory.Delete(Path.GetDirectoryName(_dbPath)!, recursive: true); } catch { } } private static RawAttendanceEvent Raw(DateTimeOffset t, string pin = "1001") => new( Generation: 1, PersonnelCode: pin, IsInvalid: false, AttendanceState: 0, VerifyMethod: 1, Year: t.Year, Month: t.Month, Day: t.Day, Hour: t.Hour, Minute: t.Minute, Second: t.Second, WorkCode: 0, SourceApi: "SSR_GetGeneralLogData", CapturedAt: DateTimeOffset.UtcNow); private static NormalizedPunch Punch(string pin, DateTimeOffset time, PunchTimeStatus status) { var id = new PunchIdentity("dev1", pin, time); return new NormalizedPunch(id, PunchSource.Reconciliation, 0, 1, 0, false, 1, "SSR_GetGeneralLogData", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1, status, time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second); } [Fact] public void R01_ClassifyTime_Uses_The_Shared_Retention_Window() { var now = DateTimeOffset.UtcNow; var tol = TimeSpan.FromMinutes(5); var retention = TimeSpan.FromDays(90); Assert.Equal(PunchTimeStatus.Acceptable, NormalizedPunch.ClassifyTime(now.AddDays(-89), now, tol, retention)); Assert.Equal(PunchTimeStatus.Expired, NormalizedPunch.ClassifyTime(now.AddDays(-91), now, tol, retention)); // Just-beyond-the-window boundary is Expired; just-inside is Acceptable. Assert.Equal(PunchTimeStatus.Expired, NormalizedPunch.ClassifyTime(now - retention - TimeSpan.FromSeconds(1), now, tol, retention)); Assert.Equal(PunchTimeStatus.Acceptable, NormalizedPunch.ClassifyTime(now - retention + TimeSpan.FromSeconds(1), now, tol, retention)); // Orthogonal classifications still win where they must. Assert.Equal(PunchTimeStatus.Invalid, NormalizedPunch.ClassifyTime(new DateTimeOffset(1999, 1, 1, 0, 0, 0, TimeSpan.Zero), now, tol, retention)); Assert.Equal(PunchTimeStatus.FutureHold, NormalizedPunch.ClassifyTime(now.AddHours(2), now, tol, retention)); // Default (omitted) retention matches the shared policy — caller and prune cannot drift. Assert.Equal(RetentionPolicy.PunchRetention, TimeSpan.FromDays(RetentionPolicy.PunchRetentionDays)); Assert.Equal(PunchTimeStatus.Expired, NormalizedPunch.ClassifyTime(now.AddDays(-91), now, tol)); } [Fact] public async Task R02_Upsert_Never_Persists_Expired_And_Does_Not_Count_It_As_Rejected() { var now = DateTimeOffset.UtcNow; var expired = Punch("1001", now.AddDays(-120), PunchTimeStatus.Expired); var fresh = Punch("1002", now.AddDays(-1), PunchTimeStatus.Acceptable); var r = await _store.UpsertBatchAsync(new[] { expired, fresh }); Assert.Equal(1, r.Expired); // counted once, as its own outcome Assert.Equal(0, r.Rejected); // NOT a rejection (keeps live-ingress warnings clean) Assert.Equal(1, r.Inserted); // only the fresh row landed Assert.NotNull(await _store.FindPunchAsync(fresh.Identity)); Assert.Null(await _store.FindPunchAsync(expired.Identity)); var up = await _store.UpsertPunchAsync(expired); Assert.Equal(PunchUpsertKind.Expired, up.Kind); } [Fact] public async Task R03_Pruned_Old_Row_Coming_Back_From_A_Full_Buffer_Read_Stays_Gone() { var now = DateTimeOffset.UtcNow; var retention = TimeSpan.FromDays(90); var recon = new ReconciliationPersistence(_store, TimeSpan.FromMinutes(5), log: null, ingestRetention: retention); // 1) An old punch is durable + acked (the state the ledger is in right after a big backfill). var oldTime = now.AddDays(-120); await _store.UpsertPunchAsync(Punch("1001", oldTime, PunchTimeStatus.Acceptable)); var found = await _store.FindPunchAsync(new PunchIdentity("dev1", "1001", oldTime)); await _store.ApplyAckAsync(found!.LocalId, RecordOutcome.AcceptedNew, null, "receipt-r3", DateTimeOffset.UtcNow, RetryPolicy.Default); // 2) The daily prune drops it (Sent + acked + older than retention). var pruned = await _store.PruneLedgerAsync(retention, TimeSpan.FromDays(30), long.MaxValue); Assert.Equal(1, pruned.PunchesDeleted); Assert.Null(await _store.FindPunchAsync(new PunchIdentity("dev1", "1001", oldTime))); // 3) The next FULL device read re-delivers that same old row (this is the churn bug). var outcome = await recon.PersistReadAsync( "dev1", new[] { Raw(oldTime) }, PunchSource.Reconciliation, sessionGeneration: 1, overlap: TimeSpan.FromMinutes(5), clockSkewTolerance: TimeSpan.FromMinutes(5)); // It is dropped at ingest: never re-persisted, so it can never be re-uploaded. Assert.Equal(1, outcome.ExpiredCount); Assert.Equal(0, outcome.Batch.Inserted); Assert.Null(await _store.FindPunchAsync(new PunchIdentity("dev1", "1001", oldTime))); // 4) A second and third pass add nothing — the cycle is broken, not merely delayed. await recon.PersistReadAsync("dev1", new[] { Raw(oldTime) }, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); await recon.PersistReadAsync("dev1", new[] { Raw(oldTime) }, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); Assert.Equal(0, (await _store.GetStatsAsync()).PunchCount); } [Fact] public async Task R04_Expired_Never_Adances_The_Watermark_But_Recent_Rows_Still_Do() { var now = DateTimeOffset.UtcNow; var retention = TimeSpan.FromDays(90); var recon = new ReconciliationPersistence(_store, TimeSpan.FromMinutes(5), log: null, ingestRetention: retention); var oldTime = now.AddDays(-150); // RawAttendanceEvent carries whole seconds only — truncate so the round-trip is exact. var recentTime = new DateTimeOffset(now.AddMinutes(-10).UtcDateTime .AddTicks(-(now.AddMinutes(-10).UtcDateTime.Ticks % TimeSpan.TicksPerSecond))); // Only an expired row: nothing durable, so the watermark must stay put (null). var onlyOld = await recon.PersistReadAsync( "dev1", new[] { Raw(oldTime) }, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); Assert.Equal(1, onlyOld.ExpiredCount); Assert.False(onlyOld.WatermarkAdvanced); Assert.Null(onlyOld.WatermarkAfter); // Old + recent in one full-buffer read: the recent row persists and carries the watermark, // the expired one is dropped and contributes nothing. var mixed = await recon.PersistReadAsync( "dev1", new[] { Raw(oldTime, "1001"), Raw(recentTime, "1002") }, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); Assert.Equal(1, mixed.ExpiredCount); Assert.Equal(1, mixed.Batch.Inserted); Assert.True(mixed.WatermarkAdvanced); Assert.Equal(recentTime, mixed.WatermarkAfter); Assert.NotNull(await _store.FindPunchAsync(new PunchIdentity("dev1", "1002", recentTime))); Assert.Null(await _store.FindPunchAsync(new PunchIdentity("dev1", "1001", oldTime))); } }