# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-child-spans-when-an-mcp-server-re-parents-a-trace-after-a-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-child-spans-when-an-mcp-server-re-parents-a-trace-after-a-reconnect.warrant.json
# Markdown SHA-256:   a8ac16bf2f3deb1fab1c04880907ccf7db25424c06d25e68571b351d6de2789c
# Code AST SHA-256:   e5d56ec80a8d65f58851ed8399247bed051fcb196febdf50958c2dda0dee9cc8
# Verified Classes:   OrphanSpanError, SpanBuffer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanSpanError(RuntimeError):
    """Raised when a span's parent cannot be resolved to a durable per-trace fact."""
    pass


class SpanBuffer:
    def __init__(self):
        # Keyed by trace_id -> list of (span_id, captured_parent_span_id)
        self._retained = {}
        self._emitted = set()

    def start_span(self, trace_id, span_id, parent_span_id):
        # Capture parent AT START, bound to trace_id, durable across reconnect.
        self._retained.setdefault(trace_id, []).append((span_id, parent_span_id))

    def on_reconnect(self, trace_id, ambient_parent_span_id):
        """Re-emit buffered spans. Must NOT fall back to ambient parent."""
        spans = self._retained.get(trace_id, [])
        if not spans:
            return []
        out = []
        for span_id, captured_parent in spans:
            if captured_parent is None:
                # legitimate root
                out.append((span_id, None))
                continue
            if captured_parent not in self._emitted and captured_parent != "root":
                # Parent state was lost; do NOT guess from ambient context.
                raise OrphanSpanError(
                    f"span {span_id} in trace {trace_id} has unresolvable parent "
                    f"{captured_parent!r}; refusing ambient fallback "
                    f"{ambient_parent_span_id!r}"
                )
            out.append((span_id, captured_parent))
        return out

    def emit(self, trace_id, span_id, parent_span_id):
        if parent_span_id is not None and parent_span_id not in self._emitted:
            raise OrphanSpanError(
                f"emit of {span_id} under missing parent {parent_span_id}"
            )
        self._emitted.add(span_id)


def reconcile(trace_id, ambient_parent_span_id, buffer: SpanBuffer):
    try:
        return buffer.on_reconnect(trace_id, ambient_parent_span_id)
    except OrphanSpanError:
        # Declare orphans explicitly; never silently re-parent.
        return [(sid, "orphan_root") for sid, _ in buffer._retained.get(trace_id, [])]
