# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-adversarial-probe-attribution-drift-from-silently-passing-a-regressed-agent-through-ci-gating.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-adversarial-probe-attribution-drift-from-silently-passing-a-regressed-agent-through-ci-gating.warrant.json
# Markdown SHA-256:   e456681cbff5e15431cdb03995cccbf2d167ca3303cbf6f4c65d624534eea627
# Code AST SHA-256:   eb91b33dc556e3b60ab368195bb229f67d9ac016dfe6bea760f9244a53a84b9f
# Verified Classes:   AttributionDriftError, RunManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AttributionDriftError(RuntimeError):
    """Raised when a LITMUS gate attempts to compare incomparable runs."""
    pass


@dataclass(frozen=True)
class RunManifest:
    probe_set_hash: str
    scorer_version: str
    rubric_hash: str
    seed_policy: str
    per_probe_outcomes: dict  # probe_id -> bool (passed)


def _tuple_hash(m: RunManifest) -> str:
    payload = json.dumps(
        {
            "probe_set_hash": m.probe_set_hash,
            "scorer_version": m.scorer_version,
            "rubric_hash": m.rubric_hash,
            "seed_policy": m.seed_policy,
        },
        sort_keys=True,
    ).encode()
    return hashlib.sha256(payload).hexdigest()


def gate(candidate: RunManifest, anchor: RunManifest, threshold_pp: float) -> str:
    # Invariant 1: experiment identity must hold before any delta is computed.
    if _tuple_hash(candidate) != _tuple_hash(anchor):
        # Do NOT compute a delta. Force re-baseline.
        return "REBASELINED"

    # Invariant 2: score only the probe-ID intersection so additions are inert.
    common = set(candidate.per_probe_outcomes) & set(anchor.per_probe_outcomes)
    if not common:
        raise AttributionDriftError(
            "No overlapping probe IDs between candidate and anchor; "
            "delta is undefined, not zero."
        )

    def rate(m: RunManifest) -> float:
        hits = sum(1 for pid in common if m.per_probe_outcomes[pid])
        return hits / len(common)

    delta_pp = (rate(candidate) - rate(anchor)) * 100.0
    if delta_pp < -threshold_pp:
        return "FAIL"
    return "PASS"


def gate_with_category_guard(
    candidate: RunManifest,
    anchor: RunManifest,
    category_of: dict,  # probe_id -> category
    threshold_pp: float,
) -> str:
    if _tuple_hash(candidate) != _tuple_hash(anchor):
        return "REBASELINED"

    common = set(candidate.per_probe_outcomes) & set(anchor.per_probe_outcomes)
    if not common:
        raise AttributionDriftError("Empty probe intersection; refusing to gate.")

    # Per-category independent gating: aggregate improvement cannot mask a
    # category-level regression.
    by_cat: dict = {}
    for pid in common:
        by_cat.setdefault(category_of.get(pid, "uncategorized"), []).append(pid)

    for cat, pids in by_cat.items():
        c_rate = sum(1 for p in pids if candidate.per_probe_outcomes[p]) / len(pids)
        a_rate = sum(1 for p in pids if anchor.per_probe_outcomes[p]) / len(pids)
        if (c_rate - a_rate) * 100.0 < -threshold_pp:
            return "FAIL"

    return "PASS"


# Example trigger: probe regeneration invalidates the anchor.
anchor = RunManifest("a1b2", "scorer-3.1", "rubric-7", "temp=0.0", {"p1": True, "p2": False})
regen = RunManifest("c9d4", "scorer-3.1", "rubric-7", "temp=0.0", {"p1": True, "p2": True})

status = gate(regen, anchor, threshold_pp=2.0)
if status == "PASS":
    raise AttributionDriftError(
        "Gate passed across mismatched probe_set_hash; experiment identity "
        "was not enforced."
    )
assert status == "REBASELINED"
