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
73 changes: 73 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ on:
# builds and its config-invariant objects (Verilator runtime, host driver) into
# cache hits.

# A new push supersedes the run of the previous one on the same pull request or
# branch. The default branch keys each run by its commit, so none is cancelled.
concurrency:
group: ci-${{ github.event_name }}-${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.sha || github.ref }}
cancel-in-progress: true

jobs:
# ---------------------------------------------------------------------------
# plan — read the test cases and emit the (category x driver x xlen) matrix
Expand All @@ -44,6 +50,7 @@ jobs:
run: ${{ steps.q.outputs.run }}
profile: ${{ steps.q.outputs.profile }}
toolchain: ${{ steps.vers.outputs.toolchain }}
runtimes: ${{ steps.runtimes.outputs.cache-matched-key }}
steps:
- uses: actions/checkout@v4
with:
Expand Down Expand Up @@ -92,6 +99,17 @@ jobs:
key: ${{ runner.os }}-toolchain-${{ steps.vers.outputs.toolchain }}-lite
restore-keys: ${{ runner.os }}-toolchain-${{ steps.vers.outputs.toolchain }}-
lookup-only: true
# The per-case times the shards are balanced on, as the newest master
# run recorded them (the runtimes job below); the committed table until
# one has. Every shard restores the same entry, so plan and pytest --shard
# split a cell identically.
- name: Restore the recorded runtimes
id: runtimes
uses: actions/cache/restore@v4
with:
path: ci/runtimes.json
key: runtimes-${{ github.run_id }}
restore-keys: runtimes-
- name: Plan matrix
id: q
env:
Expand Down Expand Up @@ -338,6 +356,16 @@ jobs:
with:
name: build-${{ matrix.xlen }}
path: build${{ matrix.xlen }}
- name: Restore the runtimes the plan used
if: matrix.shards && needs.plan.outputs.runtimes
uses: actions/cache/restore@v4
with:
path: ci/runtimes.json
key: ${{ needs.plan.outputs.runtimes }}
fail-on-cache-miss: true
- name: Use them in the build tree
if: matrix.shards && needs.plan.outputs.runtimes
run: cp ci/runtimes.json build${{ matrix.xlen }}/ci/runtimes.json
- name: Per-category deps
run: |
case "${{ matrix.category }}" in
Expand Down Expand Up @@ -431,6 +459,20 @@ jobs:
with:
name: junit-${{ env.CELL }}
path: junit-*.xml
# What the gate cases measured: every verdict in the job summary, and the
# values in the baseline format (gate_results/perf), which
# `ci/perf_baseline.py merge` folds into ci/baselines/perf.
- name: Summarize the gate verdicts
if: always()
run: |
f=build${{ matrix.xlen }}/gate_results/summary.md
if [ -f "$f" ]; then cat "$f" >> "$GITHUB_STEP_SUMMARY"; fi
- uses: actions/upload-artifact@v4
if: always()
with:
name: gate-results-${{ env.CELL }}
path: build${{ matrix.xlen }}/gate_results
if-no-files-found: ignore
# The gate's verdicts in the job summary, and per build the evidence a
# verdict names: the diff against the merge base, the area by unit, the
# calibrated risk, the deepest paths.
Expand Down Expand Up @@ -486,6 +528,37 @@ jobs:
path: .beacon_ref
key: beacon-ref-${{ steps.mb.outputs.base }}-${{ steps.mb.outputs.flow }}-${{ steps.refsave.outputs.id }}

# ---------------------------------------------------------------------------
# runtimes — a default-branch push records the case times its cells measured,
# for the next plan to balance shards on. Cases the run did not report keep
# their time.
# ---------------------------------------------------------------------------
runtimes:
needs: [tests]
# A push measures the smoke cells and the weekly full run the gate cells;
# each run's times are merged into the newest recorded table.
if: always() && (github.event_name == 'push' || github.event_name == 'schedule') && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && (needs.tests.result == 'success' || needs.tests.result == 'failure')
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/cache/restore@v4
with:
path: ci/runtimes.json
key: runtimes-${{ github.run_id }}
restore-keys: runtimes-
- uses: actions/download-artifact@v4
with:
pattern: junit-*
path: junit
merge-multiple: true
- run: pip install --quiet pyyaml
- name: Record
run: python3 ci/record_runtimes.py --junit-dir junit --run "$GITHUB_RUN_ID" --sha "$GITHUB_SHA"
- uses: actions/cache/save@v4
with:
path: ci/runtimes.json
key: runtimes-${{ github.run_id }}

complete:
runs-on: ubuntu-22.04
needs: [plan, boundaries, setup, build, tests]
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ See [docs/testing.md](docs/testing.md) and [docs/debugging.md](docs/debugging.md
- **Keep smoke/regression runs lean.** Don't enable debug or perf collection unless the run is explicitly for debug or measurement.
- **xrt is the canonical path for the integration layer (CP, AFU, host memory); unit RTL breadth runs on rtlsim.**
- **`ci/regression.sh` is the canonical source of tested configurations.** Use it to discover supported parameter combinations before inventing ad hoc ones.
- **CI tests ensure correctness; gates ensure quality.** A failed test is a bug; a red gate (`perf_gate`, `model_parity`, `logic_gate`, `fpga_gate`, `asic_gate`) is a measured change in cost or model fidelity ([continuous_integration.md §1](docs/designs/continuous_integration.md#1-overview)).
- **Golden data** (perf, synthesis and Beacon baselines, reference images) is regenerated only by its update command, with the CI toolchain, by a human or an agent the maintainer delegated that re-record to, never hand-edited (X-EV-1); a red gate means real cycles, Fmax or area moved — root-cause it ([B-3](docs/bug_fixes.md#6-performance-and-area-regressions)). See [shared/evidence.md](docs/guidelines/shared/evidence.md).
- **Beacon first for RTL that can move timing; synthesis only to confirm** (X-EV-4): `ci/logic_gate.py -b <dut> --against-rev HEAD` after each edit; a red `logic_gate` is a regression: fixed, or proven inherent per B-3 before it is re-recorded per X-EV-1 (X-EV-5). Recipes: [continuous_integration.md §3.5](docs/designs/continuous_integration.md), [Beacon's docs/beacon.md §6.3](https://github.com/orcaslab/beacon/blob/main/docs/beacon.md).
- **SimX is the RTL's timing model — keep them in lockstep** (X-EV-3, C-SIM-3): a cycle-moving change on either side lands with the other, and a `model_parity` case (`ci/testcases/core.yaml` + per-extension parity categories) shows it. Never widen a parity tolerance to absorb a divergence.
Expand Down
18 changes: 14 additions & 4 deletions ci/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ def ambient_xlen():
def pytest_addoption(parser):
# perf_gate record-mode: measure and rewrite the golden cycle
# baselines instead of asserting against them. Run per X-EV-1 and reviewed;
# CI never passes this flag. See ci/perf_baseline.py.
# CI never passes this flag (every run already writes its measurements to
# gate_results/perf). See ci/perf_baseline.py.
parser.addoption("--update-baselines", action="store_true", default=False,
help="perf_gate: record measured cycles into "
"ci/baselines/perf/ instead of comparing")
Expand Down Expand Up @@ -91,10 +92,19 @@ def _select_shard(config, items):
items[:] = keep


def pytest_sessionstart(session):
"""gate_results/ describes this session only: a measurement left by an
earlier one would otherwise be merged into the baselines as current."""
shutil.rmtree("gate_results", ignore_errors=True)


def pytest_sessionfinish(session):
if session.config.getoption("--update-baselines"):
import perf_baseline
perf_baseline.flush()
"""Publish what the gate cases measured (gate_results/), and update the
baselines with it under --update-baselines."""
import gate_report
import perf_baseline
perf_baseline.flush(session.config.getoption("--update-baselines"))
gate_report.write_summary()


def _build_vars():
Expand Down
80 changes: 80 additions & 0 deletions ci/gate_report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""Gate verdicts: every check of a case, evaluated in full and failed once.

A gate case (perf_gate, model_parity) asserts several numbers. Stopping at the
first failed check would hide the others until it is fixed, so a case collects
one verdict per check instead, prints them, and fails once listing every failed
one. A check under a known issue still runs and is reported (XFAIL, or XPASS
once it passes) but does not fail the case. conftest writes the session's
verdicts as a Markdown table (gate_results/summary.md) that CI appends to the
job summary.
"""

import os

SUMMARY_FILE = os.path.join("gate_results", "summary.md")

# (case id, check, PASS|FAIL|XFAIL|XPASS, detail) of every case this session.
_rows = []


class Verdicts:
"""The checks of one case. Used as a context manager, it reports an
unexpected exception as an `error` verdict and fails the case once on
leaving."""

def __init__(self, case_id):
self.case_id = case_id
self.rows = []

def check(self, name, ok, detail, known=""):
if known:
verdict = "XPASS" if ok else "XFAIL"
detail = "{} (known issue: {})".format(detail, known)
else:
verdict = "PASS" if ok else "FAIL"
self.rows.append((name, verdict, detail))
return ok

def fail(self, name, detail):
return self.check(name, False, detail)

def finish(self):
"""Print every verdict, keep them for the summary, and fail once."""
for name, verdict, detail in self.rows:
print("VERDICT: {}: {} {}: {}".format(self.case_id, name, verdict, detail))
_rows.append((self.case_id, name, verdict, detail))
failed = ["{}: {}".format(name, detail)
for name, verdict, detail in self.rows if verdict == "FAIL"]
assert not failed, "{}: {} of {} checks failed\n {}".format(
self.case_id, len(failed), len(self.rows), "\n ".join(failed))

def __enter__(self):
return self

def __exit__(self, kind, exc, tb):
if kind is not None and not issubclass(kind, Exception):
return False # pytest's own outcomes pass through
if exc is not None:
self.fail("error", "{}: {}".format(kind.__name__, exc))
self.finish()
return True


def write_summary():
"""The session's verdicts as a Markdown table, failures first."""
if not _rows:
return
os.makedirs(os.path.dirname(SUMMARY_FILE), exist_ok=True)
failed = sorted({r[0] for r in _rows if r[2] == "FAIL"})
known = sorted({r[0] for r in _rows if r[2] in ("XFAIL", "XPASS")})
rows = sorted(_rows, key=lambda r: (r[0] not in failed, r[0] not in known, r[0]))
marks = {"PASS": "pass", "FAIL": "**FAIL**", "XFAIL": "known issue",
"XPASS": "pass, known issue"}
with open(SUMMARY_FILE, "w") as fh:
fh.write("### Gate verdicts: {} cases, {} failed, {} with a known issue\n\n"
.format(len({r[0] for r in _rows}), len(failed), len(known)))
fh.write("| case | check | verdict | detail |\n|---|---|---|---|\n")
for cid, name, verdict, detail in rows:
fh.write("| `{}` | {} | {} | {} |\n".format(
cid, name, marks[verdict], detail.replace("|", "\\|")))
del _rows[:]
89 changes: 73 additions & 16 deletions ci/perf_baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,20 @@
The harness runs from a build tree, so the source root is resolved from the
build tree's config.mk (VORTEX_HOME) — baselines are source data, not copied
into build/, so an update lands directly on the golden a human then reviews.

Every perf_gate run also writes what it measured, in the same format, to
<build>/gate_results/perf/<category>.json (CANDIDATE_DIR). CI publishes that
directory, and `perf_baseline.py merge <dir>` folds such a directory into the
baselines, so recording a number never needs a second run.
"""

import argparse
import collections
import hashlib
import json
import os
import re
import sys

# Perf-regression tolerance: cycles must stay within +/-2% of baseline. The
# upper bound is the regression gate; the lower bound is the ratchet — an
Expand All @@ -38,10 +45,12 @@ def _source_root():


BASELINE_DIR = os.path.join(_source_root(), "ci", "baselines", "perf")
# Relative to the build tree the harness runs in.
CANDIDATE_DIR = os.path.join("gate_results", "perf")


def _path(category):
return os.path.join(BASELINE_DIR, category + ".json")
def _path(category, directory=None):
return os.path.join(directory or BASELINE_DIR, category + ".json")


# The generated headers the drivers and the RTL compile against. They are a
Expand Down Expand Up @@ -132,36 +141,84 @@ def resolved_configs(case):
return " ".join(parts)


def load(category):
def load(category, directory=None):
try:
with open(_path(category)) as fh:
with open(_path(category, directory)) as fh:
return json.load(fh)
except OSError:
return {}


# --update-baselines accumulates here across the session; conftest flushes once.
_pending = collections.defaultdict(dict)
# Every run's measurements accumulate here across the session; conftest writes
# them to CANDIDATE_DIR once, and also to the baselines under --update-baselines.
_measured = collections.defaultdict(dict)


def record(case, xlen, cycles, instrs):
entry = _pending[case.category].setdefault(case.id, {})
entry = _measured[case.category].setdefault(case.id, {})
entry["app"], entry["args"] = case.app, case.args
entry["driver"] = case.driver
entry["configs"] = resolved_configs(case)
entry["config_hash"] = config_hash(case)
entry[str(xlen)] = {"cycles": int(cycles), "instrs": int(instrs)}


def flush():
"""Merge pending records into the per-category files (preserving other xlens)."""
for category, entries in _pending.items():
merged = load(category)
def _merge_into(directory, tables):
"""Merge {category: {case id: entry}} into the per-category files of
`directory`, keeping the xlens an entry does not carry."""
for category, entries in tables.items():
merged = load(category, directory)
for cid, entry in entries.items():
cur = merged.setdefault(cid, {})
cur.update(entry) # entry carries this-run's xlen key + metadata
os.makedirs(BASELINE_DIR, exist_ok=True)
with open(_path(category), "w") as fh:
merged.setdefault(cid, {}).update(entry)
os.makedirs(directory, exist_ok=True)
with open(_path(category, directory), "w") as fh:
json.dump(merged, fh, indent=2, sort_keys=True)
fh.write("\n")
_pending.clear()


def flush(update_baselines=False):
"""Write this session's measurements as candidates, and into the baselines
when they are being updated."""
_merge_into(CANDIDATE_DIR, _measured)
if update_baselines:
_merge_into(BASELINE_DIR, _measured)
_measured.clear()


def merge(candidate_dir, case_ids=None):
"""Fold a candidate directory (a run's gate_results/perf) into the
baselines; with case_ids, only those cases. Returns the ids merged."""
tables, done = {}, []
for name in sorted(os.listdir(candidate_dir)):
if not name.endswith(".json"):
continue
with open(os.path.join(candidate_dir, name)) as fh:
entries = json.load(fh)
keep = {cid: e for cid, e in entries.items()
if case_ids is None or cid in case_ids}
if keep:
tables[name[:-len(".json")]] = keep
done += sorted(keep)
_merge_into(BASELINE_DIR, tables)
return done


def main(argv=None):
p = argparse.ArgumentParser(description="perf_gate baselines")
sub = p.add_subparsers(dest="cmd", required=True)
m = sub.add_parser("merge", help="fold a run's measured values (its "
"gate_results/perf directory) into ci/baselines/perf")
m.add_argument("candidates", help="directory of <category>.json files")
m.add_argument("cases", nargs="*", help="only these case ids (default: all)")
args = p.parse_args(argv)
done = merge(args.candidates, set(args.cases) if args.cases else None)
missing = sorted(set(args.cases) - set(done))
for cid in done:
print("merged", cid)
for cid in missing:
print("not in the candidates:", cid, file=sys.stderr)
return 1 if missing else 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading