diff --git a/.github/workflows/heart-tests.yml b/.github/workflows/heart-tests.yml index c0e95373..13ec0b6a 100644 --- a/.github/workflows/heart-tests.yml +++ b/.github/workflows/heart-tests.yml @@ -29,6 +29,12 @@ on: push: branches: [main] pull_request: + # A manual door. Measured 2026-09-05 (PyAutoHeart#209): a PR opened while + # main's tip was the daily `[skip ci]` record commit got NO pull_request run + # at all, and without this trigger nothing could run the suite on that head + # short of pushing to it. Dispatch it on the branch; the check runs land on + # the head sha like any other run. + workflow_dispatch: concurrency: group: heart-tests-${{ github.ref }} diff --git a/heart/checks/ci_timing.py b/heart/checks/ci_timing.py index c5a1b7fb..bb927f41 100644 --- a/heart/checks/ci_timing.py +++ b/heart/checks/ci_timing.py @@ -672,11 +672,17 @@ def main(argv: list[str] | None = None) -> int: today = ns.today or datetime.datetime.now(datetime.timezone.utc).date().isoformat() thr = load_thresholds() record_dir = Path(ns.record_dir) if ns.record_dir else _timings.TIMINGS_DIR + # compare within the current epoch only — a boundary in + # timings/epochs.jsonl is where the world changed (a rebuild, a runner + # change), and a baseline from before it is not a baseline. + epochs = _timings.read_epochs(record_dir / "epochs.jsonl") + since = ((_timings.current_epoch(epochs) or {}).get("date") or "") rollup = aggregate( read_sidecars(per_repo), read_prev_board(ns.prev_board), today, ts, thr, record_history=_timings.gates_history( - record_dir / "gates.jsonl", int(thr.get("history_cap", 30)) + record_dir / "gates.jsonl", int(thr.get("history_cap", 30)), + since=since, ), ) _write(Path(ns.out), rollup) diff --git a/heart/checks/smoke_timings.py b/heart/checks/smoke_timings.py index 995b9b1f..08ad49ae 100644 --- a/heart/checks/smoke_timings.py +++ b/heart/checks/smoke_timings.py @@ -815,10 +815,17 @@ def main(argv: list[str] | None = None) -> int: per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR record_dir = Path(ns.record_dir) if ns.record_dir else _timings.TIMINGS_DIR + # compare within the current epoch only — a boundary in + # timings/epochs.jsonl is where the world changed (a rebuild, a runner + # change), and a baseline from before it is not a baseline. + epochs = _timings.read_epochs(record_dir / "epochs.jsonl") + since = ((_timings.current_epoch(epochs) or {}).get("date") or "") rollup = aggregate( read_sidecars(per_repo), read_prev_board(ns.prev_board), ts, load_thresholds(), - record_prev_rows=_timings.previous_script_rows(record_dir / "scripts"), + record_prev_rows=_timings.previous_script_rows( + record_dir / "scripts", since=since + ), ) _write(Path(ns.out), rollup) print(summary_line(rollup)) diff --git a/heart/checks/unit_timings.py b/heart/checks/unit_timings.py index efcd21ab..d0141703 100644 --- a/heart/checks/unit_timings.py +++ b/heart/checks/unit_timings.py @@ -943,11 +943,17 @@ def main(argv: list[str] | None = None) -> int: per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR record_dir = Path(ns.record_dir) if ns.record_dir else _timings.TIMINGS_DIR unit_dir = record_dir / "unit" + # compare within the current epoch only — a boundary in + # timings/epochs.jsonl is where the world changed (a rebuild, a runner + # change), and a baseline from before it is not a baseline. + epochs = _timings.read_epochs(record_dir / "epochs.jsonl") + since = ((_timings.current_epoch(epochs) or {}).get("date") or "") rollup = aggregate( read_sidecars(per_repo), ts, thresholds, - record_prev_rows=_timings.previous_unit_rows(unit_dir), + record_prev_rows=_timings.previous_unit_rows(unit_dir, since=since), record_import_history=_timings.import_history( - unit_dir, int(thresholds.get("import_window", 7) or 7) + unit_dir, int(thresholds.get("import_window", 7) or 7), + since=since, ), ) _write(Path(ns.out), rollup) diff --git a/heart/dashboard.py b/heart/dashboard.py index fa22d1d2..c1c90149 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -986,15 +986,25 @@ def _record_lines(record: Any) -> tuple[str, str]: Empty strings when the census is absent — a snapshot taken before the record existed must render byte-identically to how it always did, so the caller appends nothing rather than a line saying "0 days". + + When the census carries an epoch, both lines say which one: the readers + compare inside it and nothing before it is visible to them, so the history + a row claims to stand on is the history *since that boundary*. A census + without one adds no suffix, and renders exactly as it always did. """ if not isinstance(record, dict) or not record: return "", "" days = _as_int(record.get("gates_days")) obs = _as_int(record.get("scripts_observations")) repos = _as_int(record.get("repos")) + epoch = record.get("epoch") + suffix = "" + if isinstance(epoch, dict) and epoch.get("label") and epoch.get("date"): + suffix = f" · epoch {epoch['label']} since {epoch['date']}" return ( - f"record: timings/gates.jsonl — {days} days", - f"record: timings/scripts/ — {obs} observations across {repos} repos", + f"record: timings/gates.jsonl — {days} days{suffix}", + f"record: timings/scripts/ — {obs} observations across {repos} repos" + f"{suffix}", ) @@ -1257,6 +1267,15 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non if isinstance(r, dict)], "errors": list(ut.get("errors") or []), } + epoch = record.get("epoch") + if isinstance(epoch, dict) and epoch.get("label") and epoch.get("date"): + # Additive, and emitted ONLY when there is a boundary in force (#208): + # the Brain board reads this block verbatim, so a census without an + # epoch must leave it byte-identical to what it always was. It says + # which epoch every `prev_*` figure above was drawn from — a reader + # comparing two boards across a boundary needs to know the baseline + # changed underneath them. + block["epoch"] = {"label": str(epoch["label"]), "date": str(epoch["date"])} return block diff --git a/heart/timings.py b/heart/timings.py index 05d327cb..9cfff6dd 100644 --- a/heart/timings.py +++ b/heart/timings.py @@ -15,6 +15,7 @@ Layout:: timings/README.md # the schema + the rules (doctrine) + timings/epochs.jsonl # one line per epoch boundary (a human writes it) timings/gates.jsonl # one line per UTC date timings/scripts/.jsonl # one line per (python leg, run id) timings/unit/.jsonl # one line per (python leg, run id) @@ -79,10 +80,20 @@ fresh-process cold import measured on the CI runner, and it is ``null`` — never 0.0 — when that import failed or timed out. -``timings/epochs.jsonl`` is RESERVED (``EPOCHS_FILE``) for a future labelled -epoch boundary — ``{"date", "label", "note"}``, e.g. "runners moved to 8-core" -— so a reader can tell a step change from a regression. Nothing here writes it -and the file deliberately does not exist yet. +``epochs.jsonl`` line:: + + {"date": "2026-09-05", "label": "legacy", + "note": "pre-rebuild reference round; comparisons must not cross this"} + +An epoch boundary is where **the world changed** — a rebuild, a runner change, +a cap change — and it is the one line in this record a human writes, through +``python -m heart.timings epoch`` in a PR. The daily job never touches the +file: a boundary is a judgement, not an observation. Every reader here takes a +``since`` and drops the record lines dated before it, so the current epoch is +the only window a baseline is ever drawn from — a number measured before the +world changed is not a baseline for a run after it, it is a different +experiment. No epochs at all means one unbroken epoch, which is exactly the +behaviour this record had before the file existed. """ from __future__ import annotations @@ -99,9 +110,10 @@ GATES_FILE = TIMINGS_DIR / "gates.jsonl" SCRIPTS_DIR = TIMINGS_DIR / "scripts" UNIT_DIR = TIMINGS_DIR / "unit" -# Named so the reservation is in the code, not only in the README. NOTHING -# writes this: an epoch boundary is a human's judgement about the world (a -# runner change, a cap change), not something a daily job can observe. +# The boundaries. A HUMAN writes this, through the `epoch` verb in a PR; the +# daily job never does — an epoch boundary is a judgement about the world (a +# rebuild, a runner change, a cap change), not something a daily job can +# observe. EPOCHS_FILE = TIMINGS_DIR / "epochs.jsonl" # The census key set, so a reader (and `show`) sees the same keys whether or @@ -115,6 +127,10 @@ "unit_observations": 0, "unit_repos": 0, "unparseable": 0, + # The boundaries recorded, and the one every reader is currently comparing + # inside of (`None` when there is none — one unbroken epoch). + "epochs": 0, + "epoch": None, } @@ -200,6 +216,96 @@ def _append(path: Path | str, records: list[dict[str, Any]]) -> None: handle.write(_dump(record) + "\n") +# --- epochs ------------------------------------------------------------------ +def _within_epoch(record: dict[str, Any], since: str) -> bool: + """Is this record line inside the epoch that begins on ``since``? + + An empty ``since`` is "no boundary" and keeps everything, which is exactly + how this record read before epochs existed. A line with NO date counts as + older than any boundary: the record cannot place it after the world + changed, and a baseline that might predate the change is not a baseline. + """ + if not since: + return True + date = str(record.get("date") or "") + return bool(date) and date >= since + + +def read_epochs(path: Path | str = EPOCHS_FILE) -> list[dict[str, Any]]: + """The epoch boundaries, oldest first, as ``{"date", "label", "note"}``. + + A line with no date or no label is not a boundary — it could not be + compared against and could not be named on the board — so it is dropped + rather than carried as a half-boundary. The sort is stable on ``date``, so + two boundaries recorded for the same day stay in the order they landed. + """ + records, _ = read_jsonl(path) + out: list[dict[str, Any]] = [] + for record in records: + date = str(record.get("date") or "") + label = str(record.get("label") or "") + if not date or not label: + continue + out.append({"date": date, "label": label, + "note": str(record.get("note") or "")}) + out.sort(key=lambda rec: rec["date"]) + return out + + +def current_epoch( + epochs: list[dict[str, Any]], today: str | None = None +) -> dict[str, Any] | None: + """The boundary in force today — the LAST one dated on or before it. + + ``None`` when there is none, which every reader takes as "everything is one + epoch". A boundary dated in the future is not in force yet: it can be + written ahead of the change it labels (the PR that lands a rebuild appends + it) without silently blinding every baseline the day it is committed. + """ + day = today or datetime.datetime.now(datetime.timezone.utc).date().isoformat() + current: dict[str, Any] | None = None + for epoch in epochs or []: + if str(epoch.get("date") or "") <= day: + current = epoch + return current + + +def append_epoch( + path: Path | str, date: str, label: str, note: str = "" +) -> bool: + """Append one boundary. ``False`` when it is already there, or malformed. + + Keyed on ``(date, label)``: re-running the verb is a no-op rather than a + second boundary for the same judgement. Append-only like every other writer + here — a boundary recorded wrongly is superseded by a later one, never + edited away, because the record is evidence. + """ + date = str(date or "") + label = str(label or "").strip() + if not label or not _is_iso_date(date): + return False + for existing in read_epochs(path): + if existing["date"] == date and existing["label"] == label: + return False + _append(path, [{"date": date, "label": label, "note": str(note or "")}]) + return True + + +def _is_iso_date(value: str) -> bool: + """``YYYY-MM-DD`` and nothing else — the record sorts on these as strings. + + The round-trip is the point: ``strptime`` happily parses ``2026-9-5``, and + an unpadded date sorts *after* ``2026-12-01``, which would silently place a + boundary in the wrong epoch. + """ + text = str(value) + try: + parsed = datetime.datetime.strptime(text, "%Y-%m-%d").date() + except ValueError: + return False + return parsed.isoformat() == text + + # --- gates ------------------------------------------------------------------- def gates_line_from_rollup( rollup: Any, today: str, ts: str @@ -252,7 +358,7 @@ def append_gates(path: Path | str, line: dict[str, Any] | None) -> bool: def gates_history( - path: Path | str = GATES_FILE, cap: int = 30 + path: Path | str = GATES_FILE, cap: int = 30, since: str = "" ) -> list[dict[str, Any]]: """The last ``cap`` gates lines, oldest first, in the *history* shape. @@ -262,12 +368,16 @@ def gates_history( dropped from this view: the baseline and the sparkline are about the p50, and widening the shape here would change ``board.json``'s ``performance.history`` for every consumer downstream. + + ``since`` is the current epoch's date: lines dated before the boundary are + invisible, because a gate measured before the world changed is not a + baseline for one measured after it. Empty ``since`` filters nothing. """ records, _ = read_jsonl(path) out: list[dict[str, Any]] = [] for record in records: date = str(record.get("date") or "") - if not date: + if not date or not _within_epoch(record, since): continue gates = record.get("gates") if not isinstance(gates, dict): @@ -377,7 +487,7 @@ def append_scripts(path: Path | str, lines: list[dict[str, Any]]) -> int: def previous_script_rows( - scripts_dir: Path | str = SCRIPTS_DIR, + scripts_dir: Path | str = SCRIPTS_DIR, since: str = "", ) -> dict[tuple[str, str, str], dict[str, Any]]: """``{(repo, python, entry): prev_row}`` — the last recorded observation. @@ -389,6 +499,10 @@ def previous_script_rows( is append-only, so the last line for a leg is the most recently recorded one. Timed entries only — the record holds no untimed rows to begin with, and a row with no seconds could not be compared anyway. + + ``since`` is the current epoch's date, applied BEFORE "latest per leg" is + chosen: a pre-boundary line is not a stale baseline to be superseded, it is + a measurement of a different world, so it must not be the latest either. """ out: dict[tuple[str, str, str], dict[str, Any]] = {} root = Path(scripts_dir) @@ -399,6 +513,8 @@ def previous_script_rows( records, _ = read_jsonl(path) latest: dict[str, dict[str, Any]] = {} for record in records: + if not _within_epoch(record, since): + continue latest[str(record.get("python") or "")] = record for python, record in latest.items(): entries = record.get("entries") @@ -519,7 +635,7 @@ def append_unit(path: Path | str, lines: list[dict[str, Any]]) -> int: def previous_unit_rows( - unit_dir: Path | str = UNIT_DIR, + unit_dir: Path | str = UNIT_DIR, since: str = "", ) -> dict[tuple[str, str, str], dict[str, Any]]: """``{(repo, python, nodeid): prev_row}`` — the last recorded observation. @@ -532,6 +648,10 @@ def previous_unit_rows( one. Only the recorded (slowest) tests are in there to begin with — a test that dropped out of the top N simply has no baseline next run, which is honest: nothing was recorded about it. + + ``since`` is the current epoch's date, applied BEFORE "latest per leg" is + chosen, for the reason ``previous_script_rows`` gives: a pre-boundary line + measured a different world and must not stand in as the latest. """ out: dict[tuple[str, str, str], dict[str, Any]] = {} root = Path(unit_dir) @@ -542,6 +662,8 @@ def previous_unit_rows( records, _ = read_jsonl(path) latest: dict[str, dict[str, Any]] = {} for record in records: + if not _within_epoch(record, since): + continue latest[str(record.get("python") or "")] = record for python, record in latest.items(): slowest = record.get("slowest") @@ -560,7 +682,7 @@ def previous_unit_rows( def import_history( - unit_dir: Path | str = UNIT_DIR, window: int = 7 + unit_dir: Path | str = UNIT_DIR, window: int = 7, since: str = "" ) -> dict[tuple[str, str, str], list[float]]: """``{(repo, package, python): [seconds, ...]}`` — oldest first, last N. @@ -569,6 +691,10 @@ def import_history( ``null`` observation — an import that failed or timed out — is skipped rather than carried as a zero, which would drag the median toward a number nothing ever measured. + + ``since`` is the current epoch's date, applied BEFORE the window is taken: + a window that reached back across a boundary would take the median of two + different worlds, which is a number nothing ever measured either. """ out: dict[tuple[str, str, str], list[float]] = {} root = Path(unit_dir) @@ -580,7 +706,7 @@ def import_history( records, _ = read_jsonl(path) for record in records: package = str(record.get("package") or "") - if not package: + if not package or not _within_epoch(record, since): continue seconds = _as_float(record.get("import_s")) if seconds is None: @@ -600,9 +726,19 @@ def census(directory: Path | str = TIMINGS_DIR) -> dict[str, Any]: ``unparseable`` is summed across every file so a corrupt line is reported rather than silently dropped: the record is evidence, and a hole in it is itself a finding. + + ``epoch`` is the boundary every reader is currently comparing inside of, + carried as ``{"date", "label"}`` — the note is the human's reasoning and + belongs in the file, not on a board row. ``None`` means one unbroken epoch. """ root = Path(directory) out = dict(EMPTY_CENSUS) + epochs = read_epochs(root / "epochs.jsonl") + out["epochs"] = len(epochs) + epoch = current_epoch(epochs) + out["epoch"] = ( + {"date": epoch["date"], "label": epoch["label"]} if epoch else None + ) gates, skipped = read_jsonl(root / "gates.jsonl") dates = sorted(str(rec.get("date") or "") for rec in gates if rec.get("date")) out["gates_days"] = len(dates) @@ -708,6 +844,29 @@ def _do_append(ns: argparse.Namespace) -> int: return 0 +def _do_epoch(ns: argparse.Namespace) -> int: + """The human door: record where the world changed, in a PR. + + Exit 2 is a malformed boundary (a date that is not ``YYYY-MM-DD``, an empty + label) — that is a typo at a keyboard, and a keyboard is where it should be + reported. A boundary already recorded is exit 0: re-running the verb is a + no-op, not a failure. + """ + directory = Path(ns.dir) if ns.dir else TIMINGS_DIR + date = ns.date or datetime.datetime.now(datetime.timezone.utc).date().isoformat() + label = str(ns.label or "").strip() + if not label or not _is_iso_date(date): + print("epoch: need an ISO YYYY-MM-DD --date and a non-empty --label", + file=sys.stderr) + return 2 + path = directory / "epochs.jsonl" + if append_epoch(path, date, label, ns.note): + print(_dump({"date": date, "label": label, "note": str(ns.note or "")})) + else: + print(f"epoch already recorded: {date} {label}") + return 0 + + def _do_show(ns: argparse.Namespace) -> int: directory = Path(ns.dir) if ns.dir else TIMINGS_DIR for key, value in census(directory).items(): @@ -742,6 +901,23 @@ def main(argv: list[str] | None = None) -> int: help="where the census JSON lands (default: " "$HEART_STATE_DIR/timings_record.json)") + # A HUMAN's verb, run in a PR — never the daily job's. `append` above does + # not touch epochs.jsonl, and must not: an epoch boundary is a judgement + # about the world (a rebuild, a runner change), not an observation. + ap_epoch = sub.add_parser( + "epoch", help="record an epoch boundary — where the world changed" + ) + ap_epoch.add_argument("--label", required=True, + help="the short name of the boundary, e.g. `legacy`") + ap_epoch.add_argument("--note", default="", + help="why this is a boundary — the reasoning a later " + "reader needs and cannot re-derive") + ap_epoch.add_argument("--date", default="", + help="ISO date the boundary takes effect " + "(default: today, UTC)") + ap_epoch.add_argument("--dir", default="", + help=f"the record directory (default: {TIMINGS_DIR})") + ap_show = sub.add_parser("show", help="print the record's census") ap_show.add_argument("--dir", default="", help=f"the record directory (default: {TIMINGS_DIR})") @@ -750,6 +926,8 @@ def main(argv: list[str] | None = None) -> int: sys.path.insert(0, str(HEART_HOME)) if ns.command == "append": return _do_append(ns) + if ns.command == "epoch": + return _do_epoch(ns) return _do_show(ns) diff --git a/tests/test_ci_timing.py b/tests/test_ci_timing.py index 8bbc4874..3e9f2ab0 100644 --- a/tests/test_ci_timing.py +++ b/tests/test_ci_timing.py @@ -432,8 +432,11 @@ def test_main_writes_sidecar_then_aggregates(tmp_path, monkeypatch, capsys): assert side["workflows"]["Tests"]["median_s"] == 600.0 out = tmp_path / "ci_timing.json" + # An EMPTY record dir keeps this hermetic: without it the call reads the + # repo's live timings/gates.jsonl as its history (#208). rc = ct.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", - "--today", "2026-08-24", "--out", str(out)]) + "--today", "2026-08-24", "--record-dir", str(tmp_path / "empty-record"), + "--out", str(out)]) assert rc == 0 roll = json.loads(out.read_text()) assert roll["gates"][0]["repo"] == "LibA" @@ -550,3 +553,40 @@ def test_main_aggregate_reads_the_record_directory(tmp_path, monkeypatch, capsys (gate,) = json.loads(out.read_text())["gates"] assert gate["baseline_s"] == 300.0 and gate["state"] == "warn" capsys.readouterr() + + +def test_main_aggregate_compares_only_inside_the_current_epoch(tmp_path, + monkeypatch, + capsys): + """#208: a boundary in timings/epochs.jsonl is where the world changed, and + a p50 measured before it is not a baseline for one measured after it — the + record lines dated before the boundary are simply invisible here.""" + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + per_repo = tmp_path / "per-repo" + per_repo.mkdir() + (per_repo / f"{REPO}.ci_timing.json").write_text(json.dumps(_one_gate_sidecar(900.0))) + + record = tmp_path / "timings" + record.mkdir() + (record / "epochs.jsonl").write_text(json.dumps({ + "date": "2026-09-05", "label": "legacy", + "note": "the reference round before the rebuild", + }) + "\n") + # A fast gate before the boundary; a slow one after it. Taken together the + # median baseline would be 450s and this run would read as a 2x regression. + (record / "gates.jsonl").write_text("".join( + json.dumps({"date": date, + "gates": {f"{REPO}/Gate One": {"p50_s": p50, "runs": 9}}}) + "\n" + for date, p50 in (("2026-09-03", 100.0), ("2026-09-05", 800.0)))) + + out = tmp_path / "ci_timing.json" + assert ct.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--today", "2026-09-06", "--record-dir", str(record), + "--out", str(out)]) == 0 + roll = json.loads(out.read_text()) + (gate,) = roll["gates"] + assert gate["baseline_s"] == 800.0 and gate["state"] == "ok" + # ...and the pre-boundary day is not in the rolled-forward history either. + assert [h["date"] for h in roll["history"]] == ["2026-09-05", "2026-09-06"] + capsys.readouterr() diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index a941b8dc..c66eb513 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1436,3 +1436,69 @@ def test_malformed_unit_timings_slices_never_break_the_board(): for fmt in ("term", "md", "html", "json"): assert isinstance(dashboard.render(snap, make_verdict(), fmt=fmt, now=FRESH_NOW), str) + + +# --- the current epoch on the two ⏱ rows (#208) ------------------------------ +# +# A boundary in timings/epochs.jsonl is where the world changed, and every +# record reader compares only inside the current one — so the history a timing +# row claims to stand on is the history SINCE that boundary, and the row says +# so. Additive on the same rule as the census itself: a snapshot whose census +# carries no epoch renders byte-identically to how it always did. + +TIMINGS_CENSUS_EPOCH = dict(TIMINGS_CENSUS, epochs=1, + epoch={"label": "legacy", "date": "2026-09-05"}) + + +def _epoch_snapshot(**kw): + return make_snapshot(ci_timing=_ci_timing_slice(), no_run_census=_no_run_slice(), + smoke_timings=_smoke_timings_slice(), + timings_record=TIMINGS_CENSUS_EPOCH, **kw) + + +def test_both_record_lines_name_the_epoch_they_are_measured_inside(): + board = dashboard.build_board(_epoch_snapshot(), make_verdict(), now=FRESH_NOW) + assert _section(board, "ci_timing").details[-1] == ( + "record: timings/gates.jsonl — 42 days · epoch legacy since 2026-09-05") + assert _section(board, "smoke_timings").details[-1] == ( + "record: timings/scripts/ — 96 observations across 3 repos" + " · epoch legacy since 2026-09-05") + + +def test_a_census_without_an_epoch_renders_the_lines_it_always_did(): + """One unbroken epoch is the record's old behaviour, and it must read like + it: no suffix, not an empty one.""" + board = dashboard.build_board(_record_snapshot(), make_verdict(), now=FRESH_NOW) + for key in ("ci_timing", "smoke_timings"): + assert "epoch" not in _section(board, key).details[-1] + + +def test_the_performance_block_carries_the_epoch_only_when_there_is_one(): + """`performance` is the contract the Brain board reads verbatim: the key is + additive, and a census with no boundary leaves the block byte-identical.""" + v = make_verdict() + with_epoch = json.loads(dashboard.render(_epoch_snapshot(), v, fmt="json", + now=FRESH_NOW)) + without = json.loads(dashboard.render(_record_snapshot(), v, fmt="json", + now=FRESH_NOW)) + assert with_epoch["performance"]["epoch"] == {"label": "legacy", + "date": "2026-09-05"} + assert "epoch" not in without["performance"] + stripped = dict(with_epoch["performance"]) + stripped.pop("epoch") + assert stripped == without["performance"] + + +def test_a_half_written_epoch_is_no_epoch_at_all(): + """A boundary with no label could not be named on a row and a boundary with + no date could not be compared against — neither is one.""" + v = make_verdict() + for epoch in (None, {}, {"label": "legacy"}, {"date": "2026-09-05"}, "legacy"): + census = dict(TIMINGS_CENSUS, epoch=epoch) + board = dashboard.build_board( + make_snapshot(ci_timing=_ci_timing_slice(), + no_run_census=_no_run_slice(), + smoke_timings=_smoke_timings_slice(), + timings_record=census), + v, now=FRESH_NOW) + assert "epoch" not in _section(board, "ci_timing").details[-1] diff --git a/tests/test_smoke_timings.py b/tests/test_smoke_timings.py index c5191b85..0b828f6e 100644 --- a/tests/test_smoke_timings.py +++ b/tests/test_smoke_timings.py @@ -439,8 +439,13 @@ def test_main_writes_sidecar_then_aggregates(tmp_path, monkeypatch, capsys): prev = tmp_path / "board.json" prev.write_text(json.dumps(_prev_board([_prev_row(10.0)]))) roll_path = tmp_path / "smoke_timings.json" + # An EMPTY record dir, so the test exercises the previous-board fallback it + # was written for. Without it the call falls through to the repo's live + # timings/ (#208: the first daily record commit landed and this test went + # red on main — a test-isolation hole, not a regression). assert smt.main(["--aggregate", "--per-repo-dir", str(per_repo), "--prev-board", str(prev), "--ts", "T", + "--record-dir", str(tmp_path / "empty-record"), "--out", str(roll_path)]) == 0 roll = json.loads(roll_path.read_text()) assert roll["rows"][0]["repo"] == REPO and roll["rows"][0]["state"] == "warn" @@ -563,3 +568,59 @@ def test_main_aggregate_reads_the_record_directory(tmp_path, monkeypatch, capsys (row,) = _json.loads(out.read_text())["rows"] assert row["state"] == "warn" and row["prev_s"] == 10.0 and row["prev_run_id"] == 6 capsys.readouterr() + + +def test_main_aggregate_compares_only_inside_the_current_epoch(tmp_path, + monkeypatch, + capsys): + """#208: a script's seconds recorded before a boundary in + timings/epochs.jsonl measured a different world — the 3.12 leg here was + last recorded before the rebuild, so it has no baseline at all rather than + a stale one, while the 3.13 leg is compared against its post-boundary + observation.""" + import json as _json + + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + per_repo = tmp_path / "per-repo" + per_repo.mkdir() + legs = [ + {"artifact": _selected(name="smoke-timings-3.12", id_=11), + "dir": _extracted(tmp_path, [_entry("imaging/x.py", seconds=30.0)], + sub="a12", python="3.12"), + "error": ""}, + {"artifact": _selected(name="smoke-timings-3.13", id_=12), + "dir": _extracted(tmp_path, [_entry("imaging/x.py", seconds=30.0)], + sub="a13", python="3.13"), + "error": ""}, + ] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + (per_repo / f"{REPO}.smoke_timings.json").write_text(_json.dumps(side)) + + record = tmp_path / "timings" + (record / "scripts").mkdir(parents=True) + (record / "epochs.jsonl").write_text(_json.dumps({ + "date": "2026-09-05", "label": "legacy", + "note": "the reference round before the rebuild", + }) + "\n") + + def _line(date, python, run_id, seconds): + return {"date": date, "at": "", "python": python, "run_id": run_id, + "run_url": PREV_RUN_URL, "head_branch": "", "head_sha": "", + "env_profile": "smoke", + "entries": {"imaging/x.py": [seconds, "passed", 600.0]}} + + (record / "scripts" / f"{REPO}.jsonl").write_text("".join( + _json.dumps(line) + "\n" for line in ( + _line("2026-09-03", "3.12", 5, 10.0), # before the boundary + _line("2026-09-05", "3.13", 6, 28.0), # after it + ))) + + out = tmp_path / "smoke_timings.json" + assert smt.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--record-dir", str(record), "--out", str(out)]) == 0 + rows = {r["python"]: r for r in _json.loads(out.read_text())["rows"]} + # 30s against a pre-boundary 10s would have read as a 3x regression. + assert rows["3.12"]["prev_s"] is None and rows["3.12"]["state"] == "ok" + assert rows["3.13"]["prev_s"] == 28.0 and rows["3.13"]["prev_run_id"] == 6 + capsys.readouterr() diff --git a/tests/test_timings.py b/tests/test_timings.py index 0449fd01..6df81ce1 100644 --- a/tests/test_timings.py +++ b/tests/test_timings.py @@ -252,10 +252,14 @@ def test_the_census_counts_days_observations_and_repos(tmp_path): timings.append_scripts(timings.scripts_file(repo, tmp_path), lines) # The two unit_* keys arrived with the unit-timings slice (#206): the # census is the record's key set, and the record now holds three slices. + # The two unit_* keys arrived with #206; `epochs`/`epoch` with #208 — the + # census is the record's key set, and the record now holds the boundaries + # every reader compares inside of as well as the three observation slices. assert timings.census(tmp_path) == { "gates_days": 2, "gates_first": "2026-09-04", "gates_last": TODAY, "scripts_observations": 2, "repos": 2, "unit_observations": 0, "unit_repos": 0, "unparseable": 0, + "epochs": 0, "epoch": None, } @@ -329,9 +333,12 @@ def test_main_show_prints_the_census_one_key_per_line(tmp_path, capsys): assert {ln.split(":")[0] for ln in lines} == set(timings.EMPTY_CENSUS) -def test_the_epoch_file_is_reserved_and_never_written(tmp_path): +def test_the_daily_append_never_writes_the_epoch_file(tmp_path): """`epochs.jsonl` is a human's judgement about the world, not an - observation — the path is named so the reservation lives in the code.""" + observation — so the daily job's verb never creates it and never adds to + it. (#208: the file is live now; before it, this test asserted the stronger + "and it does not exist" — the half that survives is the load-bearing one, + that the writer of observations is not the writer of boundaries.)""" assert timings.EPOCHS_FILE.name == "epochs.jsonl" ci, smoke = _write_rollups(tmp_path) record = tmp_path / "timings" @@ -339,7 +346,6 @@ def test_the_epoch_file_is_reserved_and_never_written(tmp_path): "--today", TODAY, "--dir", str(record), "--census-out", str(tmp_path / "census.json")]) assert not (record / "epochs.jsonl").exists() - assert not timings.EPOCHS_FILE.exists() # --- the unit slice: per-test durations + the cold import (#206) -------------- @@ -509,3 +515,273 @@ def test_a_run_without_the_unit_flag_reads_exactly_as_it_always_did(tmp_path, ]) == 0 assert "unit +" not in capsys.readouterr().out assert "unit" not in json.loads(census_out.read_text())["appended_today"] + + +# --- epochs: where the world changed (#208) ---------------------------------- +# +# A boundary is the one line in this record a HUMAN writes, in a PR, because it +# is a judgement about the world (a rebuild, a runner change) and not something +# a daily job can observe. What it buys is the thing these tests pin: every +# reader compares INSIDE the current epoch, so a number measured before the +# world changed never stands in as the baseline for a run measured after it. + +EPOCH_NOTE = "the reference round; comparisons must not cross this boundary" + + +def _epochs_file(tmp_path, *lines): + """Write an epochs.jsonl by hand — the readers must cope with any order.""" + path = tmp_path / "epochs.jsonl" + path.write_text("".join(json.dumps(line) + "\n" for line in lines)) + return path + + +def test_read_epochs_sorts_normalises_and_drops_the_half_boundaries(tmp_path): + path = _epochs_file( + tmp_path, + {"date": "2026-09-05", "label": "legacy", "note": EPOCH_NOTE}, + {"date": "2026-07-01", "label": "runners"}, + # Neither of these is a boundary: one cannot be compared against, the + # other cannot be named on a board row. + {"date": "2026-08-01"}, + {"label": "nameless"}, + ) + assert timings.read_epochs(path) == [ + {"date": "2026-07-01", "label": "runners", "note": ""}, + {"date": "2026-09-05", "label": "legacy", "note": EPOCH_NOTE}, + ] + # A missing file is an empty record, never an error. + assert timings.read_epochs(tmp_path / "nope.jsonl") == [] + + +def test_two_boundaries_on_one_day_keep_the_order_they_landed(tmp_path): + path = _epochs_file(tmp_path, + {"date": "2026-09-05", "label": "first"}, + {"date": "2026-09-05", "label": "second"}) + assert [e["label"] for e in timings.read_epochs(path)] == ["first", "second"] + + +def test_current_epoch_is_the_latest_boundary_on_or_before_today(): + epochs = [ + {"date": "2026-07-01", "label": "runners", "note": ""}, + {"date": "2026-09-05", "label": "legacy", "note": EPOCH_NOTE}, + # Written ahead of the change it labels: not in force yet, so it cannot + # blind every baseline the day its PR lands. + {"date": "2026-12-01", "label": "fast-tests", "note": ""}, + ] + assert timings.current_epoch(epochs, TODAY)["label"] == "legacy" + assert timings.current_epoch(epochs, "2026-08-31")["label"] == "runners" + assert timings.current_epoch(epochs, "2026-06-30") is None + # No boundaries at all is one unbroken epoch, which is the old behaviour. + assert timings.current_epoch([], TODAY) is None + + +def test_append_epoch_dedupes_on_date_and_label_and_never_rewrites(tmp_path): + path = tmp_path / "epochs.jsonl" + assert timings.append_epoch(path, TODAY, "legacy", EPOCH_NOTE) is True + before = path.read_bytes() + # The same judgement recorded twice is a no-op, not a second boundary. + assert timings.append_epoch(path, TODAY, "legacy", "a different note") is False + assert path.read_bytes() == before + # A different label on the same day IS a different judgement. + assert timings.append_epoch(path, TODAY, "runners", "") is True + after = path.read_bytes() + assert after.startswith(before) and len(after) > len(before) + assert [e["label"] for e in timings.read_epochs(path)] == ["legacy", "runners"] + + +def test_append_epoch_refuses_a_bad_date_or_an_empty_label(tmp_path): + """The record sorts on these dates as strings, so `YYYY-MM-DD` and nothing + else; a label-less boundary could not be named on a board row.""" + path = tmp_path / "epochs.jsonl" + for date in ("05-09-2026", "2026-9-5", "20260905", "tomorrow", ""): + assert timings.append_epoch(path, date, "legacy", "") is False + for label in ("", " "): + assert timings.append_epoch(path, TODAY, label, "") is False + assert not path.exists() + + +# --- every reader compares inside the current epoch --------------------------- +def _dated_gates(date, p50): + return {"date": date, "ts": TS, + "gates": {"RepoA/Gate One": {"p50_s": p50, "runs": 5}}} + + +def test_gates_history_drops_the_lines_before_the_boundary(tmp_path): + path = tmp_path / "gates.jsonl" + for line in (_dated_gates("2026-09-03", 100.0), + _dated_gates("2026-09-05", 900.0)): + timings.append_gates(path, line) + assert [h["date"] for h in timings.gates_history(path, 30)] == [ + "2026-09-03", "2026-09-05"] + # A gate measured before the world changed is not a baseline for one + # measured after it. + assert [h["date"] for h in timings.gates_history(path, 30, since=TODAY)] == [ + "2026-09-05"] + assert timings.gates_history(path, 30, since="2026-12-01") == [] + + +def _scripts_line(date, run_id, seconds): + return {"date": date, "at": "", "python": "3.12", "run_id": run_id, + "run_url": RUN_URL, "head_branch": "", "head_sha": "", + "env_profile": "smoke", + "entries": {"imaging/x.py": [seconds, "passed", 600.0]}} + + +def test_previous_script_rows_filters_before_it_picks_the_latest(tmp_path): + """The order matters: a pre-boundary line is not a stale baseline to be + superseded, it is a measurement of a different world — so it must not win + the "latest per leg" race either.""" + scripts = tmp_path / "scripts" + scripts.mkdir() + path = scripts / "RepoA.jsonl" + timings._append(path, [_scripts_line("2026-09-04", 6, 10.0), + _scripts_line("2026-09-05", 7, 30.0)]) + key = ("RepoA", "3.12", "imaging/x.py") + assert timings.previous_script_rows(scripts)[key]["seconds"] == 30.0 + assert timings.previous_script_rows(scripts, since=TODAY)[key]["run_id"] == 7 + # With only the pre-boundary line inside reach, there is no baseline at all + # — which is honest: nothing comparable was recorded. + only_old = tmp_path / "old" + only_old.mkdir() + timings._append(only_old / "RepoA.jsonl", [_scripts_line("2026-09-04", 6, 10.0)]) + assert timings.previous_script_rows(only_old, since=TODAY) == {} + assert timings.previous_script_rows(only_old)[key]["seconds"] == 10.0 + + +def test_an_undated_line_is_older_than_any_boundary(tmp_path): + """The record cannot place it after the world changed, and a baseline that + MIGHT predate the change is not a baseline. With no boundary in force it is + read exactly as it always was.""" + scripts = tmp_path / "scripts" + scripts.mkdir() + undated = _scripts_line("", 6, 10.0) + undated.pop("date") + timings._append(scripts / "RepoA.jsonl", [undated]) + key = ("RepoA", "3.12", "imaging/x.py") + assert timings.previous_script_rows(scripts)[key]["seconds"] == 10.0 + assert timings.previous_script_rows(scripts, since=TODAY) == {} + + +def _unit_line(date, run_id, seconds, import_s): + return {"date": date, "at": "", "python": "3.12", "run_id": run_id, + "run_url": RUN_URL, "head_branch": "", "head_sha": "", + "package": PACKAGE, "import_s": import_s, + "suite": {"tests": 2, "failures": 0, "errors": 0, "skipped": 0, + "wall_s": 40.0}, + "slowest": {NODEID: seconds}} + + +def test_previous_unit_rows_and_import_history_honour_the_boundary(tmp_path): + unit = tmp_path / "unit" + unit.mkdir() + timings._append(unit / "RepoA.jsonl", [ + _unit_line("2026-09-03", 5, 1.0, 1.0), + _unit_line("2026-09-04", 6, 2.0, 2.0), + _unit_line("2026-09-05", 7, 9.0, 9.0), + ]) + key = ("RepoA", "3.12", NODEID) + assert timings.previous_unit_rows(unit)[key]["run_id"] == 7 + assert timings.previous_unit_rows(unit, since=TODAY)[key]["run_id"] == 7 + + hist_key = ("RepoA", PACKAGE, "3.12") + assert timings.import_history(unit, 7)[hist_key] == [1.0, 2.0, 9.0] + # A window reaching back across a boundary would take the median of two + # different worlds — so the boundary is applied BEFORE the window. + assert timings.import_history(unit, 7, since=TODAY)[hist_key] == [9.0] + assert timings.import_history(unit, 7, since="2026-09-04")[hist_key] == [2.0, 9.0] + + +def test_an_empty_since_reads_byte_identically_to_no_since_at_all(tmp_path): + """The whole record predates epochs; with no boundary in force every reader + must answer exactly what it always answered.""" + scripts = tmp_path / "scripts" + scripts.mkdir() + timings._append(scripts / "RepoA.jsonl", [_scripts_line("2026-09-04", 6, 10.0)]) + unit = tmp_path / "unit" + unit.mkdir() + timings._append(unit / "RepoA.jsonl", [_unit_line("2026-09-04", 6, 2.0, 2.0)]) + gates = tmp_path / "gates.jsonl" + timings.append_gates(gates, _dated_gates("2026-09-04", 100.0)) + + assert timings.gates_history(gates, 30, since="") == timings.gates_history(gates, 30) + assert (timings.previous_script_rows(scripts, since="") + == timings.previous_script_rows(scripts)) + assert (timings.previous_unit_rows(unit, since="") + == timings.previous_unit_rows(unit)) + assert timings.import_history(unit, 7, since="") == timings.import_history(unit, 7) + + +# --- the census and the CLI --------------------------------------------------- +def test_the_census_carries_the_boundaries_and_the_one_in_force(tmp_path): + empty = timings.census(tmp_path) + assert empty["epochs"] == 0 and empty["epoch"] is None + _epochs_file(tmp_path, + {"date": "2026-07-01", "label": "runners", "note": ""}, + {"date": "2026-09-05", "label": "legacy", "note": EPOCH_NOTE}, + {"date": "2099-01-01", "label": "not yet", "note": ""}) + census = timings.census(tmp_path) + assert census["epochs"] == 3 + # The note is the human's reasoning and belongs in the file, not on a row. + assert census["epoch"] == {"date": "2026-09-05", "label": "legacy"} + + +def test_main_epoch_appends_once_and_says_so_on_the_repeat(tmp_path, capsys): + record = tmp_path / "timings" + argv = ["epoch", "--date", TODAY, "--label", "legacy", "--note", EPOCH_NOTE, + "--dir", str(record)] + assert timings.main(argv) == 0 + assert json.loads(capsys.readouterr().out.strip()) == { + "date": TODAY, "label": "legacy", "note": EPOCH_NOTE} + before = (record / "epochs.jsonl").read_bytes() + + assert timings.main(argv) == 0 + assert capsys.readouterr().out.strip() == f"epoch already recorded: {TODAY} legacy" + assert (record / "epochs.jsonl").read_bytes() == before + + +def test_main_epoch_exits_2_on_a_boundary_it_cannot_record(tmp_path, capsys): + record = tmp_path / "timings" + assert timings.main(["epoch", "--date", "05-09-2026", "--label", "legacy", + "--dir", str(record)]) == 2 + assert timings.main(["epoch", "--date", TODAY, "--label", " ", + "--dir", str(record)]) == 2 + capsys.readouterr() + assert not (record / "epochs.jsonl").exists() + + +def test_main_append_leaves_the_epoch_file_byte_identical(tmp_path): + """The daily job writes observations; a boundary is a judgement, and the + two writers are not the same one.""" + ci, smoke = _write_rollups(tmp_path) + record = tmp_path / "timings" + record.mkdir() + epochs = _epochs_file(record, {"date": TODAY, "label": "legacy", + "note": EPOCH_NOTE}) + before = epochs.read_bytes() + assert timings.main([ + "append", "--ci-timing", str(ci), "--smoke-timings", str(smoke), + "--today", TODAY, "--dir", str(record), + "--census-out", str(tmp_path / "census.json"), + ]) == 0 + assert epochs.read_bytes() == before + assert json.loads((tmp_path / "census.json").read_text())["epoch"] == { + "date": TODAY, "label": "legacy"} + + +def test_main_show_prints_the_epoch_keys_too(tmp_path, capsys): + _epochs_file(tmp_path, {"date": TODAY, "label": "legacy", "note": EPOCH_NOTE}) + assert timings.main(["show", "--dir", str(tmp_path)]) == 0 + out = capsys.readouterr().out + assert "epochs: 1" in out + assert "'label': 'legacy'" in out and "'date': '2026-09-05'" in out + + +def test_the_committed_record_carries_exactly_the_legacy_boundary(): + """Declared data in the record, read the way the config tests read + config/repos.yaml: the `legacy` boundary labels the pre-rebuild reference + round, and the phase that lands the rebuild appends the NEXT one.""" + epochs = timings.read_epochs(timings.EPOCHS_FILE) + assert len(epochs) == 1 + assert epochs[0]["date"] == "2026-09-05" and epochs[0]["label"] == "legacy" + assert epochs[0]["note"] + assert len(timings.EPOCHS_FILE.read_text().splitlines()) == 1 diff --git a/tests/test_unit_timings.py b/tests/test_unit_timings.py index 07c43000..8b824c89 100644 --- a/tests/test_unit_timings.py +++ b/tests/test_unit_timings.py @@ -690,3 +690,63 @@ def test_summary_lines_are_honest_about_unavailability(monkeypatch): assert "UNAVAILABLE" in ut.repo_summary_line(dead) roll = ut.aggregate([dead], "T", THRESHOLDS) assert "1 unavailable" in ut.summary_line(roll) + + +def test_main_aggregate_compares_only_inside_the_current_epoch(tmp_path, + monkeypatch, + capsys): + """#208: the record is the only baseline here, so a boundary in + timings/epochs.jsonl decides what that baseline is. The pre-boundary + observations measured a different world: they are neither the previous + seconds a test is judged against nor part of the import median window.""" + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + per_repo = tmp_path / "per-repo" + per_repo.mkdir() + side = _sidecar(tmp_path, junit=_junit(_case(time="6.0")), + imports=_import_json(seconds=6.0)) + (per_repo / f"{REPO}.unit_timings.json").write_text(json.dumps(side)) + + record = tmp_path / "timings" + (record / "unit").mkdir(parents=True) + (record / "epochs.jsonl").write_text(json.dumps({ + "date": "2026-09-05", "label": "legacy", + "note": "the reference round before the rebuild", + }) + "\n") + + def _line(date, run_id, seconds, import_s): + return {"date": date, "at": "", "python": "3.12", "run_id": run_id, + "run_url": PREV_RUN_URL, "head_branch": "", "head_sha": "", + "package": PACKAGE, "import_s": import_s, + "suite": {"tests": 2, "failures": 0, "errors": 0, "skipped": 0, + "wall_s": 40.0}, + "slowest": {NODEID: seconds}} + + (record / "unit" / f"{REPO}.jsonl").write_text("".join( + json.dumps(line) + "\n" for line in ( + _line("2026-09-02", 3, 1.0, 1.0), # three fast observations, + _line("2026-09-03", 4, 1.0, 1.0), # all before the boundary — + _line("2026-09-04", 5, 1.0, 1.0), # a median of a lost world + _line("2026-09-05", 6, 5.0, 5.0), # the only one after it + ))) + + legacy = tmp_path / "legacy" + out = tmp_path / "unit_timings.json" + assert ut.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--record-dir", str(record), "--legacy-dir", str(legacy), + "--out", str(out)]) == 0 + roll = json.loads(out.read_text()) + # 6.0s against the post-boundary 5.0s is jitter; against the pre-boundary + # 1.0s it would have been a 6x regression. + (row,) = roll["tests"] + assert row["prev_s"] == 5.0 and row["prev_run_id"] == 6 and row["state"] == "ok" + # ...and the import window holds one observation, not four, so the import + # is still building rather than judged against a median of a lost world. + # Four observations, one epoch: the window holds the single post-boundary + # one, so the import is still BUILDING rather than judged against a median + # of a lost world. + (imp,) = roll["imports"] + assert imp["samples"] == 1 and imp["state"] == "building" + assert json.loads( + (legacy / "import_time.json").read_text())["new_packages_no_baseline"] == 1 + capsys.readouterr() diff --git a/timings/README.md b/timings/README.md index 804f7c12..c876e3ae 100644 --- a/timings/README.md +++ b/timings/README.md @@ -1,10 +1,13 @@ # `timings/` — the permanent CI timing record -This directory is PyAutoHeart's **append-only record of how long CI takes**. It -is written by exactly one thing — the daily `heart-health.yml` cloud job, which -commits it beside the README board block, one commit a day — and read by the -timing checks as the first source for their baselines (for `unit_timings` it is -the *only* source: the board never carried per-test rows). +This directory is PyAutoHeart's **append-only record of how long CI takes**. Its +observations are written by exactly one thing — the daily `heart-health.yml` +cloud job, which commits them beside the README board block, one commit a day — +and read by the timing checks as the first source for their baselines (for +`unit_timings` it is the *only* source: the board never carried per-test rows). +The one exception is [`epochs.jsonl`](#epochsjsonl--where-the-world-changed), +which a **human** writes in a PR: a boundary is a judgement about the world, not +an observation, and it decides how far back every baseline here can see. It exists because the alternative did not last. `ci_timing` and `smoke_timings` both carried their history in the `board.json` published to Pages by the @@ -21,6 +24,8 @@ carries the same rules for a reader who arrives from the Python side. ``` timings/README.md # this file — doctrine, not data +timings/legacy_round_2026-09.md # the digest of the first (legacy) round — prose, not data +timings/epochs.jsonl # one line per epoch boundary — a human writes it timings/gates.jsonl # one line per UTC date timings/scripts/.jsonl # one line per (python leg, run id) — smoke scripts timings/unit/.jsonl # one line per (python leg, run id) — unit tests + import @@ -130,19 +135,72 @@ Keyed on the day, that writes seven copies of one measurement — the to be re-derived — and a flat week reads as a week of measurements. Keyed on the run, a quiet week records nothing, which is the truth. -## Reserved: `epochs.jsonl` +## `epochs.jsonl` — where the world changed -`timings/epochs.jsonl` is **reserved** for a future labelled epoch boundary: +One JSON object per line, one **boundary** per line, sorted by date: ```json -{"date":"2026-09-05","label":"runners moved to 8 cores","note":"..."} +{"date":"2026-09-05","label":"legacy","note":"why this is a boundary"} ``` -A reader could then tell a step change in the world from a regression in the -code. Nothing writes it, and the file deliberately does not exist yet — -`heart/timings.py` names the path (`EPOCHS_FILE`) so the reservation lives in -the code as well as here. An epoch is a human's judgement about the world, not -something a daily job can observe. +* `date` is `YYYY-MM-DD` and nothing else — the record sorts these as strings, + and an unpadded `2026-9-5` would sort *after* `2026-12-01`. +* `label` is the short name the board shows (`legacy`, `fast-tests`). A line + with no date or no label is not a boundary and is dropped on read: one could + not be compared against, the other could not be named on a row. +* `note` is the reasoning a later reader cannot re-derive — *why* this is a + boundary, not a restatement of the label. + +**Readers compare within the current epoch** — the latest boundary dated on or +before today. Records dated before it are invisible to every baseline: +`gates_history`, `previous_script_rows`, `previous_unit_rows` and +`import_history` each take a `since` and drop the earlier lines *before* they +pick the latest observation per leg or take the median window. A number +measured before the world changed is not a baseline for a run after it — it is +a different experiment. A record line with **no** date counts as older than any +boundary: the record cannot place it after the change, and a baseline that +might predate the change is not a baseline. No boundaries at all means one +unbroken epoch, which is exactly how this record read before the file existed. + +A boundary dated in the **future** is not in force yet, which is what lets a PR +append the boundary for the change it is landing without blinding every +baseline the moment it merges. + +### Who writes it + +A **human**, in a PR, through the verb: + +```bash +PYTHONPATH="$PWD" python -m heart.timings epoch \ + --date 2026-09-05 --label legacy --note "why this is a boundary" +``` + +Never the daily job. `heart.timings append` writes observations and does not +touch this file — an epoch boundary is a *judgement about the world* (a +rebuild, a runner change, a cap change), and a daily job cannot observe one. +The verb is append-only like every other writer here: it refuses a duplicate +`(date, label)` and prints `epoch already recorded: …`, so re-running it is a +no-op rather than a second boundary for the same judgement. + +### The standing instruction + +**The phase that lands a rebuild appends the next boundary, in its own PR.** +That is the whole mechanism: the post-rebuild history starts fresh, because +from the boundary's date onwards no reader can see a single pre-rebuild number. +A rebuild that lands without its boundary leaves every baseline comparing two +different worlds and reporting the difference as a regression — the failure +mode this file exists to prevent. For the `ci-timing-fast-tests` epic the next +one is `label: fast-tests`, appended by the phase that lands the rebuild. + +### The current content + +One boundary: + +* **`legacy` @ 2026-09-05** — the pre-rebuild reference round of the + `ci-timing-fast-tests` epic. Phases 5–7 of that epic change `_test` script + content, datasets, pinned likelihoods and CI caches; everything recorded up + to and including this date measured the world as it stood *before* those + changes, and comparisons must not cross the boundary. ## Growth @@ -152,6 +210,8 @@ something a daily job can observe. practice far fewer — a line lands only when a new run produced a new artifact. Two legs per repo is the current shape, so ≤ 2 lines/day/repo, and a quiet repo contributes nothing at all. +* `epochs.jsonl`: a handful of lines a year at most — a boundary is written + only when the world actually changed. * `unit/.jsonl`: the same shape and the same cap — ≤ 2 lines/day/repo, and only when a new run produced a new artifact. A line is larger than a scripts line (the slowest N tests plus the suite totals) but bounded by @@ -166,7 +226,8 @@ exchange for nothing. ## Reading it ```bash -# The one-screen answer: days recorded, observations, repos, holes. +# The one-screen answer: days recorded, observations, repos, holes — and the +# epoch every reader is currently comparing inside of. PYTHONPATH="$PWD" python -m heart.timings show # One gate's daily p50s. diff --git a/timings/epochs.jsonl b/timings/epochs.jsonl new file mode 100644 index 00000000..1f049295 --- /dev/null +++ b/timings/epochs.jsonl @@ -0,0 +1 @@ +{"date":"2026-09-05","label":"legacy","note":"pre-rebuild reference round of the ci-timing-fast-tests epic: phases 5-7 change _test script content, datasets, pinned likelihoods and CI caches; comparisons must not cross this boundary"} diff --git a/timings/legacy_round_2026-09.md b/timings/legacy_round_2026-09.md new file mode 100644 index 00000000..f550cc5c --- /dev/null +++ b/timings/legacy_round_2026-09.md @@ -0,0 +1,188 @@ +# Legacy timing round — where CI time went before the rebuild (2026-09-05) + +Phase 4 of the `ci-timing-fast-tests` epic (the PyAutoMind ledger +`draft/feature/pyautoheart/ci_timing_fast_tests_epic.md`; PyAutoHeart#208). It lives +beside the record it describes, in `timings/`, and is linked from the ledger. +This is the **LEGACY reference**, not the start of the long-term history: +phases 5–7 change `_test` script content, simulated datasets, pinned +likelihoods and CI caches, so nothing measured after them may be compared +against these numbers. The boundary is recorded in the Heart's permanent +record as `timings/epochs.jsonl` → `legacy @ 2026-09-05`; the phase that lands +the rebuild appends the next one. + +**Source.** The first live round of the finished board: `heart-health.yml` +dispatched by hand on 2026-09-05 (run after PyAutoHeart#207 merged), which +seeded `PyAutoHeart/timings/gates.jsonl` (26 gates) and +`timings/scripts/.jsonl` (22 legs — 11 repos × Python 3.12/3.13, 494 +script rows, **0 legs unavailable**; the cross-repo artifact 403 risk did not +materialise). Per-script seconds are the runner's own `[PASS] — s` +measurement inside the gate job; gate wall-clock is `updated_at − +run_started_at` medians over success runs, PR runs included. Board: +. + +**Not yet in this round.** Unit-test durations and import times: the +`unit-timings-` artifact (PyAutoHeart#207) is emitted by the next +library CI run after 2026-09-05 23:02 UTC and ingested on the following daily +run; imports render `building` until three runs are recorded. The unit/import +section below is therefore a placeholder to be filled by the phase-9 census, +and the Python-leg totals are the only library-suite figure this round has. + +## 1. Gate wall-clock (what a contributor waits on) + +| Gate | p50 | PR p50 | max | runs | +|---|---|---|---|---| +| autogalaxy_workspace_test Smoke Tests | 11.9 m | 11.8 m | 3.7 h (a stall, see §5) | 36 | +| autolens_workspace_test Smoke Tests | 9.2 m | 8.4 m | 19.5 m | 34 | +| autolens_workspace Smoke Tests | 7.8 m | 7.9 m | 14.6 m | 16 | +| HowToLens Smoke Tests | 6.3 m | 6.9 m | 8.6 m | 14 | +| autocti_workspace Smoke Tests | 5.3 m | 4.9 m | 9.5 m | 7 | +| PyAutoFit Tests | 4.6 m | 4.5 m | 7.4 m | 26 | +| PyAutoCTI Tests | 4.2 m | 4.4 m | 9.5 m | 43 | +| HowToGalaxy Smoke Tests | 4.1 m | 5.1 m | 5.4 m | 17 | +| autogalaxy_workspace Smoke Tests | 3.9 m | 3.7 m | 12.2 m | 17 | +| PyAutoLens Tests | 3.4 m | 3.1 m | 5.1 m | 27 | +| PyAutoGalaxy Tests | 3.4 m | 3.4 m | 8.2 m | 26 | +| autocti_workspace_test Smoke Tests | 3.2 m | 3.6 m | 9.5 m | 50 | +| PyAutoArray Tests | 2.7 m | 2.7 m | 4.2 m | 49 | +| autofit_workspace Smoke Tests | 2.5 m | 2.4 m | 6.6 m | 25 | +| autofit_workspace_test Smoke Tests | 2.0 m | 1.9 m | 9.3 m | 49 | +| HowToFit Smoke Tests | 1.8 m | 1.9 m | 4.7 m | 17 | +| PyAutoNerves Tests | 0.8 m | 0.8 m | 5.9 m | 45 | +| Navigator Check (6 repos) | 15–18 s (autocti 88 s) | 14–18 s | ≤ 4 m | — | +| PyAutoHeart Workspace Smoke (weekly) | 38 m | — | 38 m | 1 | +| PyAutoBrain Nightly Release | 83 m | — | 85 m | 2 | + +Overhead beside the scripts: the two `_test` flagships spend **~2–3 minutes +per leg on checkout + install** before the first script runs +(autogalaxy_test: 714 s gate vs 537 s of scripts; autolens_test: 552 s vs 435 s). +That fixed cost is the same for every PR and is the ceiling phase 7's caches +work under. + +## 2. The `_test` workspaces — the epic's target + +Per-script seconds, Python 3.12 leg (3.13 is within a few percent; §4). + +**autogalaxy_workspace_test** — 39 scripts, 537 s total, median 12.7 s. +Bands: 16 scripts < 10 s, 14 in 10–20 s, 9 in 20–40 s, none ≥ 40 s. + +| s | script | class | +|---|---|---| +| 35.5 | multi_dataset/jax_likelihood/mge_group.py | compile (JAX full-dataset, MGE basis) | +| 31.7 | interferometer/jax_likelihood/delaunay_mge.py | compile | +| 30.1 | imaging/visualization/visualization.py | **execution — plot output** | +| 25.0 | multi_dataset/jax_likelihood/delaunay_mge.py | compile | +| 23.1 | imaging/jax_likelihood/mge_group.py | compile | +| 22.6 | interferometer/jax_likelihood/mge_group.py | compile | +| 21.9 | imaging/jax_likelihood/rectangular_mge.py | compile | +| 21.7 | imaging/jax_likelihood/delaunay.py | compile | + +Eight of the nine scripts above 20 s are `jax_likelihood` — the `ENV: jax +full_datasets` class the ledger already named (compile ~12–18 s + full-res +vmap + ~5–7 s import). `visualization.py` is the one execution-dominated +outlier. The 20–40 s band alone is 232 s of the 537 s. + +**autolens_workspace_test** — 27 scripts, 435 s total, median 12.0 s. +Bands: 10 < 10 s, 9 in 10–20 s, 6 in 20–40 s, 2 ≥ 40 s. + +| s | script | class | +|---|---|---| +| 45.0 | multi_dataset/jax_likelihood/shared_preloads.py | compile (multi-dataset, Eigen-pool coverage class) | +| 42.5 | misc/jax_assertions/delaunay_nn_caps.py | compile + assertion sweep | +| 33.0 | imaging/jax_likelihood/rectangular.py | compile | +| 32.8 | misc/jax_assertions/delaunay_nn.py | compile + assertion sweep | +| 27.8 | interferometer/jax_likelihood/rectangular.py | compile | +| 27.0 | point_source/jax_likelihood/point.py | compile | +| 22.7 | interferometer/datacube/shared_preloads.py | compile | +| 20.4 | imaging/jax_likelihood/mge.py | compile | + +Every script above 20 s is JAX-compiled. The eight above are 251 s of the +435 s; the `multi_dataset/jax_likelihood/*` scripts (the Eigen-pool bug class) +must keep their coverage through phase 6, per the epic's standing assumptions. + +**autofit_workspace_test** — 14 scripts, 47 s; one outlier +(`graphical/analytic_gaussian_collapse.py` 17.3 s), the rest ≤ 4.5 s. +**autocti_workspace_test** — 3 scripts, 17 s. Neither is a target. + +**What the rebuild waves should expect.** In both flagships the time is in +~15 compile-dominated scripts, not spread thin: shrinking datasets (pixel scale, +over-sampling, MGE basis size — phase 5/6 levers) shrinks both the compile +graph and the execution, and the persistent JAX cache (phase 7) removes the +compile share on cache-hit runs before the content changes are even measured. +That is why the ledger's review puts 7 before 5/6: the waves should target what +remains once compile is cached. + +## 3. User-facing workspaces and HowTos — the import floor + +| Repo | scripts | total | median | > 10 s | +|---|---|---|---|---| +| autolens_workspace | 39 | 303 s | 7.6 s | 8 | +| HowToLens | 50 | 254 s | 4.9 s | 3 | +| HowToGalaxy | 32 | 135 s | 4.1 s | 1 | +| autogalaxy_workspace | 16 | 104 s | 7.7 s | 2 | +| autocti_workspace | 3 | 94 s | 17.0 s | 3 | +| autofit_workspace | 10 | 25 s | 1.7 s | 0 | +| HowToFit | 14 | 27 s | 0.9 s | 1 | + +The user-facing surface is **floor-dominated**: HowToLens runs 47 of 50 +scripts under 10 s at a ~5 s median, so ~230 of its 254 s is the per-process +import + config floor, not science. The floor itself scales with the stack — +HowToFit's median is 0.9 s (autofit alone), HowToGalaxy's 4.1 s, HowToLens's +4.9 s, autolens_workspace's 7.6 s (autolens import + `PYAUTO_SMALL_DATASETS` +work). The few genuine bottlenecks: + +| s | repo | script | +|---|---|---| +| 61.0 | autocti_workspace | imaging_ci/modeling/start_here.py — the slowest script in the organism | +| 18.7 | autolens_workspace | interferometer/features/pixelization/delaunay.py | +| 18.6 | autolens_workspace | guides/mappings.py (new, image-source-mappings p3) | +| 15.7 | HowToLens | chapter_3_pixelizations/tutorial_6_borders.py | +| 13.4 | autolens_workspace | imaging/features/pixelization/delaunay.py | +| 13.0 | HowToLens | chapter_2_lens_modeling/tutorial_5_linear_profiles.py | +| 13.0 | autolens_workspace | multi_galaxy/features/advanced/shapelets/modeling.py | +| 12.6 | autogalaxy_workspace | imaging/start_here.py | + +Implication for phase 8: per-script fixes buy little here except the autocti +outlier; the lever is the shared floor (autolens import time, which the +phase-3 import leg now measures on every library CI run, and whatever the +`PYAUTO_SKIP_*` profile still lets through). + +## 4. Python 3.13 vs 3.12 + +Leg totals agree within ~5 % for the `_test` flagships (autogalaxy_test 537 vs +541 s; autolens_test 435 vs 434 s). The user workspaces run **faster on 3.13** +(autolens_workspace 303 → 228 s, HowToLens 254 → 219 s, autogalaxy_workspace +104 → 84 s) — an import/interpreter floor effect, consistent with §3; +autocti_workspace is the exception (94 → 132 s). Comparability key stays +runner × Python leg, as the design doc says. + +## 5. Hang events still on the board + +Six `suspect_cancelled` events, all historical (2026-07-27 → 2026-08-29), five +of them autogalaxy_workspace_test runs killed at ~6 h (21,600 s) — the +jax-compile-stall arc's runs before the kill timer existed — plus one 397 s +Workspace Smoke cancel on 2026-08-29. None is from the current window's +runs; they age out of the 50-run window on their own. + +## 6. Unit tests and imports — pending the first library CI run + +`lib-tests.yml` emits `unit-timings-` from the next push or PR on any +library; the daily run then records `timings/unit/.jsonl` and the +Unit-test timing / Import timing rows come alive (imports `building` for three +runs). Until then the only library figures are the gate medians in §1 +(PyAutoFit 4.6 m, PyAutoCTI 4.2 m, PyAutoLens 3.4 m, PyAutoGalaxy 3.4 m, +PyAutoArray 2.7 m, PyAutoNerves 0.8 m — each including a source install of its +dependency chain). Phase 9 reads the per-test and per-import rows once they +exist; this section is the placeholder it fills. + +## What this digest feeds + +- **Phase 7 (CI caches)** — the compile share of the ~15 scripts in §2 is the + expected win; measure cache-hit vs cache-miss legs against these totals. +- **Phase 5 (autogalaxy_workspace_test rebuild)** — the nine 20–40 s scripts + in §2 are the target list; `visualization.py` is the one execution-dominated + case and needs a different lever. +- **Phase 6 (autolens_workspace_test rebuild)** — the eight scripts ≥ 20 s; + keep `multi_dataset/jax_likelihood/*` reproducing the Eigen-pool class. +- **Phase 8 (user workspaces / HowTos)** — the shared import floor, plus the + autocti `imaging_ci/modeling/start_here.py` outlier. +- **Phase 9 (unit-test / import census)** — §6, once the unit record exists.