# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-resolve-trace-eval-safety-joins-at-agent-step-granularity-rather-than-at-session-or-request-granularity.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-resolve-trace-eval-safety-joins-at-agent-step-granularity-rather-than-at-session-or-request-granularity.warrant.json
# Markdown SHA-256:   14dd3f0eaf953cd5ae63dd769a65d6930ca498c0b8eaf86076c9b5d9c09d7f9c
# Code AST SHA-256:   10737f9d7856e9c4df88ba863da70c9fdc646f0b8aaccdb91c0d6798f6e93292
# Verified Classes:   StepJoinAttributionError, SpanRecord, Verdict, StepJoinResolver
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class StepJoinAttributionError(RuntimeError):
    """Raised when a late-bound eval/safety verdict cannot be soundly
    attributed to a specific agent step."""


@dataclass(frozen=True)
class SpanRecord:
    trace_id: str
    span_id: str
    step_index: int
    payload_hash: str
    is_retry: bool = False


@dataclass(frozen=True)
class Verdict:
    trace_id: str
    target_span_id: Optional[str]
    scored_payload_hash: Optional[str]
    step_index_hint: int
    kind: str  # "eval" | "safety"
    revision: int = 1


@dataclass
class StepJoinResolver:
    spans_by_id: dict[str, SpanRecord] = field(default_factory=dict)
    spans_by_ordinal: dict[tuple[str, int], list[SpanRecord]] = field(default_factory=dict)

    def register(self, span: SpanRecord) -> None:
        self.spans_by_id[span.span_id] = span
        self.spans_by_ordinal.setdefault((span.trace_id, span.step_index), []).append(span)

    def resolve(self, verdict: Verdict, min_granularity: str = "step") -> SpanRecord:
        if min_granularity != "step":
            raise StepJoinAttributionError(
                "caller requested session-granularity fallback; do not call step resolver"
            )

        # Rule 1: identity must be span_id, never ordinal.
        if verdict.target_span_id is None:
            raise StepJoinAttributionError(
                f"verdict for trace {verdict.trace_id} step {verdict.step_index_hint} "
                f"has no target_span_id; ordinal-only join is unsound under retry"
            )

        span = self.spans_by_id.get(verdict.target_span_id)
        if span is None:
            raise StepJoinAttributionError(
                f"target span {verdict.target_span_id} absent from trace store; "
                f"cannot verify attribution (sampling or loss)"
            )

        # Rule 2: payload hash must match what was actually scored.
        if verdict.scored_payload_hash is None:
            raise StepJoinAttributionError(
                f"verdict {verdict.kind} rev {verdict.revision} lacks payload hash; "
                f"revision-aware attribution impossible"
            )
        if verdict.scored_payload_hash != span.payload_hash:
            raise StepJoinAttributionError(
                f"payload hash mismatch for span {span.span_id}: "
                f"scored {verdict.scored_payload_hash} != stored {span.payload_hash}; "
                f"likely stale verdict against a prior attempt"
            )

        # Rule 3: detect ordinal drift and refuse silent collapse.
        siblings = self.spans_by_ordinal.get((span.trace_id, span.step_index), [])
        if len(siblings) > 1 and span.is_retry is False:
            raise StepJoinAttributionError(
                f"ordinal drift detected: step {span.step_index} in trace {span.trace_id} "
                f"has {len(siblings)} spans; step-level verdict must name span_id explicitly"
            )

        return span
