import json, sqlite3, datetime, collections, statistics as st, os HERE = os.path.dirname(os.path.abspath(__file__)) DB = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\attendancehub_v2.db" SLOW = os.path.join(HERE, "slow_from_mysql.json") SITE, SKEW = 12600, 84 def parse(s): if s is None: 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 slow = json.load(open(SLOW, encoding="utf-8")) print(f"slow rows from MySQL: {len(slow)}") con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True, timeout=20) # index sqlite punches for today by (pin, punch_time label) idx = {} for pc, pt, fs, src, stt, ack in con.execute( "SELECT personnel_code, punch_time, first_seen_at, source, upload_state, acked_at " "FROM punches WHERE punch_time >= '2026-10-10'"): key = (pc, pt[:19].replace(" ", "T") if pt else pt) idx.setdefault(key, []).append((parse(fs), src, stt, parse(ack), pt)) matched, unmatched = [], [] for r in slow: pc, pt, ct, diff_s, ip = r["personnel_code"], r["pt"], r["ct"], r["diff_s"], r["ip"] key = (pc, pt) hit = idx.get(key) if not hit: # tolerate seconds/micro differences cand = [v for (p, t), v in idx.items() if p == pc and t and t[:16] == pt[:16]] hit = cand[0] if cand else None if hit: fs, src, stt, ack, _ = hit[0] matched.append(dict(pc=pc, pt=pt, ct=ct, diff=diff_s, ip=ip, first_seen=fs, source=src, state=stt, acked=ack)) else: unmatched.append(dict(pc=pc, pt=pt, ct=ct, diff=diff_s, ip=ip)) print(f"matched in SQLite: {len(matched)} unmatched: {len(unmatched)}") print("\n=== 1) SOURCE of the slow punches (did LIVE deliver them?) ===") c = collections.Counter(m["source"] for m in matched) for k, v in c.most_common(): print(f" {k:<16} {v:>4} ({100*v/max(1,len(matched)):.0f}%)") print("\n=== 2) latency decomposition (seconds) ===") rows = [] for m in matched: if not m["first_seen"]: continue # punch label -> true UTC instant pl = datetime.datetime.fromisoformat(m["pt"].replace(" ", "T")).replace( tzinfo=datetime.timezone.utc) punch_utc = pl - datetime.timedelta(seconds=SITE - SKEW) ingest = (m["first_seen"] - punch_utc).total_seconds() # device -> sqlite (LIVE leg) acklag = ((m["acked"] - m["first_seen"]).total_seconds() if m["acked"] else None) # sqlite -> mysql ack # mysql created h, mi, s = map(int, m["ct"].split(":")) mysql_utc = (datetime.datetime(2026, 10, 10, h, mi, s, tzinfo=datetime.timezone.utc) - datetime.timedelta(seconds=SITE)) to_mysql = (mysql_utc - m["first_seen"]).total_seconds() # sqlite -> mysql created rows.append((ingest, to_mysql, acklag, m["source"], m["pc"], m["pt"], m["ct"], m["diff"])) if rows: ing = [r[0] for r in rows] tm = [r[1] for r in rows] print(f" device -> SQLite (LIVE leg): n={len(ing)} min={min(ing):.0f}s " f"p50={st.median(ing):.0f}s max={max(ing):.0f}s") print(f" SQLite -> MySQL created: n={len(tm)} min={min(tm):.0f}s " f"p50={st.median(tm):.0f}s max={max(tm):.0f}s") fast = sum(1 for x in ing if x <= 60) print(f" LIVE leg <= 60s : {fast}/{len(ing)} ({100*fast/len(ing):.0f}%)") fast30 = sum(1 for x in ing if x <= 40) print(f" LIVE leg <= 40s : {fast30}/{len(ing)} ({100*fast30/len(ing):.0f}%)") print("\n=== 3) worst 12 decomposed ===") rows.sort(key=lambda x: -x[1]) print(f" {'pin':<8}{'punch(dev)':<20}{'live leg':>10}{'to MySQL':>10}{'total':>8} source") for ing_, tm_, ak, src, pc, pt, ct, diff in rows[:12]: print(f" {pc:<8}{pt:<20}{ing_:>9.0f}s{tm_:>9.0f}s{diff:>7}s {src}") print("\n=== 4) SQLite source mix TODAY (all punches) ===") for r in con.execute( "SELECT source, COUNT(*) FROM punches WHERE punch_time >= '2026-10-10' GROUP BY source"): print(f" {r[0]}: {r[1]}") print("\n=== 5) upload backlog evidence: acked_at clusters ===") ackhours = collections.Counter() inghours = collections.Counter() for r in con.execute( "SELECT first_seen_at, acked_at FROM punches WHERE punch_time >= '2026-10-10'"): a = parse(r[1]); f = parse(r[0]) if a: ackhours[a.astimezone(datetime.timezone(datetime.timedelta(hours=3, minutes=30))).strftime("%H")] += 1 if f: inghours[f.astimezone(datetime.timezone(datetime.timedelta(hours=3, minutes=30))).strftime("%H")] += 1 print(" ingest hour (local):", dict(sorted(inghours.items()))) print(" ack hour (local):", dict(sorted(ackhours.items()))) if unmatched: print(f"\n=== UNMATCHED sample (first 8) ===") for u in unmatched[:8]: print(f" {u}") con.close()