# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-delegated-span-whose-parent-trace-was-sampled-out-mid-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-delegated-span-whose-parent-trace-was-sampled-out-mid-hop.warrant.json
# Markdown SHA-256:   c58ffa849aa8bedb6ab69a2a345a20c8e06b4a149f66f5316611d260424393d9
# Code AST SHA-256:   2b9f7f89d18ef193bd5c2d6e02a5eb62d8c9ea6dadb92e478730148d957040bb
# Verified Classes:   CausalityIncompleteError, TraceStitcher
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CausalityIncompleteError(RuntimeError):
    """Raised when a trace is consumed for replay/verification but its
    causal stitch is incomplete (orphaned spans present)."""
    pass


class TraceStitcher:
    def __init__(self, spans: dict[str, dict]):
        # spans keyed by span_id; each has 'parent_span_id', 'trace_id'
        self.spans = spans

    def stitch(self, trace_id: str) -> dict:
        """Exact-match stitching only. Never re-parents. Returns a graph
        with orphaned spans flagged and causality_complete computed."""
        in_trace = {
            sid: s for sid, s in self.spans.items()
            if s["trace_id"] == trace_id
        }
        orphans = []
        for sid, s in in_trace.items():
            parent = s.get("parent_span_id")
            if parent is not None and parent not in in_trace:
                s["orphaned"] = True
                s["original_parent_span_id"] = parent
                orphans.append(sid)
        return {
            "trace_id": trace_id,
            "spans": in_trace,
            "orphans": orphans,
            "causality_complete": len(orphans) == 0,
        }


def assert_replayable(stitched: dict) -> None:
    """Replay and verification consumers MUST call this before executing.
    A connected graph is not the same as a correct graph."""
    if not stitched["causality_complete"]:
        raise CausalityIncompleteError(
            f"trace {stitched['trace_id']} has {len(stitched['orphans'])} "
            f"orphaned span(s): {stitched['orphans']}. Refusing to replay: "
            f"re-parenting heuristics would fabricate causality."
        )


def run_replay(stitched: dict, executor) -> None:
    assert_replayable(stitched)
    executor(stitched["spans"])
