Files
leleka/scripts/gpu-bringup/smoke_inventory.py
T

333 lines
15 KiB
Python
Executable File

#!/usr/bin/env python3
"""Inventory of the #[ignore]d Root-only GPU smokes and the env flags that enable them.
Scans crates/**/*.rs for `#[ignore]` attributes (real attributes only, not doc comments), finds the enabling
LELEKA_* variables each test reads, classifies it and assigns it to a group of scripts/gpu-bringup/smoke-groups.json.
smoke_inventory.py --emit table # human table
smoke_inventory.py --emit markdown # the table embedded in docs/gpu-bringup.md
smoke_inventory.py --emit plan # TSV consumed by run_gpu_smokes.sh
smoke_inventory.py --emit groups # TSV: group, deps, kind, description
smoke_inventory.py --emit json
smoke_inventory.py --update-doc docs/gpu-bringup.md # rewrite the table between the markers
Classes: device (needs only the GPU and a flag), assets (reads model/pack/oracle paths: never run without
--allow-model-runs), mock (isolated CPU harness, not a GPU test).
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Dict, List, Optional
HERE = Path(__file__).resolve().parent
REPO = HERE.parents[1]
GROUPS_FILE = HERE / "smoke-groups.json"
TABLE_START = "<!-- smoke-table:start (generated by scripts/gpu-bringup/smoke_inventory.py --update-doc) -->"
TABLE_END = "<!-- smoke-table:end -->"
CRATE_PACKAGE = {"cuda-driver": "leleka-cuda-driver", "leleka-runtime": "leleka-runtime", "native-cpu-expert": "leleka-native-cpu-expert",
"context": "leleka-context"}
CRATE_FEATURES = {"cuda-driver": "cuda-driver"}
GATE_WORDS = ("_RUN_", "_GPU", "REAL_GPU", "ENABLE", "MOCK_HARNESS", "RT_BANK_GPU", "_SMOKE")
ASSET_WORDS = ("SHARD", "PACK", "STAGING", "KAR_FD", "KAR_ARCHIVE", "PROVENANCE", "REFERENCE", "METADATA", "LAYER0_DIR", "CAPTURE_DIR",
"EVIDENCE", "ORACLE", "TRUSTED_PTX", "REAL_INPUT", "GPU_ROOT", "PAIR_OUTPUT", "EXPERT_PROFILE", "NATIVE_ORACLE",
"FAMILY_MODES", "FAMILY_NATIVE", "FAMILY_QUANTIZER_PTX", "FAMILY_R", "HEAD_NATIVE")
DEFAULT_VALUE = {"LELEKA_CUDA_REAL_GPU": "1", "LELEKA_FAMILY_REAL_GPU": "1"}
@dataclass
class Smoke:
crate: str
file: str # repo-relative
line: int
name: str
reason: str
target: str # "lib" or "test:<stem>"
gates: Dict[str, str] = field(default_factory=dict) # enabling vars -> value
needs: List[str] = field(default_factory=list) # asset/path variables (caller must provide)
klass: str = "device"
group: str = ""
expected: int = 1 # tests of the same target whose name contains this one (filter matches)
order: int = 0
@property
def package(self) -> str:
return CRATE_PACKAGE.get(self.crate, self.crate)
@property
def features(self) -> str:
return CRATE_FEATURES.get(self.crate, "")
# ------------------------------------------------------------------------------------------- scanning
_IGNORE_RE = re.compile(r'^[ \t]*#\[ignore(?:\s*=\s*"([^"]*)")?\s*\]', re.M)
_FN_RE = re.compile(r"\bfn\s+([A-Za-z0-9_]+)\s*\(")
_LIT_RE = re.compile(r'"(LELEKA_[A-Z0-9_]+)"')
_CONST_RE = re.compile(r'const\s+([A-Z0-9_]+)\s*:\s*&(?:\'static\s+)?str\s*=\s*"(LELEKA_[A-Z0-9_]+)"')
_READS_FILES = re.compile(r"OpenOptions|File::open|fs::read|read_to_end|read_to_string")
_VAL_RE = re.compile(r'(?:Ok|Some)\(\s*"(yes|1)"\s*\)|==\s*"(yes|1)"|!=\s*(?:Ok|Some)\(\s*"(yes|1)"\s*\)')
def _body(text: str, start: int) -> str:
"""Source of the function whose `fn` keyword match starts at `start` (brace matching, strings skipped)."""
i = text.find("{", start)
if i < 0:
return ""
depth, j = 0, i
while j < len(text):
c = text[j]
if c == '"':
j += 1
while j < len(text) and text[j] != '"':
j += 2 if text[j] == "\\" else 1
elif c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
return text[i : j + 1]
j += 1
return text[i:]
def _vars_in(text: str, consts: Dict[str, str]) -> List[str]:
found = list(dict.fromkeys(_LIT_RE.findall(text)))
for name, value in consts.items():
if re.search(r"\b" + re.escape(name) + r"\b", text) and value not in found:
found.append(value)
return found
def _value_for(var: str, text: str, file_text: str, consts: Dict[str, str]) -> str:
# the comparison usually follows the variable (or the ENABLE const bound to it)
names = [re.escape(f'"{var}"')] + [re.escape(c) + r"\b" for c, v in consts.items() if v == var]
for scope in (text, file_text):
for n in names:
for m in re.finditer(n, scope):
v = _VAL_RE.search(scope[m.end() : m.end() + 200])
if v:
return next(g for g in v.groups() if g)
return DEFAULT_VALUE.get(var, "yes")
def scan(root: Path) -> List[Smoke]:
out: List[Smoke] = []
for path in sorted((root / "crates").rglob("*.rs")):
if "target" in path.parts:
continue
text = path.read_text(encoding="utf-8", errors="replace")
if "#[ignore" not in text:
continue
rel = path.relative_to(root)
crate = rel.parts[1]
target = f"test:{path.stem}" if len(rel.parts) > 3 and rel.parts[2] == "tests" else "lib"
consts = dict(_CONST_RE.findall(text))
file_vars = _vars_in(text, consts)
file_readers = [fm.group(1) for fm in _FN_RE.finditer(text)
if _READS_FILES.search(_body(text, fm.start())) and not _IGNORE_RE.search(text[max(0, fm.start() - 200) : fm.start()])]
for m in _IGNORE_RE.finditer(text):
fm = _FN_RE.search(text, m.end())
if not fm:
continue
body = _body(text, fm.start())
vars_body = _vars_in(body, consts)
gates_body = [v for v in vars_body if any(w in v for w in GATE_WORDS)]
use = vars_body # no file-level fallback: large files (lib.rs) mention gates of unrelated tests
gates = {v: _value_for(v, body, text, consts) for v in use if any(w in v for w in GATE_WORDS)}
needs = [v for v in use if v not in gates and any(w in v for w in ASSET_WORDS)]
klass = "device"
real = any("REAL_GPU" in g for g in gates)
if "LELEKA_CUDA_MOCK_HARNESS" in gates and not real:
klass = "mock"
elif needs:
klass = "assets"
elif any(re.search(r"\b" + re.escape(h) + r"\s*\(", body) for h in file_readers):
# synthetic-looking, but a helper it calls opens files: the fixture may be a private artifact
klass = "assets"
needs = ["(fixture files read via a helper; inspect before running)"]
out.append(Smoke(crate=crate, file=str(rel), line=text.count("\n", 0, m.start()) + 1, name=fm.group(1),
reason=m.group(1) or "", target=target, gates=gates, needs=needs, klass=klass))
by_target: Dict[tuple, List[Smoke]] = {}
for s in out:
by_target.setdefault((s.crate, s.target), []).append(s)
for items in by_target.values():
for s in items:
s.expected = sum(1 for t in items if s.name in t.name)
return out
# --------------------------------------------------------------------------------------------- groups
def load_groups(path: Path = GROUPS_FILE) -> dict:
data = json.loads(path.read_text(encoding="utf-8"))
names = [g["name"] for g in data["groups"]]
if len(set(names)) != len(names):
raise ValueError("duplicate group names")
seen = set()
for g in data["groups"]:
for d in g.get("depends_on", []):
if d not in seen:
raise ValueError(f"group {g['name']} depends on {d}, which must be declared before it")
seen.add(g["name"])
return data
def assign(smokes: List[Smoke], data: dict) -> None:
rules = []
for g in data["groups"]:
for i, pat in enumerate(g.get("match", [])):
rules.append((g["name"], i, re.compile(pat)))
for s in smokes:
if s.klass == "assets":
s.group = data["asset_group"]
elif s.klass == "mock":
s.group = data["mock_group"]
else:
target = f"{s.file}::{s.name}"
for name, i, rx in rules:
if rx.search(target):
s.group, s.order = name, i
break
else:
s.group = data["fallback_group"]
s.order = 999
smokes.sort(key=lambda s: (s.group, s.order, s.file, s.line))
def unique_filters(smokes: List[Smoke]) -> List[str]:
"""Names that two different tests of one target share (the cargo filter could not tell them apart)."""
seen: Dict[tuple, int] = {}
for s in smokes:
seen[(s.crate, s.target, s.name)] = seen.get((s.crate, s.target, s.name), 0) + 1
return [f"{k[0]}/{k[1]}::{k[2]}" for k, v in seen.items() if v > 1]
# -------------------------------------------------------------------------------------------- output
def env_string(s: Smoke) -> str:
return " ".join(f"{k}={v}" for k, v in s.gates.items())
def emit_table(smokes: List[Smoke], markdown: bool) -> str:
rows = []
head = ["group", "crate / target", "test", "class", "enabling env", "needs (caller supplies)"]
for s in smokes:
target = s.crate + (" lib" if s.target == "lib" else f" --test {s.target[5:]}")
rows.append([s.group, target, s.name, s.klass, env_string(s) or "(ignore only)", ", ".join(s.needs) or "-"])
if markdown:
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
lines += ["| " + " | ".join(f"`{c}`" if i in (2,) else c.replace("|", "\\|") for i, c in enumerate(r)) + " |" for r in rows]
return "\n".join(lines)
widths = [max(len(r[i]) for r in rows + [head]) for i in range(len(head))]
widths = [min(w, 58) for w in widths]
fmt = " ".join("{:<%d}" % w for w in widths)
return "\n".join(fmt.format(*[c[:w] for c, w in zip(r, widths)]) for r in [head] + rows)
def emit_plan(smokes: List[Smoke]) -> str:
lines = []
for idx, s in enumerate(smokes):
lines.append("\t".join([s.group, str(idx), s.package, s.features or "-", s.target, s.name, str(s.expected), env_string(s) or "-",
s.klass, ",".join(s.needs) or "-", f"{s.file}:{s.line}"]))
return "\n".join(lines)
def emit_groups(data: dict) -> str:
rows = [(g["name"], ",".join(g.get("depends_on", [])) or "-", g.get("kind", "device"), g["desc"]) for g in data["groups"]]
rows.append((data["asset_group"], "-", "assets", "tests that read model/pack/oracle paths; need --allow-model-runs and caller-supplied env"))
rows.append((data["mock_group"], "-", "mock", "isolated CPU harness protocol tests; not GPU smokes, never run here"))
return "\n".join("\t".join(r) for r in rows)
def select_order(data: dict, select: Optional[List[str]], skip: List[str], with_assets: bool) -> List[str]:
"""Group names in run order: the selection plus (transitively) the groups it depends on."""
kinds = {g["name"]: g.get("kind", "device") for g in data["groups"]}
deps = {g["name"]: g.get("depends_on", []) for g in data["groups"]}
kinds[data["asset_group"]] = "assets"
deps[data["asset_group"]] = []
names = [g["name"] for g in data["groups"]] + [data["asset_group"]]
for n in (select or []) + skip:
if n not in kinds and n != data["mock_group"]:
raise SystemExit(f"unknown group {n!r}; known: {', '.join(names)}")
chosen = set(select) if select else {n for n in names if kinds[n] == "device" or (with_assets and kinds[n] == "assets")}
if select and data["asset_group"] in chosen and not with_assets:
raise SystemExit(f"group {data['asset_group']} reads model/pack paths: pass --with-assets (run_gpu_smokes.sh --allow-model-runs)")
chosen -= set(skip)
stack = list(chosen)
while stack:
n = stack.pop()
for d in deps[n]:
if d in skip:
raise SystemExit(f"group {n} depends on skipped group {d}")
if d not in chosen:
chosen.add(d)
stack.append(d)
return [n for n in names if n in chosen]
def update_doc(path: Path, table: str) -> bool:
text = path.read_text(encoding="utf-8")
if TABLE_START not in text or TABLE_END not in text:
raise SystemExit(f"{path}: smoke-table markers not found")
head, rest = text.split(TABLE_START, 1)
_, tail = rest.split(TABLE_END, 1)
new = head + TABLE_START + "\n" + table + "\n" + TABLE_END + tail
if new != text:
path.write_text(new, encoding="utf-8")
return True
return False
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", type=Path, default=REPO)
ap.add_argument("--groups-file", type=Path, default=GROUPS_FILE)
ap.add_argument("--emit", choices=("table", "markdown", "plan", "groups", "json", "order"), default="table")
ap.add_argument("--select", help="with --emit order/plan: comma list of groups (dependencies are added)")
ap.add_argument("--skip-groups", default="", help="comma list of groups to leave out")
ap.add_argument("--with-assets", action="store_true", help="include the model-assets group")
ap.add_argument("--update-doc", type=Path)
args = ap.parse_args(argv)
smokes = scan(args.root)
data = load_groups(args.groups_file)
assign(smokes, data)
dups = unique_filters(smokes)
if dups:
print("warning: ambiguous cargo filters (same fn name twice in one target): " + ", ".join(dups), file=sys.stderr)
if args.update_doc:
changed = update_doc(args.update_doc, emit_table(smokes, markdown=True))
print(f"{args.update_doc}: {'updated' if changed else 'already current'}")
return 0
select = [x for x in (args.select or "").split(",") if x] or None
skip = [x for x in args.skip_groups.split(",") if x]
if args.emit == "order":
print("\n".join(select_order(data, select, skip, args.with_assets)))
return 0
if args.emit == "plan" and (select or skip or args.with_assets):
keep = set(select_order(data, select, skip, args.with_assets))
smokes = [x for x in smokes if x.group in keep]
if args.emit == "table":
print(emit_table(smokes, False))
elif args.emit == "markdown":
print(emit_table(smokes, True))
elif args.emit == "plan":
print(emit_plan(smokes))
elif args.emit == "groups":
print(emit_groups(data))
else:
print(json.dumps([asdict(s) for s in smokes], indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())