# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-causal-trace-rejoins-a-federated-span-tree-after-a-sibling-has-already-been-garbage-collected.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-causal-trace-rejoins-a-federated-span-tree-after-a-sibling-has-already-been-garbage-collected.warrant.json
# Markdown SHA-256:   e10d1437d37816593b0f3c3f5bfd4d3e3ed824f30673d1521d70c9310af539f8
# Code AST SHA-256:   312c40751dee0e2e62be468316c1b832acc9d6c216ad1a01dac48924f72b36d1
# Verified Classes:   CausalRejoinViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalRejoinViolation(RuntimeError):
    """Raised when an arriving span cannot be soundly attached to its causal parent
    because the parent's dispatch ledger no longer accounts for the span's identity."""
    pass


def rejoin_span(span, parent, dispatch_ledger):
    # parent: surviving span node; dispatch_ledger: open child slots at parent.
    # Sound rejoin requires the parent to still hold an OPEN slot matching this
    # span's causal identity (child_id). A live parent alone is insufficient.
    if parent is None:
        raise CausalRejoinViolation(
            f"span {span.id}: no surviving causal parent; quarantine required"
        )

    open_slots = dispatch_ledger.open_children(parent.id)
    matched = [s for s in open_slots if s.child_id == span.causal_child_id]

    if not matched:
        # Parent alive, but no open slot for this child. Either the slot was
        # reaped (sibling GC'd early) or this span is a re-parenting artifact.
        # Attaching here would silently promote span to a higher cause.
        raise CausalRejoinViolation(
            f"span {span.id}: parent {parent.id} live but dispatch slot for "
            f"child {span.causal_child_id} is closed/missing; "
            f"resolve-to-nearest-live-ancestor would misattribute cause"
        )

    slot = matched[0]
    slot.close(span.id)
    return parent.attach(span)
