# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-reconstruction-has-silently-forked-in-federated-multi-agent-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-reconstruction-has-silently-forked-in-federated-multi-agent-observability.warrant.json
# Markdown SHA-256:   5674e2e63a8b31de9d0797a9cd06b57133d443d11ef2575fc1d9afa70400e471
# Code AST SHA-256:   d5f050d184799e3925cd7981bef5e1bdaa3a5b544b1e15be46c4ebd5d0c225e2
# Verified Classes:   CausalForkError, Span, LinkBarrierReconstructor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalForkError(RuntimeError):
    """Raised when a federated trace reconstructs into multiple valid causal topologies."""
    pass


@dataclass
class Span:
    span_id: str
    trace_id: str
    agent_id: str
    parent_span_id: Optional[str]
    link_target_span_id: Optional[str]
    gen_ai_model: str
    operation: str
    arrival_ms: int
    is_root: bool = False


class LinkBarrierReconstructor:
    def __init__(self, admission_window_ms: int):
        self.window_ms = admission_window_ms
        self.admitted: dict[str, Span] = {}
        self.pending: dict[str, list[Span]] = {}

    def admit(self, span: Span) -> None:
        if span.link_target_span_id is None:
            self.admitted[span.span_id] = span
            self._drain(span.span_id)
            return

        target = span.link_target_span_id
        if target in self.admitted:
            self._attach(span, self.admitted[target])
        else:
            # Correct behavior: hold, never promote to root.
            self.pending.setdefault(target, []).append(span)

    def _drain(self, newly_admitted_id: str) -> None:
        for child in self.pending.pop(newly_admitted_id, []):
            self._attach(child, self.admitted[newly_admitted_id])

    def _attach(self, child: Span, parent: Span) -> None:
        if child.gen_ai_model != parent.gen_ai_model and child.operation == "chat":
            raise CausalForkError(
                f"model-identity mismatch on link {child.span_id}->{parent.span_id}: "
                f"{child.gen_ai_model} vs {parent.gen_ai_model}; trace likely forked"
            )
        self.admitted[child.span_id] = child

    def expire(self, now_ms: int) -> list[Span]:
        stale = []
        for target, children in list(self.pending.items()):
            for c in children:
                if now_ms - c.arrival_ms > self.window_ms:
                    raise CausalForkError(
                        f"link target {target} never arrived within {self.window_ms}ms "
                        f"for span {c.span_id}; refusing root-promotion"
                    )
        return stale
