#!/usr/bin/env python3
"""Turn the logs of an index-build run into one table.

The harness that ran the builds writes its own lines (they start with "SCALE") and the
shell wraps the run in /usr/bin/time -l, which adds the real, user and sys seconds, the
largest resident set size and the peak memory footprint. This script reads those two
things and nothing else, so every figure in the table can be found in a log line.

It also writes a filtered copy of each log: the SCALE lines, the time block and the app's own
[FileAccess] lines (a bookmark check it makes about every 90 s), with the home folder replaced
by ~. The rest of a raw log is PDFKit warnings about the test files.

Usage:
    python3 -I extract-scale.py <log-dir> <out-dir>                 the 2026-10-12 runs
    python3 -I extract-scale.py <log-dir> <out-dir> --queue <RUN>   every <RUN>-*.log a queue
                                                                    (run-when-quiet.sh) wrote

The queue mode also reads <RUN>.conditions.tsv (what else the Mac was doing during each
phase) and writes queries.tsv beside runs.tsv. It checks every scan phase's isolation:
the scan journal's allowed_roots must be the phase's own test root and nothing else, and
outside_root must be 0. If any scan phase fails or cannot show that, the tables are still
written but the script exits 1, because those numbers include files that were not the
test corpus (2026-10-15: a scan read 36 files from the real inbox). It also exits 1 when the
attempt to quote slept (the conditions file says so): its times include the sleep.

It also reads the harness's heartbeat (one line every 15 s, from a timer thread) and records
the longest silence in each log as max_heartbeat_gap_s. A gap over STALL_S means the process
stopped making progress for that long, whatever the Mac's CPU was doing, so the step's time is
not a measurement of the build: the script says STALLED and exits 1. (2026-10-28: a 100,000
file build had a silence of 1,005 s and 196 s, with 274 documents done in the longer one, and
the queue still called the step quiet because it only watches other processes' CPU.)

Standard library only. It reads files and writes files; it makes no network connection.
"""
import json
import os
import re
import sys

# log file -> (group, label). The group says which build and which files; it is a label
# for a human, the figures come from the log.
RUNS = [
    ("fixed-R010-cold.log",   "A", "10,000 files, cold"),
    ("fixed-R030-cold.log",   "A", "30,000 files, cold"),
    ("fixed-R100-cold.log",   "A", "100,000 files, cold"),
    ("fixed-R100-warm.log",   "A", "100,000 files, rebuilt over the finished index"),
    ("merged-R100-cold.log",  "B", "100,000 files, cold"),
    ("merged-R100-warm.log",  "B", "100,000 files, rebuilt over the finished index"),
    ("real-library-cold.log", "R", "One real library, cold"),
    ("real-library-warm.log", "R", "One real library, rebuilt over the finished index"),
]

DONE = re.compile(r"SCALE DONE phase=(\S+) didBuild=(\S+) processed=(\d+) total=(\d+) "
                  r"elapsed_s=([\d.]+) db_bytes=(\d+) peak_rss_gb=([\d.]+) error=(.*)$")
TIME = re.compile(r"^\s*([\d.]+) real\s+([\d.]+) user\s+([\d.]+) sys\s*$")
RSS = re.compile(r"^\s*(\d+)\s+maximum resident set size\s*$")
FOOT = re.compile(r"^\s*(\d+)\s+peak memory footprint\s*$")

# Lines the queue-era harness adds (2026-10-15 on).
START = re.compile(r"^SCALE start phase=\S+ root=(.*) db=\S+$")
ENV = re.compile(r"^SCALE env commit=(\S+) app=(.*?) macos=.* load=([\d.]+) [\d.]+ [\d.]+ "
                 r"swap_used_gib=([\d.]+)")
MEMORY = re.compile(r"^SCALE memory .*swap_used_gib=([\d.]+) load=([\d.]+) ")
STAGE = re.compile(r"^SCALE stage name=(\w+) elapsed_s=([\d.]+)(?: processed=(\d+))?")
VERIFY = re.compile(r"^SCALE verify (.*)$")
SKIPPED = re.compile(r"^SCALE skipped (.*)$")
HEARTBEAT = re.compile(r"^SCALE heartbeat t=(\d+)s")
# The heartbeat comes every 15 s. Last night's other steps never went past 60 s of silence.
STALL_S = 90

QUERY = re.compile(r"^SCALE query term=(\S+) quick_hits=(\d+) quick_ms=([\d.]+) "
                   r"full_hits=(\d+) full_ms=([\d.]+)")
RUN_JSON = re.compile(r"^SCALE run_json dir=\S+ (\{.*)$")
EXIT = re.compile(r"^=== exit=(\d+)")
PHASE = re.compile(r"^(smoke|R\d{3})-(index|scan)-(cold|warm)(?:-r(\d))?$")

COLUMNS = ["file", "group", "label", "did_build", "files", "total", "elapsed_s", "real_s",
           "user_s", "sys_s", "max_rss_bytes", "peak_footprint_bytes", "index_bytes", "error"]

QCOLUMNS = ["phase", "size", "tier", "temp", "attempt", "use", "exit", "commit", "app",
            "did_build", "files", "total", "elapsed_s", "real_s", "user_s", "sys_s",
            "max_rss_bytes", "peak_footprint_bytes", "index_bytes",
            "ocr_s", "ocr_docs", "pipeline_s", "word_index_s",
            "verify_ok", "verify_docs", "empty_body", "outside_root",
            "skipped_locked", "skipped_unreadable", "skipped_damaged", "skipped_online_only",
            "root", "allowed_roots", "isolation",
            "load1_start", "load1_end", "swap_start_gib", "swap_end_gib",
            "other_cpu_mean", "other_cpu_max", "pageouts", "swap_mb_start", "swap_mb_end",
            "verdict", "slept", "max_heartbeat_gap_s", "error"]

QUERY_COLUMNS = ["phase", "term", "quick_hits", "quick_ms", "full_hits", "full_ms"]

# run-when-quiet.sh writes this file with no header line. "slept" was added 2026-10-17; a
# file from an earlier queue has the first seven columns only, and slept stays blank.
CONDITION_COLUMNS = ["phase", "other_cpu_mean", "other_cpu_max", "pageouts",
                     "swap_mb_start", "swap_mb_end", "verdict", "slept"]


def fields(text):
    """'docs=10 ok=true' -> {'docs': '10', 'ok': 'true'}"""
    return dict(kv.split("=", 1) for kv in text.split() if "=" in kv)


def parse(path):
    row = {c: "" for c in COLUMNS + QCOLUMNS}
    keep, queries, roots, in_time, beats = [], [], [], False, []
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.rstrip("\n")
            m = DONE.search(line)
            if m:
                row.update(did_build=m.group(2), files=m.group(3), total=m.group(4),
                           elapsed_s=m.group(5), index_bytes=m.group(6), error=m.group(8).strip())
            t = TIME.match(line)
            if t:
                in_time = True
                row.update(real_s=t.group(1), user_s=t.group(2), sys_s=t.group(3))
            if (m2 := RSS.match(line)):
                row["max_rss_bytes"] = m2.group(1)
            if (m3 := FOOT.match(line)):
                row["peak_footprint_bytes"] = m3.group(1)
            if (s := START.match(line)):
                row["root"] = s.group(1)
            if (e := ENV.match(line)):
                row.update(commit=e.group(1), app=e.group(2), load1_start=e.group(3),
                           swap_start_gib=e.group(4))
            if (mm := MEMORY.match(line)):
                row.update(swap_end_gib=mm.group(1), load1_end=mm.group(2))
            if (st := STAGE.match(line)):
                row[f"{st.group(1)}_s"] = st.group(2)
                if st.group(1) == "ocr":
                    row["ocr_docs"] = st.group(3) or ""
            if (v := VERIFY.match(line)):
                kv = fields(v.group(1))
                row.update(verify_ok=kv.get("ok", ""), verify_docs=kv.get("docs", ""),
                           empty_body=kv.get("empty_body", ""),
                           outside_root=kv.get("outside_root", ""))
            if (sk := SKIPPED.match(line)):
                for k, val in fields(sk.group(1)).items():
                    row[f"skipped_{k}"] = val
            if (hb := HEARTBEAT.match(line)):
                beats.append(int(hb.group(1)))
            if (q := QUERY.match(line)):
                queries.append(list(q.groups()))
            if (rj := RUN_JSON.match(line)):
                try:
                    roots.append(json.loads(rj.group(1)).get("allowed_roots") or [])
                except ValueError:
                    roots.append(None)
            if (x := EXIT.match(line)):
                row["exit"] = x.group(1)
            if line.startswith("SCALE ") or in_time or line.startswith("=== ") or "[FileAccess]" in line:
                keep.append(line.replace(os.path.expanduser("~"), "~"))
    # Longest silence: between the start, each beat, and the end of the build. A step shorter
    # than one beat has no beats at all, and its gap is its own length.
    if row["elapsed_s"]:
        marks = [0] + beats + [max(float(row["elapsed_s"]), beats[-1] if beats else 0)]
        row["max_heartbeat_gap_s"] = str(round(max(b - a for a, b in zip(marks, marks[1:]))))
    home = os.path.expanduser("~")
    row["allowed_roots"] = ";".join(sorted({r.replace(home, "~") for rs in roots if rs for r in rs}))
    return row, keep, queries, roots


def isolation(row, roots):
    """ok: every scan journal lists the phase's root and nothing else, and outside_root is 0.
    FAIL: some journal lists another root, or outside_root is not 0. unknown: no journal, or
    one that would not parse. n/a: an index phase, which writes no scan journal."""
    if not roots:
        return "unknown" if row["tier"] == "scan" else "n/a"
    if any(rs is None for rs in roots):
        return "unknown"
    if any(set(rs) != {row["root"]} for rs in roots):
        return "FAIL"
    if row["outside_root"] not in ("", "0"):
        return "FAIL"
    if row["tier"] == "scan" and row["outside_root"] == "":
        return "unknown"  # the harness before 060e62f2 did not count it
    return "ok"


def write_tsv(path, columns, rows):
    with open(path, "w", encoding="utf-8") as f:
        f.write("\t".join(columns) + "\n")
        for r in rows:
            f.write("\t".join(str(r[c]) for c in columns) + "\n")


def main_fixed(src, out):
    rows = []
    for name, group, label in RUNS:
        path = os.path.join(src, name)
        if not os.path.exists(path):
            print(f"missing: {name}", file=sys.stderr)
            continue
        row, keep, _, _ = parse(path)
        row.update(file=name, group=group, label=label)
        rows.append(row)
        with open(os.path.join(out, name), "w", encoding="utf-8") as f:
            f.write("\n".join(keep) + "\n")
    write_tsv(os.path.join(out, "runs.tsv"), COLUMNS, rows)
    print(f"wrote {len(rows)} rows to {os.path.join(out, 'runs.tsv')}")


def main_queue(src, out, run):
    conditions = {}
    cpath = os.path.join(src, f"{run}.conditions.tsv")
    if os.path.exists(cpath):
        with open(cpath, encoding="utf-8") as f:
            for line in f:
                parts = line.rstrip("\n").split("\t")
                if len(parts) in (len(CONDITION_COLUMNS) - 1, len(CONDITION_COLUMNS)):
                    conditions[parts[0]] = dict(zip(CONDITION_COLUMNS, parts))
    else:
        print(f"no {run}.conditions.tsv (queues before 2ae51e9 did not record one)",
              file=sys.stderr)

    names = sorted(n for n in os.listdir(src) if n.startswith(run + "-") and n.endswith(".log"))
    if not names:
        sys.exit(f"no {run}-*.log in {src}")
    rows, qrows = [], []
    for name in names:
        phase = name[:-len(".log")]
        row, keep, queries, roots = parse(os.path.join(src, name))
        p = PHASE.match(phase[len(run) + 1:])
        if p:
            row.update(size=p.group(1), tier=p.group(2), temp=p.group(3),
                       attempt=p.group(4) or "1")
        else:
            print(f"phase name not understood, kept with blanks: {phase}", file=sys.stderr)
        row["phase"] = phase
        row["isolation"] = isolation(row, roots)
        c = conditions.get(phase, {})
        for k in CONDITION_COLUMNS[1:]:
            row[k] = c.get(k, "")
        rows.append(row)
        qrows += [dict(zip(QUERY_COLUMNS, [phase] + q)) for q in queries]
        with open(os.path.join(out, name), "w", encoding="utf-8") as f:
            f.write("\n".join(keep) + "\n")

    # The queue reruns a grossly contended phase as -r2, then -r3: the last attempt is the
    # one to quote, the others stay in the table marked superseded.
    last = {}
    for r in rows:
        key = (r["size"], r["tier"], r["temp"])
        if r["attempt"] and int(r["attempt"]) >= int(last.get(key, {}).get("attempt") or 0):
            last[key] = r
    for r in rows:
        if not r["attempt"]:
            r["use"] = "?"
        else:
            r["use"] = "yes" if last.get((r["size"], r["tier"], r["temp"])) is r else "superseded"

    write_tsv(os.path.join(out, "runs.tsv"), QCOLUMNS, rows)
    write_tsv(os.path.join(out, "queries.tsv"), QUERY_COLUMNS, qrows)
    print(f"wrote {len(rows)} rows to {os.path.join(out, 'runs.tsv')}, "
          f"{len(qrows)} to queries.tsv")

    bad = 0
    for r in rows:
        if r["use"] != "yes":
            continue
        if r["slept"] == "yes":
            bad += 1
            print(f"SLEPT {r['phase']}: the Mac slept during the phase, so its wall-clock "
                  f"times include the sleep", file=sys.stderr)
        if r["max_heartbeat_gap_s"] and int(r["max_heartbeat_gap_s"]) > STALL_S:
            bad += 1
            print(f"STALLED {r['phase']}: no heartbeat for {r['max_heartbeat_gap_s']} s (more than "
                  f"{STALL_S}), so the process stopped making progress and its time is not a "
                  f"measurement of the build", file=sys.stderr)
        if r["tier"] == "scan" and r["isolation"] != "ok":
            bad += 1
            print(f"UNTRUSTED {r['phase']}: isolation={r['isolation']} "
                  f"allowed_roots={r['allowed_roots'] or '(none recorded)'} "
                  f"outside_root={r['outside_root'] or '(not counted)'}", file=sys.stderr)
        if r["exit"] not in ("", "0") or not r["did_build"]:
            print(f"INCOMPLETE {r['phase']}: exit={r['exit'] or '?'} "
                  f"done_line={'yes' if r['did_build'] else 'no'}", file=sys.stderr)
        if r["verdict"] and r["verdict"] not in ("quiet", "slept"):
            print(f"{r['verdict'].upper()} {r['phase']}: other CPU mean {r['other_cpu_mean']}%, "
                  f"max {r['other_cpu_max']}%, {r['pageouts']} pages out", file=sys.stderr)
    if bad:
        sys.exit(f"{bad} phase(s) slept, stalled, or scanned without proof of staying inside "
                 f"their test root: do not publish their numbers")


def main():
    args = sys.argv[1:]
    if len(args) == 2:
        src, out, run = args[0], args[1], None
    elif len(args) == 4 and args[2] == "--queue":
        src, out, run = args[0], args[1], args[3]
    else:
        sys.exit(__doc__)
    os.makedirs(out, exist_ok=True)
    if run:
        main_queue(src, out, run)
    else:
        main_fixed(src, out)


if __name__ == "__main__":
    main()
