diff --git a/docs/internals.md b/docs/internals.md index c4aac43b..80fea312 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -60,7 +60,13 @@ unobserved on the cloud board. Timing cards are a pure presentation layer in `heart/timing_display.py`. They expose seconds, comparison coverage and source separately; missing imports -and baseline-building observations never imply a passing comparison. Suite +and baseline-building observations never imply a passing comparison. Unit-test +comparisons select the latest distinct run strictly before each current +repo/Python leg's observation time, within the current epoch. The current run, +future runs and append order never substitute for prior evidence. Legacy +records with only a date establish prior days; unknown chronology and tests +absent from the selected prior run retain missing comparisons. Cache-state +compatibility still guards every comparison. Suite legs stay separate (parallel wall-clocks are never summed); the three slowest measured tests appear first, with remaining tests and legs under disclosures. CI charts use dated daily medians with gaps for missing observations and an diff --git a/heart/checks/unit_timings.py b/heart/checks/unit_timings.py index d717246a..4cdc1b79 100644 --- a/heart/checks/unit_timings.py +++ b/heart/checks/unit_timings.py @@ -989,9 +989,16 @@ def main(argv: list[str] | None = None) -> int: # 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 "") + sidecars = read_sidecars(per_repo) + current_runs = { + (str(side.get("name") or ""), str(leg.get("python") or "")): leg + for side in sidecars if isinstance(side, dict) + for leg in (side.get("legs") or []) if isinstance(leg, dict) + } rollup = aggregate( - read_sidecars(per_repo), ts, thresholds, - record_prev_rows=_timings.previous_unit_rows(unit_dir, since=since), + sidecars, ts, thresholds, + record_prev_rows=_timings.previous_unit_rows( + unit_dir, since=since, current_runs=current_runs), record_import_history=_timings.import_history( unit_dir, int(thresholds.get("import_window", 7) or 7), since=since, diff --git a/heart/timings.py b/heart/timings.py index 413bee21..d12a7453 100644 --- a/heart/timings.py +++ b/heart/timings.py @@ -740,6 +740,7 @@ def append_unit(path: Path | str, lines: list[dict[str, Any]]) -> int: def previous_unit_rows( unit_dir: Path | str = UNIT_DIR, since: str = "", + current_runs: dict[tuple[str, str], dict[str, Any]] | None = None, ) -> dict[tuple[str, str, str], dict[str, Any]]: """``{(repo, python, nodeid): prev_row}`` — the last recorded observation. @@ -751,6 +752,13 @@ def previous_unit_rows( combined and naming it after half of what it means would mislead every reader of the record. + With ``current_runs`` keyed by (repo, python), select the newest distinct + observation strictly before that leg's observation time, never its own run + or future evidence. Date-only legacy rows establish prior days only; + unknown chronology yields no comparison. Selection precedes test lookup, + so a test absent from the selected run retains an unknown comparison. + Without current observations, preserve the legacy behavior below. + The *latest* line per python leg wins, and "latest" is file order: the file is append-only, so the last line for a leg is the most recently recorded one. Only the recorded (slowest) tests are in there to begin with — a test @@ -761,6 +769,20 @@ def previous_unit_rows( chosen, for the reason ``previous_script_rows`` gives: a pre-boundary line measured a different world and must not stand in as the latest. """ + def observed(record: dict[str, Any]) -> tuple[datetime.datetime, datetime.datetime] | None: + at = str(record.get("at") or "") + try: + if at: + stamp = datetime.datetime.fromisoformat(at.replace("Z", "+00:00")) + if stamp.tzinfo is None: + return None + return stamp, stamp + day = datetime.date.fromisoformat(str(record.get("date") or "")) + start = datetime.datetime.combine(day, datetime.time(), datetime.timezone.utc) + return start, start + datetime.timedelta(days=1) + except (ValueError, TypeError): + return None + out: dict[tuple[str, str, str], dict[str, Any]] = {} root = Path(unit_dir) if not root.is_dir(): @@ -772,7 +794,20 @@ def previous_unit_rows( for record in records: if not _within_epoch(record, since): continue - latest[str(record.get("python") or "")] = record + python = str(record.get("python") or "") + if current_runs is not None: + current = current_runs.get((repo, python)) + if not current or not current.get("run_id") or not record.get("run_id"): + continue + if str(record["run_id"]) == str(current["run_id"]): + continue + before, now = observed(record), observed(current) + if before is None or now is None or before[1] >= now[0]: + continue + previous = latest.get(python) + if previous is not None and observed(previous)[1] >= before[1]: + continue + latest[python] = record for python, record in latest.items(): slowest = record.get("slowest") if not isinstance(slowest, dict): diff --git a/tests/test_timings.py b/tests/test_timings.py index e1de056d..512e828f 100644 --- a/tests/test_timings.py +++ b/tests/test_timings.py @@ -452,6 +452,42 @@ def test_previous_unit_rows_takes_the_latest_line_per_leg_and_drives_drift(tmp_p "ok", None, None) +def test_previous_unit_rows_selects_distinct_prior_run_by_time(tmp_path): + path = timings.unit_file("RepoA", tmp_path) + for run_id, at in ((8, "2026-09-04T11:00:00Z"), + (9, "2026-09-04T12:00:00Z"), + (10, "2026-09-04T13:00:00Z"), + (7, "2026-09-04T10:00:00Z")): + lines = timings.unit_lines_from_rollup(_unit_rollup(run_id=run_id), TODAY)["RepoA"] + lines[0]["at"] = at + timings.append_unit(path, lines) + current = {("RepoA", "3.12"): {"run_id": 9, "at": "2026-09-04T12:00:00Z"}} + rows = timings.previous_unit_rows(tmp_path / "unit", current_runs=current) + assert rows[("RepoA", "3.12", NODEID)]["run_id"] == 8 + assert timings.previous_unit_rows(tmp_path / "unit", since="2026-09-06", + current_runs=current) == {} + + +def test_previous_unit_rows_legacy_identity_and_missing_current(tmp_path): + path = timings.unit_file("RepoA", tmp_path) + for run_id in (8, 9, 10, 7): + lines = timings.unit_lines_from_rollup(_unit_rollup(run_id=run_id), TODAY)["RepoA"] + lines[0]["at"] = "" + timings.append_unit(path, lines) + current = {("RepoA", "3.12"): {"run_id": 9, "at": ""}} + assert timings.previous_unit_rows(tmp_path / "unit", current_runs=current) == {} + assert timings.previous_unit_rows(tmp_path / "unit", current_runs={}) == {} + # Numeric run IDs cannot establish chronology; even an apparently newer + # ID is excluded without an observation time. Date-only prior-day rows + # remain useful, but same-day evidence is ambiguous. + current[("RepoA", "3.12")]["at"] = "2026-09-06T12:00:00Z" + assert timings.previous_unit_rows(tmp_path / "unit", current_runs=current)[ + ("RepoA", "3.12", NODEID)]["run_id"] == 8 + current[("RepoA", "3.12")]["at"] = "2026-09-05T12:00:00Z" + assert timings.previous_unit_rows(tmp_path / "unit", current_runs=current) == {} + + + def test_import_history_is_oldest_first_window_capped_and_skips_nulls(tmp_path): unit_dir = tmp_path / "unit" path = timings.unit_file("RepoA", tmp_path) diff --git a/tests/test_unit_timings.py b/tests/test_unit_timings.py index 39722c39..ca1b7bd3 100644 --- a/tests/test_unit_timings.py +++ b/tests/test_unit_timings.py @@ -637,7 +637,7 @@ def test_main_writes_the_sidecar_then_the_rollup_and_both_legacy_files( per_repo = tmp_path / "per-repo" per_repo.mkdir() listing = tmp_path / "listing.json" - listing.write_text(json.dumps({"artifacts": [_artifact()]})) + listing.write_text(json.dumps({"artifacts": [_artifact(created="2026-09-06T10:00:00Z")]})) downloads = tmp_path / "downloads" _extracted(downloads, sub="11", junit=_junit(_case(time="6.0"))) @@ -661,6 +661,15 @@ def test_main_writes_the_sidecar_then_the_rollup_and_both_legacy_files( "slowest": {NODEID: 2.0}, }) + "\n") + # The daily append has already recorded the current run; it must not + # suppress the comparison to the genuinely prior observation. + with (unit_dir / f"{REPO}.jsonl").open("a") as record_file: + record_file.write(json.dumps({ + "date": "2026-09-06", "at": side["legs"][0]["at"], + "python": "3.12", "run_id": side["legs"][0]["run_id"], + "slowest": {NODEID: 6.0}, + }) + "\n") + legacy = tmp_path / "legacy" roll_path = tmp_path / "unit_timings.json" assert ut.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", @@ -728,6 +737,7 @@ def test_main_aggregate_compares_only_inside_the_current_epoch(tmp_path, per_repo.mkdir() side = _sidecar(tmp_path, junit=_junit(_case(time="6.0")), imports=_import_json(seconds=6.0)) + side["legs"][0]["at"] = "2026-09-06T10:00:00Z" (per_repo / f"{REPO}.unit_timings.json").write_text(json.dumps(side)) record = tmp_path / "timings"