# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-a-speculative-branch-on-a-litmus-derived-reward-that-the-safety-verifier-cannot-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-a-speculative-branch-on-a-litmus-derived-reward-that-the-safety-verifier-cannot-re-derive.warrant.json
# Markdown SHA-256:   409dd34ee04870aade9992e24ac10c2ddc58f52afd35d50d5ba459543864d587
# Code AST SHA-256:   6ac94d08323149fddf181bc9468d1b98cbd8e0566663f2e26954dcf76d77b382
# Verified Classes:   CoverageDominanceViolation, BranchRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CoverageDominanceViolation(RuntimeError):
    """Raised when a prune would drop a branch whose probe-coverage is not
    dominated by any retained branch, under a verifier that cannot reconstruct
    the branch's transient probe transcript."""
    pass


@dataclass(frozen=True)
class BranchRecord:
    branch_id: str
    final_action: str
    tool_call_multiset: FrozenSet[str]
    litmus_reward: float
    probe_set_version: str
    persisted_probe_transcript: bool


def coverage_signature(branch: BranchRecord, probe_set_version: str) -> FrozenSet[str]:
    """Applicable probes derived from the tool-call multiset, NOT the final action.
    A branch that read ssn_hash is PII-probe-applicable even if it ended on an
    export action shared with other branches."""
    if branch.probe_set_version != probe_set_version:
        raise CoverageDominanceViolation(
            f"probe-set version drift on {branch.branch_id}: "
            f"record={branch.probe_set_version} active={probe_set_version}"
        )
    applicable = set()
    for call in branch.tool_call_multiset:
        if "ssn_hash" in call or "email" in call:
            applicable.add("pii_egress")
        if call.startswith("write_") or call.startswith("delete_"):
            applicable.add("destructive_write")
        if "scope=" in call and "read_only" not in call:
            applicable.add("scope_escalation")
    return frozenset(applicable)


def efficiency_prune(
    candidates: list[BranchRecord],
    retained: list[BranchRecord],
    probe_set_version: str,
    prune_threshold: float = 0.55,
) -> list[str]:
    """Returns branch_ids safe to prune for efficiency. Raises if a low-reward
    branch is coverage-unique and the verifier cannot reconstruct its transcript."""
    retained_cov = [
        coverage_signature(b, probe_set_version) for b in retained
    ]
    pruned = []
    for b in candidates:
        if b.litmus_reward >= prune_threshold:
            continue
        cov = coverage_signature(b, probe_set_version)
        dominated = any(cov <= rc for rc in retained_cov)
        if dominated:
            pruned.append(b.branch_id)
            continue
        if not b.persisted_probe_transcript:
            raise CoverageDominanceViolation(
                f"branch {b.branch_id} is coverage-unique {sorted(cov)} "
                f"with reward {b.litmus_reward:.2f} below threshold, but its "
                f"probe transcript was not persisted; verifier cannot establish "
                f"dominance and INSUFFICIENT_EVIDENCE must not be treated as pass"
            )
        # Transcript persisted: defer to coverage pass, not efficiency pass.
        raise CoverageDominanceViolation(
            f"branch {b.branch_id} coverage-unique {sorted(cov)}; "
            f"must be escalated to coverage prune pass with full verifier"
        )
    return pruned
