# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-correlated-safety-violations-when-span-sampling-drops-the-violating-step-from-the-exported-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-trace-correlated-safety-violations-when-span-sampling-drops-the-violating-step-from-the-exported-trace.warrant.json
# Markdown SHA-256:   629a22159047b2ec96a60c3d1d8420ec359b9327b87b68a8e72679931ee64924
# Code AST SHA-256:   8621f9a9d881afc6ce31052d154cf2d9b0faaf5be539681495d2f7c79109055d
# Verified Classes:   UnattributableViolation, ViolationRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnattributableViolation(RuntimeError):
    """Raised when a classifier-named span is absent from the exported trace.

    The join must fail closed: never resolve to an ancestor, never inherit cost.
    """
    def __init__(self, violation_id: str, classifier_span_id: str, reason: str):
        self.violation_id = violation_id
        self.classifier_span_id = classifier_span_id
        self.reason = reason
        super().__init__(
            f"violation {violation_id} names span {classifier_span_id} "
            f"absent from export: {reason}"
        )


@dataclass
class ViolationRecord:
    violation_id: str
    policy_id: str
    span_id: Optional[str]        # None => unattributable
    cost_tokens: Optional[int]    # None => do not inherit from ancestor
    sampling_decision: str        # e.g. "dropped:cheap_fast_no_error"


def join_violation_to_trace(
    violation_id: str,
    policy_id: str,
    classifier_span_id: str,
    exported_spans: dict,          # span_id -> span dict
    transcript_ledger: dict,       # span_id -> token count (full transcript)
    sampling_decision: str,
) -> ViolationRecord:
    span = exported_spans.get(classifier_span_id)

    if span is None:
        # Fail closed. Do NOT walk to parent. Do NOT bill a surviving span.
        raise UnattributableViolation(
            violation_id=violation_id,
            classifier_span_id=classifier_span_id,
            reason=f"sampling_decision={sampling_decision}",
        )

    # Attribution proven: cost must come from the transcript ledger that saw
    # the full step, never from the surviving span's own counters.
    cost = transcript_ledger.get(classifier_span_id)
    if cost is None:
        raise UnattributableViolation(
            violation_id=violation_id,
            classifier_span_id=classifier_span_id,
            reason="span exported but absent from transcript token ledger",
        )

    return ViolationRecord(
        violation_id=violation_id,
        policy_id=policy_id,
        span_id=classifier_span_id,
        cost_tokens=cost,
        sampling_decision=sampling_decision,
    )
