using AttendanceHub.Sync.Domain; using AttendanceHub.Sync.Ingestion; using AttendanceHub.Sync.Persistence; using AttendanceHub.Sync.Persistence.Sqlite; using Xunit; namespace AttendanceHub.Sync.Tests; public class Phase3SqliteStoreTests : IAsyncLifetime { private string _dbPath = null!; private SQLiteSyncStore _store = null!; public async Task InitializeAsync() { _dbPath = Path.Combine(Path.GetTempPath(), "ahub-phase3", 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 NormalizedPunch Punch( string device = "dev1", string pin = "1001", DateTimeOffset? time = null, PunchSource source = PunchSource.Reconciliation, PunchTimeStatus status = PunchTimeStatus.Acceptable, int attendanceState = 0) { var t = time ?? new DateTimeOffset(2026, 9, 22, 12, 0, 0, TimeSpan.Zero); var id = new PunchIdentity(device, pin, t); return new NormalizedPunch(id, source, attendanceState, 1, 0, false, 1, "SSR_GetGeneralLogData", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1, status, t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second); } [Fact] public async Task T01_Insert_One_Punch_Is_Durable() { var p = Punch(); var r = await _store.UpsertPunchAsync(p); Assert.Equal(PunchUpsertKind.Inserted, r.Kind); var found = await _store.FindPunchAsync(p.Identity); Assert.NotNull(found); Assert.Equal(p.PersonnelCode, found!.Identity.PersonnelCode); Assert.Equal(p.PunchTime, found.Identity.PunchTime); } [Fact] public async Task T02_Insert_Same_Punch_Twice_One_Logical_Row() { var p = Punch(); await _store.UpsertPunchAsync(p); await _store.UpsertPunchAsync(p); var list = await _store.ListPunchesAsync("dev1"); Assert.Single(list); Assert.Equal(2, list[0].OccurrenceCount); } [Fact] public async Task T03_Realtime_Plus_Reconciliation_Same_Identity_One_Row() { var t = new DateTimeOffset(2026, 9, 22, 8, 0, 0, TimeSpan.Zero); await _store.UpsertPunchAsync(Punch(time: t, source: PunchSource.Realtime)); await _store.UpsertPunchAsync(Punch(time: t, source: PunchSource.Reconciliation)); var list = await _store.ListPunchesAsync("dev1"); Assert.Single(list); // First source retained for Realtime preference in UPSERT Assert.Equal(PunchSource.Realtime, list[0].Source); } [Fact] public async Task T04_Different_AttendanceState_Same_Identity_Still_One_Row() { // punch_type / attendance_state is metadata, NOT identity var t = new DateTimeOffset(2026, 9, 22, 9, 0, 0, TimeSpan.Zero); await _store.UpsertPunchAsync(Punch(time: t, attendanceState: 0)); await _store.UpsertPunchAsync(Punch(time: t, attendanceState: 1)); var list = await _store.ListPunchesAsync("dev1"); Assert.Single(list); Assert.Equal(2, list[0].OccurrenceCount); } [Fact] public async Task T05_Different_Device_Distinct_Rows() { var t = new DateTimeOffset(2026, 9, 22, 10, 0, 0, TimeSpan.Zero); await _store.UpsertPunchAsync(Punch(device: "dev1", time: t)); await _store.UpsertPunchAsync(Punch(device: "dev2", time: t)); Assert.Single(await _store.ListPunchesAsync("dev1")); Assert.Single(await _store.ListPunchesAsync("dev2")); } [Fact] public async Task T06_Different_Personnel_Distinct_Rows() { var t = new DateTimeOffset(2026, 9, 22, 10, 0, 0, TimeSpan.Zero); await _store.UpsertPunchAsync(Punch(pin: "A", time: t)); await _store.UpsertPunchAsync(Punch(pin: "B", time: t)); Assert.Equal(2, (await _store.ListPunchesAsync("dev1")).Count); } [Fact] public async Task T07_Different_PunchTime_Distinct_Rows() { await _store.UpsertPunchAsync(Punch(time: new DateTimeOffset(2026, 9, 22, 10, 0, 0, TimeSpan.Zero))); await _store.UpsertPunchAsync(Punch(time: new DateTimeOffset(2026, 9, 22, 10, 0, 1, TimeSpan.Zero))); Assert.Equal(2, (await _store.ListPunchesAsync("dev1")).Count); } [Fact] public async Task T08_Batch_Succeeds_Watermark_Advances() { var recon = new ReconciliationPersistence(_store, TimeSpan.FromMinutes(5)); var rows = new[] { new RawAttendanceEvent(1, "1", false, 0, 1, 2026, 9, 22, 10, 0, 0, 0, "SSR", DateTimeOffset.UtcNow), new RawAttendanceEvent(1, "1", false, 0, 1, 2026, 9, 22, 10, 5, 0, 0, "SSR", DateTimeOffset.UtcNow) }; var outcome = await recon.PersistReadAsync("dev1", rows, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2)); Assert.True(outcome.Batch.AllCommitted); Assert.True(outcome.WatermarkAdvanced); Assert.Equal(new DateTimeOffset(2026, 9, 22, 10, 5, 0, TimeSpan.Zero), outcome.WatermarkAfter); } [Fact] public async Task T09_Batch_Fails_Watermark_Does_Not_Advance() { // Force Invalid rows (rejected) mixed with success — commit succeeds but // simulate failed commit path: empty after prior watermark await _store.SaveWatermarkAsync(new ReconciliationWatermark( "dev1", new DateTimeOffset(2026, 9, 22, 8, 0, 0, TimeSpan.Zero), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2), DateTimeOffset.UtcNow, 1)); // All invalid -> no advance even if allow=true var recon = new ReconciliationPersistence(_store, TimeSpan.FromMinutes(5)); var rows = new[] { new RawAttendanceEvent(1, "1", false, 0, 1, 1999, 1, 1, 0, 0, 0, 0, "SSR", DateTimeOffset.UtcNow) }; var outcome = await recon.PersistReadAsync("dev1", rows, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2)); Assert.False(outcome.WatermarkAdvanced); var wm = await _store.GetWatermarkAsync("dev1"); Assert.Equal(new DateTimeOffset(2026, 9, 22, 8, 0, 0, TimeSpan.Zero), wm!.LastPersistedPunchTime); } [Fact] public async Task T10_Crash_After_Insert_Before_Watermark_Replay_Safe() { var p = Punch(time: new DateTimeOffset(2026, 9, 22, 11, 0, 0, TimeSpan.Zero)); await _store.UpsertPunchAsync(p); // watermark intentionally NOT advanced (crash window) await _store.DisposeAsync(); _store = new SQLiteSyncStore(_dbPath); await _store.InitializeAsync(); // replay same punch var r = await _store.UpsertPunchAsync(p); Assert.Equal(PunchUpsertKind.Duplicate, r.Kind); Assert.Single(await _store.ListPunchesAsync("dev1")); var wm = await _store.GetWatermarkAsync("dev1"); Assert.True(wm?.LastPersistedPunchTime is null); // never advanced } [Fact] public async Task T11_OutOfOrder_Watermark_Uses_Max_Not_Last_Row() { var recon = new ReconciliationPersistence(_store, TimeSpan.FromMinutes(5)); var rows = new[] { // last drained is earlier than max new RawAttendanceEvent(1, "1", false, 0, 1, 2026, 9, 22, 15, 0, 0, 0, "SSR", DateTimeOffset.UtcNow), new RawAttendanceEvent(1, "1", false, 0, 1, 2026, 9, 22, 9, 0, 0, 0, "SSR", DateTimeOffset.UtcNow) }; var outcome = await recon.PersistReadAsync("dev1", rows, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2)); Assert.Equal(new DateTimeOffset(2026, 9, 22, 15, 0, 0, TimeSpan.Zero), outcome.WatermarkAfter); } [Fact] public async Task T12_Future_Timestamp_Persisted_But_Does_Not_Advance_Watermark() { var recon = new ReconciliationPersistence(_store, TimeSpan.FromMinutes(10)); var now = DateTimeOffset.UtcNow; var future = now.AddHours(2); var rows = new[] { new RawAttendanceEvent(1, "1", false, 0, 1, future.Year, future.Month, future.Day, future.Hour, future.Minute, future.Second, 0, "SSR", DateTimeOffset.UtcNow), new RawAttendanceEvent(1, "2", false, 0, 1, now.AddMinutes(-5).Year, now.AddMinutes(-5).Month, now.AddMinutes(-5).Day, now.AddMinutes(-5).Hour, now.AddMinutes(-5).Minute, now.AddMinutes(-5).Second, 0, "SSR", DateTimeOffset.UtcNow) }; var outcome = await recon.PersistReadAsync("dev1", rows, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2)); Assert.Equal(1, outcome.FutureHoldCount); // Watermark advances only to max acceptable (past row), NOT the future one if (outcome.WatermarkAdvanced) { Assert.True(outcome.WatermarkAfter < future); } // Future row is persisted/classified var stats = await _store.GetStatsAsync(); Assert.Equal(1, stats.FutureHoldCount); } [Fact] public async Task T13_Multiple_Devices_Independent_State() { var recon = new ReconciliationPersistence(_store, TimeSpan.FromMinutes(5)); await recon.PersistReadAsync("devA", new[] { new RawAttendanceEvent(1, "1", false, 0, 1, 2026, 9, 22, 10, 0, 0, 0, "SSR", DateTimeOffset.UtcNow) }, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2)); await recon.PersistReadAsync("devB", new[] { new RawAttendanceEvent(1, "1", false, 0, 1, 2026, 9, 22, 20, 0, 0, 0, "SSR", DateTimeOffset.UtcNow) }, PunchSource.Reconciliation, 1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2)); var a = await _store.GetWatermarkAsync("devA"); var b = await _store.GetWatermarkAsync("devB"); Assert.Equal(new DateTimeOffset(2026, 9, 22, 10, 0, 0, TimeSpan.Zero), a!.LastPersistedPunchTime); Assert.Equal(new DateTimeOffset(2026, 9, 22, 20, 0, 0, TimeSpan.Zero), b!.LastPersistedPunchTime); } [Fact] public async Task T14_Busy_Lock_Controlled_Retry_No_Corruption() { // Concurrent upserts of distinct identities should all succeed (busy_timeout + write gate). var tasks = Enumerable.Range(0, 20).Select(i => _store.UpsertPunchAsync(Punch(pin: $"P{i}", time: new DateTimeOffset(2026, 9, 22, 12, i, 0, TimeSpan.Zero)))); var results = await Task.WhenAll(tasks); Assert.All(results, r => Assert.Equal(PunchUpsertKind.Inserted, r.Kind)); Assert.Equal(20, (await _store.ListPunchesAsync("dev1", limit: 100)).Count); var stats = await _store.GetStatsAsync(); Assert.True(stats.BatchesCommitted >= 20); } [Fact] public async Task T15_Schema_Migration_From_Empty_Db() { var path = Path.Combine(Path.GetTempPath(), "ahub-phase3", Guid.NewGuid().ToString("N") + ".db"); await using var store = new SQLiteSyncStore(path); await store.InitializeAsync(); // reopen and migrate again (idempotent) await using var store2 = new SQLiteSyncStore(path); await store2.InitializeAsync(); await store2.UpsertPunchAsync(Punch()); Assert.Single(await store2.ListPunchesAsync("dev1")); } [Fact] public async Task T16_Restart_With_Existing_Db() { await _store.UpsertPunchAsync(Punch()); await _store.SaveWatermarkAsync(new ReconciliationWatermark( "dev1", new DateTimeOffset(2026, 9, 22, 12, 0, 0, TimeSpan.Zero), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(2), DateTimeOffset.UtcNow, 3)); await _store.DisposeAsync(); _store = new SQLiteSyncStore(_dbPath); await _store.InitializeAsync(); Assert.Single(await _store.ListPunchesAsync("dev1")); var wm = await _store.GetWatermarkAsync("dev1"); Assert.Equal(3, wm!.LastSessionGeneration); } [Fact] public async Task T17_Fault_Injection_Insert_Success_Crash_Restart_Dedupe() { var p = Punch(pin: "FAULT", time: new DateTimeOffset(2026, 9, 22, 13, 0, 0, TimeSpan.Zero)); await _store.UpsertPunchAsync(p); // simulated crash before watermark await _store.DisposeAsync(); _store = new SQLiteSyncStore(_dbPath); await _store.InitializeAsync(); // reread + dedupe await _store.UpsertPunchAsync(p); await _store.UpsertPunchAsync(p); var rows = await _store.ListPunchesAsync("dev1"); var fault = Assert.Single(rows, r => r.Identity.PersonnelCode == "FAULT"); Assert.Equal(3, fault.OccurrenceCount); // 1 initial + 2 replays } [Fact] public async Task T18_Live_Ingress_Moves_Off_Com_Callback_Thread() { await using var ingress = new LivePunchIngress(_store, "dev1", TimeSpan.FromMinutes(5)); var raw = new RawAttendanceEvent(1, "LIVE", false, 0, 1, 2026, 9, 22, 14, 0, 0, 0, "OnAttTransactionEx", DateTimeOffset.UtcNow); var comThread = Environment.CurrentManagedThreadId; var observed = 0; var t = new Thread(() => { // simulate COM callback thread: enqueue only ingress.EnqueueFromCom(raw, 1); observed = Environment.CurrentManagedThreadId; }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.NotEqual(comThread, observed); await ingress.FlushAsync(TimeSpan.FromSeconds(3)); Assert.Equal(1, ingress.Persisted); Assert.Single(await _store.ListPunchesAsync("dev1")); } } public class Phase3DomainTests { [Fact] public void PunchType_Is_Not_Identity() { var t = new DateTimeOffset(2026, 9, 22, 10, 0, 0, TimeSpan.Zero); var a = new PunchIdentity("d", "1", t); var b = new PunchIdentity("d", "1", t); Assert.Equal(a, b); } [Fact] public void Future_Timestamp_Classified() { var now = DateTimeOffset.UtcNow; var future = now.AddHours(3); Assert.Equal(PunchTimeStatus.FutureHold, NormalizedPunch.ClassifyTime(future, now, TimeSpan.FromMinutes(5))); Assert.Equal(PunchTimeStatus.Acceptable, NormalizedPunch.ClassifyTime(now.AddMinutes(-1), now, TimeSpan.FromMinutes(5))); Assert.Equal(PunchTimeStatus.Invalid, NormalizedPunch.ClassifyTime(default, now, TimeSpan.FromMinutes(5))); Assert.Equal(PunchTimeStatus.Invalid, NormalizedPunch.ClassifyTime(new DateTimeOffset(1990, 1, 1, 0, 0, 0, TimeSpan.Zero), now, TimeSpan.FromMinutes(5))); } [Fact] public void Watermark_Candidate_Ignores_FutureHold() { var ok = new NormalizedPunch(new PunchIdentity("d", "1", new DateTimeOffset(2026, 9, 22, 10, 0, 0, TimeSpan.Zero)), PunchSource.Reconciliation, 0, 1, 0, false, 1, "x", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1, PunchTimeStatus.Acceptable, 2026, 9, 22, 10, 0, 0); var fut = new NormalizedPunch(new PunchIdentity("d", "2", new DateTimeOffset(2026, 9, 22, 20, 0, 0, TimeSpan.Zero)), PunchSource.Reconciliation, 0, 1, 0, false, 1, "x", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1, PunchTimeStatus.FutureHold, 2026, 9, 22, 20, 0, 0); var cand = ReconciliationWatermark.ComputeAdvanceCandidate(new[] { ok, fut }, null); Assert.Equal(ok.PunchTime, cand); } }