"""Release gate: block publishing when quality or packaging is insufficient. Usage: python pipeline/check_gate.py --metrics reports/metrics.json \ --repo DevGwardo/minicpm5-1b-toolcall --dataset DevGwardo/toolcall-mini python pipeline/check_gate.py --metrics reports/metrics.json --strict Checks: A) Quality thresholds from metrics.json (base vs tuned, plus multiturn if present). B) Packaging files exist in the repo checkout. C) Public access of the model repo and dataset via the HF API (network problems degrade to WARN, never crash the run; --strict makes them fatal). Exit code 0 only if every required check passes (and, under --strict, no warnings either). Always writes reports/gate.md + reports/gate.json when possible. """ import argparse import datetime import json import sys from pathlib import Path try: import requests except ImportError: # pragma: no cover requests = None ROOT = Path(__file__).resolve().parent.parent # Thresholds (per spec). MIN_ABSTENTION = 0.90 MIN_POSITIVE_EXACT = 0.65 MIN_PARSE = 0.95 MIN_MT_STAGE1 = 0.60 MIN_MT_STAGE2_TYPE = 0.70 def resolve(p: str) -> Path: """Resolve a path: absolute as-is, else relative to CWD, else to repo root.""" path = Path(p) if path.is_absolute(): return path if path.exists(): return path rooted = ROOT / path return rooted def check(status, cid, name, detail, required=True): return {"id": cid, "name": name, "status": status, "detail": detail, "required": required} def fmt(x): if x is None: return "n/a" if isinstance(x, float): return f"{x:.4f}" return str(x) def hf_get(url): """GET with a short timeout. Returns (ok, status_code, data, error).""" try: r = requests.get(url, timeout=10) except Exception as e: # network never fails the whole run return False, None, None, f"{type(e).__name__}: {e}" try: data = r.json() if r.status_code == 200 else None except Exception: data = None return True, r.status_code, data, "" def main(): ap = argparse.ArgumentParser(description="Release gate for MiniCPM5 toolcall.") ap.add_argument("--metrics", default="reports/metrics.json") ap.add_argument("--repo", default="DevGwardo/minicpm5-1b-toolcall") ap.add_argument("--dataset", default="DevGwardo/toolcall-mini") ap.add_argument("--strict", action="store_true", help="warnings are fatal") ap.add_argument("--gate-md", default="reports/gate.md") ap.add_argument("--gate-json", default="reports/gate.json") args = ap.parse_args() metrics_path = resolve(args.metrics) try: metrics_rel = metrics_path.relative_to(ROOT).as_posix() except ValueError: metrics_rel = str(metrics_path) md_path = resolve(args.gate_md) js_path = resolve(args.gate_json) checks = [] # ---- A) Quality ---- try: metrics = json.loads(metrics_path.read_text(encoding="utf-8")) except FileNotFoundError: metrics = None checks.append(check("FAIL", "quality/metrics-file", "metrics.json loads", f"not found: {metrics_path}", True)) except Exception as e: metrics = None checks.append(check("FAIL", "quality/metrics-file", "metrics.json loads", f"unreadable {metrics_path}: {e}", True)) if metrics is not None: base = metrics.get("base") or {} tuned = metrics.get("tuned") or {} mt = metrics.get("multiturn_tuned") def num(d, k): v = d.get(k) return v if isinstance(v, (int, float)) else None abst = num(tuned, "abstention_accuracy") if abst is None: checks.append(check("FAIL", "quality/abstention", "abstention_accuracy >= 0.90", "tuned.abstention_accuracy missing", True)) else: checks.append(check("PASS" if abst >= MIN_ABSTENTION else "FAIL", "quality/abstention", "abstention_accuracy >= 0.90", f"tuned={fmt(abst)} threshold={MIN_ABSTENTION}", True)) pex = num(tuned, "positive_exact_rate") if pex is None: checks.append(check("FAIL", "quality/positive-exact", "positive_exact_rate >= 0.65", "tuned.positive_exact_rate missing", True)) else: checks.append(check("PASS" if pex >= MIN_POSITIVE_EXACT else "FAIL", "quality/positive-exact", "positive_exact_rate >= 0.65", f"tuned={fmt(pex)} threshold={MIN_POSITIVE_EXACT}", True)) prs = num(tuned, "parse_rate") if prs is None: checks.append(check("FAIL", "quality/parse", "parse_rate >= 0.95", "tuned.parse_rate missing", True)) else: checks.append(check("PASS" if prs >= MIN_PARSE else "FAIL", "quality/parse", "parse_rate >= 0.95", f"tuned={fmt(prs)} threshold={MIN_PARSE}", True)) b_exact = num(base, "exact_call_rate") t_exact = num(tuned, "exact_call_rate") if b_exact is None or t_exact is None: checks.append(check("FAIL", "quality/improvement", "tuned.exact_call_rate > base", f"missing (base={fmt(b_exact)} tuned={fmt(t_exact)})", True)) else: checks.append(check("PASS" if t_exact > b_exact else "FAIL", "quality/improvement", "tuned.exact_call_rate > base", f"base={fmt(b_exact)} tuned={fmt(t_exact)} " f"delta={t_exact - b_exact:+.4f} (strict >)", True)) if isinstance(mt, dict) and mt: s1 = num(mt, "stage1_exact") s2 = num(mt, "stage2_type_accuracy") if s1 is None: checks.append(check("FAIL", "quality/mt-stage1", "stage1_exact >= 0.60", "multiturn_tuned.stage1_exact missing", True)) else: checks.append(check("PASS" if s1 >= MIN_MT_STAGE1 else "FAIL", "quality/mt-stage1", "stage1_exact >= 0.60", f"tuned={fmt(s1)} threshold={MIN_MT_STAGE1}", True)) if s2 is None: checks.append(check("FAIL", "quality/mt-stage2", "stage2_type_accuracy >= 0.70", "multiturn_tuned.stage2_type_accuracy missing", True)) else: checks.append(check("PASS" if s2 >= MIN_MT_STAGE2_TYPE else "FAIL", "quality/mt-stage2", "stage2_type_accuracy >= 0.70", f"tuned={fmt(s2)} threshold={MIN_MT_STAGE2_TYPE}", True)) else: checks.append(check("SKIP", "quality/mt-stage1", "stage1_exact >= 0.60", "no multiturn_tuned in metrics; skipped", False)) checks.append(check("SKIP", "quality/mt-stage2", "stage2_type_accuracy >= 0.70", "no multiturn_tuned in metrics; skipped", False)) # ---- B) Packaging ---- def exists(rel): return (ROOT / rel).is_file() checks.append(check("PASS" if exists("PROJECT.md") else "FAIL", "packaging/project-md", "PROJECT.md exists", "found" if exists("PROJECT.md") else "missing PROJECT.md", True)) checks.append(check("PASS" if exists("pipeline/test_runtime.py") else "FAIL", "packaging/test-runtime", "pipeline/test_runtime.py exists", "found" if exists("pipeline/test_runtime.py") else "missing pipeline/test_runtime.py", True)) checks.append(check("PASS" if exists("repro/README.md") else "FAIL", "packaging/repro-readme", "repro/README.md exists", "found" if exists("repro/README.md") else "missing repro/README.md", True)) card_ok = exists("card/README.md") root_ok = exists("README.md") if card_ok or root_ok: detail = "found " + ", ".join( [p for p, ok in (("card/README.md", card_ok), ("README.md", root_ok)) if ok]) else: detail = "missing both card/README.md and README.md (need at least one)" checks.append(check("PASS" if (card_ok or root_ok) else "FAIL", "packaging/model-card", "card/README.md or README.md exists", detail, True)) pred_candidates = [ROOT / "reports" / "predictions.jsonl", ROOT / "out" / "predictions.jsonl", ROOT / "predictions.jsonl"] found_pred = next((p for p in pred_candidates if p.is_file()), None) if found_pred is None: # fallback: any *predict* file under reports/ reports_dir = ROOT / "reports" if reports_dir.is_dir(): alts = sorted([p for p in reports_dir.glob("*predict*") if p.is_file()]) if alts: found_pred = alts[0] if found_pred is not None: try: rel = found_pred.relative_to(ROOT).as_posix() except ValueError: rel = str(found_pred) checks.append(check("PASS", "packaging/predictions", "predictions file exists", f"found {rel}", True)) else: checks.append(check("FAIL", "packaging/predictions", "predictions file exists", "missing reports/predictions.jsonl (no *predict* fallback found)", True)) # ---- C) Public access ---- if requests is None: checks.append(check("WARN", "access/dataset", f"dataset {args.dataset} public", "requests not installed; cannot verify", False)) checks.append(check("WARN", "access/model", f"model {args.repo} public", "requests not installed; cannot verify", False)) else: durl = f"https://huggingface.co/api/datasets/{args.dataset}" ok, code, data, err = hf_get(durl) if not ok: checks.append(check("WARN", "access/dataset", f"dataset {args.dataset} public", f"network error ({err}); could not verify {durl}", False)) elif code != 200: checks.append(check("FAIL", "access/dataset", f"dataset {args.dataset} public", f"GET {durl} -> HTTP {code}", True)) elif isinstance(data, dict) and data.get("private") is True: checks.append(check("FAIL", "access/dataset", f"dataset {args.dataset} public", "dataset is private (private == true)", True)) else: checks.append(check("PASS", "access/dataset", f"dataset {args.dataset} public", f"GET {durl} -> 200, private == false", True)) murl = f"https://huggingface.co/api/models/{args.repo}" ok, code, data, err = hf_get(murl) if not ok: checks.append(check("WARN", "access/model", f"model {args.repo} public", f"network error ({err}); could not verify {murl}", False)) elif code != 200: checks.append(check("FAIL", "access/model", f"model {args.repo} public", f"GET {murl} -> HTTP {code}", True)) else: checks.append(check("PASS", "access/model", f"model {args.repo} public", f"GET {murl} -> 200", True)) fails = [c for c in checks if c["status"] == "FAIL" and c["required"]] warns = [c for c in checks if c["status"] == "WARN"] verdict = "PASS" if not fails and not (args.strict and warns) else "FAIL" # ---- console ---- for c in checks: print(f'[{c["status"]}] {c["id"]}: {c["name"]} -- {c["detail"]}') print(f"VERDICT: {verdict} " f"({len(fails)} required failure(s), {len(warns)} warning(s)" f"{', --strict' if args.strict else ''})") # ---- reports ---- payload = { "verdict": verdict, "strict": args.strict, "repo": args.repo, "dataset": args.dataset, "metrics": metrics_rel, "generated_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(), "thresholds": { "abstention_accuracy": MIN_ABSTENTION, "positive_exact_rate": MIN_POSITIVE_EXACT, "parse_rate": MIN_PARSE, "multiturn_stage1_exact": MIN_MT_STAGE1, "multiturn_stage2_type_accuracy": MIN_MT_STAGE2_TYPE, "exact_improvement": "tuned.exact_call_rate > base.exact_call_rate (strict)", }, "checks": checks, } try: md_path.parent.mkdir(parents=True, exist_ok=True) js_path.parent.mkdir(parents=True, exist_ok=True) js_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") lines = [f"# Release gate: {verdict}", "", f"- repo: `{args.repo}`", f"- dataset: `{args.dataset}`", f"- metrics: `{metrics_rel}` (`{metrics_path}`)", f"- strict: `{args.strict}`", f"- generated (UTC): `{payload['generated_utc']}`", "", "| Check | Status | Detail | Required |", "|---|---|---|---|"] for c in checks: lines.append(f"| `{c['id']}` | {c['status']} | {c['detail']} | {c['required']} |") lines += ["", f"**Verdict: {verdict}**", "" if verdict == "PASS" else "_FAIL: do not publish until every required FAIL is fixed" + (" (warnings fatal under --strict)." if args.strict and warns and not fails else "."), ""] md_path.write_text("\n".join(lines), encoding="utf-8") print(f"wrote {md_path} and {js_path}") except Exception as e: print(f"WARNING: could not write reports: {e}", file=sys.stderr) return 0 if verdict == "PASS" else 1 if __name__ == "__main__": sys.exit(main())