# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forks-its-trace-mid-span-causal-replay-divergence-from-non-atomic-span-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forks-its-trace-mid-span-causal-replay-divergence-from-non-atomic-span-lineage.warrant.json
# Markdown SHA-256:   518d994f85f07af20ef54e596214e862644f4713132c64922bc9b9a93e0174e0
# Code AST SHA-256:   348ee189c98df1fc3dc2a9b9c6b5af5aaae247ffe00a4f72655adbab2e2b2d2b
# Verified Classes:   LineageIntegrityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class LineageIntegrityError(RuntimeError):
    """Raised when a span's causal position cannot be proven from recorded lineage."""
    pass


def resolve_causal_order(spans, complete_set_confirmed, max_quarantine=10_000):
    """
    Reconstruct causal order strictly from parent_span_id + recorded timestamps.
    Never uses arrival order or ingestion time as causal data.
    """
    by_id = {s["span_id"]: s for s in spans}
    orphans = [s for s in spans if s["parent_span_id"] and s["parent_span_id"] not in by_id]

    if orphans and not complete_set_confirmed:
        # Parent may simply be in flight. Do NOT reparent. Do NOT guess.
        raise LineageIntegrityError(
            f"{len(orphans)} spans have unresolved parents and the trace set is not "
            f"confirmed complete; refusing to infer causal position. "
            f"First orphan: {orphans[0]['span_id']} -> parent {orphans[0]['parent_span_id']}"
        )

    if orphans and complete_set_confirmed:
        # Parents are provably absent: surface as quarantined, never reparent.
        for s in orphans:
            s["lineage_status"] = "quarantined"
        raise LineageIntegrityError(
            f"{len(orphans)} spans have parents absent from a confirmed-complete set; "
            f"lineage is broken, not repairable."
        )

    if len(by_id) > max_quarantine:
        raise LineageIntegrityError("working set exceeded quarantine bound; aborting replay")

    for s in spans:
        s["lineage_status"] = "recorded"
    return sorted(spans, key=lambda s: (s["start_time_ns"], s["span_id"]))
