|
| 1 | +"""CERC plan validation helpers. |
| 2 | +
|
| 3 | +This layer validates experiment plans without executing them. It checks for |
| 4 | +queue integrity, duplicate plan signatures, and whether the requested sampling |
| 5 | +is still needed. |
| 6 | +""" |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import hashlib |
| 10 | +import json |
| 11 | +from datetime import datetime |
| 12 | +from pathlib import Path |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +from causetrace.core import JSONStore |
| 16 | + |
| 17 | +from .constraints import validate_execution_queue |
| 18 | +from .experiment_planner import DEFAULT_PLAN_OUTPUT_DIR |
| 19 | +from .gap_analyzer import analyze_gaps |
| 20 | +from .subset_registry import SUBSET_DEFINITIONS |
| 21 | + |
| 22 | + |
| 23 | +DEFAULT_PLAN_VALIDATION_OUTPUT_DIR = Path.home() / ".causetrace" / "plan_validation" |
| 24 | + |
| 25 | + |
| 26 | +def _load_json(path: Path) -> dict[str, Any]: |
| 27 | + data = json.loads(path.read_text(encoding="utf-8")) |
| 28 | + if not isinstance(data, dict): |
| 29 | + raise ValueError(f"{path.name} must contain a JSON object") |
| 30 | + return data |
| 31 | + |
| 32 | + |
| 33 | +def _canonicalize_queue(queue: dict[str, Any]) -> dict[str, Any]: |
| 34 | + def _clean(value: Any) -> Any: |
| 35 | + if isinstance(value, dict): |
| 36 | + cleaned: dict[str, Any] = {} |
| 37 | + for key, item in value.items(): |
| 38 | + if key in {"experiment_id", "generated_at", "output_dir", "queue_hash", "validation"}: |
| 39 | + continue |
| 40 | + cleaned[key] = _clean(item) |
| 41 | + return cleaned |
| 42 | + if isinstance(value, list): |
| 43 | + return [_clean(item) for item in value] |
| 44 | + return value |
| 45 | + |
| 46 | + return _clean(queue) |
| 47 | + |
| 48 | + |
| 49 | +def _queue_signature(queue: dict[str, Any]) -> str: |
| 50 | + canonical = _canonicalize_queue(queue) |
| 51 | + encoded = json.dumps(canonical, sort_keys=True, separators=(",", ":")) |
| 52 | + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() |
| 53 | + |
| 54 | + |
| 55 | +def _scan_duplicate_plans(plan_root: Path, signature: str, current_plan_dir: Path) -> list[str]: |
| 56 | + duplicates: list[str] = [] |
| 57 | + if not plan_root.exists(): |
| 58 | + return duplicates |
| 59 | + for queue_path in plan_root.rglob("experiment_queue.json"): |
| 60 | + if queue_path.parent == current_plan_dir: |
| 61 | + continue |
| 62 | + try: |
| 63 | + queue = _load_json(queue_path) |
| 64 | + except Exception: |
| 65 | + continue |
| 66 | + if _queue_signature(queue) == signature: |
| 67 | + duplicates.append(str(queue_path.parent)) |
| 68 | + return sorted(duplicates) |
| 69 | + |
| 70 | + |
| 71 | +def validate_experiment_plan( |
| 72 | + store: JSONStore, |
| 73 | + *, |
| 74 | + plan_dir: str | Path, |
| 75 | + output_dir: str | Path | None = None, |
| 76 | + write: bool = True, |
| 77 | +) -> dict[str, Any]: |
| 78 | + """Validate an experiment plan without executing it.""" |
| 79 | + plan_path = Path(plan_dir) |
| 80 | + queue_path = plan_path / "experiment_queue.json" |
| 81 | + gap_path = plan_path / "gap_report.json" |
| 82 | + if not queue_path.exists(): |
| 83 | + raise FileNotFoundError(f"missing plan queue: {queue_path}") |
| 84 | + |
| 85 | + queue = _load_json(queue_path) |
| 86 | + gap_report = _load_json(gap_path) if gap_path.exists() else {} |
| 87 | + target_subset = str(queue.get("target_subset") or gap_report.get("target_subset") or "unknown") |
| 88 | + if target_subset in SUBSET_DEFINITIONS: |
| 89 | + current_gap = analyze_gaps(store, subset_ids=[target_subset])["subset_gaps"][0] |
| 90 | + else: |
| 91 | + current_gap = None |
| 92 | + |
| 93 | + constraint_check = validate_execution_queue(queue) |
| 94 | + signature = _queue_signature(queue) |
| 95 | + plan_root = plan_path.parent if plan_path.parent != plan_path else DEFAULT_PLAN_OUTPUT_DIR |
| 96 | + duplicate_plans = _scan_duplicate_plans(plan_root, signature, plan_path) |
| 97 | + required_sessions = int(queue.get("required_sessions", 0) or 0) |
| 98 | + missing_sessions = int((current_gap or {}).get("missing_sessions", required_sessions)) |
| 99 | + needed = missing_sessions > 0 and required_sessions > 0 |
| 100 | + valid = constraint_check["ok"] and not duplicate_plans and needed |
| 101 | + |
| 102 | + report: dict[str, Any] = { |
| 103 | + "schema": "causetrace.cerc.plan_validation.v0.1", |
| 104 | + "generated_at": datetime.now().isoformat(), |
| 105 | + "plan_dir": str(plan_path), |
| 106 | + "target_subset": target_subset, |
| 107 | + "required_sessions": required_sessions, |
| 108 | + "current_gap": current_gap, |
| 109 | + "gap_report": gap_report, |
| 110 | + "queue_signature": signature, |
| 111 | + "duplicate_plans": duplicate_plans, |
| 112 | + "constraint_check": constraint_check, |
| 113 | + "necessity": { |
| 114 | + "missing_sessions": missing_sessions, |
| 115 | + "sampling_needed": needed, |
| 116 | + }, |
| 117 | + "validation": { |
| 118 | + "ok": valid, |
| 119 | + "status": "ready" if valid else ("duplicate" if duplicate_plans else "not_needed"), |
| 120 | + }, |
| 121 | + "constraints": { |
| 122 | + "external_only": True, |
| 123 | + "no_execution": True, |
| 124 | + "no_evidence_inflation": True, |
| 125 | + "no_phase4_grade_promotion": True, |
| 126 | + }, |
| 127 | + } |
| 128 | + |
| 129 | + if write: |
| 130 | + root = Path(output_dir) if output_dir else DEFAULT_PLAN_VALIDATION_OUTPUT_DIR |
| 131 | + run_dir = root / plan_path.name |
| 132 | + run_dir.mkdir(parents=True, exist_ok=True) |
| 133 | + (run_dir / "plan_validation.json").write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8") |
| 134 | + (run_dir / "plan_validation.md").write_text( |
| 135 | + "\n".join([ |
| 136 | + f"# Plan validation: {plan_path.name}", |
| 137 | + "", |
| 138 | + f"- target subset: `{target_subset}`", |
| 139 | + f"- required sessions: `{required_sessions}`", |
| 140 | + f"- missing sessions: `{missing_sessions}`", |
| 141 | + f"- sampling needed: `{needed}`", |
| 142 | + f"- duplicate plans: `{len(duplicate_plans)}`", |
| 143 | + f"- validation ok: `{valid}`", |
| 144 | + f"- queue signature: `{signature}`", |
| 145 | + "", |
| 146 | + "## Safety Boundary", |
| 147 | + "", |
| 148 | + "Plan validation is read-only. It does not execute runtimes, alter evidence grades, or emit commands.", |
| 149 | + ]) |
| 150 | + + "\n", |
| 151 | + encoding="utf-8", |
| 152 | + ) |
| 153 | + report["output_dir"] = str(run_dir) |
| 154 | + else: |
| 155 | + report["output_dir"] = None |
| 156 | + |
| 157 | + return report |
0 commit comments