# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-joins-a-federated-trace-after-a-privacy-sampled-parent-span-has-been-dropped.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-joins-a-federated-trace-after-a-privacy-sampled-parent-span-has-been-dropped.warrant.json
# Markdown SHA-256:   e260ea3b4b4c40fa3650638506a2050a4ecb3b77c0f889395ee5561565c65676
# Code AST SHA-256:   cb77f5b6a8362c1f5ef41fb471281f6f32bbd5790fa97ff5c075efc5b399ea15
# Verified Classes:   TraceReconstructionError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TraceReconstructionError(RuntimeError):
    """Raised when a federated trace cannot be reconstructed without silently
    re-rooting an orphaned span or discarding causally-anchored spans."""
    pass


class Span:
    def __init__(self, span_id, parent_span_id, trace_id, org, tombstone=False, known_dropped=False):
        self.span_id = span_id
        self.parent_span_id = parent_span_id
        self.trace_id = trace_id
        self.org = org
        self.tombstone = tombstone          # structural placeholder for a sampled-out span
        self.known_dropped = known_dropped  # declared absent via propagated tracestate ancestry


def reconstruct_trace(trace_id, spans, expected_span_ids):
    """
    spans: list[Span] present in the federated store for trace_id.
    expected_span_ids: set of span_ids the federation knows were supposed to exist
                       (from propagated tracestate ancestry lists).
    Returns an ordered root-to-leaf reconstruction. Raises on any gap that cannot
    be resolved by a tombstone or a known-dropped declaration.
    """
    by_id = {s.span_id: s for s in spans}
    present = set(by_id)
    declared = present | set(expected_span_ids)

    # Step 1: every retained span's parent must be present, tombstoned, or known-dropped.
    for s in spans:
        if s.parent_span_id is None:
            continue  # candidate root
        if s.parent_span_id not in present and s.parent_span_id not in expected_span_ids:
            raise TraceReconstructionError(
                f"trace {trace_id}: span {s.span_id} (org={s.org}) references parent "
                f"{s.parent_span_id} that is neither retained, tombstoned, nor declared "
                f"known-dropped. Cross-org sampler dropped an ancestor without a tombstone."
            )

    # Step 2: identify true roots. A span is a root only if it has no parent AND is
    # declared as a root by the federation, never by promotion.
    roots = [s for s in spans if s.parent_span_id is None]
    if len(roots) != 1:
        raise TraceReconstructionError(
            f"trace {trace_id}: expected exactly one root, found {len(roots)}. "
            f"Refusing to re-root orphaned spans."
        )
    root = roots[0]

    # Step 3: build children map, excluding tombstones from the emitted sequence
    # but retaining them as structural nodes.
    children = {}
    for s in spans:
        if s.parent_span_id is not None:
            children.setdefault(s.parent_span_id, []).append(s)

    # Step 4: walk root-to-leaf; a tombstoned or known-dropped intermediate is a
    # hard gap that must be reported, not skipped silently.
    ordered = []
    stack = [root]
    while stack:
        node = stack.pop()
        if node.tombstone or node.known_dropped:
            raise TraceReconstructionError(
                f"trace {trace_id}: reconstruction path passes through dropped span "
                f"{node.span_id} (org={node.org}). Trace is incomplete; cannot emit a "
                f"verified causal sequence."
            )
        ordered.append(node)
        stack.extend(children.get(node.span_id, []))

    # Step 5: completeness check against declared ancestry.
    missing = declared - present
    if missing:
        raise TraceReconstructionError(
            f"trace {trace_id}: {len(missing)} declared span(s) absent without tombstone: "
            f"{sorted(missing)}. Federation completeness invariant violated."
        )
    return ordered
