|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from dataclasses import asdict, dataclass |
| 5 | +from pathlib import Path |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from src.validation.admissibility_scorer import AdmissibilityScorer |
| 9 | +from src.validation.contract_validator import ContractValidator |
| 10 | + |
| 11 | + |
| 12 | +@dataclass(frozen=True, slots=True) |
| 13 | +class FixtureScorePoint: |
| 14 | + fixture_id: str |
| 15 | + fixture_version: str |
| 16 | + fixture_path: str |
| 17 | + expected_admissible: bool |
| 18 | + observed_admissible: bool |
| 19 | + structural_score: float |
| 20 | + relational_score: float |
| 21 | + operational_score: float |
| 22 | + governance_score: float |
| 23 | + overall_admissibility_score: float |
| 24 | + passed_contracts: tuple[str, ...] |
| 25 | + failed_contracts: tuple[str, ...] |
| 26 | + failure_labels: tuple[str, ...] |
| 27 | + |
| 28 | + |
| 29 | +@dataclass(frozen=True, slots=True) |
| 30 | +class DegradationCurve: |
| 31 | + curve_id: str |
| 32 | + version: str |
| 33 | + generated_by: str |
| 34 | + points: tuple[FixtureScorePoint, ...] |
| 35 | + |
| 36 | + |
| 37 | +class DegradationCurveGenerator: |
| 38 | + VERSION = "1.0" |
| 39 | + |
| 40 | + def _load_json(self, path: Path) -> dict[str, Any]: |
| 41 | + if not path.exists(): |
| 42 | + raise FileNotFoundError(f"missing required fixture file: {path}") |
| 43 | + return json.loads(path.read_text(encoding="utf-8")) |
| 44 | + |
| 45 | + def _fixture_version(self, fixture_path: Path, expected_admissibility: dict[str, Any]) -> str: |
| 46 | + if "fixture_version" not in expected_admissibility: |
| 47 | + raise ValueError(f"missing fixture_version in {fixture_path / 'expected/admissibility.json'}") |
| 48 | + return str(expected_admissibility["fixture_version"]) |
| 49 | + |
| 50 | + def _validate_expected_failures( |
| 51 | + self, |
| 52 | + fixture_path: Path, |
| 53 | + expected_failures_payload: dict[str, Any], |
| 54 | + observed_failure_labels: tuple[str, ...], |
| 55 | + ) -> None: |
| 56 | + expected = set(expected_failures_payload.get("expected_failures", [])) |
| 57 | + disallowed = set(expected_failures_payload.get("disallowed_failures", [])) |
| 58 | + observed = set(observed_failure_labels) |
| 59 | + |
| 60 | + missing_expected = sorted(expected - observed) |
| 61 | + if missing_expected: |
| 62 | + raise ValueError(f"missing expected failure labels for {fixture_path}: {missing_expected}") |
| 63 | + |
| 64 | + emitted_disallowed = sorted(disallowed & observed) |
| 65 | + if emitted_disallowed: |
| 66 | + raise ValueError(f"emitted disallowed failure labels for {fixture_path}: {emitted_disallowed}") |
| 67 | + |
| 68 | + def evaluate_fixture(self, fixture_path: Path) -> FixtureScorePoint: |
| 69 | + original = { |
| 70 | + **self._load_json(fixture_path / "original/trace.json"), |
| 71 | + **self._load_json(fixture_path / "original/state.json"), |
| 72 | + "dependency_graph": self._load_json(fixture_path / "original/dependency_graph.json"), |
| 73 | + } |
| 74 | + reconstructed = { |
| 75 | + **self._load_json(fixture_path / "reconstructed/trace.json"), |
| 76 | + **self._load_json(fixture_path / "reconstructed/state.json"), |
| 77 | + "dependency_graph": self._load_json(fixture_path / "reconstructed/dependency_graph.json"), |
| 78 | + } |
| 79 | + contracts_dir = fixture_path / "original/contracts" |
| 80 | + contracts = [self._load_json(contract_path) for contract_path in sorted(contracts_dir.glob("*.json"))] |
| 81 | + if not contracts: |
| 82 | + raise FileNotFoundError(f"no contract files found in fixture: {contracts_dir}") |
| 83 | + |
| 84 | + expected_admissibility = self._load_json(fixture_path / "expected/admissibility.json") |
| 85 | + expected_admissible = bool(expected_admissibility["expected_admissible"]) |
| 86 | + fixture_version = self._fixture_version(fixture_path, expected_admissibility) |
| 87 | + expected_failures = self._load_json(fixture_path / "expected/failures.json") |
| 88 | + |
| 89 | + results = ContractValidator().validate_contracts(original=original, reconstructed=reconstructed, contracts=contracts) |
| 90 | + score = AdmissibilityScorer().score(results, expected_admissible=expected_admissible) |
| 91 | + self._validate_expected_failures(fixture_path, expected_failures, score.failure_labels) |
| 92 | + |
| 93 | + return FixtureScorePoint( |
| 94 | + fixture_id=fixture_path.name, |
| 95 | + fixture_version=fixture_version, |
| 96 | + fixture_path=fixture_path.as_posix(), |
| 97 | + expected_admissible=score.expected_admissible, |
| 98 | + observed_admissible=score.observed_admissible, |
| 99 | + structural_score=score.structural_score, |
| 100 | + relational_score=score.relational_score, |
| 101 | + operational_score=score.operational_score, |
| 102 | + governance_score=score.governance_score, |
| 103 | + overall_admissibility_score=score.overall_admissibility_score, |
| 104 | + passed_contracts=tuple(sorted(score.passed_contracts)), |
| 105 | + failed_contracts=tuple(sorted(score.failed_contracts)), |
| 106 | + failure_labels=tuple(sorted(score.failure_labels)), |
| 107 | + ) |
| 108 | + |
| 109 | + def generate(self, fixtures: list[Path], curve_id: str) -> DegradationCurve: |
| 110 | + points = tuple(self.evaluate_fixture(path) for path in fixtures) |
| 111 | + return DegradationCurve(curve_id=curve_id, version=self.VERSION, generated_by=self.__class__.__name__, points=points) |
| 112 | + |
| 113 | + def to_dict(self, curve: DegradationCurve) -> dict[str, object]: |
| 114 | + return { |
| 115 | + "curve_id": curve.curve_id, |
| 116 | + "version": curve.version, |
| 117 | + "generated_by": curve.generated_by, |
| 118 | + "points": [ |
| 119 | + { |
| 120 | + **asdict(point), |
| 121 | + "passed_contracts": list(point.passed_contracts), |
| 122 | + "failed_contracts": list(point.failed_contracts), |
| 123 | + "failure_labels": list(point.failure_labels), |
| 124 | + } |
| 125 | + for point in curve.points |
| 126 | + ], |
| 127 | + } |
| 128 | + |
| 129 | + def write_json(self, curve: DegradationCurve, output_path: Path) -> None: |
| 130 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 131 | + output_path.write_text(json.dumps(self.to_dict(curve), indent=2, sort_keys=True) + "\n", encoding="utf-8") |
| 132 | + |
| 133 | + def write_markdown(self, curve: DegradationCurve, output_path: Path) -> None: |
| 134 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 135 | + rows = [] |
| 136 | + for point in curve.points: |
| 137 | + labels = ", ".join(point.failure_labels) if point.failure_labels else "none" |
| 138 | + rows.append( |
| 139 | + f"| {point.fixture_id} | {str(point.expected_admissible).lower()} | {str(point.observed_admissible).lower()} | " |
| 140 | + f"{point.structural_score:.3f} | {point.relational_score:.3f} | {point.operational_score:.3f} | " |
| 141 | + f"{point.governance_score:.3f} | {point.overall_admissibility_score:.3f} | {labels} |" |
| 142 | + ) |
| 143 | + |
| 144 | + markdown = "\n".join( |
| 145 | + [ |
| 146 | + "# Layered Admissibility Degradation Benchmark", |
| 147 | + "", |
| 148 | + "## Purpose", |
| 149 | + "", |
| 150 | + "Deterministically compare admissibility outcomes across fixture bundles using ContractValidator and AdmissibilityScorer.", |
| 151 | + "", |
| 152 | + "## Fixture results", |
| 153 | + "", |
| 154 | + "| fixture_id | expected_admissible | observed_admissible | structural_score | relational_score | operational_score | governance_score | overall_admissibility_score | failure_labels |", |
| 155 | + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |", |
| 156 | + *rows, |
| 157 | + "", |
| 158 | + "## Interpretation", |
| 159 | + "", |
| 160 | + "The positive fixture remains fully admissible while the degraded fixture shows deterministic score loss and explicit failure labels.", |
| 161 | + "", |
| 162 | + "## Non-goals", |
| 163 | + "", |
| 164 | + "- no LLM judges", |
| 165 | + "- no embeddings", |
| 166 | + "- no fuzzy matching", |
| 167 | + "- no semantic equivalence", |
| 168 | + "", |
| 169 | + "## Future", |
| 170 | + "", |
| 171 | + "- add more fixture families", |
| 172 | + "- add progressive degradation levels", |
| 173 | + "- add SVG curve visualization later", |
| 174 | + "", |
| 175 | + ] |
| 176 | + ) |
| 177 | + output_path.write_text(markdown, encoding="utf-8") |
0 commit comments