# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-reputation-attestation-from-a-receipt-it-cannot-re-verify-the-verifier-side-non-reproducibility-gap-in-cros.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-reputation-attestation-from-a-receipt-it-cannot-re-verify-the-verifier-side-non-reproducibility-gap-in-cros.warrant.json
# Markdown SHA-256:   1d744681fe16fd69152ce6815c3882bb3f0d0d7b10be39e77b61df82bb11c3e5
# Code AST SHA-256:   3eaa29f96397175530800997e9f36511fbb9ce019583ec42b769c52f5fdbb5b0
# Verified Classes:   UnverifiableReceiptError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnverifiableReceiptError(RuntimeError):
    """Raised when a receipt cannot be deterministically re-derived by the verifier."""
    pass


REPLAY_DETERMINISTIC = "deterministic"
REPLAY_SEEDED = "seeded"
REPLAY_NONDETERMINISTIC = "nondeterministic"

VERDICT_PASS = "verified_pass"
VERDICT_FAIL = "verified_fail"
VERDICT_UNVERIFIABLE = "unverifiable"


def score_receipt(receipt: dict, verifier_manifest: dict) -> str:
    """
    Return a three-valued verdict for one receipt. Never coerce 'unverifiable'
    into pass or fail. Re-execution is stratified by replay_class.
    """
    replay_class = receipt.get("replay_class")
    if replay_class is None:
        raise UnverifiableReceiptError(
            f"receipt {receipt.get('id')} lacks replay_class; cannot stratify"
        )

    # Nondeterministic receipts must never be re-executed: entropy would
    # manufacture false failures. Signature-trust only.
    if replay_class == REPLAY_NONDETERMINISTIC:
        return VERDICT_UNVERIFIABLE

    receipt_manifest = receipt.get("manifest")
    if receipt_manifest != verifier_manifest:
        # Environment drift: this is a verifier-side mismatch, not an
        # executor failure. Must not be scored as fail.
        return VERDICT_UNVERIFIABLE

    if replay_class not in (REPLAY_DETERMINISTIC, REPLAY_SEEDED):
        raise UnverifiableReceiptError(
            f"unknown replay_class {replay_class!r} for receipt {receipt.get('id')}"
        )

    try:
        rederived = _reexecute(receipt, seed=receipt.get("seed"))
    except TimeoutError:
        # Conservative fallback: exclude, never optimistic-pass.
        return VERDICT_UNVERIFIABLE

    if rederived["output_hash"] == receipt["output_hash"]:
        return VERDICT_PASS
    return VERDICT_FAIL


def aggregate_reputation(receipts: list[dict], verifier_manifest: dict) -> dict:
    counts = {VERDICT_PASS: 0, VERDICT_FAIL: 0, VERDICT_UNVERIFIABLE: 0}
    for r in receipts:
        counts[score_receipt(r, verifier_manifest)] += 1

    decided = counts[VERDICT_PASS] + counts[VERDICT_FAIL]
    if decided == 0:
        raise UnverifiableReceiptError(
            "no receipts were re-derivable; reputation score is undefined, "
            "not 1.0 and not 0.0"
        )

    return {
        "rate": counts[VERDICT_PASS] / decided,
        "verified_coverage": decided / len(receipts),
        "unverifiable": counts[VERDICT_UNVERIFIABLE],
    }


def _reexecute(receipt: dict, seed) -> dict:
    # Placeholder for sandboxed re-execution against the pinned manifest.
    return {"output_hash": receipt["output_hash"]}
