# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-trace-correlated-safety-verdicts-are-being-retroactively-misattributed-across-a-resumed-agent-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-trace-correlated-safety-verdicts-are-being-retroactively-misattributed-across-a-resumed-agent-run.warrant.json
# Markdown SHA-256:   d6b1217d63b6a5e5a4bc9374c5d5dd69d205eded51d41445eeebde82b01b09cd
# Code AST SHA-256:   2b9c3880d67ece203ddb07c6c5b0fb3e20d1c8e27e32a014d435f93ee05c23ff
# Verified Classes:   VerdictAttributionError, Span, Verdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


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


@dataclass(frozen=True)
class Span:
    span_id: str
    run_id: str
    attempt_id: str
    start_time: float


@dataclass(frozen=True)
class Verdict:
    span_id: str
    attempt_id: str | None
    computed_at: float
    label: str


def attribute_verdict(span: Span, verdict: Verdict, skew_tolerance_s: float = 2.0) -> str:
    """
    Bind a late-arriving safety verdict to a span under the attempt-scoped
    invariant. Returns the label on sound binding; raises otherwise.
    """
    if verdict.span_id != span.span_id:
        raise VerdictAttributionError(
            f"span_id mismatch: verdict={verdict.span_id} span={span.span_id}"
        )

    # Absent attempt_id is a mismatch, never a wildcard. This is the
    # permissive-default bug that inverts safety signals across resume.
    if verdict.attempt_id is None:
        raise VerdictAttributionError(
            f"verdict for span {span.span_id} carries no attempt_id; "
            "cannot prove it was computed against this materialization"
        )

    if verdict.attempt_id != span.attempt_id:
        raise VerdictAttributionError(
            f"attempt mismatch on span {span.span_id}: "
            f"verdict attempt={verdict.attempt_id} span attempt={span.attempt_id}; "
            "replay verdict against current attempt content"
        )

    if verdict.computed_at < span.start_time - skew_tolerance_s:
        raise VerdictAttributionError(
            f"causal inversion on span {span.span_id}: "
            f"verdict computed_at={verdict.computed_at} precedes "
            f"span start_time={span.start_time} beyond {skew_tolerance_s}s tolerance"
        )

    return verdict.label


def correlate(span: Span, verdict: Verdict) -> dict:
    try:
        label = attribute_verdict(span, verdict)
    except VerdictAttributionError as exc:
        # Reject-and-requeue: the verdict is real, the binding is not.
        return {"span_id": span.span_id, "status": "requeue", "reason": str(exc)}
    return {"span_id": span.span_id, "status": "bound", "label": label}
