# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-latency-slo-breach-is-a-hallucination-rate-artifact-not-a-tool-error-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-latency-slo-breach-is-a-hallucination-rate-artifact-not-a-tool-error-artifact.warrant.json
# Markdown SHA-256:   c3a801c9456f01578b40fd98463a38573a6c2658625720642684a6ec4454bf2c
# Code AST SHA-256:   78694999f56b8be1687b5a439a7f12fdcac1d4bde2cfd21c11f92238b2f64d4c
# Verified Classes:   AttributionCollapseError, TurnTelemetry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal


class AttributionCollapseError(RuntimeError):
    """Raised when latency, tool-error, and hallucination telemetry
    cannot be joined on a common retry-aware key, indicating that a
    latency SLO breach may be misattributed to the tool-error budget."""


@dataclass(frozen=True)
class TurnTelemetry:
    trace_id: str
    span_id: str
    regeneration: int  # 0 = original, >=1 = retry span
    latency_ms: float
    tool_calls: int
    tool_errors: int
    claims_emitted: int
    claims_flagged_pre_retry: int
    claims_surviving: int


def diagnose_latency_breach(
    turns: list[TurnTelemetry],
    latency_slo_ms: float,
    hallucination_ceiling: float,
) -> Literal["tool_error_driven", "hallucination_retry_driven", "inconclusive"]:
    if not turns:
        raise AttributionCollapseError("empty telemetry window: cannot diagnose")

    # Invariant: every stream must be joinable on (trace_id, span_id, regeneration).
    keys = [(t.trace_id, t.span_id, t.regeneration) for t in turns]
    if len(keys) != len(set(keys)):
        raise AttributionCollapseError(
            "duplicate (trace_id, span_id, regeneration) keys: retry spans "
            "are not partitioned; latency and hallucination streams will "
            "disagree on unit of account"
        )

    slow = [t for t in turns if t.latency_ms > latency_slo_ms]
    if not slow:
        return "inconclusive"

    # Bimodality check: slow cohort's mean latency should approximate
    # one full synthesis pass, not one tool-call timeout.
    slow_mean = sum(t.latency_ms for t in slow) / len(slow)
    fast = [t for t in turns if t.latency_ms <= latency_slo_ms]
    fast_mean = sum(t.latency_ms for t in fast) / len(fast) if fast else 0.0
    gap_ratio = slow_mean / fast_mean if fast_mean else float("inf")

    # Retry amplification: regeneration spans per user turn.
    user_turns = {t.trace_id for t in turns}
    retries = sum(1 for t in turns if t.regeneration >= 1)
    amplification = retries / len(user_turns) if user_turns else 0.0

    # Hallucination rate: must be measured on PRE-retry triggers to be
    # comparable to latency. Post-retry survivors hide the cause.
    total_claims = sum(t.claims_emitted for t in turns)
    pre_retry_flagged = sum(t.claims_flagged_pre_retry for t in turns)
    if total_claims == 0:
        raise AttributionCollapseError("no claims emitted: hallucination rate undefined")
    hallucination_rate_pre_retry = pre_retry_flagged / total_claims

    surviving = sum(t.claims_surviving for t in turns)
    hallucination_rate_post_retry = (total_claims - surviving) / total_claims

    # Structural signature of the collapse.
    tool_error_rate = (
        sum(t.tool_errors for t in turns) / max(1, sum(t.tool_calls for t in turns))
    )
    tool_calls_per_turn = sum(t.tool_calls for t in turns) / len(user_turns)

    if (
        gap_ratio > 1.8
        and amplification > 1.5
        and hallucination_rate_post_retry < hallucination_rate_pre_retry
        and tool_error_rate < 0.01
        and tool_calls_per_turn > 1.5
    ):
        return "hallucination_retry_driven"

    if tool_error_rate >= 0.01 and amplification <= 1.2:
        return "tool_error_driven"

    # Compound condition that should have fired the amplification alarm
    # before the latency SLO did.
    if amplification > 1.5 and hallucination_rate_post_retry < hallucination_rate_pre_retry:
        raise AttributionCollapseError(
            f"amplification={amplification:.2f} with hallucination rate "
            f"falling ({hallucination_rate_pre_retry:.3f} -> "
            f"{hallucination_rate_post_retry:.3f}): retry loop is hiding "
            f"the cause of the latency breach; partition aggregator by "
            f"regeneration attribute before remediation"
        )

    return "inconclusive"
