# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-trace-span-it-did-not-open-orphan-span-attribution-failure-in-cross-hop-a2a-trace-correlation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-trace-span-it-did-not-open-orphan-span-attribution-failure-in-cross-hop-a2a-trace-correlation.warrant.json
# Markdown SHA-256:   633df6340f2153c02465b5793c24b4b56e06aa4937b9958e77190ca4194be70c
# Code AST SHA-256:   c554b2107fd4f96928a7b4598fd5bd05e1cf2942f20b080719e65d54efd3af93
# Verified Classes:   OrphanSpanAttributionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class OrphanSpanAttributionError(RuntimeError):
    """Raised when a span would be attached to a parent whose open state
    cannot be proven by the emitting instance. Grafting is forbidden;
    the span must be re-rooted as an explicit orphan."""
    pass


def open_child_span(parent_traceparent: str, live_registry: dict, span_id: str) -> dict:
    """
    Open a child span under parent_traceparent, but only if the parent
    is provably open in this process's live span registry.

    live_registry: {span_id: {"open": bool, "minted_in_process": bool}}
    """
    parent_id = _parse_span_id(parent_traceparent)
    entry = live_registry.get(parent_id)

    if entry is None:
        raise OrphanSpanAttributionError(
            f"parent span {parent_id} absent from live registry; "
            f"cannot prove open state — refusing to graft. "
            f"Emit as orphan root with orphan_reason=parent_evicted."
        )
    if not entry["open"]:
        raise OrphanSpanAttributionError(
            f"parent span {parent_id} is closed; child {span_id} "
            f"would encode a false causal edge. orphan_reason=parent_closed."
        )
    if not entry["minted_in_process"]:
        raise OrphanSpanAttributionError(
            f"parent span {parent_id} was not minted in this process "
            f"lifetime (replay after checkpoint). orphan_reason=replay_after_checkpoint."
        )

    return {
        "span_id": span_id,
        "parent_id": parent_id,
        "orphaned": False,
        "resolution": "resolved",
    }


def _parse_span_id(traceparent: str) -> str:
    # traceparent: 00-<trace-id>-<span-id>-<flags>
    parts = traceparent.split("-")
    if len(parts) != 4:
        raise OrphanSpanAttributionError(f"malformed traceparent: {traceparent!r}")
    return parts[2]
