Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions .github/workflows/heart-health.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ name: Heart Health
# * step summary — fmt="md" into $GITHUB_STEP_SUMMARY (zero hosting)
# * README — a shields verdict badge + an auto-updated
# <!-- heart:begin -->…<!-- heart:end --> md block
# and commits, beside that block, the day's lines of the PERMANENT timing
# record (timings/gates.jsonl + timings/scripts/<repo>.jsonl). This job is
# the record's single writer; the two timing checks read it back as the
# first source for their baselines, with the published board.json only as
# the fallback, so a Pages gap no longer loses history.
# 2. opens-or-updates a single "[heart-health]" tracking ISSUE when anything
# is red/degraded and closes it when clean — the ALERTING channel (kept).
#
Expand Down Expand Up @@ -114,6 +119,26 @@ jobs:
bash heart/checks/smoke_timings.sh
exit 0

- name: Append today's observations to the timing record
run: |
# ORDERING: after the checks, before the render. The checks' aggregate
# passes have already READ the record for their baselines, and neither
# can be fooled by today's own line — ci_timing's `history_baseline`
# excludes today's date, and smoke_timings compares by run id and
# refuses to compare a run against itself. So appending here is safe,
# and it lets the render census a record that already includes today.
#
# SINGLE WRITER: only this workflow appends. The record is committed
# into this repo (below, beside the README block), and two writers on
# an append-only file in git is a merge conflict waiting for a human —
# a dev-box tick never appends.
#
# A missing rollup means "nothing to append from that slice", never an
# error: this exits 0 whatever the checks managed to produce.
PYTHONPATH="$PWD" python -m heart.timings append \
--ci-timing "$HEART_STATE_DIR/ci_timing.json" \
--smoke-timings "$HEART_STATE_DIR/smoke_timings.json"

- name: Aggregate snapshot + compute readiness verdict
run: |
# Fold the per-repo sidecars into state.json, then compute the
Expand Down Expand Up @@ -150,7 +175,7 @@ jobs:
echo "_Published board: https://pyautolabs.github.io/PyAutoHeart/_"
} >> "$GITHUB_STEP_SUMMARY"

- name: Update README badge + block (own repo only, main only)
- name: Commit the README block + today's timing record (own repo only, main only)
if: github.ref == 'refs/heads/main'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand All @@ -175,14 +200,18 @@ jobs:
text = "\n".join(lines)
readme.write_text(text)
PY
if ! git diff --quiet README.md; then
# `git status --porcelain` rather than `git diff --quiet`, because
# the record's first line for a repo creates an UNTRACKED file, which
# a diff of the working tree cannot see. One commit a day carries both
# the README block and the day's appended lines.
if [ -n "$(git status --porcelain README.md timings/)" ]; then
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add README.md
git commit -m "docs(heart): auto-update health dashboard block [skip ci]"
git add README.md timings/
git commit -m "docs(heart): daily board block + timing record [skip ci]"
git push
else
echo "README health block unchanged — nothing to commit."
echo "README health block and timing record unchanged — nothing to commit."
fi

- name: Upload Pages artifact
Expand Down
38 changes: 35 additions & 3 deletions heart/checks/ci_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@
* **A failed fetch is not a quiet repo.** ``--fetch-error`` records the reason
and writes empty ``workflows``/``events``; "we could not ask" must never
render as "all quiet".
* **The history comes from the committed record first.** ``timings/gates.jsonl``
(see ``heart/timings.py``) is durable; the previously published ``board.json``
is the same artifact this render produces, so a Pages gap loses it. The board
stays as the fallback — first run, fresh clone, no record yet — and the
rolled-forward ``performance.history`` is written either way.

Per-repo sidecar schema (``<name>.ci_timing.json``)::

Expand Down Expand Up @@ -479,10 +484,27 @@ def aggregate(
today: str,
ts: str,
thresholds: dict[str, float] | None = None,
record_history: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Fold the per-repo sidecars + the previous board into the global rollup."""
"""Fold the per-repo sidecars + the history into the global rollup.

``record_history`` is the COMMITTED record (``timings/gates.jsonl``, via
``heart.timings.gates_history``) and is preferred whenever it is non-empty:
it is durable, whereas the previously published board is the same artifact
the render produces and a Pages gap loses it. The board stays as the
fallback for the very first run, a fresh clone, or a record that is not
there yet.

Whichever history was used is also what ``roll_history`` rolls forward, so
``board.json``'s ``performance.history`` keeps its shape either way — it
remains the fallback cache and the Brain board's sparkline input.
"""
thr = dict(thresholds or DEFAULT_CI_TIMING_THRESHOLDS)
history_in = prev_history_of(prev_board)
history_in = (
[e for e in record_history if isinstance(e, dict)]
if record_history
else prev_history_of(prev_board)
)

gates: list[dict[str, Any]] = []
events: list[dict[str, Any]] = []
Expand Down Expand Up @@ -631,6 +653,10 @@ def main(argv: list[str] | None = None) -> int:
help="ISO date for the history entry (default: today, UTC)")
ap.add_argument("--per-repo-dir", default="",
help="where the sidecars live (default: $HEART_STATE_DIR/per-repo)")
ap.add_argument("--record-dir", default="",
help="the committed timing record (default: HEART_HOME/timings); "
"its gates.jsonl is the preferred history source, the "
"previous board.json only the fallback")
ap.add_argument("--fetch-error", default="",
help="reason the runs fetch failed; recorded instead of a bogus quiet repo")
ns = ap.parse_args(argv)
Expand All @@ -640,12 +666,18 @@ def main(argv: list[str] | None = None) -> int:
if ns.aggregate:
sys.path.insert(0, str(HEART_HOME))
from heart import state as _state
from heart import timings as _timings

per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR
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
rollup = aggregate(
read_sidecars(per_repo), read_prev_board(ns.prev_board), today, ts,
load_thresholds(),
thr,
record_history=_timings.gates_history(
record_dir / "gates.jsonl", int(thr.get("history_cap", 30))
),
)
_write(Path(ns.out), rollup)
print(summary_line(rollup))
Expand Down
4 changes: 4 additions & 0 deletions heart/checks/ci_timing.sh
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,12 @@ check_ci_timing_all() {

local prev
prev="$(_ci_timing_prev_board)"
# The committed record (timings/gates.jsonl) is the source of truth for the
# history; the previously published board is only the fallback for when it
# is not there yet (first run, fresh clone, a Pages-only consumer).
PYTHONPATH="$HEART_HOME" python3 -m heart.checks.ci_timing \
--aggregate --prev-board "$prev" --ts "$(date -Iseconds)" \
--record-dir "$HEART_HOME/timings" \
--out "$HEART_STATE_DIR/ci_timing.json"
[[ -n "$prev" ]] && rm -f "$prev"

Expand Down
34 changes: 30 additions & 4 deletions heart/checks/smoke_timings.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@
self-carried through the published board, so a re-render on the same day sees
the same run's rows. Every row carries its ``run_id``; a previous row from
the SAME run yields ``ok`` with no ratio rather than a reassuring 1.0×.
* **The previous observation comes from the committed record first.**
``timings/scripts/<repo>.jsonl`` (see ``heart/timings.py``) is durable and
keyed by ``(python, run_id)``; the published board is the same artifact this
render produces, so a Pages gap loses it. The board stays as the fallback,
and the ``performance.scripts.rows`` block is written either way.
* **Drift is advisory.** Rows are ``ok`` or ``warn``, never ``fail``; only
TIMEOUT entries are hard rows. The readiness verdict is untouched — this is
a dashboard leg, not a gate.
Expand Down Expand Up @@ -80,8 +85,9 @@
Global rollup schema (``smoke_timings.json``)::

{"ts",
"repos": [{repo, python, run_id, run_url, head_branch, at, entries,
timed, total_s, error, slowest: [...]}],
"repos": [{repo, python, run_id, run_url, head_branch, head_sha,
env_profile, at, entries, timed, total_s, error,
slowest: [...]}],
"rows": [{repo, python, entry, kind, status, seconds, cap_s, exit_code,
run_id, run_url, prev_s, prev_run_id, ratio, delta_s, state,
prompt}],
Expand Down Expand Up @@ -513,10 +519,19 @@ def aggregate(
prev_board: Any,
ts: str,
thresholds: dict[str, float] | None = None,
record_prev_rows: dict[tuple[str, str, str], dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Fold the per-repo sidecars + the previous board into the global rollup."""
"""Fold the per-repo sidecars + the previous observation into the rollup.

``record_prev_rows`` is the COMMITTED record (``timings/scripts/``, via
``heart.timings.previous_script_rows``) in the same
``(repo, python, entry) -> row`` shape ``prev_rows_of`` returns, and is
preferred whenever it is non-empty. The published board stays as the
fallback: it is the same artifact this render produces, so a Pages gap
costs the comparison, while the record does not.
"""
thr = dict(thresholds or DEFAULT_SMOKE_TIMINGS_THRESHOLDS)
prev_rows = prev_rows_of(prev_board)
prev_rows = dict(record_prev_rows) if record_prev_rows else prev_rows_of(prev_board)
top_n = int(thr.get("top_n", 5) or 5)

repos: list[dict[str, Any]] = []
Expand Down Expand Up @@ -605,6 +620,10 @@ def _name_of(side: Any) -> str:
"run_id": run_id,
"run_url": run_url,
"head_branch": str(leg.get("head_branch") or ""),
# Provenance the committed record stores per observation: which
# commit was measured, and under which environment profile.
"head_sha": str(leg.get("head_sha") or ""),
"env_profile": str(leg.get("env_profile") or ""),
"at": at,
"entries": len(entries),
"timed": timed if timed is not None else len(leg_rows),
Expand Down Expand Up @@ -757,6 +776,10 @@ def main(argv: list[str] | None = None) -> int:
"missing/unreadable => no comparison, never an error")
ap.add_argument("--per-repo-dir", default="",
help="where the sidecars live (default: $HEART_STATE_DIR/per-repo)")
ap.add_argument("--record-dir", default="",
help="the committed timing record (default: HEART_HOME/timings); "
"its scripts/ files are the preferred previous "
"observation, the previous board.json only the fallback")
ap.add_argument("--fetch-error", default="",
help="reason the artifacts listing fetch failed; recorded "
"instead of a bogus quiet repo")
Expand All @@ -780,11 +803,14 @@ def main(argv: list[str] | None = None) -> int:
if ns.aggregate:
sys.path.insert(0, str(HEART_HOME))
from heart import state as _state
from heart import timings as _timings

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
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"),
)
_write(Path(ns.out), rollup)
print(summary_line(rollup))
Expand Down
4 changes: 4 additions & 0 deletions heart/checks/smoke_timings.sh
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,12 @@ check_smoke_timings_all() {

local prev
prev="$(_smoke_timings_prev_board)"
# The committed record (timings/scripts/<repo>.jsonl) is the source of truth
# for the previous observation; the previously published board is only the
# fallback for when it is not there yet.
PYTHONPATH="$HEART_HOME" python3 -m heart.checks.smoke_timings \
--aggregate --prev-board "$prev" --ts "$(date -Iseconds)" \
--record-dir "$HEART_HOME/timings" \
--out "$HEART_STATE_DIR/smoke_timings.json"
[[ -n "$prev" ]] && rm -f "$prev"

Expand Down
44 changes: 40 additions & 4 deletions heart/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,8 +892,27 @@ def build_board(
)


def _record_lines(record: Any) -> tuple[str, str]:
"""The two `record:` detail lines from the committed record's census.

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".
"""
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"))
return (
f"record: timings/gates.jsonl — {days} days",
f"record: timings/scripts/ — {obs} observations across {repos} repos",
)


def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict],
errors: list, history: list[dict]) -> Section:
errors: list, history: list[dict],
record: Any = None) -> Section:
"""The CI wall-clock row: how long the gates a change must pass now take."""
timed = [g for g in gates if _as_int(g.get("runs_counted"))]
warned = [g for g in gates if g.get("state") == "warn"]
Expand Down Expand Up @@ -927,6 +946,11 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict],
f"max {_dur(g.get('max_s'))} ({_as_int(g.get('runs_counted'))} runs)")
spark = _gate_spark(history, f"{g.get('repo')}/{g.get('workflow')}")
details.append(f"{line} {spark}" if spark else line)
# How much durable history stands behind those sparklines. Absent census
# (an older snapshot) adds no line at all.
gates_line = _record_lines(record)[0]
if gates_line:
details.append(gates_line)

links = [
{"label": f"{e.get('repo')} {e.get('kind')}", "url": str(e.get("run_url")),
Expand All @@ -948,7 +972,7 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict],

def _smoke_timings_section(st: dict, repos: list[dict], rows: list[dict],
slowed: list[dict], events: list[dict],
errors: list) -> Section:
errors: list, record: Any = None) -> Section:
"""The per-script row: which script inside the gate is spending the time."""
# A TIMEOUT is a killed script — the only hard row here. A slowed script,
# like a slowed gate, is advisory by construction: this measurement rides on
Expand Down Expand Up @@ -982,6 +1006,11 @@ def _smoke_timings_section(st: dict, repos: list[dict], rows: list[dict],
tail = f"({_as_int(r.get('timed'))} scripts, {_dur(r.get('total_s'))} total)"
prefix = f"{r.get('repo')} py{r.get('python') or '?'}:"
details.append(f"{prefix} {head} {tail}" if head else f"{prefix} {tail}")
# Same as the gate row: how much durable history stands behind the
# run-to-run comparisons. Absent census adds no line at all.
scripts_line = _record_lines(record)[1]
if scripts_line:
details.append(scripts_line)

links = [
{"label": f"{e.get('repo')} {e.get('entry')} TIMEOUT",
Expand Down Expand Up @@ -1051,6 +1080,12 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non
nr = nr if isinstance(nr, dict) else {}
st = snapshot.get("smoke_timings")
st = st if isinstance(st, dict) else {}
# The census of the committed timing record. It decorates the two timing
# rows with one detail line each and touches NOTHING else — in particular
# the `performance` block below is unchanged by it, so the Brain board and
# the next render's fallback read exactly what they always read.
record = snapshot.get("timings_record")
record = record if isinstance(record, dict) else {}
if not ct and not nr and not st:
return None

Expand All @@ -1069,10 +1104,11 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non
st_errors = list(st.get("errors") or [])

if ct:
sections.append(_ci_timing_section(ct, gates, events, errors, history))
sections.append(_ci_timing_section(ct, gates, events, errors, history,
record))
if st:
sections.append(_smoke_timings_section(st, st_repos, st_rows, st_slowed,
st_events, st_errors))
st_events, st_errors, record))
if nr:
sections.append(_no_run_section(totals, rows, repo_rows))

Expand Down
5 changes: 5 additions & 0 deletions heart/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ def aggregate() -> dict[str, Any]:
"test_run": _read_json_or_default(HEART_STATE_DIR / "test_run.json", {}),
"ci_timing": _read_json_or_default(HEART_STATE_DIR / "ci_timing.json", {}),
"smoke_timings": _read_json_or_default(HEART_STATE_DIR / "smoke_timings.json", {}),
# The census of the COMMITTED timing record (timings/), written by
# `heart.timings append` in the daily cloud job. A snapshot taken
# before the record existed simply has no key, and the board renders
# exactly as it did — the census adds a detail line, never a row.
"timings_record": _read_json_or_default(HEART_STATE_DIR / "timings_record.json", {}),
"no_run_census": _read_json_or_default(HEART_STATE_DIR / "no_run_census.json", {}),
"workspace_testmode_timing": _read_json_or_default(HEART_STATE_DIR / "workspace_testmode_timing.json", {}),
"version_skew": _read_json_or_default(HEART_STATE_DIR / "version_skew.json", {}),
Expand Down
Loading
Loading