import sqlite3, datetime, collections, statistics as st, os DB = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\attendancehub_v2.db" NOW = datetime.datetime.now(datetime.timezone.utc) today = NOW.strftime("%Y-%m-%d") def parse(s): if not s: return None s = s.rstrip("Z") w, _, fr = s.partition(".") fr = (fr + "0000000")[:7] try: return (datetime.datetime.fromisoformat(w).replace(tzinfo=datetime.timezone.utc) + datetime.timedelta(microseconds=int(fr) / 10)) except Exception: return None con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True, timeout=20) print("=== 1) TODAY: live vs reconciliation (excluding future-dated garbage) ===") rows = con.execute( "SELECT personnel_code, device_id, punch_time, first_seen_at, source, upload_state " "FROM punches WHERE punch_time >= ? AND punch_time <= ?", (today, today + "T23:59:59.9999999Z")).fetchall() c = collections.Counter(r[4] for r in rows) tot = sum(c.values()) for k, v in c.most_common(): print(f" {k:<16} {v:>5} ({100*v/tot:.2f}%)") print(f" TOTAL real punches today = {tot}") print("\n=== 2) per-device live ratio ===") per = collections.defaultdict(collections.Counter) for r in rows: per[r[1]][r[4]] += 1 for d in sorted(per): t = sum(per[d].values()) rt = per[d].get("Realtime", 0) print(f" {d:<16} total={t:<5} realtime={rt:<5} recon={per[d].get('Reconciliation',0):<4} " f"{100*rt/max(1,t):.1f}% live") print("\n=== 3) LIVE leg latency today (device label -> first_seen) ===") lat = [] for pc, dev, pt, fs, src, stt in rows: if src != "Realtime": continue p, f = parse(pt), parse(fs) if not p or not f: continue # label is site-local stored as UTC-ish; convert to true instant lat.append((f - (p - datetime.timedelta(seconds=12600 - 84))).total_seconds()) lat.sort() if lat: n = len(lat) p = lambda q: lat[min(n-1, int(round(q*(n-1))))] print(f" n={n} min={lat[0]:.0f}s p05={p(.05):.0f}s p50={p(.5):.0f}s " f"p95={p(.95):.0f}s max={lat[-1]:.0f}s") for thr in (30, 45, 60, 90): k = sum(1 for x in lat if x <= thr) print(f" <= {thr:>2}s : {k:>5}/{n} ({100*k/n:.1f}%)") print("\n=== 4) reconciliation punches: WHEN did they occur vs when ingested ===") recon = [(parse(r[3]), parse(r[2]), r[0], r[1]) for r in rows if r[4] == "Reconciliation"] recon = [(a, b, pc, d) for a, b, pc, d in recon if a and b] if recon: lag = [(a - (b - datetime.timedelta(seconds=12600 - 84))).total_seconds() for a, b, _, _ in recon] print(f" n={len(lag)} min={min(lag)/60:.1f}min p50={st.median(lag)/60:.1f}min " f"max={max(lag)/60:.1f}min") print(" samples (punchTime -> ingested, device):") for a, b, pc, d in sorted(recon, key=lambda x: x[1])[-8:]: true_p = b - datetime.timedelta(seconds=12600 - 84) print(f" pin={pc:<8} {d:<16} punch={true_p.astimezone().strftime('%H:%M:%S')} " f"ingest={a.astimezone().strftime('%H:%M:%S')} " f"lag={(a-true_p).total_seconds()/60:.1f}min") print("\n=== 5) upload state now ===") for r in con.execute("SELECT upload_state, COUNT(*) FROM punches GROUP BY upload_state"): print(f" {r[0]}: {r[1]}") print("\n=== 6) oldest still-Pending (is anything stuck?) ===") for r in con.execute( "SELECT MIN(punch_time), MAX(punch_time), COUNT(*) FROM punches " "WHERE upload_state='Pending'"): print(f" Pending: n={r[2]} punch_time {r[0]} .. {r[1]}") print(f"\n db size = {os.path.getsize(DB)/1024/1024:.1f} MB") con.close()