# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-retry-causality-collapse-in-genai-span-attributes-when-reasoning-traces-are-re-emitted-across-retry-attempts.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-retry-causality-collapse-in-genai-span-attributes-when-reasoning-traces-are-re-emitted-across-retry-attempts.warrant.json
# Markdown SHA-256:   92e00a5a5c4dad4024bb48aacacac493feedfdddff1390fa128013617fad3108
# Code AST SHA-256:   d444cd2e633183a3e62d5e9e68e5524c6c453070fd4836b90ecb49057a7bd669
# Verified Classes:   RetryCausalityCollapse, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class RetryCausalityCollapse(RuntimeError):
    """Raised when a retry span's reasoning trace is causally orphaned from its failure."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    task_key: str
    attempt: Optional[int]              # genai.retry.attempt
    parent_span_id: Optional[str]       # genai.retry.parent_span_id
    status_code: str                    # "OK" | "ERROR"
    output_tokens: int
    timestamp: float = field(default_factory=time.time)


def validate_retry_causality(
    span: GenAISpan,
    task_p50_output_tokens: int,
    error_siblings: list[GenAISpan],
    retry_window_s: float = 30.0,
) -> None:
    """
    Enforce the retry-causality invariant on a single span.
    Raises RetryCausalityCollapse when an OK span is a causally orphaned retry.
    """
    if span.status_code != "OK":
        return  # error spans are roots by definition; nothing to validate

    inflation = span.output_tokens / max(task_p50_output_tokens, 1)
    if inflation <= 2.0:
        return  # ordinary recovery, no narration signature

    # Inflation present. Is there an unlinked error sibling in the window?
    nearby_errors = [
        e for e in error_siblings
        if e.task_key == span.task_key
        and abs(e.timestamp - span.timestamp) <= retry_window_s
    ]
    if not nearby_errors:
        return  # latent divergence, not retry collapse; caller flags separately

    has_ordinal = span.attempt is not None and span.attempt > 1
    has_parent = span.parent_span_id is not None and any(
        e.span_id == span.parent_span_id for e in nearby_errors
    )

    if not (has_ordinal and has_parent):
        raise RetryCausalityCollapse(
            f"span {span.span_id} (task={span.task_key}) has OK status with "
            f"{inflation:.2f}x output inflation and an unlinked error sibling "
            f"{nearby_errors[0].span_id} within {retry_window_s}s, but "
            f"attempt={span.attempt!r} parent_span_id={span.parent_span_id!r}. "
            f"Reasoning trace is causally orphaned; demote from canonical trace."
        )


def relink_and_demote(
    span: GenAISpan,
    error_siblings: list[GenAISpan],
    task_p50_output_tokens: int,
) -> GenAISpan:
    """Attempt structural repair: synthesize the missing causal edge, then re-validate."""
    try:
        validate_retry_causality(span, task_p50_output_tokens, error_siblings)
        return span
    except RetryCausalityCollapse:
        candidate = min(
            (e for e in error_siblings if e.task_key == span.task_key),
            key=lambda e: abs(e.timestamp - span.timestamp),
            default=None,
        )
        if candidate is None:
            raise RetryCausalityCollapse(
                f"cannot relink span {span.span_id}: no error sibling for task {span.task_key}"
            )
        repaired = GenAISpan(
            span_id=span.span_id,
            task_key=span.task_key,
            attempt=2,
            parent_span_id=candidate.span_id,
            status_code=span.status_code,
            output_tokens=span.output_tokens,
            timestamp=span.timestamp,
        )
        validate_retry_causality(repaired, task_p50_output_tokens, error_siblings)
        return repaired
