# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-it-cannot-causally-witness-the-dangling-parent-invariant-in-multi-agent-genai-trace-schemas.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-span-it-cannot-causally-witness-the-dangling-parent-invariant-in-multi-agent-genai-trace-schemas.warrant.json
# Markdown SHA-256:   dd44e9236bf87f3f230cef5ae86f34406cbb7ffe7f0f56e836b26d1c62fc5c9a
# Code AST SHA-256:   0a72e8138e1ba062035be8741f420b580620446e59acccbd4069d2486b35a013
# Verified Classes:   DanglingParentError, CausalOrderViolation, Span, TraceStore, SpanEmitter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class DanglingParentError(RuntimeError):
    """Raised when an instance attempts to emit a causally-claimed span
    whose parent is not durably committed and cannot be deferred."""
    pass


class CausalOrderViolation(RuntimeError):
    """Raised when a declared parent terminates after the child begins,
    contradicting the asserted causal edge."""
    pass


ParentSource = Literal["self", "handoff", "memory", "checkpoint", "resume"]


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    parent_source: ParentSource
    start_ts: float
    end_ts: Optional[float] = None
    attributes: dict = field(default_factory=dict)


class TraceStore:
    """Minimal committed-span store. A span is 'durable' only after commit()."""

    def __init__(self):
        self._committed: dict[str, Span] = {}

    def commit(self, span: Span) -> None:
        self._committed[span.span_id] = span

    def is_durable(self, span_id: str) -> bool:
        return span_id in self._committed

    def get(self, span_id: str) -> Optional[Span]:
        return self._committed.get(span_id)


class SpanEmitter:
    """Enforces the span-commit barrier: no causally-claimed child span is
    exported until its parent is durable, or until the deferral deadline
    expires (in which case it is emitted flagged, never silently re-rooted)."""

    def __init__(self, store: TraceStore, defer_deadline_s: float = 5.0):
        self.store = store
        self.defer_deadline_s = defer_deadline_s
        self._pending: list[Span] = []
        self._exported: list[Span] = []

    def emit(self, span: Span) -> None:
        if span.parent_span_id is None:
            self._exported.append(span)
            return

        parent = self.store.get(span.parent_span_id)

        # Durability precedes reference: if the parent is not committed,
        # we must NOT let the collector re-root this span. Defer it.
        if not self.store.is_durable(span.parent_span_id):
            if span.parent_source in ("handoff", "memory", "checkpoint"):
                span.attributes["parent_pending"] = True
                span.attributes["parent_source"] = span.parent_source
                self._pending.append(span)
                return
            # A self-created parent that is not durable is an emitter bug.
            raise DanglingParentError(
                f"span {span.span_id} claims self-parent {span.parent_span_id} "
                f"but parent is not committed; refusing to emit a causally false edge"
            )

        # Parent is durable. Check causal order.
        if parent.end_ts is not None and parent.end_ts > span.start_ts:
            raise CausalOrderViolation(
                f"span {span.span_id} starts at {span.start_ts} but parent "
                f"{parent.span_id} terminates at {parent.end_ts}; causal edge contradicted"
            )

        # Resumed instance must not mint a second root for the same logical op.
        if span.parent_source == "resume":
            span.attributes.setdefault("resume_of", span.parent_span_id)

        self._exported.append(span)

    def flush_pending(self, now: float) -> None:
        """After the deferral window, emit unresolved pending spans FLAGGED,
        never re-rooted. The asserted parent is retained for repair."""
        still_pending = []
        for span in self._pending:
            waited = now - span.start_ts
            if self.store.is_durable(span.parent_span_id):
                span.attributes["parent_pending"] = False
                self._exported.append(span)
            elif waited > self.defer_deadline_s:
                # Deadline expired: quarantine, do not reparent.
                span.attributes["orphaned"] = True
                span.attributes["quarantined_parent"] = span.parent_span_id
                self._exported.append(span)
            else:
                still_pending.append(span)
        self._pending = still_pending


def reconstruct_tree(emitter: SpanEmitter) -> dict:
    """Reconstruction pass: never re-roots. Quarantined spans keep their
    asserted parent so a later repair pass can resolve the edge."""
    tree = {"roots": [], "edges": [], "quarantined": []}
    for span in emitter._exported:
        if span.attributes.get("orphaned"):
            tree["quarantined"].append(span.span_id)
            continue
        if span.parent_span_id is None:
            tree["roots"].append(span.span_id)
        else:
            if emitter.store.is_durable(span.parent_span_id):
                tree["edges"].append((span.parent_span_id, span.span_id))
            else:
                # Should be unreachable if emit() is correct; fail loud.
                raise DanglingParentError(
                    f"reconstruction found non-durable edge "
                    f"{span.parent_span_id}->{span.span_id}; invariant breached"
                )
    return tree
