# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-correlated-trace-when-memory-span-parentage-is-reconstructed-after-the-fact-in-an-otel-genai-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-correlated-trace-when-memory-span-parentage-is-reconstructed-after-the-fact-in-an-otel-genai-observability.warrant.json
# Markdown SHA-256:   8a07b0494ca1a93ab5fe0ff9eef87036be29726b3fa9c57a5ad17471251b6b01
# Code AST SHA-256:   0c888f332814d2ddcee1d86109665598b3f372bb87b5c78abf1ebf77ff8319be
# Verified Classes:   CorrelationInvariantViolation, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CorrelationInvariantViolation(RuntimeError):
    """Raised when a reconstructed parentage edge would be non-unique or would
    rewrite an immutable trace identifier."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    start_ms: int
    end_ms: int
    kind: str  # "prompt" | "tool" | "memory"


def reconstruct_parent(
    child: Span,
    candidates: list[Span],
) -> str:
    """Return the span_id of the unique containing prompt span, or raise.

    Invariant: a parentage edge is admissible only if exactly one candidate
    prompt span's interval strictly contains the child's interval. Temporal
    proximity and 'nearest open span' are explicitly rejected.
    """
    if child.kind == "prompt":
        raise CorrelationInvariantViolation(
            f"refusing to reconstruct parent for prompt span {child.span_id}; "
            "prompt spans must carry emitted parentage"
        )

    containing = [
        c
        for c in candidates
        if c.kind == "prompt"
        and c.start_ms <= child.start_ms
        and c.end_ms >= child.end_ms
        and c.span_id != child.span_id
    ]

    if len(containing) == 0:
        # Honest degradation: emit as unresolved orphan, do NOT guess.
        raise CorrelationInvariantViolation(
            f"no containing prompt span for {child.kind} span {child.span_id}; "
            "emit correlation.status=unresolved on its own trace"
        )
    if len(containing) > 1:
        # Concurrent turns: containment is non-unique. Guessing corrupts
        # cost and safety attribution. Refuse.
        raise CorrelationInvariantViolation(
            f"ambiguous parentage for {child.span_id}: contained by "
            f"{[c.span_id for c in containing]}; refusing to pick nearest"
        )
    return containing[0].span_id


def attach(child: Span, candidates: list[Span], target_trace_id: str) -> Span:
    """Attach child to its reconstructed parent without rewriting trace_id."""
    if target_trace_id != child.trace_id:
        raise CorrelationInvariantViolation(
            f"refusing to rewrite trace_id of {child.span_id}: "
            f"{child.trace_id} -> {target_trace_id}; trace_id is immutable"
        )
    parent_id = reconstruct_parent(child, candidates)
    return Span(
        trace_id=child.trace_id,
        span_id=child.span_id,
        parent_span_id=parent_id,
        start_ms=child.start_ms,
        end_ms=child.end_ms,
        kind=child.kind,
    )
