# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-semantic-convention-spans-when-an-async-sub-agent-resumes-after-its-parent-span-has-already-ended.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-semantic-convention-spans-when-an-async-sub-agent-resumes-after-its-parent-span-has-already-ended.warrant.json
# Markdown SHA-256:   9d3d39f26ad7af03cd165f33bc6b1fd01f4938fe968e8b6810c493f9ea7adf67
# Code AST SHA-256:   83697aac6b65b0b985f680433f2a2678b054d33bfda8066a09fcd6c484a374c0
# Verified Classes:   SpanContainmentViolation, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class SpanContainmentViolation(RuntimeError):
    """Raised when a child span's lifetime escapes its parent's exported lifetime."""
    pass

@dataclass
class Span:
    name: str
    parent_id: Optional[str]
    start: float
    end: Optional[float] = None
    detached: bool = False

def close_child_span(child: Span, parent: Span, now: float) -> Span:
    """Close a child span, enforcing the GenAI containment invariant.

    If the parent has already ended before the child, the parent-child
    edge is semantically invalid: downgrade to a detached link.
    """
    child.end = now
    if parent.end is None:
        return child  # parent still open, containment holds
    if now > parent.end:
        # Parent closed before child: temporal containment violated.
        # Do NOT silently keep the edge; detach and mark.
        child.detached = True
        child.parent_id = None  # caller must emit as a span *link*
        # If policy forbids silent detach, fail loudly instead:
        if not _policy_allows_detach():
            raise SpanContainmentViolation(
                f"child '{child.name}' (end={now}) outlived parent "
                f"'{parent.name}' (end={parent.end}); handoff must be "
                f"emitted as a link, not a parent edge"
            )
    return child

def _policy_allows_detach() -> bool:
    # Strict mode: refuse to emit a causally-inconsistent trace.
    return False
