|
| 1 | +"""Generic kpis.json -> metrics.json + parameters.json conversion. |
| 2 | +
|
| 3 | +Reads a hierarchical kpis.json (schema v2) and writes per-test-run |
| 4 | +metrics.json and parameters.json files into the matching artifact tree |
| 5 | +directories. The MLflow export backend picks these up automatically via |
| 6 | +``_log_metrics_and_params_from_tree``. |
| 7 | +
|
| 8 | +This replaces project-specific metrics.json generation (e.g. in |
| 9 | +mcp_gateway parsers) with a single generic caliper mechanism that works |
| 10 | +for every project producing a kpis.json. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import json |
| 16 | +import logging |
| 17 | +from pathlib import Path |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | +METRICS_FILE = "metrics.json" |
| 23 | +PARAMETERS_FILE = "parameters.json" |
| 24 | +TEST_LABELS_MARKER = "__test_labels__.yaml" |
| 25 | + |
| 26 | + |
| 27 | +def _build_run_dir_index(artifact_tree: Path) -> dict[str, Path]: |
| 28 | + """Map run directory names to their paths using __test_labels__.yaml markers.""" |
| 29 | + index: dict[str, Path] = {} |
| 30 | + for marker in sorted(artifact_tree.rglob(TEST_LABELS_MARKER)): |
| 31 | + if marker.is_file(): |
| 32 | + run_dir = marker.parent |
| 33 | + try: |
| 34 | + rel = run_dir.relative_to(artifact_tree) |
| 35 | + except ValueError: |
| 36 | + rel = Path(run_dir.name) |
| 37 | + index[str(rel)] = run_dir |
| 38 | + index[run_dir.name] = run_dir |
| 39 | + return index |
| 40 | + |
| 41 | + |
| 42 | +def _is_scalar(value: Any) -> bool: |
| 43 | + """Check if a KPI value is a scalar number (not 2D data).""" |
| 44 | + return isinstance(value, int | float) and not isinstance(value, bool) |
| 45 | + |
| 46 | + |
| 47 | +def _extract_2d_points(value: Any) -> list[dict[str, float]] | None: |
| 48 | + """Extract sorted (x, y) data points from a 2D KPI value. |
| 49 | +
|
| 50 | + Returns a list of ``{"x": ..., "y": ...}`` dicts sorted by x, |
| 51 | + or ``None`` if the value is not a valid 2D structure. |
| 52 | + """ |
| 53 | + if not isinstance(value, dict): |
| 54 | + return None |
| 55 | + data_points = value.get("data_points") |
| 56 | + if not isinstance(data_points, list) or not data_points: |
| 57 | + return None |
| 58 | + points = [] |
| 59 | + for pt in data_points: |
| 60 | + if isinstance(pt, dict) and _is_scalar(pt.get("x")) and _is_scalar(pt.get("y")): |
| 61 | + points.append({"x": float(pt["x"]), "y": float(pt["y"])}) |
| 62 | + if not points: |
| 63 | + return None |
| 64 | + points.sort(key=lambda p: p["x"]) |
| 65 | + return points |
| 66 | + |
| 67 | + |
| 68 | +def _write_json(path: Path, data: dict[str, Any]) -> None: |
| 69 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 70 | + with path.open("w", encoding="utf-8") as f: |
| 71 | + json.dump(data, f, indent=2, sort_keys=True) |
| 72 | + f.write("\n") |
| 73 | + |
| 74 | + |
| 75 | +def generate_metrics_from_kpis( |
| 76 | + kpis_json_path: Path, |
| 77 | + artifact_tree: Path, |
| 78 | +) -> dict[str, Any]: |
| 79 | + """Convert kpis.json into per-run metrics.json and parameters.json files. |
| 80 | +
|
| 81 | + For each test entry in kpis.json, finds the matching directory under |
| 82 | + ``artifact_tree`` (via ``__test_labels__.yaml`` markers) and writes: |
| 83 | +
|
| 84 | + - ``metrics.json``: ``{kpi_id: value}`` for all scalar KPIs |
| 85 | + - ``parameters.json``: test-level labels as string key-value pairs |
| 86 | +
|
| 87 | + Args: |
| 88 | + kpis_json_path: Path to the kpis.json file (schema v2). |
| 89 | + artifact_tree: Root of the caliper artifact tree containing |
| 90 | + test run directories with ``__test_labels__.yaml`` markers. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + Status dict with counts and any warnings. |
| 94 | + """ |
| 95 | + if not kpis_json_path.is_file(): |
| 96 | + raise FileNotFoundError(f"kpis.json not found: {kpis_json_path}") |
| 97 | + |
| 98 | + with kpis_json_path.open(encoding="utf-8") as f: |
| 99 | + data = json.load(f) |
| 100 | + |
| 101 | + if not isinstance(data, dict) or data.get("schema_version") != "2": |
| 102 | + return {"status": "skipped", "reason": "Not a schema v2 kpis.json"} |
| 103 | + |
| 104 | + tests = data.get("tests", []) |
| 105 | + if not tests: |
| 106 | + return {"status": "skipped", "reason": "No tests in kpis.json"} |
| 107 | + |
| 108 | + run_dir_index = _build_run_dir_index(artifact_tree) |
| 109 | + if not run_dir_index: |
| 110 | + logger.warning("No test run directories found under %s", artifact_tree) |
| 111 | + return {"status": "skipped", "reason": "No run directories with __test_labels__.yaml found"} |
| 112 | + |
| 113 | + written = 0 |
| 114 | + warnings: list[str] = [] |
| 115 | + |
| 116 | + for test_entry in tests: |
| 117 | + run_id = test_entry.get("run_id", "") |
| 118 | + test_base_path = ( |
| 119 | + test_entry.get("metadata", {}).get("source", {}).get("test_base_path", run_id) |
| 120 | + ) |
| 121 | + |
| 122 | + run_dir = run_dir_index.get(test_base_path) or run_dir_index.get(run_id) |
| 123 | + if run_dir is None: |
| 124 | + warnings.append(f"No matching directory for run_id={run_id!r}") |
| 125 | + continue |
| 126 | + |
| 127 | + kpis = test_entry.get("kpis", []) |
| 128 | + metrics: dict[str, Any] = {} |
| 129 | + for kpi in kpis: |
| 130 | + kpi_id = kpi.get("id", "") |
| 131 | + if not kpi_id: |
| 132 | + continue |
| 133 | + value = kpi.get("value") |
| 134 | + is_2d = kpi.get("is_2d", False) |
| 135 | + if is_2d: |
| 136 | + points = _extract_2d_points(value) |
| 137 | + if points: |
| 138 | + metrics[kpi_id] = points |
| 139 | + elif _is_scalar(value): |
| 140 | + metrics[kpi_id] = value |
| 141 | + |
| 142 | + if metrics: |
| 143 | + _write_json(run_dir / METRICS_FILE, metrics) |
| 144 | + |
| 145 | + labels = test_entry.get("labels", {}) |
| 146 | + if labels: |
| 147 | + params = {str(k): ("" if v is None else str(v)) for k, v in labels.items()} |
| 148 | + _write_json(run_dir / PARAMETERS_FILE, params) |
| 149 | + |
| 150 | + written += 1 |
| 151 | + |
| 152 | + result: dict[str, Any] = { |
| 153 | + "status": "success", |
| 154 | + "tests_processed": written, |
| 155 | + "total_tests": len(tests), |
| 156 | + } |
| 157 | + if warnings: |
| 158 | + result["warnings"] = warnings |
| 159 | + for w in warnings: |
| 160 | + logger.warning("kpis-to-metrics: %s", w) |
| 161 | + |
| 162 | + logger.info( |
| 163 | + "Generated metrics.json for %d/%d test(s) from %s", |
| 164 | + written, |
| 165 | + len(tests), |
| 166 | + kpis_json_path.name, |
| 167 | + ) |
| 168 | + return result |
0 commit comments