using System.Diagnostics; using System.Threading.Channels; using AttendanceHub.Sync.Domain; using AttendanceHub.Sync.Ingestion; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace AttendanceHub.Sync.Workers; /// /// Production V2: one device = one DeviceWorker = TWO exclusive IZkComSessions: /// LIVE session — Connect, sink attach, RegEvent(1), OnAttTransactionEx, enqueue to ingress. NEVER executes reads. /// READ session — ReadGeneralLogData + SSR_GetGeneralLogData (Auto), sequential scheduler, /// limited retries with backoff, idempotent reconciliation persistence. /// READ failures are independent of LIVE: they are logged, retried on the READ session only, /// and never recreate/stop/reset the LIVE session. Application code never touches COM; /// every SDK call marshals to the owning DeviceSessionWorker owner thread. /// public sealed class DeviceWorker : IAsyncDisposable { // Reconciliation watermark policy — same proven values used by the Phase2C soak composition. private static readonly TimeSpan ReconOverlap = TimeSpan.FromMinutes(5); private static readonly TimeSpan ReconClockSkew = TimeSpan.FromMinutes(2); private static readonly TimeSpan ConnectRetryDelayFloor = TimeSpan.FromMilliseconds(500); private const int ConnectFailureRecreateThreshold = 6; private readonly IZkComSession _live; private readonly IZkComSession _read; private readonly Phase1DeviceConfig _config; private readonly ILogger _log; private readonly ReconciliationPersistence? _reconciliation; private readonly LivePunchIngress? _ingress; private readonly Channel _rtChannel; private readonly CancellationTokenSource _cts = new(); private readonly SemaphoreSlim _readGate = new(1, 1); private Task? _loop; private int _staleRejected; private int _disposed; private int _liveConnectFailures; private int _readConnectFailures; private int _consecutiveReadFailures; private DateTimeOffset _nextLiveConnectAt = DateTimeOffset.MinValue; private DateTimeOffset _nextReadConnectAt = DateTimeOffset.MinValue; private DateTimeOffset _nextHealthAt = DateTimeOffset.MinValue; private string _phase = "IDLE"; // ---- self-healing / liveness ---- private int _liveBackoffMs; // exponential backoff (reset on success) private int _readBackoffMs; private int _livePingFailures; // consecutive failed liveness probes private int _readPingFailures; private int _liveStaleOccurrences; // LIVE reported healthy while READ kept proving traffic private long _readSessionEvents; // realtime events observed on the READ session // ---- windowed-read validation (READ throughput) ---- private WindowReadState _windowState = WindowReadState.Unknown; private int _windowValidationAttempt; private int _windowValidationBaseline; // records inside the probe window from the preceding full read private DateTimeOffset? _probeWindowStart; // exact window measured at baseline time private DateTimeOffset? _probeWindowEnd; private DateTimeOffset? _lastFullReadAt; private DateTimeOffset? _lastReadInsertAt; private DateTimeOffset? _lastReadSessionEventAt; private bool _attemptWindowed; // was the in-flight read cycle a windowed attempt? private DateTimeOffset? _lastLiveStaleLogAt; private DateTimeOffset _startedAt = DateTimeOffset.UtcNow; private enum WindowReadState { /// No verdict yet: one full read (baseline) then one windowed probe. Unknown = 0, /// Device honoured ReadTimeGLogData — short cycles allowed. Valid = 1, /// Windowed load rejected/ignored/under-fetching — full-buffer reads only. Invalid = 2 } public string WorkerId { get; } public DeviceWorkerHealth Health { get; private set; } = new("Created", false, false, false, null, null, 0, 0); public ChannelReader RealtimeReader => _rtChannel.Reader; public int StaleGenerationRejections => _staleRejected; public DeviceWorker( IZkComSession liveSession, IZkComSession readSession, Phase1DeviceConfig config, ILogger? log = null, ReconciliationPersistence? reconciliation = null, LivePunchIngress? ingress = null) { _live = liveSession; _read = readSession; _config = config; _log = log ?? NullLogger.Instance; _reconciliation = reconciliation; _ingress = ingress; WorkerId = config.Device.DeviceId; _rtChannel = Channel.CreateBounded(new BoundedChannelOptions(config.Realtime.ChannelCapacity) { SingleReader = true, SingleWriter = false, FullMode = BoundedChannelFullMode.DropOldest }); // Realtime subscription on BOTH sessions: // - LIVE is the fast path (RegEvent + OnAttTransactionEx). // - READ is the safety path. The COM layer raises the same events on every subscribed // session; historically the READ session attached sinks but had NO subscriber, so events // that landed there were silently discarded (no log, no counter). Now they are counted, // logged and fed into the same idempotent ingress — a punch can never be lost just // because it arrived on the "wrong" session. _live.AttendanceReceived += OnRealtime; if (!ReferenceEquals(_read, _live)) _read.AttendanceReceived += OnReadRealtime; else _log.LogInformation("WORKER_DUAL_SUBSCRIBE device={Device} mode=shared_session — READ and LIVE are the same session, single realtime subscriber used", WorkerId); } /// LIVE-session realtime event (fast path). private void OnRealtime(RawAttendanceEvent evt) { HandleRealtime(evt, _live, "LIVE"); } /// READ-session realtime event (safety path — same idempotent ingestion). private void OnReadRealtime(RawAttendanceEvent evt) { Interlocked.Increment(ref _readSessionEvents); _lastReadSessionEventAt = DateTimeOffset.UtcNow; HandleRealtime(evt, _read, "READ"); } private void HandleRealtime(RawAttendanceEvent evt, IZkComSession session, string channel) { try { if (evt.Generation != session.Generation) { Interlocked.Increment(ref _staleRejected); _log.LogWarning("STALE_GENERATION_REJECTED device={Device} channel={Ch} evtGen={G} sessionGen={S}", WorkerId, channel, evt.Generation, session.Generation); return; } if (channel == "LIVE") Health = Health with { LastLiveEventAt = DateTimeOffset.UtcNow }; else Health = Health with { LastReadSessionEventAt = _lastReadSessionEventAt }; _log.LogInformation( "RT device={Device} channel={Ch} gen={Gen} pin={Pin} state={State} verify={Verify} time={Y}-{Mo:00}-{D:00} {H:00}:{Mi:00}:{S:00} src={Src}", WorkerId, channel, evt.Generation, evt.PersonnelCode, evt.AttendanceState, evt.VerifyMethod, evt.Year, evt.Month, evt.Day, evt.Hour, evt.Minute, evt.Second, evt.SourceApi); if (!_rtChannel.Writer.TryWrite(evt)) { _log.LogWarning("RT_CHANNEL_DROP device={Device} channel={Ch} generation={G}", WorkerId, channel, evt.Generation); } // Enqueue-only path (no SQLite / no upload / no SDK re-entry) — existing LIVE ingress. _ingress?.EnqueueFromCom(evt, session.Generation); } catch (Exception ex) { _log.LogError(ex, "RT_ENQUEUE_FAILURE device={Device} channel={Ch}", WorkerId, channel); } } public async Task StartAsync() { _log.LogInformation( "WORKER_START device={Device} mode=DUAL_SESSION live={L} read={R} reconWired={Recon} ingressWired={Ingress} windowedReads={Win} windowedIntervalMs={Wi} fullEveryMin={Fm}", WorkerId, _live.Info.WorkerId, _read.Info.WorkerId, _reconciliation is not null, _ingress is not null, _config.Read.TryTimeWindow, _config.Read.WindowedIntervalMs, _config.Read.FullReconcileMinutes); _startedAt = DateTimeOffset.UtcNow; Health = Health with { State = "Starting" }; await _live.InitializeAsync(_cts.Token).ConfigureAwait(false); await _read.InitializeAsync(_cts.Token).ConfigureAwait(false); _loop = Task.Run(() => LoopAsync(_cts.Token)); } private async Task LoopAsync(CancellationToken ct) { var healthInterval = TimeSpan.FromMilliseconds(Math.Max(500, _config.Supervisor.HealthIntervalMs)); var connectRetryDelay = TimeSpan.FromMilliseconds(Math.Max(500, _config.Supervisor.ReconnectDelayMs)); var maxConnectDelay = TimeSpan.FromMilliseconds( Math.Max(connectRetryDelay.TotalMilliseconds, _config.Supervisor.MaxReconnectDelayMs)); try { while (!ct.IsCancellationRequested) { _phase = "IDLE"; try { // ---------------- LIVE ensure (paced independently; never waits on READ) ---------------- var now = DateTimeOffset.UtcNow; if (!_live.IsConnected && now >= _nextLiveConnectAt) { _phase = "LIVE_CONNECT"; var lc = await _live.ConnectAsync(ct).ConfigureAwait(false); if (lc.Success) { _phase = "LIVE_REGEVENT"; await _live.RegEventAsync(_config.Realtime.EventMask, ct).ConfigureAwait(false); _liveConnectFailures = 0; _liveBackoffMs = 0; _nextLiveConnectAt = DateTimeOffset.MinValue; Health = Health with { LiveConnected = true, LiveGeneration = _live.Generation, LiveOwnerThreadId = _live.Info.OwnerThreadId, }; _log.LogInformation( "LIVE_READY device={Device} generation={G} ownerTid={Tid} apt={Apt} mask={Mask}", WorkerId, _live.Generation, _live.Info.OwnerThreadId, _live.Info.ApartmentState, _config.Realtime.EventMask); } else { _liveConnectFailures++; Health = Health with { LiveConnected = false }; _log.LogWarning("LIVE_CONNECT_FAILED device={Device} failures={N} err={Err}", WorkerId, _liveConnectFailures, lc.Error); if (_liveConnectFailures >= ConnectFailureRecreateThreshold) { _phase = "LIVE_RECREATE"; _log.LogWarning("SESSION_LIVE_RECREATE device={Device} reason=connect_failures n={N}", WorkerId, _liveConnectFailures); await _live.RecreateSessionAsync(ct).ConfigureAwait(false); _liveConnectFailures = 0; _log.LogInformation("LIVE_SESSION_RECREATED device={Device} generation={G}", WorkerId, _live.Generation); } _nextLiveConnectAt = DateTimeOffset.UtcNow + NextBackoff(ref _liveBackoffMs, connectRetryDelay, maxConnectDelay); } } // ---------------- READ ensure (fully independent of LIVE) ---------------- now = DateTimeOffset.UtcNow; if (!_read.IsConnected && now >= _nextReadConnectAt) { _phase = "READ_CONNECT"; var rc = await _read.ConnectAsync(ct).ConfigureAwait(false); if (rc.Success) { _phase = "READ_PROBE"; var cap = await _read.ProbeCapabilityAsync(ct).ConfigureAwait(false); _readConnectFailures = 0; _readBackoffMs = 0; _nextReadConnectAt = DateTimeOffset.MinValue; Health = Health with { ReadConnected = true, ReadGeneration = _read.Generation, ReadOwnerThreadId = _read.Info.OwnerThreadId, Capability = cap, DeviceInfoOk = true, }; _log.LogInformation( "READ_READY device={Device} generation={G} ownerTid={Tid} apt={Apt} serial={Serial}", WorkerId, _read.Generation, _read.Info.OwnerThreadId, _read.Info.ApartmentState, cap.Serial); } else { _readConnectFailures++; Health = Health with { ReadConnected = false }; _log.LogWarning("READ_CONNECT_FAILED device={Device} failures={N} err={Err}", WorkerId, _readConnectFailures, rc.Error); if (_readConnectFailures >= ConnectFailureRecreateThreshold) { _phase = "READ_RECREATE"; _log.LogWarning("SESSION_READ_RECREATE device={Device} reason=connect_failures n={N}", WorkerId, _readConnectFailures); await _read.RecreateSessionAsync(ct).ConfigureAwait(false); _readConnectFailures = 0; _log.LogInformation("READ_SESSION_RECREATED device={Device} generation={G}", WorkerId, _read.Generation); } _nextReadConnectAt = DateTimeOffset.UtcNow + NextBackoff(ref _readBackoffMs, connectRetryDelay, maxConnectDelay); } } // ---------------- health tick (timestamp-based, non-blocking; NEVER gates the read cycle) ---------------- await EnsureHealthDueAsync(healthInterval, ct).ConfigureAwait(false); // ---------------- sequential read cycle: complete -> reconcile -> wait interval -> next ---------------- // The interval wait still performs due health checks so health cadence is preserved // without a blocking timer ever delaying or skipping the read scheduler. // Short cycles while the device proves it can serve a bounded window; full-buffer // cadence otherwise (each full read costs ~50s on a 50k-record buffer). var waitEnd = DateTimeOffset.UtcNow + CurrentReadInterval(); while (DateTimeOffset.UtcNow < waitEnd && !ct.IsCancellationRequested) { await EnsureHealthDueAsync(healthInterval, ct).ConfigureAwait(false); var remaining = waitEnd - DateTimeOffset.UtcNow; if (remaining <= TimeSpan.Zero) break; await Task.Delay(remaining < TimeSpan.FromSeconds(1) ? remaining : TimeSpan.FromSeconds(1), ct).ConfigureAwait(false); } _phase = "READ_CYCLE"; await RunReadCycleAsync(ct).ConfigureAwait(false); // Persistent READ failures must self-heal: a session that keeps refusing reads is // torn down and rebuilt instead of being retried forever on the same wedged RCW. if (_consecutiveReadFailures >= _config.Supervisor.ReadRecreateThreshold) { _phase = "READ_RECREATE"; _log.LogWarning("SESSION_READ_RECREATE device={Device} reason=consecutive_read_failures n={N} threshold={T}", WorkerId, _consecutiveReadFailures, _config.Supervisor.ReadRecreateThreshold); try { await _read.RecreateSessionAsync(ct).ConfigureAwait(false); _log.LogInformation("READ_SESSION_RECREATED device={Device} generation={G} reason=consecutive_read_failures", WorkerId, _read.Generation); } catch (Exception rex) { _log.LogError(rex, "SESSION_RECREATE_FAILED device={Device} phase={Phase}", WorkerId, _phase); } _consecutiveReadFailures = 0; _readBackoffMs = 0; _nextReadConnectAt = DateTimeOffset.UtcNow + connectRetryDelay; } // drain realtime channel counter (existing behavior) while (_rtChannel.Reader.TryRead(out _)) Health = Health with { RealtimeReceived = Health.RealtimeReceived + 1 }; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } catch (Exception ex) { _log.LogError(ex, "WORKER_LOOP_ERROR device={Device} phase={Phase}", WorkerId, _phase); Health = Health with { State = "Recovering", LastError = ex.Message }; // Recreate ONLY the session that owns the failing phase — READ failures never touch LIVE. try { if (_phase.StartsWith("LIVE", StringComparison.Ordinal)) { _log.LogWarning("SESSION_LIVE_RECREATE device={Device} reason=loop_error phase={Phase}", WorkerId, _phase); await _live.RecreateSessionAsync(ct).ConfigureAwait(false); _log.LogInformation("LIVE_SESSION_RECREATED device={Device} generation={G}", WorkerId, _live.Generation); } else { _log.LogWarning("SESSION_READ_RECREATE device={Device} reason=loop_error phase={Phase}", WorkerId, _phase); await _read.RecreateSessionAsync(ct).ConfigureAwait(false); _log.LogInformation("READ_SESSION_RECREATED device={Device} generation={G}", WorkerId, _read.Generation); } } catch (Exception rex) { _log.LogError(rex, "SESSION_RECREATE_FAILED device={Device} phase={Phase}", WorkerId, _phase); } await Task.Delay(connectRetryDelay, ct).ConfigureAwait(false); } } } finally { Health = Health with { State = "Stopped" }; _log.LogInformation("WORKER_STOP device={Device}", WorkerId); } } /// /// One sequential read cycle on the READ session, with limited failure retries and backoff. /// Holds for the whole cycle (attempt + backoff + reconciliation), /// so reads can never overlap and the interactive Host "read" command serializes too. /// private async Task RunReadCycleAsync(CancellationToken ct) { if (!_read.IsConnected) { _log.LogWarning("READ_CYCLE_SKIPPED device={Device} reason=read_not_connected", WorkerId); return; } await _readGate.WaitAsync(ct).ConfigureAwait(false); try { var mode = _config.Read.Mode switch { "TimeWindow" => AttendanceReadMode.TimeWindow, "NewOnly" => AttendanceReadMode.NewOnly, "LegacyFull" => AttendanceReadMode.LegacyFull, _ => AttendanceReadMode.Auto }; var apiLabel = mode switch { AttendanceReadMode.TimeWindow => "ReadTimeGLogData", AttendanceReadMode.NewOnly => "ReadNewGLogData", AttendanceReadMode.LegacyFull => "ReadGeneralLogData", _ => "Auto" }; // ---- read-window plan ------------------------------------------------------- // Two cadences: // * FULL pass — whole buffer (Auto/LegacyFull): the safety net that guarantees // completeness, and the baseline used to VALIDATE the device's windowed API. // * WINDOW pass— device-side ReadTimeGLogData: only the slice after the watermark, // so the cycle costs a few records instead of the entire buffer. // The windowed mode is never trusted by default: it is enabled only after the device // proved (baseline vs probe) that it honours the window, and full passes keep running // on top of it, so a broken window can delay data by at most FullReconcileMinutes. var nowUtc = DateTimeOffset.UtcNow; var lookback = TimeSpan.FromMinutes(Math.Max(1, _config.Read.LookbackMinutes)); var fullDue = _lastFullReadAt is null || (nowUtc - _lastFullReadAt.Value) >= TimeSpan.FromMinutes(Math.Max(1, _config.Read.FullReconcileMinutes)); ReconciliationWatermark? watermark = null; if (_reconciliation is not null) watermark = await _reconciliation.LoadWatermarkAsync(WorkerId, ct).ConfigureAwait(false); var tryWindow = false; var plan = "FULL"; DateTimeOffset start; DateTimeOffset end; if (!_config.Read.TryTimeWindow || _windowState == WindowReadState.Invalid || fullDue) { start = nowUtc - lookback; end = nowUtc.AddMinutes(2); plan = fullDue ? (_lastFullReadAt is null ? "FULL(initial)" : "FULL(reconcile)") : (_windowState == WindowReadState.Invalid ? "FULL(window_invalid)" : "FULL(disabled)"); } else if (_windowState == WindowReadState.Valid) { // Device-label window start (watermark) -> real instant for the SDK's ToLocalTime(). var startLabel = watermark?.LastPersistedPunchTime is { } wm && wm != DateTimeOffset.MinValue ? wm.Add(-TimeSpan.FromMinutes(Math.Max(1, _config.Read.OverlapMinutes))) : (DeviceClock.Now() - lookback); start = DeviceClock.ToInstant(startLabel); if (start < nowUtc - lookback) start = nowUtc - lookback; if (start > nowUtc) start = nowUtc - lookback; end = DateTimeOffset.Now + TimeSpan.FromMinutes(10); plan = "WINDOW(watermark)"; tryWindow = true; } else { // Unknown state -> probe exactly the window measured by the preceding FULL pass. start = _probeWindowStart ?? nowUtc - lookback; end = _probeWindowEnd ?? (DateTimeOffset.Now + TimeSpan.FromMinutes(10)); plan = "WINDOW(probe)"; tryWindow = true; } var attempt = 0; while (!ct.IsCancellationRequested) { attempt++; _attemptWindowed = tryWindow; var startUtc = DateTimeOffset.UtcNow; var sw = Stopwatch.StartNew(); _log.LogInformation( "READ_ATTEMPT device={Device} generation={G} ownerTid={Tid} api={Api} plan={Plan} start={Start} end={End} attempt={A} retry={R} wm={Wm} windowState={Ws}", WorkerId, _read.Generation, _read.Info.OwnerThreadId, apiLabel, plan, start.ToString("o"), end.ToString("o"), attempt, attempt > 1, watermark?.LastPersistedPunchTime, _windowState); AttendanceReadResult result; try { result = await _read.ReadAttendanceAsync( new AttendanceReadRequest(start, end, mode, _config.Read.MaxRecordsPerRead, AllowFallback: true, TryTimeWindow: tryWindow), ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } catch (Exception ex) { // Transport/COM exception from the READ session: still a READ failure — LIVE untouched. sw.Stop(); RecordReadFailure(apiLabel, startUtc, sw.ElapsedMilliseconds, attempt, ex.Message, "EXCEPTION"); if (attempt > _config.Read.FailureRetryLimit) { _log.LogWarning("READ_RETRY_EXHAUSTED device={Device} generation={G} ownerTid={Tid} api={Api} attempts={A} limit={L} consecutiveFailures={C}", WorkerId, _read.Generation, _read.Info.OwnerThreadId, apiLabel, attempt, _config.Read.FailureRetryLimit, _consecutiveReadFailures); return; } _log.LogInformation("READ_RETRY device={Device} generation={G} ownerTid={Tid} api={Api} attempt={A} nextAttemptInMs={B} reason=exception consecutive={C}", WorkerId, _read.Generation, _read.Info.OwnerThreadId, apiLabel, attempt, _config.Read.FailureRetryBackoffMs, _consecutiveReadFailures); await Task.Delay(_config.Read.FailureRetryBackoffMs, ct).ConfigureAwait(false); continue; } sw.Stop(); var endUtc = DateTimeOffset.UtcNow; var ok = result.Status is AttendanceReadStatus.Success or AttendanceReadStatus.TrueEmpty; var fields = new { device = WorkerId, generation = _read.Generation, ownerTid = _read.Info.OwnerThreadId, api = result.ApiUsed ?? apiLabel, startUtc = startUtc.ToString("o"), endUtc = endUtc.ToString("o"), durationMs = sw.ElapsedMilliseconds, recordCount = result.Records.Count, nativeLastError = result.LastError, status = result.Status.ToString(), attempt }; if (ok) { var wasFailing = _consecutiveReadFailures > 0; var priorFailures = _consecutiveReadFailures; _consecutiveReadFailures = 0; if (wasFailing) { _log.LogInformation( "READ_RECOVERY device={Device} generation={G} ownerTid={Tid} api={Api} startUtc={Start} endUtc={End} durationMs={Ms} recordCount={N} nativeLastError={E} status=Success priorConsecutiveFailures={P}", fields.device, fields.generation, fields.ownerTid, fields.api, fields.startUtc, fields.endUtc, fields.durationMs, fields.recordCount, fields.nativeLastError, priorFailures); } else { _log.LogInformation( "READ_SUCCESS device={Device} generation={G} ownerTid={Tid} api={Api} startUtc={Start} endUtc={End} durationMs={Ms} recordCount={N} nativeLastError={E} status=Success", fields.device, fields.generation, fields.ownerTid, fields.api, fields.startUtc, fields.endUtc, fields.durationMs, fields.recordCount, fields.nativeLastError); } Health = Health with { State = DeriveState(), FunctionalReadOk = true, ReadsCompleted = Health.ReadsCompleted + 1, LastReadSuccessAt = DateTimeOffset.UtcNow, LastReadRecordCount = result.Records.Count, LastReadDurationMs = sw.ElapsedMilliseconds, LastReadApi = result.ApiUsed ?? apiLabel, ConsecutiveReadFailures = 0, }; // ---- read-window bookkeeping (see the window plan above) ---- if (!tryWindow) { // Full-buffer pass = safety net done + validation baseline captured. _lastFullReadAt = DateTimeOffset.UtcNow; if (_config.Read.TryTimeWindow && _windowState == WindowReadState.Unknown) { _probeWindowStart = start; _probeWindowEnd = end; _windowValidationBaseline = CountInWindow(result.Records, start, end); } } else { EvaluateWindowProbe(result); } if (result.Records.Count > 0) { if (_reconciliation is null) { _log.LogWarning("READ_PERSIST_SKIPPED device={Device} reason=persistence_not_wired records={N}", WorkerId, result.Records.Count); } else { var outcome = await _reconciliation.PersistReadAsync( WorkerId, result.Records, PunchSource.Reconciliation, _read.Generation, ReconOverlap, ReconClockSkew, allowWatermarkAdvance: true, cancellationToken: ct).ConfigureAwait(false); if (outcome.Batch.Inserted > 0) _lastReadInsertAt = DateTimeOffset.UtcNow; _log.LogInformation( "READ_RECONCILED device={Device} records={N} inserted={I} duplicates={D} watermarkAdvanced={W} wm={WM}", WorkerId, result.Records.Count, outcome.Batch.Inserted, outcome.Batch.Duplicates, outcome.WatermarkAdvanced, outcome.WatermarkAfter); } } return; } // ---- READ FAILURE: log + limited retry with backoff on the READ session ONLY. No recreate (§7). ---- RecordReadFailure(apiLabel, startUtc, sw.ElapsedMilliseconds, attempt, result.Error ?? result.Status.ToString(), result.Status.ToString(), result.LastError, result.Records.Count); if (result.Status == AttendanceReadStatus.Disconnected) { _log.LogWarning("READ_SESSION_DISCONNECTED device={Device} — reconnect happens on next ensure pass; LIVE unaffected", WorkerId); return; } if (attempt > _config.Read.FailureRetryLimit) { _log.LogWarning("READ_RETRY_EXHAUSTED device={Device} generation={G} ownerTid={Tid} api={Api} attempts={A} limit={L} consecutiveFailures={C}", WorkerId, _read.Generation, _read.Info.OwnerThreadId, apiLabel, attempt, _config.Read.FailureRetryLimit, _consecutiveReadFailures); return; } _log.LogInformation("READ_RETRY device={Device} generation={G} ownerTid={Tid} api={Api} attempt={A} nextAttemptInMs={B} reason=read_failure consecutive={C}", WorkerId, _read.Generation, _read.Info.OwnerThreadId, apiLabel, attempt, _config.Read.FailureRetryBackoffMs, _consecutiveReadFailures); await Task.Delay(_config.Read.FailureRetryBackoffMs, ct).ConfigureAwait(false); } } finally { _readGate.Release(); } } private void RecordReadFailure(string api, DateTimeOffset startUtc, long durationMs, int attempt, string? error, string status, int? nativeLastError = null, int recordCount = 0) { _consecutiveReadFailures++; _log.LogWarning( "READ_FAILURE device={Device} generation={G} ownerTid={Tid} api={Api} startUtc={Start} endUtc={End} durationMs={Ms} recordCount={N} nativeLastError={E} status={Status} attempt={A} consecutive={C} error={Err}", WorkerId, _read.Generation, _read.Info.OwnerThreadId, api, startUtc.ToString("o"), DateTimeOffset.UtcNow.ToString("o"), durationMs, recordCount, nativeLastError, status, attempt, _consecutiveReadFailures, error); Health = Health with { State = "Degraded", FunctionalReadOk = false, ConsecutiveReadFailures = _consecutiveReadFailures, LastReadFailureAt = DateTimeOffset.UtcNow, LastReadFailureError = error, LastReadApi = api, LastReadDurationMs = durationMs, }; // A windowed attempt that errors must never starve the safety net: // * force a full-buffer pass on the next cycle (immediate completeness guarantee), and // * judge the probe — after repeated probe failures the fast mode is abandoned for good. if (_attemptWindowed) { _lastFullReadAt = null; if (_windowState == WindowReadState.Unknown) { _windowValidationAttempt++; if (_windowValidationAttempt >= 3) { _windowState = WindowReadState.Invalid; _log.LogError( "READ_WINDOW_MODE_DISABLED device={Device} reason=probe_repeatedly_failing attempt={A} — full-buffer reads only", WorkerId, _windowValidationAttempt); } } } } private string DeriveState() { if (!_live.IsConnected || !_read.IsConnected) return "Connecting"; if (_consecutiveReadFailures > 0) return "Degraded"; if (_livePingFailures > 0 || _readPingFailures > 0) return "Degraded"; return "Ready"; } /// /// Exponential backoff with jitter for connect attempts: 1×, 2×, 4× … capped at /// . Prevents the "thousands of identical retries against a dead /// endpoint" pattern while never giving up (recovery stays automatic). /// private static TimeSpan NextBackoff(ref int backoffMs, TimeSpan baseDelay, TimeSpan max) { var current = backoffMs <= 0 ? (int)baseDelay.TotalMilliseconds : backoffMs; var next = (int)Math.Min(max.TotalMilliseconds, Math.Max(baseDelay.TotalMilliseconds, current * 2L)); backoffMs = next; var jitter = Random.Shared.Next(0, Math.Max(1, next / 4)); return TimeSpan.FromMilliseconds(next + jitter); } /// /// Cadence of the next read cycle: short once the device has PROVEN it serves a bounded window, /// full-buffer cadence otherwise (a full read over a large buffer takes tens of seconds). /// private TimeSpan CurrentReadInterval() { // Live-first cadence: // Valid -> windowed cadence (WindowedIntervalMs); the read is a cheap sub-second slice. // Unknown -> the windowed API is still being VALIDATED, so keep the supervisor cadence: // the probe must run promptly or the device stays on full reads for a whole // interval (and can never become Valid). // Invalid -> the firmware has no usable window, so EVERY cycle is a full multi-10k // ReadGeneralLogData. Run it on the reconcile cadence (FullReconcileMinutes). // This used to return Supervisor.ReadIntervalMs for ALL non-Valid states, which made a // window=Invalid device full-read every 60s - measured 82 full reads / 95 min on // 172.30.70.5, the single largest source of device load and the cause of the minute-long // COM stalls that starved LIVE event delivery. var supervisor = TimeSpan.FromMilliseconds(Math.Max(500, _config.Supervisor.ReadIntervalMs)); if (!_config.Read.TryTimeWindow) return supervisor; var full = _windowState == WindowReadState.Invalid ? TimeSpan.FromMinutes(Math.Max(1, _config.Read.FullReconcileMinutes)) : supervisor; if (_windowState != WindowReadState.Valid) return full; var windowed = TimeSpan.FromMilliseconds(Math.Max(500, _config.Read.WindowedIntervalMs)); return windowed < full ? windowed : full; } /// How many raw records fall inside [from, to] (device labels converted to instants). private static int CountInWindow(IReadOnlyList records, DateTimeOffset from, DateTimeOffset to) { var n = 0; foreach (var r in records) { if (!DeviceClock.TryComposeDeviceLabelled(r.Year, r.Month, r.Day, r.Hour, r.Minute, r.Second, out var labelled)) continue; var instant = DeviceClock.ToInstant(labelled); if (instant >= from && instant <= to) n++; } return n; } /// /// Decide whether the device can be trusted with the windowed (fast) load. /// Never optimistic: a window that under-fetches would silently drop punches, so the mode is /// enabled only when the probe matches the full-read baseline — and full passes keep running /// afterwards as a safety net regardless. /// private void EvaluateWindowProbe(AttendanceReadResult result) { if (_windowState != WindowReadState.Unknown) return; _windowValidationAttempt++; if (!result.WindowedLoad) { _windowState = WindowReadState.Invalid; _log.LogError( "READ_WINDOW_MODE_DISABLED device={Device} reason=firmware_rejected_window attempt={A} — full-buffer reads only", WorkerId, _windowValidationAttempt); return; } var probe = result.Records.Count; var baseline = _windowValidationBaseline; if (probe < baseline) { _windowState = WindowReadState.Invalid; _log.LogError( "READ_WINDOW_MODE_DISABLED device={Device} reason=under_fetch probe={P} baseline={B} attempt={A} — window would drop records", WorkerId, probe, baseline, _windowValidationAttempt); return; } if (probe > baseline + Math.Max(20, baseline / 2)) { _windowState = WindowReadState.Invalid; _log.LogError( "READ_WINDOW_MODE_DISABLED device={Device} reason=window_ignored probe={P} baseline={B} attempt={A} — device returned the whole buffer", WorkerId, probe, baseline, _windowValidationAttempt); return; } if (probe == 0 && baseline == 0 && _windowValidationAttempt < 3) { _log.LogInformation( "READ_WINDOW_PROBE_INCONCLUSIVE device={Device} attempt={A} probe=0 baseline=0 — nothing to compare, retrying", WorkerId, _windowValidationAttempt); return; } _windowState = WindowReadState.Valid; _log.LogInformation( "READ_WINDOW_MODE_ENABLED device={Device} attempt={A} probe={P} baseline={B} intervalMs={I} fullEveryMin={F}", WorkerId, _windowValidationAttempt, probe, baseline, CurrentReadInterval().TotalMilliseconds, _config.Read.FullReconcileMinutes); } /// /// Cheap health tick: session state + LIVENESS probe + staleness alarms. /// Never performs an attendance-log read; recreates ONLY the session whose pump is dead. /// private async Task EnsureHealthDueAsync(TimeSpan healthInterval, CancellationToken ct) { var now = DateTimeOffset.UtcNow; if (now < _nextHealthAt) return; _nextHealthAt = now + healthInterval; _phase = "HEALTH"; Health = Health with { LiveConnected = _live.IsConnected, ReadConnected = _read.IsConnected, LiveGeneration = _live.Generation, ReadGeneration = _read.Generation, LiveOwnerThreadId = _live.Info.OwnerThreadId, ReadOwnerThreadId = _read.Info.OwnerThreadId, LivePumpAlive = _live.PumpAlive, ReadPumpAlive = _read.PumpAlive, EventsDirectOnOwner = _live.EventsDirectOnOwner, EventsHandedToOwner = _live.EventsHandedToOwner, EventsDropped = _live.EventsDropped, Connected = _live.IsConnected && _read.IsConnected, State = DeriveState(), ReadSessionEvents = Interlocked.Read(ref _readSessionEvents), LastReadSessionEventAt = Health.LastReadSessionEventAt ?? _lastReadSessionEventAt, LivePingFailures = _livePingFailures, ReadPingFailures = _readPingFailures, WindowedReads = _windowState.ToString(), LastFullReadAt = _lastFullReadAt, LiveStaleOccurrences = _liveStaleOccurrences, }; _log.LogInformation( "DUAL_HEALTH device={Device} liveC={LC} liveGen={LG} liveOwner={LO} livePump={LP} liveLastEvent={LE} evDirect={ED} evHanded={EH} evDropped={EDr} readC={RC} readGen={RG} readOwner={RO} readPump={RP} lastReadOk={LS} lastReadFail={LF} consecFail={CF} lastCount={N} lastMs={Ms} readEv={REV} readLastEv={RLE} pingFail={PF} window={WS} lastFull={LFu} liveStale={LSt}", WorkerId, Health.LiveConnected, Health.LiveGeneration, Health.LiveOwnerThreadId, Health.LivePumpAlive, Health.LastLiveEventAt, Health.EventsDirectOnOwner, Health.EventsHandedToOwner, Health.EventsDropped, Health.ReadConnected, Health.ReadGeneration, Health.ReadOwnerThreadId, Health.ReadPumpAlive, Health.LastReadSuccessAt, Health.LastReadFailureAt, Health.ConsecutiveReadFailures, Health.LastReadRecordCount, Health.LastReadDurationMs, Health.ReadSessionEvents, Health.LastReadSessionEventAt, _livePingFailures + _readPingFailures, _windowState, _lastFullReadAt, _liveStaleOccurrences); if (_read.IsConnected && !_read.PumpAlive && await PumpConfirmedDeadAsync(_read, ct).ConfigureAwait(false)) { _phase = "READ_RECREATE"; _log.LogError("READ_PUMP_DEAD device={Device} generation={G} — recreating READ session only", WorkerId, _read.Generation); _log.LogWarning("SESSION_READ_RECREATE device={Device} reason=pump_dead generation={G}", WorkerId, _read.Generation); await _read.RecreateSessionAsync(ct).ConfigureAwait(false); _log.LogInformation("READ_SESSION_RECREATED device={Device} reason=pump_dead generation={G}", WorkerId, _read.Generation); } if (_live.IsConnected && !_live.PumpAlive && await PumpConfirmedDeadAsync(_live, ct).ConfigureAwait(false)) { _phase = "LIVE_RECREATE"; _log.LogError("LIVE_PUMP_DEAD device={Device} generation={G} — recreating LIVE session only", WorkerId, _live.Generation); _log.LogWarning("SESSION_LIVE_RECREATE device={Device} reason=pump_dead generation={G}", WorkerId, _live.Generation); await _live.RecreateSessionAsync(ct).ConfigureAwait(false); _log.LogInformation("LIVE_SESSION_RECREATED device={Device} reason=pump_dead generation={G}", WorkerId, _live.Generation); } // ---- I/O liveness: connection state must be PROVEN, never assumed ---- // (OnDisConnected never fires on these devices; a session can be "connected" forever // while answering nothing — that is exactly the outage this catches.) if (_live.IsConnected) await ProbeLivenessAsync(_live, "LIVE", ct).ConfigureAwait(false); // Never probe the READ session while it holds the read gate (its command queue would // queue behind an in-flight read and produce a false timeout). if (_read.IsConnected && _readGate.CurrentCount > 0) await ProbeLivenessAsync(_read, "READ", ct).ConfigureAwait(false); RaiseLiveStalenessAlarm(now); } /// /// Confirms an owner-thread pump is genuinely dead before its session is torn down. /// /// is refreshed ONLY on the owner thread's wait/dispatch /// cycle (quantum 250 ms), so it reads stale-false for up to one quantum AFTER a blocking SDK /// call returns — and a full-buffer read is exactly such a call (it starves the pump for tens of /// seconds). This sequential loop's health tick fires as soon as the read+persist pass ends, so a /// fast persist lands it inside that stale window and a single false reading would recreate a /// healthy session on every cycle. Re-check once past one pump quantum: a real stall stays false. /// private async Task PumpConfirmedDeadAsync(IZkComSession session, CancellationToken ct) { try { await Task.Delay(TimeSpan.FromMilliseconds(500), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return false; } return session.IsConnected && !session.PumpAlive; } /// /// One cheap liveness round trip. Two consecutive failures mean the session is a zombie: /// its flag is dropped so the normal connect/recreate path rebuilds it automatically. /// private async Task ProbeLivenessAsync(IZkComSession session, string label, CancellationToken ct) { var isRead = label == "READ"; bool ok; try { ok = await session.PingAsync(ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } catch (Exception ex) { _log.LogWarning(ex, "LIVENESS_PROBE_ERROR device={Device} session={S}", WorkerId, label); ok = false; } if (ok) { if (isRead) _readPingFailures = 0; else _livePingFailures = 0; return; } var failures = isRead ? ++_readPingFailures : ++_livePingFailures; var threshold = Math.Max(1, _config.Supervisor.PingFailThreshold); _log.LogWarning("LIVENESS_FAILURE device={Device} session={S} consecutive={N} threshold={T}", WorkerId, label, failures, threshold); if (failures < threshold) return; try { _phase = label + "_STALE"; await session.DisconnectAsync(ct).ConfigureAwait(false); if (isRead) _readPingFailures = 0; else _livePingFailures = 0; if (isRead) _nextReadConnectAt = DateTimeOffset.UtcNow; else _nextLiveConnectAt = DateTimeOffset.UtcNow; _log.LogWarning( "SESSION_MARKED_DISCONNECTED device={Device} session={S} reason=liveness_failures n={N} — reconnect (and recreate if it keeps failing) scheduled", WorkerId, label, failures); } catch (Exception ex) { _log.LogWarning(ex, "LIVENESS_DISCONNECT_FAILED device={Device} session={S}", WorkerId, label); } } /// /// "Live says healthy but nothing arrives" detector: fires when READ keeps persisting new /// punches while the LIVE session has produced no event for the configured window. /// private void RaiseLiveStalenessAlarm(DateTimeOffset now) { if (!_live.IsConnected) return; if (_lastReadInsertAt is null || now - _lastReadInsertAt.Value > TimeSpan.FromMinutes(5)) return; // only meaningful while READ is actually observing fresh traffic var since = Health.LastLiveEventAt ?? _startedAt; if (now - since < TimeSpan.FromMinutes(Math.Max(1, _config.Supervisor.LiveStaleMinutes))) return; if (now - (_lastLiveStaleLogAt ?? DateTimeOffset.MinValue) < TimeSpan.FromMinutes(5)) return; _liveStaleOccurrences++; _lastLiveStaleLogAt = now; _log.LogError( "LIVE_STALE_ALARM device={Device} connected=True since={Since} lastLiveEvent={LE} readInsertedAt={RI} readSessionEvents={REV} occurrences={N} — LIVE reports healthy while READ observes new punches", WorkerId, since, Health.LastLiveEventAt, _lastReadInsertAt, Interlocked.Read(ref _readSessionEvents), _liveStaleOccurrences); } /// Interactive/manual read (Host command) — same READ session, serialized via the read gate. public async Task ReadOnceAsync(CancellationToken ct = default) { await _readGate.WaitAsync(ct).ConfigureAwait(false); try { var mode = _config.Read.Mode switch { "TimeWindow" => AttendanceReadMode.TimeWindow, "NewOnly" => AttendanceReadMode.NewOnly, "LegacyFull" => AttendanceReadMode.LegacyFull, _ => AttendanceReadMode.Auto }; var start = DateTimeOffset.UtcNow.AddMinutes(-_config.Read.LookbackMinutes); var end = DateTimeOffset.UtcNow.AddMinutes(2); var result = await _read.ReadAttendanceAsync( new AttendanceReadRequest(start, end, mode, _config.Read.MaxRecordsPerRead), ct).ConfigureAwait(false); _log.LogInformation( "WORKER_READ device={Device} status={Status} api={Api} drain={Drain} count={Count} ms={Ms} err={Err}", WorkerId, result.Status, result.ApiUsed, result.DrainApiUsed, result.Records.Count, result.ElapsedMs, result.Error); return result; } finally { _readGate.Release(); } } /// Operator-forced full recreate (explicit command only): READ first, then LIVE. Not used by failure paths. public async Task RecreateAsync(CancellationToken ct = default) { _log.LogWarning("WORKER_SESSION_RECREATE device={Device} scope=BOTH reason=operator_forced", WorkerId); Health = Health with { State = "Recovering" }; await _read.RecreateSessionAsync(ct).ConfigureAwait(false); _log.LogInformation("READ_SESSION_RECREATED device={Device} generation={G} reason=operator_forced", WorkerId, _read.Generation); await _live.RecreateSessionAsync(ct).ConfigureAwait(false); _log.LogInformation("LIVE_SESSION_RECREATED device={Device} generation={G} reason=operator_forced", WorkerId, _live.Generation); Health = Health with { State = DeriveState() }; } public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) return; // idempotent _live.AttendanceReceived -= OnRealtime; if (!ReferenceEquals(_read, _live)) _read.AttendanceReceived -= OnReadRealtime; await _cts.CancelAsync().ConfigureAwait(false); if (_loop is not null) { try { await _loop.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); } catch { /* best effort */ } } await _live.DisposeAsync().ConfigureAwait(false); await _read.DisposeAsync().ConfigureAwait(false); _cts.Dispose(); _readGate.Dispose(); } } public sealed record Phase1DeviceConfig( DeviceEndpoint Device, SdkConfig Sdk, SessionConfig Session, RealtimeConfig Realtime, ReadConfig Read, SupervisorConfig Supervisor); public sealed record DeviceEndpoint(string DeviceId, string DisplayName, string Ip, int Port, int MachineNumber, int CommKey); public sealed record SdkConfig(int CommTimeoutSeconds, string ExpectedSdkVersion); public sealed record SessionConfig(int OperationTimeoutMs, int ConnectTimeoutMs); public sealed record RealtimeConfig(int EventMask, int ChannelCapacity); public sealed record ReadConfig( string Mode, int LookbackMinutes, int MaxRecordsPerRead, int FailureRetryLimit = 3, int FailureRetryBackoffMs = 15000, /// Attempt the device-side windowed load first (validated at runtime; falls back safely). bool TryTimeWindow = true, /// Cycle interval while the windowed load is validated and active. int WindowedIntervalMs = 15000, /// Periodic full-buffer pass: the completeness safety net (and window validator). int FullReconcileMinutes = 10, /// How far back the watermark may sit before a window is considered too old. int OverlapMinutes = 10); public sealed record SupervisorConfig( int ReconnectDelayMs, int HealthIntervalMs, int ReadIntervalMs, /// Upper bound of the exponential reconnect backoff. int MaxReconnectDelayMs = 60000, /// Consecutive failed liveness probes before a session is dropped and rebuilt. int PingFailThreshold = 2, /// Consecutive failed read cycles before the READ session is recreated. int ReadRecreateThreshold = 6, /// Minutes without a LIVE event (while READ keeps seeing traffic) before LIVE_STALE_ALARM. int LiveStaleMinutes = 15); public sealed record DeviceWorkerHealth( string State, bool Connected, bool DeviceInfoOk, bool FunctionalReadOk, DeviceCapability? Capability, string? LastError, long RealtimeReceived, long ReadsCompleted) { // Dual-session observability (§15) — LIVE metrics public bool LiveConnected { get; init; } public int LiveGeneration { get; init; } public int? LiveOwnerThreadId { get; init; } public bool LivePumpAlive { get; init; } public DateTimeOffset? LastLiveEventAt { get; init; } public long EventsDirectOnOwner { get; init; } public long EventsHandedToOwner { get; init; } public long EventsDropped { get; init; } // Dual-session observability (§15) — READ metrics public bool ReadConnected { get; init; } public int ReadGeneration { get; init; } public int? ReadOwnerThreadId { get; init; } public bool ReadPumpAlive { get; init; } public DateTimeOffset? LastReadSuccessAt { get; init; } public int LastReadRecordCount { get; init; } public long LastReadDurationMs { get; init; } public string? LastReadApi { get; init; } public DateTimeOffset? LastReadFailureAt { get; init; } public string? LastReadFailureError { get; init; } public int ConsecutiveReadFailures { get; init; } // ---- multi-path acquisition / self-healing observability ---- /// Realtime events observed on the READ session (they used to be silently discarded). public long ReadSessionEvents { get; init; } public DateTimeOffset? LastReadSessionEventAt { get; init; } /// Consecutive failed liveness probes per session (0 = answering). public int LivePingFailures { get; init; } public int ReadPingFailures { get; init; } /// Windowed-read verdict: Unknown / Valid / Invalid. public string WindowedReads { get; init; } = "Unknown"; public DateTimeOffset? LastFullReadAt { get; init; } /// How many times LIVE looked healthy while READ kept proving fresh traffic. public int LiveStaleOccurrences { get; init; } }