385 lines
16 KiB
Python
Executable File
385 lines
16 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 as markdown
|
|
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 FILE # rewrite the table between the markers of FILE
|
|
|
|
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 directory under crates/ -> cargo package (`cargo test -p`); the directory name is the fallback
|
|
CRATE_PACKAGE = {
|
|
"cuda-driver": "leleka-cuda-driver",
|
|
"engine-core": "leleka-engine-core",
|
|
"engine-qwen35-cuda": "leleka-engine-qwen35-cuda",
|
|
"model-format": "leleka-model-format",
|
|
"native-cpu-expert": "leleka-native-cpu-expert",
|
|
"deploy": "leleka-deploy",
|
|
"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",
|
|
"PROBE_ARCHIVE", "PROBE_ROWS", "SYNTH_KAR",
|
|
)
|
|
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 _module_family(path: Path) -> List[Path]:
|
|
"""The file plus the rest of its module tree: `x.rs` with the children in `x/` (helpers moved out of a test file
|
|
by a split stay visible to it), or `x/y.rs` with its parent `x.rs` and siblings."""
|
|
owner = path.parent.parent / (path.parent.name + ".rs")
|
|
root = owner if owner.is_file() else path
|
|
kids = sorted(root.with_suffix("").rglob("*.rs")) if root.with_suffix("").is_dir() else []
|
|
return [root] + [k for k in kids if k != root]
|
|
|
|
|
|
def _calls(body: str, names: List[str]) -> bool:
|
|
return any(re.search(r"\b" + re.escape(n) + r"\s*\(", body) for n in names)
|
|
|
|
|
|
def _file_readers(texts: List[str]) -> List[str]:
|
|
"""Non-test helper functions (in any file of the module tree) that open files, directly or through another
|
|
helper: a split may leave the test calling `fixture()` while only `read()` touches the file."""
|
|
helpers: Dict[str, str] = {}
|
|
for text in texts:
|
|
for fm in _FN_RE.finditer(text):
|
|
if not _IGNORE_RE.search(text[max(0, fm.start() - 200) : fm.start()]):
|
|
helpers[fm.group(1)] = helpers.get(fm.group(1), "") + _body(text, fm.start())
|
|
readers = [n for n, body in helpers.items() if _READS_FILES.search(body)]
|
|
for _ in range(3):
|
|
more = [n for n, body in helpers.items() if n not in readers and _calls(body, readers)]
|
|
if not more:
|
|
break
|
|
readers += more
|
|
return readers
|
|
|
|
|
|
def _classify(body: str, gates: Dict[str, str], needs: List[str], readers: List[str]) -> tuple:
|
|
"""(class, needs) of one smoke from its enabling variables and the file-reading helpers it calls."""
|
|
if "LELEKA_CUDA_MOCK_HARNESS" in gates and not any("REAL_GPU" in g for g in gates):
|
|
return "mock", needs
|
|
if needs:
|
|
return "assets", needs
|
|
if _calls(body, readers):
|
|
# synthetic-looking, but a helper it calls opens files: the fixture may be a private artifact
|
|
return "assets", ["(fixture files read via a helper; inspect before running)"]
|
|
return "device", needs
|
|
|
|
|
|
def _enabling(body: str, text: str, consts: Dict[str, str]) -> tuple:
|
|
"""(gates, needs) of one test body: enabling variables with their values, and caller-supplied path variables."""
|
|
use = _vars_in(body, consts) # 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)}
|
|
return gates, [v for v in use if v not in gates and any(w in v for w in ASSET_WORDS)]
|
|
|
|
|
|
def _read(path: Path) -> str:
|
|
return path.read_text(encoding="utf-8", errors="replace")
|
|
|
|
|
|
def _smokes_in(path: Path, root: Path) -> List[Smoke]:
|
|
text = _read(path)
|
|
rel = path.relative_to(root)
|
|
target = f"test:{path.stem}" if len(rel.parts) > 3 and rel.parts[2] == "tests" else "lib"
|
|
family = [_read(p) for p in _module_family(path)]
|
|
consts = dict(_CONST_RE.findall("\n".join(family)))
|
|
readers = _file_readers(family)
|
|
out: List[Smoke] = []
|
|
for m in _IGNORE_RE.finditer(text):
|
|
fm = _FN_RE.search(text, m.end())
|
|
if fm:
|
|
body = _body(text, fm.start())
|
|
gates, needs = _enabling(body, text, consts)
|
|
klass, needs = _classify(body, gates, needs, readers)
|
|
out.append(Smoke(crate=rel.parts[1], 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))
|
|
return out
|
|
|
|
|
|
def scan(root: Path) -> List[Smoke]:
|
|
out: List[Smoke] = []
|
|
for path in sorted((root / "crates").rglob("*.rs")):
|
|
if "target" not in path.parts and "#[ignore" in _read(path):
|
|
out += _smokes_in(path, root)
|
|
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())
|