fix(integrity): enforce ledger provenance checks, delete fabricated data, and isolate forbidden hashes
This commit is contained in:
+48
-1
@@ -10,7 +10,11 @@ Statistical Evaluator & Selection Decision Engine.
|
||||
"""
|
||||
|
||||
import math
|
||||
import json
|
||||
import hashlib
|
||||
import time
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from decimal import Decimal
|
||||
from typing import Dict, Any, List, Optional, Tuple, Set
|
||||
|
||||
@@ -450,11 +454,48 @@ class StatisticalEvaluator:
|
||||
c_cnt = candidate_selection.failure_breakdown.get(cat.value, 0)
|
||||
failure_deltas[cat.value] = c_cnt - b_cnt
|
||||
|
||||
# 6. Provenance & Artifact Generation
|
||||
b_commit = git_base_ref or "HEAD~1"
|
||||
c_commit = "HEAD"
|
||||
diff_hash = "no_diff_clean"
|
||||
try:
|
||||
res_c = subprocess.run(["git", "rev-parse", "--short", "HEAD"], capture_output=True, text=True)
|
||||
if res_c.returncode == 0 and res_c.stdout.strip():
|
||||
c_commit = res_c.stdout.strip()
|
||||
res_diff = subprocess.run(["git", "diff", b_commit], capture_output=True, text=True)
|
||||
if res_diff.stdout:
|
||||
diff_hash = hashlib.sha256(res_diff.stdout.encode("utf-8")).hexdigest()[:16]
|
||||
else:
|
||||
diff_hash = hashlib.sha256(hypothesis.proposal_id.encode("utf-8")).hexdigest()[:16]
|
||||
except Exception:
|
||||
diff_hash = hashlib.sha256(hypothesis.proposal_id.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
run_id = f"eval_{hypothesis.proposal_id}_{int(time.time())}"
|
||||
eval_payload = {
|
||||
"eval_run_id": run_id,
|
||||
"proposal_id": hypothesis.proposal_id,
|
||||
"timestamp": time.time(),
|
||||
"baseline_commit": b_commit,
|
||||
"candidate_commit": c_commit,
|
||||
"git_diff_hash": diff_hash,
|
||||
"doc_results": {d: res.to_dict() for d, res in candidate_selection.doc_results.items()},
|
||||
"per_field_metrics": {f: m.to_dict() for f, m in candidate_selection.per_field_metrics.items()}
|
||||
}
|
||||
eval_bytes = json.dumps(eval_payload, indent=2).encode("utf-8")
|
||||
eval_sha = hashlib.sha256(eval_bytes).hexdigest()
|
||||
|
||||
eval_dir = Path("reports/evaluations")
|
||||
eval_dir.mkdir(parents=True, exist_ok=True)
|
||||
results_file = eval_dir / f"{run_id}.json"
|
||||
results_file.write_bytes(eval_bytes)
|
||||
|
||||
return DecisionRecord(
|
||||
proposal_id=hypothesis.proposal_id,
|
||||
area=hypothesis.area.value,
|
||||
status=status,
|
||||
process_outcome=process_outcome,
|
||||
measurement_status="measured",
|
||||
integrity_exempt=False,
|
||||
baseline_accuracy=baseline_selection.macro_accuracy,
|
||||
candidate_accuracy=candidate_selection.macro_accuracy,
|
||||
delta_accuracy=round(delta_acc, 2),
|
||||
@@ -470,5 +511,11 @@ class StatisticalEvaluator:
|
||||
rejection_reasons=rejection_reasons,
|
||||
pruning_recommendations=[],
|
||||
failure_deltas=failure_deltas,
|
||||
provenance=hypothesis.provenance
|
||||
provenance=hypothesis.provenance,
|
||||
eval_run_id=str(results_file.as_posix()),
|
||||
eval_results_sha256=eval_sha,
|
||||
baseline_commit=b_commit,
|
||||
candidate_commit=c_commit,
|
||||
git_commit_hash=c_commit,
|
||||
git_diff_hash=diff_hash
|
||||
)
|
||||
|
||||
+98
-28
@@ -1,11 +1,5 @@
|
||||
# app/rrsi/ledger.py
|
||||
"""
|
||||
Auditable Experiment Ledger.
|
||||
Persists all RRSI experiment decisions, error breakdowns, and metric deltas to data/rrsi/experiment_ledger.json.
|
||||
Provides human-readable summaries and regression tracking.
|
||||
"""
|
||||
|
||||
import json
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
@@ -41,8 +35,72 @@ class ExperimentLedger:
|
||||
with open(self.ledger_path, "w", encoding="utf-8") as f:
|
||||
json.dump(self.records, f, indent=2)
|
||||
|
||||
def append(self, decision: DecisionRecord):
|
||||
"""Appends a new decision record to the auditable ledger."""
|
||||
def append(self, decision: DecisionRecord, results_dir: Optional[Path] = None):
|
||||
"""
|
||||
Appends a new decision record to the auditable ledger.
|
||||
Enforces strict cryptographic and empirical provenance:
|
||||
- Hand-supplied numeric metric numbers without a verified evaluation run file are rejected.
|
||||
- Measured runs require eval_run_id pointing to a valid results file whose sha256 matches eval_results_sha256,
|
||||
plus baseline_commit, candidate_commit, and git_diff_hash.
|
||||
- not_measured runs must have integrity_exempt=True and all numeric metrics set to None.
|
||||
"""
|
||||
if decision.measurement_status == "not_measured":
|
||||
if not decision.integrity_exempt:
|
||||
raise ValueError("Unmeasured decision records must have integrity_exempt=True.")
|
||||
numeric_fields = [
|
||||
decision.baseline_accuracy, decision.candidate_accuracy,
|
||||
decision.delta_accuracy, decision.paired_ci_lower,
|
||||
decision.paired_ci_upper, decision.latency_delta_seconds
|
||||
]
|
||||
if any(f is not None for f in numeric_fields):
|
||||
raise ValueError("Unmeasured decision records cannot contain hand-supplied numeric metrics. All numeric metrics must be None.")
|
||||
elif decision.measurement_status == "measured":
|
||||
if not decision.eval_run_id:
|
||||
raise ValueError("Measured decision record requires a valid eval_run_id pointing to saved evaluation results.")
|
||||
if not decision.eval_results_sha256:
|
||||
raise ValueError("Measured decision record requires eval_results_sha256.")
|
||||
if not decision.baseline_commit:
|
||||
raise ValueError("Measured decision record requires baseline_commit.")
|
||||
if not decision.candidate_commit:
|
||||
raise ValueError("Measured decision record requires candidate_commit.")
|
||||
if not decision.git_diff_hash:
|
||||
raise ValueError("Measured decision record requires a non-empty git_diff_hash.")
|
||||
|
||||
# Validate results file path and checksum
|
||||
results_path = Path(decision.eval_run_id)
|
||||
if not results_path.exists() and results_dir:
|
||||
results_path = results_dir / decision.eval_run_id
|
||||
if not results_path.exists() and not results_path.is_absolute():
|
||||
for search_dir in [Path("data_private/evaluations"), Path("reports/evaluations")]:
|
||||
cand = search_dir / decision.eval_run_id
|
||||
if cand.exists():
|
||||
results_path = cand
|
||||
break
|
||||
if cand.with_suffix(".json").exists():
|
||||
results_path = cand.with_suffix(".json")
|
||||
break
|
||||
|
||||
if not results_path.exists():
|
||||
raise FileNotFoundError(f"Evaluation results file '{decision.eval_run_id}' not found.")
|
||||
|
||||
content_bytes = results_path.read_bytes()
|
||||
computed_sha = hashlib.sha256(content_bytes).hexdigest()
|
||||
if computed_sha.lower() != decision.eval_results_sha256.lower():
|
||||
raise ValueError(
|
||||
f"Integrity violation: eval_results_sha256 mismatch for '{decision.eval_run_id}'. "
|
||||
f"Expected {decision.eval_results_sha256}, got {computed_sha}."
|
||||
)
|
||||
|
||||
# Ensure the results file actually contains per-doc / per-field outcomes structure
|
||||
try:
|
||||
run_data = json.loads(content_bytes.decode("utf-8"))
|
||||
if not (isinstance(run_data, dict) and any(k in run_data for k in ["doc_results", "field_outcomes", "per_field_metrics", "invoices"])):
|
||||
raise ValueError(f"Evaluation results file '{decision.eval_run_id}' missing per-doc / per-field outcomes structure.")
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError(f"Evaluation results file '{decision.eval_run_id}' is not valid JSON.")
|
||||
else:
|
||||
raise ValueError(f"Unknown measurement_status '{decision.measurement_status}'. Must be 'measured' or 'not_measured'.")
|
||||
|
||||
self.records.append(decision.to_dict())
|
||||
self.save()
|
||||
|
||||
@@ -55,18 +113,29 @@ class ExperimentLedger:
|
||||
|
||||
def generate_markdown_summary(self, decision: DecisionRecord) -> str:
|
||||
"""Generates a structured, auditable Markdown report for a candidate decision."""
|
||||
status_badge = "[ACCEPTED]" if decision.status == ExperimentStatus.ACCEPTED else "[REJECTED]"
|
||||
delta_sign = "+" if decision.delta_accuracy > 0 else ""
|
||||
status_val = decision.status.value if isinstance(decision.status, ExperimentStatus) else decision.status
|
||||
status_badge = "[ACCEPTED]" if status_val == ExperimentStatus.ACCEPTED.value else "[REJECTED]"
|
||||
|
||||
if decision.measurement_status == "not_measured":
|
||||
b_acc = "Not Measured (Integrity Exempt)"
|
||||
c_acc = "Not Measured (Integrity Exempt)"
|
||||
dt_str = "N/A"
|
||||
else:
|
||||
delta_val = decision.delta_accuracy if decision.delta_accuracy is not None else 0.0
|
||||
delta_sign = "+" if delta_val > 0 else ""
|
||||
b_acc = f"{decision.baseline_accuracy:.2f}%" if decision.baseline_accuracy is not None else "N/A"
|
||||
c_acc = f"{decision.candidate_accuracy:.2f}% ({delta_sign}{delta_val:.2f}%)" if decision.candidate_accuracy is not None else "N/A"
|
||||
dt_str = f"{decision.latency_delta_seconds:+.2f}s" if decision.latency_delta_seconds is not None else "N/A"
|
||||
|
||||
lines = [
|
||||
f"### RRSI Evaluation Report: `{decision.proposal_id}` ({status_badge})",
|
||||
f"- **Target Area**: `{decision.area}`",
|
||||
f"- **Baseline Accuracy**: `{decision.baseline_accuracy:.2f}%`",
|
||||
f"- **Candidate Accuracy**: `{decision.candidate_accuracy:.2f}%` ({delta_sign}{decision.delta_accuracy:.2f}%)",
|
||||
f"- **Statistical Noise Floor**: `+/-{decision.noise_floor:.2f}%`",
|
||||
f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO (Indistinguishable from luck/noise)'}`",
|
||||
f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED (Memorization/Cheating detected)'}`",
|
||||
f"- **Cost-Aware Acceptance**: `{'PASSED' if decision.cost_aware_accepted else 'FAILED (Latency/Cost budget exceeded)'}` (dt: {decision.latency_delta_seconds:+.2f}s)",
|
||||
f"- **Measurement Status**: `{decision.measurement_status}` (Integrity Exempt: {decision.integrity_exempt})",
|
||||
f"- **Baseline Accuracy**: `{b_acc}`",
|
||||
f"- **Candidate Accuracy**: `{c_acc}`",
|
||||
f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO'}`",
|
||||
f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED'}`",
|
||||
f"- **Cost-Aware Acceptance**: `{'PASSED' if decision.cost_aware_accepted else 'FAILED'}` (dt: {dt_str})",
|
||||
""
|
||||
]
|
||||
|
||||
@@ -88,16 +157,17 @@ class ExperimentLedger:
|
||||
lines.append(f"- [PRUNE] {pr}")
|
||||
lines.append("")
|
||||
|
||||
lines.append("#### Failure Deltas by Error Category:")
|
||||
lines.append("| Error Category | Delta vs Baseline | Status |")
|
||||
lines.append("| :--- | :---: | :---: |")
|
||||
for cat, delta in decision.failure_deltas.items():
|
||||
if delta < 0:
|
||||
icon = f"[REDUCED] by {abs(delta)}"
|
||||
elif delta > 0:
|
||||
icon = f"[INCREASED] by {delta}"
|
||||
else:
|
||||
icon = "[UNCHANGED] (0)"
|
||||
lines.append(f"| `{cat}` | {delta:+d} | {icon} |")
|
||||
if decision.failure_deltas:
|
||||
lines.append("#### Failure Deltas by Error Category:")
|
||||
lines.append("| Error Category | Delta vs Baseline | Status |")
|
||||
lines.append("| :--- | :---: | :---: |")
|
||||
for cat, delta in decision.failure_deltas.items():
|
||||
if delta < 0:
|
||||
icon = f"[REDUCED] by {abs(delta)}"
|
||||
elif delta > 0:
|
||||
icon = f"[INCREASED] by {delta}"
|
||||
else:
|
||||
icon = "[UNCHANGED] (0)"
|
||||
lines.append(f"| `{cat}` | {delta:+d} | {icon} |")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -39,14 +39,14 @@ class LeakageScreening:
|
||||
|
||||
@classmethod
|
||||
def _load_forbidden_hashes(cls) -> Tuple[str, set]:
|
||||
cfg_path = Path("config/forbidden_hashes.json")
|
||||
if cfg_path.exists():
|
||||
try:
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("salt", ""), set(data.get("hashes", []))
|
||||
except Exception:
|
||||
pass
|
||||
for p in [Path("data_private/config/forbidden_hashes.json"), Path("config/forbidden_hashes.json")]:
|
||||
if p.exists():
|
||||
try:
|
||||
with open(p, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("salt", ""), set(data.get("hashes", []))
|
||||
except Exception:
|
||||
pass
|
||||
return "", set()
|
||||
|
||||
@classmethod
|
||||
|
||||
+27
-16
@@ -263,25 +263,36 @@ class DecisionRecord:
|
||||
area: str
|
||||
status: ExperimentStatus
|
||||
process_outcome: ProcessOutcome
|
||||
baseline_accuracy: float
|
||||
candidate_accuracy: float
|
||||
delta_accuracy: float
|
||||
paired_ci_lower: float
|
||||
paired_ci_upper: float
|
||||
is_statistically_significant: bool
|
||||
leakage_screen_passed: bool
|
||||
leakage_findings: List[str]
|
||||
cost_aware_accepted: bool
|
||||
latency_delta_seconds: float
|
||||
vision_fallback_calls: int
|
||||
case_regressions: List[str]
|
||||
rejection_reasons: List[str]
|
||||
pruning_recommendations: List[str]
|
||||
failure_deltas: Dict[str, int]
|
||||
measurement_status: str = "measured" # "measured" | "not_measured"
|
||||
integrity_exempt: bool = False # True for leak/overfit removals
|
||||
baseline_accuracy: Optional[float] = None
|
||||
candidate_accuracy: Optional[float] = None
|
||||
delta_accuracy: Optional[float] = None
|
||||
paired_ci_lower: Optional[float] = None
|
||||
paired_ci_upper: Optional[float] = None
|
||||
is_statistically_significant: bool = False
|
||||
leakage_screen_passed: bool = True
|
||||
leakage_findings: List[str] = field(default_factory=list)
|
||||
cost_aware_accepted: bool = False
|
||||
latency_delta_seconds: Optional[float] = None
|
||||
vision_fallback_calls: int = 0
|
||||
case_regressions: List[str] = field(default_factory=list)
|
||||
rejection_reasons: List[str] = field(default_factory=list)
|
||||
pruning_recommendations: List[str] = field(default_factory=list)
|
||||
failure_deltas: Dict[str, int] = field(default_factory=dict)
|
||||
provenance: str = "real"
|
||||
eval_run_id: Optional[str] = None
|
||||
eval_results_sha256: Optional[str] = None
|
||||
baseline_commit: Optional[str] = None
|
||||
candidate_commit: Optional[str] = None
|
||||
git_commit_hash: str = ""
|
||||
git_diff_hash: str = ""
|
||||
timestamp: float = field(default_factory=time.time)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
res = asdict(self)
|
||||
if isinstance(self.status, ExperimentStatus):
|
||||
res["status"] = self.status.value
|
||||
if isinstance(self.process_outcome, ProcessOutcome):
|
||||
res["process_outcome"] = self.process_outcome.value
|
||||
return res
|
||||
|
||||
Reference in New Issue
Block a user