# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-to-benchmark-correlation-as-a-causal-claim-rather-than-an-observational-join.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-to-benchmark-correlation-as-a-causal-claim-rather-than-an-observational-join.warrant.json
# Markdown SHA-256:   594b270f1cac798b93d595e328852359700f2e41754ef067290650b3d8e7d160
# Code AST SHA-256:   1099213ef9884faabae9d275e4a0da511da44682303cc63684e88e3e030e8877
# Verified Classes:   RegimeMismatchError, JoinRow, ValidityProof
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class RegimeMismatchError(RuntimeError):
    """Raised when a trace-to-benchmark join cannot support causal attribution."""


@dataclass
class JoinRow:
    item_id: str
    config_hash: str
    attempt_index: int | None
    sampler_decision: Literal["kept", "dropped"] | None
    sampler_weight: float | None
    prompt_version: str | None
    index_snapshot: str | None


@dataclass
class ValidityProof:
    attempt_identity: bool = False
    sampling_independence: bool = False
    hash_completeness: bool = False
    population_closure: bool = False
    unverified: list[str] = field(default_factory=list)


def validate_join(rows: list[JoinRow], coverage: float) -> ValidityProof:
    proof = ValidityProof()

    proof.attempt_identity = all(r.attempt_index is not None for r in rows)
    if not proof.attempt_identity:
        proof.unverified.append("attempt_identity")

    proof.sampling_independence = all(
        r.sampler_decision is not None and r.sampler_weight is not None
        for r in rows
    )
    if not proof.sampling_independence:
        proof.unverified.append("sampling_independence")

    proof.hash_completeness = all(
        r.prompt_version is not None and r.index_snapshot is not None
        for r in rows
    )
    if not proof.hash_completeness:
        proof.unverified.append("hash_completeness")

    proof.population_closure = coverage >= 0.999
    if not proof.population_closure:
        proof.unverified.append("population_closure")

    if not proof.attempt_identity:
        # Retry asymmetry alone can flip the sign of the association;
        # halt rather than emit an unlabeled correlation table.
        raise RegimeMismatchError(
            "attempt_index missing: retry dedup makes 'span present' "
            "enriched in already-failed items; correlation is a selection effect"
        )

    if not proof.hash_completeness:
        raise RegimeMismatchError(
            "config_hash omits prompt_version/index_snapshot: "
            "collisions collapse distinct regimes into one join key"
        )

    if not proof.sampling_independence:
        raise RegimeMismatchError(
            "head-based sampler without per-span weight: trace length "
            "correlates with outcome (refusals are short), biasing the join"
        )

    if not proof.population_closure:
        raise RegimeMismatchError(
            f"join coverage {coverage:.3f} < 1.0 without MAR proof: "
            "missing items cannot be assumed missing at random"
        )

    return proof
