# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-linked-safety-interventions-from-silently-decoupling-guardrail-verdicts-from-the-genai-spans-they-claim-to-govern.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-linked-safety-interventions-from-silently-decoupling-guardrail-verdicts-from-the-genai-spans-they-claim-to-govern.warrant.json
# Markdown SHA-256:   465a75b62e9fd908d3e20b5a6a4431251279e742be7c69fc39bb16b6381a180e
# Code AST SHA-256:   bf902ded22623f7e7f8171d4be3ce8d8d1be89fb4aafd806a71d257599f20b2b
# Verified Classes:   VerdictSpanDecoupledError, VerdictSpan, ExecutionSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class VerdictSpanDecoupledError(RuntimeError):
    """Raised when a guardrail verdict cannot be soundly joined to an execution span."""


@dataclass(frozen=True)
class VerdictSpan:
    trace_id: str
    verdict: str                      # "allow" | "deny" | "redact"
    policy_id: str
    target_span_id: Optional[str]     # provisional handle; a HINT, not a join key
    witness: str                      # sha256 over canonicalized classified payload
    start_ns: int
    end_ns: int


@dataclass(frozen=True)
class ExecutionSpan:
    trace_id: str
    span_id: str
    model_id: str
    canonical_prompt: str
    tool_call_args: Optional[dict]
    start_ns: int
    end_ns: int


def compute_witness(model_id: str, prompt: str, tool_args: Optional[dict]) -> str:
    payload = json.dumps(
        {"model": model_id, "prompt": prompt, "tool_args": tool_args or {}},
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def join_verdict_to_span(
    verdict: VerdictSpan,
    candidates: list[ExecutionSpan],
    epsilon_ns: int = 2_000_000_000,
) -> ExecutionSpan:
    """
    Sound join: witness must match exactly one execution span in the trace,
    and the verdict must be temporally contained within that span's window.
    target_span_id is consulted only to disambiguate, never to decide.
    """
    in_trace = [e for e in candidates if e.trace_id == verdict.trace_id]
    if not in_trace:
        raise VerdictSpanDecoupledError(
            f"no execution span in trace {verdict.trace_id} for verdict {verdict.policy_id}"
        )

    witness_matches = [
        e for e in in_trace
        if compute_witness(e.model_id, e.canonical_prompt, e.tool_call_args) == verdict.witness
    ]

    if len(witness_matches) == 0:
        # Provisional-ID drift, post-classification templating, or retry reuse.
        raise VerdictSpanDecoupledError(
            f"verdict witness {verdict.witness[:12]}... matches no span in trace "
            f"{verdict.trace_id}; target_span_id={verdict.target_span_id!r} is unresolvable"
        )

    if len(witness_matches) > 1:
        # Retries with identical prompts: disambiguate by provisional hint, else refuse.
        hinted = [e for e in witness_matches if e.span_id == verdict.target_span_id]
        if len(hinted) != 1:
            raise VerdictSpanDecoupledError(
                f"ambiguous verdict: {len(witness_matches)} spans share witness; "
                f"hint {verdict.target_span_id!r} resolved to {len(hinted)}"
            )
        witness_matches = hinted

    span = witness_matches[0]

    if not (verdict.start_ns >= span.start_ns
            and verdict.end_ns <= span.end_ns + epsilon_ns):
        raise VerdictSpanDecoupledError(
            f"verdict {verdict.policy_id} not temporally contained in span {span.span_id}: "
            f"verdict=[{verdict.start_ns},{verdict.end_ns}] span=[{span.start_ns},{span.end_ns}]"
        )

    return span
