# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-a-safety-verdict-and-the-reasoning-span-that-produced-it-when-traces-are-sampled-independently-of-eva.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-a-safety-verdict-and-the-reasoning-span-that-produced-it-when-traces-are-sampled-independently-of-eva.warrant.json
# Markdown SHA-256:   c3eada3dace7ff86a7f9fd3daecd7ae354113df65ea0b32d73578f2489d3e422
# Code AST SHA-256:   63d1070ff614f572df503afead2f91da074b73582aa99c6dc543aac7909d0927
# Verified Classes:   CorrelationContinuityError, Verdict, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CorrelationContinuityError(RuntimeError):
    """Raised when a safety verdict cannot be soundly bound to a reasoning span."""
    pass


@dataclass(frozen=True)
class Verdict:
    correlation_id: str
    evidence: str          # exact output text the classifier scored
    label: str


@dataclass(frozen=True)
class Span:
    correlation_id: str    # inherited from ingress baggage, never derived
    output: str
    parent_is_root: bool


def bind_verdict_to_span(verdict: Verdict, candidate_spans: list[Span]) -> Span:
    # Invariant 1: join key must be inherited, not derived. If the verdict's
    # correlation_id was minted post-hoc, this list will be empty or wrong.
    matches = [s for s in candidate_spans if s.correlation_id == verdict.correlation_id]

    if not matches:
        # Orphan verdict is an ERROR, not debug noise. Do not filter.
        raise CorrelationContinuityError(
            f"orphan verdict {verdict.correlation_id}: no span carries the ingress key"
        )

    if len(matches) > 1:
        raise CorrelationContinuityError(
            f"ambiguous join for {verdict.correlation_id}: {len(matches)} spans share key"
        )

    span = matches[0]

    # Invariant 2: evidence containment. The verdict's scored text must appear
    # in the span it is attached to. A content-hash join that skips this check
    # is unsound for templated prompts and retries.
    if verdict.evidence not in span.output:
        raise CorrelationContinuityError(
            f"evidence not contained in span {span.correlation_id}: "
            f"verdict scored {verdict.evidence[:32]!r}, span output differs"
        )

    # Invariant 3: the span must be the root's descendant, not a neighbor.
    if not span.parent_is_root:
        raise CorrelationContinuityError(
            f"span {span.correlation_id} is not rooted at request ingress"
        )

    return span


def correlate(verdicts: list[Verdict], spans: list[Span]) -> int:
    correct = 0
    for v in verdicts:
        try:
            bind_verdict_to_span(v, spans)
            correct += 1
        except CorrelationContinuityError:
            # Count as error; never coerce into a "successful" join.
            raise
    return correct
