using System.Collections.Concurrent; using AttendanceHub.Sync.Domain; using AttendanceHub.Sync.Ingestion; using AttendanceHub.Sync.Oversight; using AttendanceHub.Sync.Persistence.Sqlite; using AttendanceHub.Sync.Workers; using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace AttendanceHub.Sync.Tests; /// /// Production V2 dual-session worker tests (all device-free): /// independent LIVE/READ sessions, LIVE read-forbidden guard, serialized reads, /// READ-failure isolation (no LIVE impact, scheduler continues, no premature recreate), /// and idempotent BOTH-path persistence through the new wiring. /// public class DeviceWorkerV2Tests { internal static Phase1DeviceConfig Config( string deviceId = "v2-test", int readIntervalMs = 100, int failureRetryLimit = 0, int failureRetryBackoffMs = 50, bool tryTimeWindow = true) => new( new DeviceEndpoint(deviceId, deviceId, "127.0.0.1", 4370, 1, 0), new SdkConfig(1, "6.3.1.45"), new SessionConfig(1000, 1000), new RealtimeConfig(1, 64), new ReadConfig("Auto", 60, 100, failureRetryLimit, failureRetryBackoffMs, TryTimeWindow: tryTimeWindow), new SupervisorConfig(ReconnectDelayMs: 50, HealthIntervalMs: 60000, ReadIntervalMs: readIntervalMs)); internal static async Task WaitUntil(Func cond, int timeoutMs = 5000, int stepMs = 50) { var deadline = Environment.TickCount64 + timeoutMs; while (Environment.TickCount64 < deadline) { if (cond()) return; await Task.Delay(stepMs); } Assert.True(cond(), $"condition not met within {timeoutMs} ms"); } // ---------- scripted device-free session fake ---------- internal sealed class ScriptedSession : IZkComSession { private readonly ConcurrentQueue _script = new(); private int _active; public string WorkerId { get; } public int Generation => 1; public ZkSessionInfo Info => new( Environment.ProcessId, WorkerId, Environment.CurrentManagedThreadId, "STA", Generation, "6.3.1.45", DateTimeOffset.UtcNow, null, null); public bool IsConnected { get; private set; } = true; public bool PumpAlive => true; public long EventsDirectOnOwner => 0; public long EventsHandedToOwner => 0; public long EventsDropped => 0; public event Action? AttendanceReceived; public int RecreateCount; public int ReadCalls; public int MaxConcurrentReads; private static readonly AttendanceReadResult EmptySuccess = new( AttendanceReadStatus.Success, "ReadGeneralLogData", "SSR_GetGeneralLogData", Array.Empty(), 1, 0, null); public ScriptedSession(string workerId) => WorkerId = workerId; public void EnqueueRead(AttendanceReadResult result) => _script.Enqueue(result); public Task InitializeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; public Task ConnectAsync(CancellationToken cancellationToken = default) { IsConnected = true; return Task.FromResult(new ConnectResult(true, "Connect_Net", true, 0, 1, null)); } public Task DisconnectAsync(CancellationToken cancellationToken = default) { IsConnected = false; return Task.CompletedTask; } public Task RegEventAsync(int eventMask, CancellationToken cancellationToken = default) => Task.CompletedTask; public Task ProbeCapabilityAsync(CancellationToken cancellationToken = default) => Task.FromResult(new DeviceCapability("SN", "MAC", "P", "FW", "new-architecture", "6.3.1.45", "ZEM", "1.2.3.4", true, 1, 100, 99, 1, "ReadGeneralLogData", "OnAttTransactionEx", new[] { "probe" })); public Task GetFunctionalHealthAsync(CancellationToken cancellationToken = default) => Task.FromResult(new FunctionalHealth(true, true, true, "ReadGeneralLogData", 0, 1, null, null)); public async Task ReadAttendanceAsync(AttendanceReadRequest request, CancellationToken cancellationToken = default) { var n = Interlocked.Increment(ref _active); if (n > MaxConcurrentReads) MaxConcurrentReads = n; Interlocked.Increment(ref ReadCalls); try { await Task.Delay(80, cancellationToken); return _script.TryDequeue(out var scripted) ? scripted : EmptySuccess; } finally { Interlocked.Decrement(ref _active); } } public Task RecreateSessionAsync(CancellationToken cancellationToken = default) { Interlocked.Increment(ref RecreateCount); return Task.CompletedTask; } public void Emit(RawAttendanceEvent evt) => AttendanceReceived?.Invoke(evt); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } private static RawAttendanceEvent Raw(int generation, string pin, int y, int mo, int d, int h, int mi, int s) => new(generation, pin, false, 0, 1, y, mo, d, h, mi, s, 0, "OnAttTransactionEx", DateTimeOffset.UtcNow); // ---------- 1) dual sessions are independent ---------- [Fact] public async Task DeviceRuntime_Creates_Independent_Live_And_Read_Sessions() { var runtime = DeviceRuntime.Create(Config("v2-runtime"), NullLoggerFactory.Instance); await runtime.LiveSession.InitializeAsync(); await runtime.ReadSession.InitializeAsync(); try { Assert.Equal("v2-runtime:live", runtime.LiveSession.Info.WorkerId); Assert.Equal("v2-runtime:read", runtime.ReadSession.Info.WorkerId); Assert.NotEqual(runtime.LiveSession.OwnerThreadId, runtime.ReadSession.OwnerThreadId); Assert.Equal("STA", runtime.LiveSession.Info.ApartmentState); Assert.Equal("STA", runtime.ReadSession.Info.ApartmentState); Assert.True(runtime.LiveSession.PumpAlive); Assert.True(runtime.ReadSession.PumpAlive); Assert.Equal(1, runtime.LiveSession.Generation); Assert.Equal(1, runtime.ReadSession.Generation); } finally { await runtime.LiveSession.DisposeAsync(); await runtime.ReadSession.DisposeAsync(); } } // ---------- 2) LIVE session structurally forbids reads ---------- [Fact] public async Task Live_Session_Refuses_Read_APIs() { var runtime = DeviceRuntime.Create(Config("v2-live-guard"), NullLoggerFactory.Instance); await runtime.LiveSession.InitializeAsync(); try { var request = new AttendanceReadRequest( DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow, AttendanceReadMode.Auto, 100); var ex = await Assert.ThrowsAsync( () => runtime.LiveSession.ReadAttendanceAsync(request)); Assert.Contains("LIVE_SESSION_READ_FORBIDDEN", ex.Message); var ex2 = await Assert.ThrowsAsync( () => runtime.LiveSession.GetFunctionalHealthAsync()); Assert.Contains("LIVE_SESSION_READ_FORBIDDEN", ex2.Message); } finally { await runtime.LiveSession.DisposeAsync(); await runtime.ReadSession.DisposeAsync(); } } // ---------- 3) reads are serialized (never overlap), even from concurrent callers ---------- [Fact] public async Task Concurrent_Reads_Are_Serialized_Through_Read_Gate() { var live = new ScriptedSession("v2-serial:live"); var read = new ScriptedSession("v2-serial:read"); await using var worker = new DeviceWorker(live, read, Config("v2-serial")); var results = await Task.WhenAll( worker.ReadOnceAsync(), worker.ReadOnceAsync(), worker.ReadOnceAsync()); Assert.Equal(3, results.Length); Assert.Equal(1, read.MaxConcurrentReads); // strictly sequential — no overlapping reads Assert.Equal(0, live.ReadCalls); // LIVE session never receives reads } // ---------- 4) READ failure: LIVE untouched, no premature recreate, scheduler continues, recovery ---------- [Fact] public async Task Read_Failure_Does_Not_Affect_Live_And_Scheduler_Recovers() { var live = new ScriptedSession("v2-fail:live"); var read = new ScriptedSession("v2-fail:read"); read.EnqueueRead(new AttendanceReadResult( AttendanceReadStatus.ReadFailure, "ReadGeneralLogData", "SSR_GetGeneralLogData", Array.Empty(), 1, 0, "ReadGeneralLogData returned false (NOT empty)")); // second cycle returns success from the script default await using var worker = new DeviceWorker(live, read, Config("v2-fail", readIntervalMs: 100, failureRetryLimit: 0)); await worker.StartAsync(); try { // LIVE keeps delivering events even while READ is failing: live.Emit(Raw(1, "777", 2026, 9, 28, 8, 0, 0)); var gotLive = false; await WaitUntil(() => { if (worker.RealtimeReader.TryRead(out _)) gotLive = true; return gotLive || worker.Health.RealtimeReceived >= 1; }, timeoutMs: 3000); // scheduler continues after failure and reaches a later successful read await WaitUntil(() => worker.Health.ReadsCompleted >= 1 && worker.Health.LastReadSuccessAt is not null, timeoutMs: 5000); Assert.Equal(0, worker.Health.EventsDropped); // LIVE_DROPS = 0 while READ fails Assert.True(read.ReadCalls >= 2, $"expected scheduler to continue after failure, ReadCalls={read.ReadCalls}"); Assert.Equal(0, read.RecreateCount); // ReadFailure alone must NOT recreate (even READ session) Assert.Equal(0, live.RecreateCount); // LIVE must never be recreated by READ outcomes Assert.Equal(1, live.Generation); Assert.Equal(1, read.Generation); Assert.Equal(0, worker.Health.ConsecutiveReadFailures); // reset by the later success Assert.NotNull(worker.Health.LastReadFailureAt); // failure was recorded Assert.NotNull(worker.Health.LastReadSuccessAt); // recovery observed Assert.Equal(1, read.MaxConcurrentReads); // still no overlap across cycles } finally { } } // ---------- 5) idempotent BOTH-path persistence (LIVE + repeated READ => one canonical row) ---------- [Fact] public async Task Both_Live_And_Repeated_Reads_Persist_One_Canonical_Row() { var dbPath = Path.Combine(Path.GetTempPath(), "ahub-v2", Guid.NewGuid().ToString("N") + ".db"); Directory.CreateDirectory(Path.GetDirectoryName(dbPath)!); await using var store = new SQLiteSyncStore(dbPath); await store.InitializeAsync(); const string deviceId = "v2-recon"; var recon = new ReconciliationPersistence(store, TimeSpan.FromMinutes(5)); await using var ingress = new LivePunchIngress(store, deviceId, TimeSpan.FromMinutes(5), 64); // identical canonical identity: device|123|2026-09-20 08:01:02 var readRow = new RawAttendanceEvent(1, "123", false, 0, 1, 2026, 9, 20, 8, 1, 2, 0, "SSR_GetGeneralLogData", DateTimeOffset.UtcNow); var live = new ScriptedSession("v2-recon:live"); var read = new ScriptedSession("v2-recon:read"); read.EnqueueRead(new AttendanceReadResult( AttendanceReadStatus.Success, "ReadGeneralLogData", "SSR_GetGeneralLogData", new[] { readRow }, 10, 0, null)); read.EnqueueRead(new AttendanceReadResult( AttendanceReadStatus.Success, "ReadGeneralLogData", "SSR_GetGeneralLogData", new[] { readRow }, 10, 0, null)); // same identity again on the next full read await using var worker = new DeviceWorker( live, read, Config(deviceId, readIntervalMs: 120), log: null, reconciliation: recon, ingress: ingress); await worker.StartAsync(); try { // LIVE observes the same identity first live.Emit(new RawAttendanceEvent(1, "123", false, 0, 1, 2026, 9, 20, 8, 1, 2, 0, "OnAttTransactionEx", DateTimeOffset.UtcNow)); await WaitUntil(() => worker.Health.ReadsCompleted >= 2, timeoutMs: 6000); // allow the ingress pump to flush its queued write await WaitUntil(async () => { var list = await store.ListPunchesAsync(deviceId, 10); return list.Count >= 1; }, timeoutMs: 3000).ConfigureAwait(false); await Task.Delay(400); // settle: any erroneous extra insert would land here var punches = await store.ListPunchesAsync(deviceId, 10); Assert.Equal(1, punches.Count); // ONE canonical row: LIVE + READ1 + READ2 => idempotent Assert.Equal("123", punches[0].Identity.PersonnelCode); Assert.Equal(2, worker.Health.ReadsCompleted); Assert.Equal(0, live.RecreateCount); Assert.Equal(0, read.RecreateCount); } finally { try { File.Delete(dbPath); } catch { /* temp file */ } } } // ---------- Test F: READ-only recovery — LIVE misses X, READ sees X ---------- [Fact] public async Task Read_Only_Recovery_Inserts_Missed_Punch_With_Reconciliation_Source() { var dbPath = Path.Combine(Path.GetTempPath(), "ahub-v2", Guid.NewGuid().ToString("N") + ".db"); Directory.CreateDirectory(Path.GetDirectoryName(dbPath)!); await using var store = new SQLiteSyncStore(dbPath); await store.InitializeAsync(); var recon = new ReconciliationPersistence(store, TimeSpan.FromMinutes(5)); const string deviceId = "v2-recovery"; var missedByLive = new RawAttendanceEvent( 1, "321", false, 0, 1, 2026, 9, 21, 9, 10, 11, 0, "SSR_GetGeneralLogData", DateTimeOffset.UtcNow); var live = new ScriptedSession("v2-recovery:live"); // never emits X var read = new ScriptedSession("v2-recovery:read"); read.EnqueueRead(new AttendanceReadResult( AttendanceReadStatus.Success, "ReadGeneralLogData", "SSR_GetGeneralLogData", new[] { missedByLive }, 10, 0, null)); await using var worker = new DeviceWorker( live, read, Config(deviceId, readIntervalMs: 120), log: null, reconciliation: recon, ingress: null); await worker.StartAsync(); try { await WaitUntil(() => worker.Health.ReadsCompleted >= 1, timeoutMs: 5000); await WaitUntil(async () => { var list = await store.ListPunchesAsync(deviceId, 10); return list.Count >= 1; }, timeoutMs: 4000); var punches = await store.ListPunchesAsync(deviceId, 10); var recovered = Assert.Single(punches); Assert.Equal("321", recovered.Identity.PersonnelCode); Assert.Equal(PunchSource.Reconciliation, recovered.Source); // READ_ONLY recovery source Assert.Equal(0, live.RecreateCount); Assert.Equal(0, read.RecreateCount); } finally { try { File.Delete(dbPath); } catch { /* temp file */ } } } // ---------- Test G: repeated full reads — first inserts, later duplicates only ---------- [Fact] public async Task Repeated_Full_Reads_Insert_Once_Then_Duplicates_Only() { var dbPath = Path.Combine(Path.GetTempPath(), "ahub-v2", Guid.NewGuid().ToString("N") + ".db"); Directory.CreateDirectory(Path.GetDirectoryName(dbPath)!); await using var store = new SQLiteSyncStore(dbPath); await store.InitializeAsync(); var recon = new ReconciliationPersistence(store, TimeSpan.FromMinutes(5)); const string deviceId = "v2-repeat"; static RawAttendanceEvent Row(string pin, int sec) => new(1, pin, false, 0, 1, 2026, 9, 22, 8, 0, sec, 0, "SSR_GetGeneralLogData", DateTimeOffset.UtcNow); var snapshot = new[] { Row("101", 1), Row("102", 2), Row("103", 3), Row("104", 4), Row("105", 5) }; var live = new ScriptedSession("v2-repeat:live"); var read = new ScriptedSession("v2-repeat:read"); for (var i = 0; i < 3; i++) // same full-buffer snapshot read three times read.EnqueueRead(new AttendanceReadResult( AttendanceReadStatus.Success, "ReadGeneralLogData", "SSR_GetGeneralLogData", snapshot, 5, 0, null)); // This test exercises repeated FULL-buffer passes, so it must say so: with the windowed API // left enabled the fake would be probed, judged window=Invalid, and the safety-net cadence // would then legitimately drop to the reconcile period (minutes) instead of readIntervalMs. await using var worker = new DeviceWorker( live, read, Config(deviceId, readIntervalMs: 120, tryTimeWindow: false), log: null, reconciliation: recon, ingress: null); await worker.StartAsync(); try { await WaitUntil(() => worker.Health.ReadsCompleted >= 3, timeoutMs: 8000); await WaitUntil(async () => { var list = await store.ListPunchesAsync(deviceId, 10); return list.Count == 5 && list.All(p => p.OccurrenceCount >= 3); }, timeoutMs: 4000); var punches = await store.ListPunchesAsync(deviceId, 10); Assert.Equal(5, punches.Count); // canonical rows never grow Assert.All(punches, p => Assert.True(p.OccurrenceCount >= 3)); // 1 insert + >=2 duplicate observations each Assert.Equal(0, read.RecreateCount); } finally { try { File.Delete(dbPath); } catch { /* temp file */ } } } internal static async Task WaitUntil(Func> cond, int timeoutMs = 3000, int stepMs = 50) { var deadline = Environment.TickCount64 + timeoutMs; while (Environment.TickCount64 < deadline) { if (await cond()) return; await Task.Delay(stepMs); } Assert.True(await cond(), $"async condition not met within {timeoutMs} ms"); } }