# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-traces-it-did-not-author-cross-federation-span-grafting-and-the-orphaned-parent-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-traces-it-did-not-author-cross-federation-span-grafting-and-the-orphaned-parent-invariant.warrant.json
# Markdown SHA-256:   efe494f24633ab0aed1d9865e733e84c5646f9e76afb0d6665012e487c6086a7
# Code AST SHA-256:   fd732c27d1117211041d8ba4e21453d9bc1fdd4f828890908c74457c4f246443
# Verified Classes:   TraceReconciliationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TraceReconciliationError(RuntimeError):
    """Raised when a cross-agent causal edge cannot be reconciled to an authored parent."""
    pass


def admit_edge(child_span: dict, parent_index: dict, federation_watermark: int) -> None:
    parent_id = child_span["parent_span_id"]
    parent = parent_index.get(parent_id)

    if parent is None:
        # Parent never arrived. Distinguish "delayed" from "absent" via watermark.
        if child_span["emitter_seq"] <= federation_watermark:
            # All agents have flushed past this child; parent is genuinely absent
            # OR was re-derived locally (tracestate drop). Never graft across trust boundary.
            raise TraceReconciliationError(
                f"orphaned cross-agent parent {parent_id!r} for span "
                f"{child_span['span_id']!r} in trace {child_span['trace_id']!r}: "
                f"parent not present at watermark {federation_watermark}; "
                f"quarantine subtree, do not reparent"
            )
        # Parent may still be in flight; defer rather than graft.
        return

    if parent["emitter"] != child_span["emitter"]:
        # Cross-agent edge: verify the child cited the parent's true namespace id,
        # not a locally re-derived placeholder.
        if child_span.get("parent_namespace") != parent.get("namespace"):
            raise TraceReconciliationError(
                f"namespace mismatch on edge {parent_id!r} -> {child_span['span_id']!r}: "
                f"child namespace {child_span.get('parent_namespace')!r} != "
                f"parent namespace {parent.get('namespace')!r}; "
                f"tracestate likely dropped at handoff"
            )

    child_span["admitted_parent"] = parent_id
