diff --git a/tools/v1_time_audit.py b/tools/v1_time_audit.py new file mode 100644 index 0000000..31246f4 --- /dev/null +++ b/tools/v1_time_audit.py @@ -0,0 +1,156 @@ +"""Audit how a v1 (pre-platform-v2) pos.db stored its timestamps. + +Platform v2 (APPS_PLATFORM.md D-11) stores every moment in UTC. v1 stored naive +strings ('2026-05-01 12:59:16.078901'), written by a mix of server code and +client-supplied values, so the history importer (plan step 7.1) must know, per +column, whether a value is UTC or venue-local before converting it. + +How a column is classified (reference = orders.opened_at, written server-side +with datetime.now(timezone.utc), i.e. UTC): + * linked columns (rows that point at an order, or at a business day): the + median gap to the reference event, split into summer (UTC+3) and winter + (UTC+2) months. A gap that jumps by ~1 h with DST and sits near +3/+2 h + means "local"; a gap near 0 in both seasons means "UTC". + * unlinked columns: the hour-of-day histogram is compared with the + reference's; the hour shift that matches best (0 = same basis = UTC). +It also reports values with an explicit offset, and values with millisecond +precision (microseconds ending in 000), which usually came from a browser. + +Usage (read-only; never modifies the database): + python tools/v1_time_audit.py [--tz Europe/Athens] +""" +import argparse +import re +import sqlite3 +import statistics +from collections import Counter +from datetime import datetime, timezone +from zoneinfo import ZoneInfo + +TS = re.compile(r"^\d{4}-\d\d-\d\d[ T]\d\d:\d\d") + + +def parse(v): + if v is None or not isinstance(v, str) or not TS.match(v): + return None + s = v.replace("T", " ").replace("Z", "+00:00") + try: + return datetime.fromisoformat(s) + except ValueError: + return None + + +def naive_utc(d): + return d.astimezone(timezone.utc).replace(tzinfo=None) if d.tzinfo else d + + +def ts_columns(con): + out = {} + for (t,) in con.execute("select name from sqlite_master where type='table' order by name"): + cols = [r[1] for r in con.execute(f'pragma table_info("{t}")')] + hits = [] + for col in cols: + v = con.execute(f'select "{col}" from "{t}" where "{col}" is not null and typeof("{col}")="text" limit 1').fetchone() + if v and TS.match(v[0]): + hits.append(col) + if hits: + out[t] = (hits, cols) + return out + + +def season(d, tz): + return "summer" if d.replace(tzinfo=timezone.utc).astimezone(tz).utcoffset().total_seconds() >= 3 * 3600 - 1 else "winter" + + +def gaps_by_season(pairs, tz): + by = {"summer": [], "winter": []} + for val, ref in pairs: + by[season(ref, tz)].append((val - ref).total_seconds() / 3600) + return {k: (round(statistics.median(v), 2), len(v)) for k, v in by.items() if v} + + +def hour_hist(values): + h = Counter(v.hour for v in values) + total = sum(h.values()) or 1 + return [h.get(i, 0) / total for i in range(24)] + + +def best_shift(hist, ref_hist): + def score(s): + return sum(hist[(i + s) % 24] * ref_hist[i] for i in range(24)) + scores = {s: score(s) for s in range(-6, 7)} + best = max(scores, key=scores.get) + return best, round(scores[best] / (scores[0] or 1e-9), 2) + + +def classify(gaps, shift): + if gaps: + s, w = gaps.get("summer"), gaps.get("winter") + meds = [g[0] for g in (s, w) if g] + if s and w and abs(s[0] - 3) < 0.6 and abs(w[0] - 2) < 0.6: + return "LOCAL (DST signature)" + if all(abs(m) < 0.6 for m in meds): + return "UTC" + if all(2.4 < m < 3.6 for m in meds) or all(1.4 < m < 2.6 for m in meds): + return "LOCAL?" + return "unclear (gap is a real duration?)" + if shift is not None: + return "UTC (hist)" if shift == 0 else f"shifted {shift:+d} h vs UTC (hist)" + return "n/a" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("db") + ap.add_argument("--tz", default="Europe/Athens") + a = ap.parse_args() + tz = ZoneInfo(a.tz) + con = sqlite3.connect(f"file:{a.db}?mode=ro", uri=True) + cols = ts_columns(con) + + order_ref = {r[0]: naive_utc(parse(r[1])) for r in con.execute("select id, opened_at from orders") if parse(r[1])} + bd_ref = {r[0]: naive_utc(parse(r[1])) for r in con.execute("select id, opened_at from business_days") if parse(r[1])} + ref_hist = hour_hist(order_ref.values()) + + print(f"# v1 timestamp audit: {a.db}\n") + print("Reference: orders.opened_at (server-written UTC). Gaps are value minus reference, in hours, as median (n).\n") + print("| table.column | n | min | max | offset-tagged | ms-precision | gap summer | gap winter | hist shift | verdict |") + print("|---|---|---|---|---|---|---|---|---|---|") + for t, (hits, allcols) in cols.items(): + for col in hits: + rows = con.execute(f'select * from "{t}" where "{col}" is not null').fetchall() + names = allcols + ci = names.index(col) + raw = [r[ci] for r in rows] + vals = [parse(v) for v in raw] + ok = [(r, v) for r, v in zip(rows, vals) if v] + if not ok: + continue + tagged = sum(1 for v in raw if isinstance(v, str) and re.search(r"(Z|[+-]\d\d:?\d\d)$", v)) + ms = sum(1 for v in raw if isinstance(v, str) and re.search(r"\.\d{3}000$", v)) + pairs = [] + if t == "orders" and col == "opened_at": + pairs = [] + elif "order_id" in names: + oi = names.index("order_id") + pairs = [(naive_utc(v), order_ref[r[oi]]) for r, v in ok if r[oi] in order_ref] + elif t == "orders": + ii = names.index("id") + pairs = [(naive_utc(v), order_ref[r[ii]]) for r, v in ok if r[ii] in order_ref] + elif "business_day_id" in names: + bi = names.index("business_day_id") + pairs = [(naive_utc(v), bd_ref[r[bi]]) for r, v in ok if r[bi] in bd_ref] + gaps = gaps_by_season(pairs, tz) if pairs else {} + shift = None + ratio = None + if not gaps and len(ok) >= 20: + shift, ratio = best_shift(hour_hist([naive_utc(v) for _, v in ok]), ref_hist) + g = lambda k: f"{gaps[k][0]} ({gaps[k][1]})" if k in gaps else "" + dmin = min(naive_utc(v) for _, v in ok) + dmax = max(naive_utc(v) for _, v in ok) + print(f"| {t}.{col} | {len(ok)} | {dmin:%Y-%m-%d} | {dmax:%Y-%m-%d} | {tagged} | {ms} | {g('summer')} | {g('winter')} | " + f"{'' if shift is None else f'{shift:+d} (x{ratio})'} | {classify(gaps, shift)} |") + + +if __name__ == "__main__": + main()