# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-delegation-span-orphaned-parent-context-in-otel-genai-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-delegation-span-orphaned-parent-context-in-otel-genai-agent-handoffs.warrant.json
# Markdown SHA-256:   619d8722cac8cfa291814a8e1d56a3ffae680e6d5ec13e08fbb61039700b052b
# Code AST SHA-256:   6f64f19b3faa23971bdadbcc2b14c2e4326821b8f1ee91936f56a544e438f9fc
# Verified Classes:   OrphanedDelegationError, SpanContext, DelegationHandoff
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class OrphanedDelegationError(RuntimeError):
    """Raised when a callee cannot confirm its parent span is durably emitted."""


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    durable: bool = False


class DelegationHandoff:
    def __init__(self, tracer, collector, parent_check_timeout_s: float = 2.0):
        self.tracer = tracer
        self.collector = collector
        self.parent_check_timeout_s = parent_check_timeout_s

    def open_parent(self, trace_id: str, span_id: str) -> SpanContext:
        return SpanContext(trace_id=trace_id, span_id=span_id, durable=False)

    def confirm_parent_durable(self, ctx: SpanContext) -> SpanContext:
        # Force flush the parent batch BEFORE serializing traceparent.
        flushed = self.tracer.force_flush(timeout_millis=1000)
        if not flushed:
            raise OrphanedDelegationError(
                f"parent span {ctx.span_id} could not be flushed; "
                f"refusing to propagate non-durable context for trace {ctx.trace_id}"
            )
        if not self.collector.has_span(ctx.trace_id, ctx.span_id):
            raise OrphanedDelegationError(
                f"collector does not yet hold parent {ctx.span_id} in trace {ctx.trace_id}; "
                f"handoff would produce an orphan"
            )
        ctx.durable = True
        return ctx

    def open_child(self, envelope: dict) -> SpanContext:
        parent = envelope.get("traceparent", {})
        child = SpanContext(
            trace_id=parent.get("trace_id", envelope["new_trace_id"]),
            span_id=envelope["child_span_id"],
            durable=False,
        )
        if not parent.get("parent_durable", False):
            # Emit as annotated root instead of silently re-rooting.
            self.tracer.annotate(child, {"delegation.orphaned": True})
            return child
        deadline = time.monotonic() + self.parent_check_timeout_s
        while time.monotonic() < deadline:
            if self.collector.has_span(child.trace_id, parent["span_id"]):
                return child
            time.sleep(0.05)
        raise OrphanedDelegationError(
            f"callee {child.span_id} cannot resolve parent {parent['span_id']} "
            f"within {self.parent_check_timeout_s}s; delegation chain broken"
        )
