Spaces:
Running
Running
siddhm11 Claude Opus 5.5 commited on
Commit ·
aa9e84e
1
Parent(s): eb40cc2
feat(scripts): baseline reading metrics for the redesign
Browse filesscripts/baseline_metrics.py reports readers, sessions, saves per session,
Pass share, opens, open-to-save and seven-day return per ISO week, plus a
read-only snapshot of /healthz/runtime. --export copies user_interactions
from Turso for the owner to run; reports never contain a user id. Clicks
are split by surface only from the card-fix date, because earlier clicks
were all stored as recommendations.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- scripts/baseline_metrics.py +320 -0
- tests/test_baseline_metrics.py +121 -0
scripts/baseline_metrics.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Baseline reading metrics: the "before" numbers the redesign is judged against.
|
| 4 |
+
|
| 5 |
+
Two modes, both read-only against production:
|
| 6 |
+
|
| 7 |
+
# Owner only: copy user_interactions from Turso into a local file.
|
| 8 |
+
python scripts/baseline_metrics.py --export data/baseline.sqlite
|
| 9 |
+
|
| 10 |
+
# Anyone: weekly metrics from that file, written to reports/baseline/.
|
| 11 |
+
python scripts/baseline_metrics.py --db data/baseline.sqlite \\
|
| 12 |
+
--since 2026-08-01 --fix-date 2026-10-20 \\
|
| 13 |
+
--runtime-url https://siddhm11-researchit.hf.space/healthz/runtime
|
| 14 |
+
|
| 15 |
+
The export mode reads real reader activity, which is why only the project
|
| 16 |
+
owner runs it. The report holds counts and rates only, never a user id.
|
| 17 |
+
|
| 18 |
+
Definitions (also printed into every report, so nobody has to guess later)
|
| 19 |
+
---------------------------------------------------------------------------
|
| 20 |
+
reader a user_id with any event that week
|
| 21 |
+
session one reader's events with no gap over 30 minutes
|
| 22 |
+
pass share not_interested / (save + not_interested); unsave is not a pass
|
| 23 |
+
opens click + view events (feed click-throughs and direct visits)
|
| 24 |
+
open-to-save sessions where a paper is opened and later saved in the same
|
| 25 |
+
session, divided by sessions with an open
|
| 26 |
+
seven-day return reader-days followed by another session 1-7 days later,
|
| 27 |
+
divided by reader-days; days in the last week of data are
|
| 28 |
+
left out because their week is not over yet
|
| 29 |
+
clicks by surface click events grouped by `source`, only from --fix-date on:
|
| 30 |
+
before the card fix every click was stored as
|
| 31 |
+
"recommendation" whatever page it came from
|
| 32 |
+
excluded user_ids with more than 500 events in one UTC day
|
| 33 |
+
"""
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import argparse
|
| 37 |
+
import datetime as dt
|
| 38 |
+
import json
|
| 39 |
+
import os
|
| 40 |
+
import sqlite3
|
| 41 |
+
import sys
|
| 42 |
+
from collections import Counter, defaultdict
|
| 43 |
+
from dataclasses import dataclass, field
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
|
| 46 |
+
DEFINITIONS = __doc__[__doc__.index(" reader"):].rstrip()
|
| 47 |
+
|
| 48 |
+
SESSION_GAP = dt.timedelta(minutes=30)
|
| 49 |
+
RETURN_WINDOW_DAYS = 7
|
| 50 |
+
BOT_EVENTS_PER_DAY = 500
|
| 51 |
+
|
| 52 |
+
COLUMNS = ["id", "user_id", "paper_id", "event_type", "source", "position", "query_id",
|
| 53 |
+
"ranker_version", "candidate_source", "cluster_id", "propensity", "policy_id",
|
| 54 |
+
"timestamp"]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ── loading ──────────────────────────────────────────────────────────────────
|
| 58 |
+
|
| 59 |
+
@dataclass(frozen=True)
|
| 60 |
+
class Event:
|
| 61 |
+
user_id: str
|
| 62 |
+
paper_id: str
|
| 63 |
+
event_type: str
|
| 64 |
+
source: str | None
|
| 65 |
+
ts: dt.datetime
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def parse_ts(raw: str) -> dt.datetime:
|
| 69 |
+
"""SQLite datetime('now') strings carry no zone and are UTC."""
|
| 70 |
+
text = raw.strip().replace("T", " ").rstrip("Z")
|
| 71 |
+
ts = dt.datetime.fromisoformat(text)
|
| 72 |
+
return ts.replace(tzinfo=dt.timezone.utc) if ts.tzinfo is None else ts.astimezone(dt.timezone.utc)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_events(db_path: str, since: dt.date | None = None) -> list[Event]:
|
| 76 |
+
conn = sqlite3.connect(db_path)
|
| 77 |
+
try:
|
| 78 |
+
rows = conn.execute(
|
| 79 |
+
"SELECT user_id, paper_id, event_type, source, timestamp FROM interactions "
|
| 80 |
+
"WHERE timestamp IS NOT NULL ORDER BY timestamp").fetchall()
|
| 81 |
+
finally:
|
| 82 |
+
conn.close()
|
| 83 |
+
events = [Event(str(u), str(p), str(e), s, parse_ts(t)) for u, p, e, s, t in rows]
|
| 84 |
+
if since:
|
| 85 |
+
events = [e for e in events if e.ts.date() >= since]
|
| 86 |
+
return events
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ── metrics ──────────────────────────────────────────────────────────────────
|
| 90 |
+
|
| 91 |
+
def heavy_users(events: list[Event], limit: int = BOT_EVENTS_PER_DAY) -> set[str]:
|
| 92 |
+
per_day = Counter((e.user_id, e.ts.date()) for e in events)
|
| 93 |
+
return {u for (u, _day), n in per_day.items() if n > limit}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def sessions(events: list[Event], gap: dt.timedelta = SESSION_GAP) -> list[list[Event]]:
|
| 97 |
+
"""Every reader's events split wherever two events are more than `gap` apart."""
|
| 98 |
+
by_user: dict[str, list[Event]] = defaultdict(list)
|
| 99 |
+
for e in events:
|
| 100 |
+
by_user[e.user_id].append(e)
|
| 101 |
+
out = []
|
| 102 |
+
for evs in by_user.values():
|
| 103 |
+
evs.sort(key=lambda e: e.ts)
|
| 104 |
+
cur = [evs[0]]
|
| 105 |
+
for prev, e in zip(evs, evs[1:]):
|
| 106 |
+
if e.ts - prev.ts > gap:
|
| 107 |
+
out.append(cur)
|
| 108 |
+
cur = []
|
| 109 |
+
cur.append(e)
|
| 110 |
+
out.append(cur)
|
| 111 |
+
return out
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def opened_then_saved(session: list[Event]) -> bool:
|
| 115 |
+
opened: set[str] = set()
|
| 116 |
+
for e in session:
|
| 117 |
+
if e.event_type in ("click", "view"):
|
| 118 |
+
opened.add(e.paper_id)
|
| 119 |
+
elif e.event_type == "save" and e.paper_id in opened:
|
| 120 |
+
return True
|
| 121 |
+
return False
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def iso_week(day: dt.date) -> str:
|
| 125 |
+
year, week, _ = day.isocalendar()
|
| 126 |
+
return f"{year}-W{week:02d}"
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@dataclass
|
| 130 |
+
class Week:
|
| 131 |
+
readers: set = field(default_factory=set)
|
| 132 |
+
sessions: int = 0
|
| 133 |
+
sessions_with_open: int = 0
|
| 134 |
+
open_then_save: int = 0
|
| 135 |
+
events: Counter = field(default_factory=Counter)
|
| 136 |
+
reader_days: int = 0
|
| 137 |
+
returning_reader_days: int = 0
|
| 138 |
+
clicks_by_surface: Counter = field(default_factory=Counter)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def compute(events: list[Event], *, fix_date: dt.date | None = None,
|
| 142 |
+
today: dt.date | None = None) -> dict:
|
| 143 |
+
excluded = heavy_users(events)
|
| 144 |
+
events = [e for e in events if e.user_id not in excluded]
|
| 145 |
+
weeks: dict[str, Week] = defaultdict(Week)
|
| 146 |
+
if not events:
|
| 147 |
+
return {"weeks": {}, "excluded_users": len(excluded)}
|
| 148 |
+
last_day = today or max(e.ts for e in events).date()
|
| 149 |
+
|
| 150 |
+
for e in events:
|
| 151 |
+
w = weeks[iso_week(e.ts.date())]
|
| 152 |
+
w.readers.add(e.user_id)
|
| 153 |
+
w.events[e.event_type] += 1
|
| 154 |
+
if e.event_type == "click" and fix_date and e.ts.date() >= fix_date:
|
| 155 |
+
w.clicks_by_surface[e.source or "unknown"] += 1
|
| 156 |
+
|
| 157 |
+
session_days: dict[str, set[dt.date]] = defaultdict(set)
|
| 158 |
+
for s in sessions(events):
|
| 159 |
+
start = s[0].ts.date()
|
| 160 |
+
w = weeks[iso_week(start)]
|
| 161 |
+
w.sessions += 1
|
| 162 |
+
if any(e.event_type in ("click", "view") for e in s):
|
| 163 |
+
w.sessions_with_open += 1
|
| 164 |
+
w.open_then_save += opened_then_saved(s)
|
| 165 |
+
for e in s:
|
| 166 |
+
session_days[e.user_id].add(e.ts.date())
|
| 167 |
+
|
| 168 |
+
for days in session_days.values():
|
| 169 |
+
ordered = sorted(days)
|
| 170 |
+
for i, d in enumerate(ordered):
|
| 171 |
+
if (last_day - d).days < RETURN_WINDOW_DAYS:
|
| 172 |
+
continue # its return window isn't over yet
|
| 173 |
+
w = weeks[iso_week(d)]
|
| 174 |
+
w.reader_days += 1
|
| 175 |
+
nxt = ordered[i + 1] if i + 1 < len(ordered) else None
|
| 176 |
+
if nxt and 1 <= (nxt - d).days <= RETURN_WINDOW_DAYS:
|
| 177 |
+
w.returning_reader_days += 1
|
| 178 |
+
|
| 179 |
+
def ratio(a: int, b: int) -> float | None:
|
| 180 |
+
return round(a / b, 4) if b else None
|
| 181 |
+
|
| 182 |
+
out = {}
|
| 183 |
+
for key in sorted(weeks):
|
| 184 |
+
w = weeks[key]
|
| 185 |
+
saves, passes = w.events["save"], w.events["not_interested"]
|
| 186 |
+
out[key] = {
|
| 187 |
+
"readers": len(w.readers),
|
| 188 |
+
"sessions": w.sessions,
|
| 189 |
+
"saves": saves,
|
| 190 |
+
"passes": passes,
|
| 191 |
+
"unsaves": w.events["unsave"],
|
| 192 |
+
"opens": w.events["click"] + w.events["view"],
|
| 193 |
+
"saves_per_session": ratio(saves, w.sessions),
|
| 194 |
+
"pass_share": ratio(passes, saves + passes),
|
| 195 |
+
"open_to_save": ratio(w.open_then_save, w.sessions_with_open),
|
| 196 |
+
"seven_day_return": ratio(w.returning_reader_days, w.reader_days),
|
| 197 |
+
"clicks_by_surface": dict(w.clicks_by_surface),
|
| 198 |
+
}
|
| 199 |
+
return {"weeks": out, "excluded_users": len(excluded)}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ── report ───────────────────────────────────────────────────────────────────
|
| 203 |
+
|
| 204 |
+
def _pct(v: float | None) -> str:
|
| 205 |
+
return "–" if v is None else f"{v * 100:.1f}%"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def render_markdown(result: dict, *, generated: str, fix_date: dt.date | None,
|
| 209 |
+
runtime: dict | None) -> str:
|
| 210 |
+
lines = [f"# Baseline reading metrics, {generated}", ""]
|
| 211 |
+
lines += ["| Week | Readers | Sessions | Saves per session | Pass share | Opens | "
|
| 212 |
+
"Open-to-save | Seven-day return |", "| --- | --- | --- | --- | --- | --- | --- | --- |"]
|
| 213 |
+
for week, m in result["weeks"].items():
|
| 214 |
+
sps = "–" if m["saves_per_session"] is None else f"{m['saves_per_session']:.2f}"
|
| 215 |
+
lines.append(f"| {week} | {m['readers']} | {m['sessions']} | {sps} | {_pct(m['pass_share'])} | "
|
| 216 |
+
f"{m['opens']} | {_pct(m['open_to_save'])} | {_pct(m['seven_day_return'])} |")
|
| 217 |
+
lines.append("")
|
| 218 |
+
lines.append(f"Excluded as automated: {result['excluded_users']} user ids.")
|
| 219 |
+
if fix_date:
|
| 220 |
+
lines.append(f"Clicks by surface count from {fix_date} only.")
|
| 221 |
+
for week, m in result["weeks"].items():
|
| 222 |
+
if m["clicks_by_surface"]:
|
| 223 |
+
parts = ", ".join(f"{k} {v}" for k, v in sorted(m["clicks_by_surface"].items()))
|
| 224 |
+
lines.append(f"- {week}: {parts}")
|
| 225 |
+
else:
|
| 226 |
+
lines.append("Clicks are not split by surface: before the card fix every click was "
|
| 227 |
+
"stored as \"recommendation\". Pass --fix-date once it is deployed.")
|
| 228 |
+
if runtime:
|
| 229 |
+
feed = (runtime.get("timings") or {}).get("feed", {}).get("build_ms")
|
| 230 |
+
page = (runtime.get("timings") or {}).get("paper_page", {}).get("total_ms")
|
| 231 |
+
lines.append("")
|
| 232 |
+
lines.append("Live timings (last 200 requests per kind, since the last restart):")
|
| 233 |
+
if feed:
|
| 234 |
+
lines.append(f"- Feed build: p50 {feed['p50']} ms, p95 {feed['p95']} ms")
|
| 235 |
+
if page:
|
| 236 |
+
lines.append(f"- Paper page: p50 {page['p50']} ms, p95 {page['p95']} ms")
|
| 237 |
+
lines += ["", "## Definitions", "", "```", DEFINITIONS, "```", ""]
|
| 238 |
+
return "\n".join(lines)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
# ── export (owner only) ──────────────────────────────────────────────────────
|
| 242 |
+
|
| 243 |
+
def export_from_turso(out_path: str, page: int = 5000) -> int:
|
| 244 |
+
import httpx
|
| 245 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 246 |
+
from app import config
|
| 247 |
+
from app.turso_sync import _uncell, _url
|
| 248 |
+
|
| 249 |
+
if not (config.TURSO_URL and config.TURSO_DB_TOKEN):
|
| 250 |
+
raise SystemExit("TURSO_URL and TURSO_DB_TOKEN are required for --export")
|
| 251 |
+
conn = sqlite3.connect(out_path)
|
| 252 |
+
conn.execute(f"CREATE TABLE IF NOT EXISTS interactions ({', '.join(COLUMNS)})")
|
| 253 |
+
conn.execute("DELETE FROM interactions")
|
| 254 |
+
last, total = 0, 0
|
| 255 |
+
with httpx.Client(timeout=120) as http:
|
| 256 |
+
while True:
|
| 257 |
+
stmt = {"sql": f"SELECT {', '.join(COLUMNS)} FROM user_interactions WHERE id > ? ORDER BY id LIMIT {page}",
|
| 258 |
+
"args": [{"type": "integer", "value": str(last)}]}
|
| 259 |
+
r = http.post(f"{_url()}/v2/pipeline",
|
| 260 |
+
headers={"Authorization": f"Bearer {config.TURSO_DB_TOKEN}"},
|
| 261 |
+
json={"requests": [{"type": "execute", "stmt": stmt}, {"type": "close"}]})
|
| 262 |
+
r.raise_for_status()
|
| 263 |
+
rows = r.json()["results"][0]["response"]["result"]["rows"]
|
| 264 |
+
if not rows:
|
| 265 |
+
break
|
| 266 |
+
values = [[_uncell(c) for c in row] for row in rows]
|
| 267 |
+
conn.executemany(f"INSERT INTO interactions VALUES ({', '.join('?' * len(COLUMNS))})", values)
|
| 268 |
+
total += len(values)
|
| 269 |
+
last = values[-1][0]
|
| 270 |
+
print(f"[baseline] exported {total} rows", flush=True)
|
| 271 |
+
conn.commit()
|
| 272 |
+
conn.close()
|
| 273 |
+
return total
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def fetch_runtime(url: str) -> dict | None:
|
| 277 |
+
import httpx
|
| 278 |
+
try:
|
| 279 |
+
r = httpx.get(url, timeout=20)
|
| 280 |
+
r.raise_for_status()
|
| 281 |
+
return r.json()
|
| 282 |
+
except (httpx.HTTPError, ValueError) as e:
|
| 283 |
+
print(f"[baseline] runtime snapshot failed: {e}")
|
| 284 |
+
return None
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def main(argv: list[str] | None = None) -> int:
|
| 288 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 289 |
+
ap.add_argument("--export", metavar="OUT", help="copy user_interactions from Turso (owner only)")
|
| 290 |
+
ap.add_argument("--db", help="local SQLite file made by --export")
|
| 291 |
+
ap.add_argument("--since", type=dt.date.fromisoformat)
|
| 292 |
+
ap.add_argument("--fix-date", type=dt.date.fromisoformat,
|
| 293 |
+
help="deploy date of the card-link fix; clicks are split by surface from then on")
|
| 294 |
+
ap.add_argument("--runtime-url", help="a /healthz/runtime URL to snapshot (read-only GET)")
|
| 295 |
+
ap.add_argument("--out", default="reports/baseline")
|
| 296 |
+
args = ap.parse_args(argv)
|
| 297 |
+
|
| 298 |
+
if args.export:
|
| 299 |
+
n = export_from_turso(args.export)
|
| 300 |
+
print(f"[baseline] wrote {n} interactions to {args.export}")
|
| 301 |
+
return 0
|
| 302 |
+
if not args.db:
|
| 303 |
+
ap.error("--db or --export is required")
|
| 304 |
+
|
| 305 |
+
events = load_events(args.db, args.since)
|
| 306 |
+
result = compute(events, fix_date=args.fix_date)
|
| 307 |
+
runtime = fetch_runtime(args.runtime_url) if args.runtime_url else None
|
| 308 |
+
today = dt.date.today().isoformat()
|
| 309 |
+
os.makedirs(args.out, exist_ok=True)
|
| 310 |
+
md = render_markdown(result, generated=today, fix_date=args.fix_date, runtime=runtime)
|
| 311 |
+
Path(args.out, f"{today}.md").write_text(md)
|
| 312 |
+
Path(args.out, f"{today}.json").write_text(json.dumps(
|
| 313 |
+
{"generated": today, "since": str(args.since or ""), "fix_date": str(args.fix_date or ""),
|
| 314 |
+
**result, "runtime": runtime}, indent=1))
|
| 315 |
+
print(md)
|
| 316 |
+
return 0
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
raise SystemExit(main())
|
tests/test_baseline_metrics.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
scripts/baseline_metrics.py: the numbers every later change is compared with.
|
| 3 |
+
|
| 4 |
+
All on a synthetic interactions table built in tmp_path. The edge cases are the
|
| 5 |
+
ones a reader of the report would otherwise have to guess at: where a session
|
| 6 |
+
ends, which days count as a return, and what counts as a Pass.
|
| 7 |
+
"""
|
| 8 |
+
import datetime as dt
|
| 9 |
+
import importlib.util
|
| 10 |
+
import json
|
| 11 |
+
import sqlite3
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
_spec = importlib.util.spec_from_file_location(
|
| 16 |
+
"baseline_metrics", Path(__file__).resolve().parents[1] / "scripts" / "baseline_metrics.py")
|
| 17 |
+
bm = importlib.util.module_from_spec(_spec)
|
| 18 |
+
sys.modules["baseline_metrics"] = bm # dataclasses look their module up
|
| 19 |
+
_spec.loader.exec_module(bm)
|
| 20 |
+
|
| 21 |
+
T0 = dt.datetime(2026, 9, 1, 9, 0, tzinfo=dt.timezone.utc) # a Tuesday
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def ev(user, kind, minutes=0, paper="2609.00001", source=None, days=0):
|
| 25 |
+
return bm.Event(user, paper, kind, source, T0 + dt.timedelta(days=days, minutes=minutes))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def make_db(tmp_path, rows):
|
| 29 |
+
path = tmp_path / "baseline.sqlite"
|
| 30 |
+
conn = sqlite3.connect(path)
|
| 31 |
+
conn.execute(f"CREATE TABLE interactions ({', '.join(bm.COLUMNS)})")
|
| 32 |
+
for i, (user, kind, ts, source) in enumerate(rows, 1):
|
| 33 |
+
conn.execute("INSERT INTO interactions (id, user_id, paper_id, event_type, source, timestamp) "
|
| 34 |
+
"VALUES (?, ?, ?, ?, ?, ?)", (i, user, "2609.00001", kind, source, ts))
|
| 35 |
+
conn.commit()
|
| 36 |
+
conn.close()
|
| 37 |
+
return str(path)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_a_29_minute_gap_is_one_session_and_31_minutes_is_two():
|
| 41 |
+
one = bm.sessions([ev("a", "save", 0), ev("a", "save", 29)])
|
| 42 |
+
two = bm.sessions([ev("a", "save", 0), ev("a", "save", 31)])
|
| 43 |
+
assert len(one) == 1 and len(two) == 2
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_sessions_are_per_reader():
|
| 47 |
+
out = bm.sessions([ev("a", "save", 0), ev("b", "save", 1), ev("a", "save", 2)])
|
| 48 |
+
assert sorted(len(s) for s in out) == [1, 2]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_a_return_on_day_seven_counts_and_day_eight_does_not():
|
| 52 |
+
seven = bm.compute([ev("a", "view"), ev("a", "view", days=7)], today=T0.date() + dt.timedelta(days=30))
|
| 53 |
+
eight = bm.compute([ev("a", "view"), ev("a", "view", days=8)], today=T0.date() + dt.timedelta(days=30))
|
| 54 |
+
week = bm.iso_week(T0.date())
|
| 55 |
+
assert seven["weeks"][week]["seven_day_return"] == 1.0
|
| 56 |
+
assert eight["weeks"][week]["seven_day_return"] == 0.0
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_days_whose_return_window_is_still_open_are_left_out():
|
| 60 |
+
out = bm.compute([ev("a", "view")], today=T0.date() + dt.timedelta(days=3))
|
| 61 |
+
assert out["weeks"][bm.iso_week(T0.date())]["seven_day_return"] is None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_open_then_save_in_one_session_counts_and_across_sessions_does_not():
|
| 65 |
+
same = bm.compute([ev("a", "click", 0), ev("a", "save", 5)])
|
| 66 |
+
split = bm.compute([ev("a", "click", 0), ev("a", "save", 90)])
|
| 67 |
+
week = bm.iso_week(T0.date())
|
| 68 |
+
assert same["weeks"][week]["open_to_save"] == 1.0
|
| 69 |
+
assert split["weeks"][week]["open_to_save"] == 0.0
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_saving_a_different_paper_is_not_open_to_save():
|
| 73 |
+
out = bm.compute([ev("a", "click", 0, paper="x"), ev("a", "save", 5, paper="y")])
|
| 74 |
+
assert out["weeks"][bm.iso_week(T0.date())]["open_to_save"] == 0.0
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_unsave_is_not_a_pass():
|
| 78 |
+
out = bm.compute([ev("a", "save"), ev("a", "unsave", 1), ev("a", "not_interested", 2)])
|
| 79 |
+
week = out["weeks"][bm.iso_week(T0.date())]
|
| 80 |
+
assert week["pass_share"] == 0.5
|
| 81 |
+
assert week["unsaves"] == 1
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_a_reader_with_600_events_in_a_day_is_excluded():
|
| 85 |
+
bot = [ev("bot", "view", i % 600) for i in range(600)]
|
| 86 |
+
out = bm.compute(bot + [ev("a", "save")])
|
| 87 |
+
assert out["excluded_users"] == 1
|
| 88 |
+
assert out["weeks"][bm.iso_week(T0.date())]["readers"] == 1
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_clicks_are_split_by_surface_only_from_the_fix_date():
|
| 92 |
+
events = [ev("a", "click", source="recommendation"),
|
| 93 |
+
ev("a", "click", source="search", days=2),
|
| 94 |
+
ev("a", "click", source="recommendation", days=3)]
|
| 95 |
+
out = bm.compute(events, fix_date=T0.date() + dt.timedelta(days=2))
|
| 96 |
+
assert out["weeks"][bm.iso_week(T0.date())]["clicks_by_surface"] == {"search": 1, "recommendation": 1}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_an_empty_database_gives_an_empty_report(tmp_path):
|
| 100 |
+
db = make_db(tmp_path, [])
|
| 101 |
+
assert bm.compute(bm.load_events(db)) == {"weeks": {}, "excluded_users": 0}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_timestamps_without_a_zone_are_utc(tmp_path):
|
| 105 |
+
db = make_db(tmp_path, [("a", "save", "2026-09-01 23:59:59", None)])
|
| 106 |
+
(e,) = bm.load_events(db)
|
| 107 |
+
assert e.ts == dt.datetime(2026, 9, 1, 23, 59, 59, tzinfo=dt.timezone.utc)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_the_report_holds_no_user_ids(tmp_path):
|
| 111 |
+
db = make_db(tmp_path, [("reader-secret-id", "save", "2026-09-01 10:00:00", None),
|
| 112 |
+
("reader-secret-id", "click", "2026-09-01 10:05:00", "search")])
|
| 113 |
+
out = tmp_path / "out"
|
| 114 |
+
assert bm.main(["--db", db, "--out", str(out), "--fix-date", "2026-09-01"]) == 0
|
| 115 |
+
files = list(out.iterdir())
|
| 116 |
+
assert {f.suffix for f in files} == {".md", ".json"}
|
| 117 |
+
for f in files:
|
| 118 |
+
assert "reader-secret-id" not in f.read_text()
|
| 119 |
+
data = json.loads(next(f for f in files if f.suffix == ".json").read_text())
|
| 120 |
+
assert data["weeks"]["2026-W36"]["saves"] == 1
|
| 121 |
+
assert "## Definitions" in next(f for f in files if f.suffix == ".md").read_text()
|