# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-divergence-between-prompt-lineage-and-tool-invocation-causality-in-genai-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-divergence-between-prompt-lineage-and-tool-invocation-causality-in-genai-observability-pipelines.warrant.json
# Markdown SHA-256:   64a0c932f42d3dd45ab7b595dadca37e70e72b488b8924a1298a7d7b53d9a9a8
# Code AST SHA-256:   7f0303520b15e32f8c91c5fd7666b06255bc7e6589dcbf8b264d18e5f8b0623c
# Verified Classes:   LineageCausalityError, ToolSpan, SafetyIntervention
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LineageCausalityError(RuntimeError):
    """Raised when a tool span's issuance predates the safety verdict
    that authorized its lineage branch, indicating a turn_id collision
    or a clock-domain mismatch in the observability pipeline."""


@dataclass(frozen=True)
class ToolSpan:
    span_id: str
    turn_id: str
    lineage_parent: str
    issued_at: float


@dataclass(frozen=True)
class SafetyIntervention:
    turn_id: str
    verdict_at: float
    retry_child_id: str


def check_span_causality(
    span: ToolSpan,
    interventions: list[SafetyIntervention],
    clock_skew_bound: float = 0.050,
) -> None:
    for iv in interventions:
        if iv.turn_id != span.turn_id:
            continue
        owns_retry_branch = span.lineage_parent == iv.retry_child_id
        if not owns_retry_branch:
            # Span belongs to the blocked attempt; pre-verdict issuance is expected.
            continue
        if span.issued_at < iv.verdict_at - clock_skew_bound:
            raise LineageCausalityError(
                f"span {span.span_id} on turn {span.turn_id} issued at "
                f"{span.issued_at} precedes verdict at {iv.verdict_at} "
                f"but is owned by retry branch {iv.retry_child_id}; "
                f"likely turn_id collision or clock-domain mismatch"
            )
