# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-log-skew-when-otel-genai-spans-and-policy-decision-logs-disagree-on-injection-causality.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-log-skew-when-otel-genai-spans-and-policy-decision-logs-disagree-on-injection-causality.warrant.json
# Markdown SHA-256:   7d0da2adce32349df3c9c86fad48e952a0a58e5956fcfcfbd9055c1412764ca4
# Code AST SHA-256:   3ed549c48257c11c9ab9d641e070ce1a9381df2a850891e7ce6f9dbf12a3630b
# Verified Classes:   TraceLogSkewError, Verdict, Span, Decision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class TraceLogSkewError(RuntimeError):
    """Raised when a policy decision cannot be causally bound to a span."""
    pass


class Verdict(Enum):
    GATED_ALLOW = "gated_allow"
    GATED_BLOCK = "gated_block"
    GATE_BYPASS = "gate_bypass"      # BLOCK decision but span completed
    UNVERIFIED = "unverified"        # no hash-equal, contained decision


@dataclass(frozen=True)
class Span:
    span_id: str
    start_us: int
    end_us: int
    prompt_hash: str
    completed: bool


@dataclass(frozen=True)
class Decision:
    span_id: str
    ts_decision_us: int
    prompt_hash: str
    blocked: bool


def correlate(span: Span, decision: Optional[Decision]) -> Verdict:
    if decision is None:
        return Verdict.UNVERIFIED

    # Byte-identity invariant: the decision must have inspected the exact
    # bytes the span dispatched. A re-rendered prompt is not the same prompt.
    if decision.prompt_hash != span.prompt_hash:
        # Mismatch is admissible only as context, never as gating evidence.
        return Verdict.UNVERIFIED

    if not (span.start_us <= decision.ts_decision_us <= span.end_us):
        # Decision is stale (pre-dispatch) or late (post-completion).
        # Either way it did not gate this span.
        raise TraceLogSkewError(
            f"decision ts={decision.ts_decision_us} outside span "
            f"[{span.start_us},{span.end_us}] for span_id={span.span_id}; "
            f"hash matched but temporal containment failed"
        )

    if decision.blocked and span.completed:
        # Hash-equal BLOCK + completed span = enforcement/observation split.
        return Verdict.GATE_BYPASS

    return Verdict.GATED_BLOCK if decision.blocked else Verdict.GATED_ALLOW


def forensic_verdict(spans: list[Span], decisions: list[Decision]) -> dict[str, Verdict]:
    by_span = {d.span_id: d for d in decisions}
    out: dict[str, Verdict] = {}
    for s in spans:
        out[s.span_id] = correlate(s, by_span.get(s.span_id))
    # Any UNVERIFIED span in a trace with a GATE_BYPASS must not be resolved
    # by proximity; escalate rather than default to ALLOW.
    if Verdict.GATE_BYPASS in out.values():
        for sid, v in out.items():
            if v is Verdict.UNVERIFIED:
                raise TraceLogSkewError(
                    f"span {sid} unverified alongside gate bypass; "
                    f"manual review required, refusing to auto-attribute"
                )
    return out
