# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-causal-span-orphaned-handoff-attribution-in-multi-agent-observability-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-causal-span-orphaned-handoff-attribution-in-multi-agent-observability-traces.warrant.json
# Markdown SHA-256:   a2e2f4869b5dfae9921de67c91361a593fd1ba2bbd506fdd3a2e2cf32c391591
# Code AST SHA-256:   3d9d72dfa71e82530389c8c6d214014644fc2ae903608fdbe48406f8031ad56f
# Verified Classes:   SpanState, CausalIntegrityError, Span, TraceCollector
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpanState(Enum):
    OPEN = "open"
    CLOSED = "closed"
    CONSUMED = "consumed"   # read by a downstream classifier; immutable
    TOMBSTONED = "tombstoned"


class CausalIntegrityError(RuntimeError):
    """Raised when a trace cannot honor its causal-completeness invariant."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    state: SpanState = SpanState.OPEN
    reserved_children: set = field(default_factory=set)
    linked_children: set = field(default_factory=set)


class TraceCollector:
    def __init__(self, flush_deadline_s: float, retention_s: float):
        if flush_deadline_s >= retention_s:
            # structural guarantee of orphans; refuse to start
            raise CausalIntegrityError(
                f"flush_deadline {flush_deadline_s}s must be < retention "
                f"{retention_s}s, else orphans are guaranteed"
            )
        self.flush_deadline_s = flush_deadline_s
        self.retention_s = retention_s
        self.spans: dict[str, Span] = {}

    def reserve_child(self, parent_id: str, child_span_id: str) -> None:
        parent = self.spans.get(parent_id)
        if parent is None:
            raise CausalIntegrityError(f"reserve on unknown parent {parent_id}")
        if parent.state is not SpanState.OPEN:
            raise CausalIntegrityError(
                f"parent {parent_id} is {parent.state.value}; "
                f"cannot reserve child {child_span_id} after close"
            )
        parent.reserved_children.add(child_span_id)

    def close_span(self, span_id: str) -> None:
        span = self.spans[span_id]
        pending = span.reserved_children - span.linked_children
        if pending:
            # do NOT silently close with unaccounted children
            raise CausalIntegrityError(
                f"refusing to close {span_id}: {len(pending)} reserved "
                f"child span(s) unaccounted: {sorted(pending)}"
            )
        span.state = SpanState.CLOSED

    def receive_child(self, span_id: str, parent_id: str) -> Span:
        parent = self.spans.get(parent_id)
        if parent is None:
            # lost parent entirely: record as orphan, never re-root silently
            orphan = Span(span_id, parent_id=None, state=SpanState.TOMBSTONED)
            self.spans[span_id] = orphan
            return orphan
        if parent.state is SpanState.CONSUMED:
            # parent already analyzed: re-rooting would rewrite published causality
            orphan = Span(span_id, parent_id=parent_id, state=SpanState.TOMBSTONED)
            self.spans[span_id] = orphan
            return orphan
        parent.linked_children.add(span_id)
        child = Span(span_id, parent_id=parent_id)
        self.spans[span_id] = child
        return child
