# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-replay-of-a-genai-semantic-convention-trace-before-a-span-reorder-silently-rewrites-the-agent-s-causal-history.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-replay-of-a-genai-semantic-convention-trace-before-a-span-reorder-silently-rewrites-the-agent-s-causal-history.warrant.json
# Markdown SHA-256:   408f925b0dbe0371ede0cd385c24aa083033da2eec7922bf7acb44200390f672
# Code AST SHA-256:   0f2e69defcbc066a30f580db97cd3faad0ada4c321200390656738cd852b6cf7
# Verified Classes:   CausalReplayAmbiguity, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalReplayAmbiguity(RuntimeError):
    """Raised when replay would order spans by timestamp across emitter boundaries
    without a monotonic causal key, fabricating a causal history."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    emitter: str                 # e.g. "orchestrator", "sandbox", "gateway"
    start_ns: int
    end_ns: int
    seq: Optional[int] = None    # orchestrator-stamped monotonic key, if present


def order_children(parent: Span, children: list[Span]) -> list[Span]:
    """Order the children of a single parent. Timestamp sort is permitted only
    when all children share one emitter; otherwise a causal key is required."""
    if not children:
        return []

    emitters = {c.emitter for c in children}
    has_key = all(c.seq is not None for c in children)

    if len(emitters) == 1:
        # Single emitter: timestamps are causally reliable within it.
        return sorted(children, key=lambda c: (c.start_ns, c.span_id))

    if has_key:
        # Multi-emitter: the monotonic key is authoritative; timestamps demoted.
        return sorted(children, key=lambda c: (c.seq, c.span_id))

    # Multi-emitter, no causal key: refuse to fabricate an order.
    raise CausalReplayAmbiguity(
        f"parent {parent.span_id} has children from emitters {sorted(emitters)} "
        f"with no monotonic causal key; timestamp sort would fabricate causal order. "
        f"children={[c.span_id for c in children]}"
    )


def replay(root: Span, spans: list[Span]) -> list[str]:
    """Depth-first causal replay. Returns span_ids in causal order or raises."""
    by_parent: dict[Optional[str], list[Span]] = {}
    for s in spans:
        by_parent.setdefault(s.parent_span_id, []).append(s)

    ordered: list[str] = []

    def visit(node: Span) -> None:
        ordered.append(node.span_id)
        kids = by_parent.get(node.span_id, [])
        # A tool span whose interval precedes its parent is a skew artifact;
        # clamp it into the parent interval rather than reorder.
        for k in kids:
            if k.start_ns < node.start_ns:
                k.start_ns = node.start_ns
        for child in order_children(node, kids):
            visit(child)

    visit(root)
    return ordered
