# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-refusal-consistency-scores-as-non-comparable-across-elicitation-batches.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-refusal-consistency-scores-as-non-comparable-across-elicitation-batches.warrant.json
# Markdown SHA-256:   b070c3f10eefe6ad523e3ac08077cab78818d9980d5bbc07208d6f61f62f6e48
# Code AST SHA-256:   46cfdd1315ebd4b959628d079cd5c8bb08dcd3e57c744a59d6978d5e4cb3e007
# Verified Classes:   NonComparableScoreError, BatchCertificate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Sequence


class NonComparableScoreError(RuntimeError):
    """Raised when a LITMUS refusal-consistency score is promoted to a
    comparable/poolable metric without satisfying the four validity conditions."""
    pass


@dataclass
class BatchCertificate:
    batch_id: str
    order_delta: float                 # |score(orderA) - score(orderB)|
    preamble_persistence: float        # fraction of scenarios with preamble in attended ctx
    untagged_tool_persistence: int     # count of tool outputs not scoped to scenario
    batch_length: int
    score: float
    orderings: Sequence[str] = field(default_factory=tuple)

    def comparability(self) -> str:
        if (self.untagged_tool_persistence > 0
                or self.preamble_persistence < 0.90
                or self.order_delta > 0.10):
            return "local"
        if self.order_delta > 0.05 or len(set(self.orderings)) < 2:
            return "hold"
        return "comparable"


def promote_score(cert: BatchCertificate, pool: list[float]) -> float:
    """Attempt to pool a batch score into an aggregate. Refuses on non-comparable input."""
    verdict = cert.comparability()
    if verdict != "comparable":
        raise NonComparableScoreError(
            f"batch {cert.batch_id} scored {cert.score:.3f} but is {verdict}: "
            f"order_delta={cert.order_delta:.3f}, "
            f"preamble_persistence={cert.preamble_persistence:.2f}, "
            f"untagged_tool_persistence={cert.untagged_tool_persistence}, "
            f"orderings={list(cert.orderings)}. "
            f"Report as local observation; do not pool."
        )
    pool.append(cert.score)
    return sum(pool) / len(pool)


def certificate_digest(cert: BatchCertificate) -> str:
    h = hashlib.sha256()
    h.update(repr((cert.batch_id, cert.order_delta, cert.preamble_persistence,
                   cert.untagged_tool_persistence, cert.batch_length, cert.score)).encode())
    return h.hexdigest()[:16]


if __name__ == "__main__":
    # Reproduces the observed failure: same scenarios, two orderings, 0.17 gap.
    bad = BatchCertificate(
        batch_id="A-vs-B",
        order_delta=0.17,
        preamble_persistence=0.84,
        untagged_tool_persistence=1,
        batch_length=40,
        score=0.91,
        orderings=("escalation", "shuffled"),
    )
    try:
        promote_score(bad, pool=[])
    except NonComparableScoreError as e:
        print(f"REFUSED: {e}")
