# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reuses-a-causal-parent-span-id-after-a-context-compaction-boundary-and-the-trace-becomes-non-reconstructable-across-fede.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reuses-a-causal-parent-span-id-after-a-context-compaction-boundary-and-the-trace-becomes-non-reconstructable-across-fede.warrant.json
# Markdown SHA-256:   87119517276f36e36e4ef10bbcd8293b146f879fefbd6db6ac8ab71dd556ab5b
# Code AST SHA-256:   7d4a2c65598d4e341ee498bf1bd97dc4b7a668695e694ba023119c63a7125065
# Verified Classes:   CausalAncestryViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalAncestryViolation(RuntimeError):
    """Raised when a restored span context would forge causal ancestry."""
    pass


def reparent_on_resume(checkpoint: dict, live_span_open: bool) -> dict:
    """
    Decide the parent span for post-resume work.

    checkpoint: restored trace context, must include trace_id, parent_span_id,
                and parent_span_end_ts (None if the parent was open at capture).
    live_span_open: True only if the runtime holds a verified liveness lease
                    on the named parent span in its owning domain.
    """
    trace_id = checkpoint.get("trace_id")
    parent_id = checkpoint.get("parent_span_id")
    parent_end = checkpoint.get("parent_span_end_ts")

    if not trace_id or not parent_id:
        raise CausalAncestryViolation(
            f"checkpoint lacks trace context: {checkpoint!r}"
        )

    # Safe to reuse the parent only if it was open at capture AND is still live.
    if parent_end is None and live_span_open:
        return {"trace_id": trace_id, "parent_span_id": parent_id, "linked_to": None}

    # Parent was closed at capture, or we cannot prove it is still open.
    # Reusing it would assert a causal link that does not exist.
    if parent_end is not None:
        raise CausalAncestryViolation(
            f"refusing to reuse closed parent {parent_id} (ended at {parent_end}); "
            f"open a resumption span and link to it instead"
        )

    # Parent open at capture but liveness unverifiable across the boundary:
    # do not forge ancestry; emit a resumption span linked to the old one.
    return {
        "trace_id": trace_id,
        "parent_span_id": None,          # new resumption span becomes the parent
        "linked_to": parent_id,          # audit link, not a causal parent
    }
