# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-attribution-when-a-child-span-outlives-its-parent-s-genai-semantic-context.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-attribution-when-a-child-span-outlives-its-parent-s-genai-semantic-context.warrant.json
# Markdown SHA-256:   ef393b78e6b4da64fcbe9c60fc9769baecd4ad862d08c83837788eebe7568edd
# Code AST SHA-256:   5b5041fa459bb3e891955a1396b48817731e0a45c27ebf98bf768c00117ed0f1
# Verified Classes:   SemanticContextEvictionError, Span, ActiveSpanRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class SemanticContextEvictionError(RuntimeError):
    """Raised when a child span resolves gen_ai.* attributes by parent lookup
    after the parent has been exported and evicted from the active registry."""


@dataclass
class Span:
    name: str
    parent: "Span | None" = None
    attributes: dict[str, object] = field(default_factory=dict)
    exported: bool = False
    children_alive: int = 0


class ActiveSpanRegistry:
    """Models a batch exporter that evicts spans from the active registry on export."""

    def __init__(self) -> None:
        self._active: dict[str, Span] = {}

    def register(self, span: Span) -> None:
        self._active[span.name] = span
        if span.parent is not None:
            span.parent.children_alive += 1

    def export(self, span: Span) -> None:
        # Eviction happens regardless of live children in naive runtimes.
        span.exported = True
        self._active.pop(span.name, None)

    def resolve_genai_attr(self, span: Span, key: str) -> object:
        # Lazy parent traversal: the exact mechanism that breaks under eviction.
        cursor: Span | None = span
        while cursor is not None:
            if key in cursor.attributes:
                if cursor.exported:
                    raise SemanticContextEvictionError(
                        f"span {span.name!r} resolved {key!r} from exported "
                        f"ancestor {cursor.name!r}; attribute inheritance is "
                        f"not guaranteed after eviction"
                    )
                return cursor.attributes[key]
            cursor = cursor.parent
        raise SemanticContextEvictionError(
            f"span {span.name!r} could not resolve {key!r} in any ancestor"
        )


def capture_at_creation(parent: Span, child: Span, keys: tuple[str, ...]) -> None:
    """Guardrail: copy semantic join keys into the child at creation time."""
    for key in keys:
        if key in parent.attributes:
            child.attributes[key] = parent.attributes[key]


def run_agent_turn(registry: ActiveSpanRegistry, tool_duration_exceeds_flush: bool) -> Span:
    infer = Span(name="S_infer", attributes={
        "gen_ai.operation.name": "chat",
        "gen_ai.request.model": "gpt-4o",
        "gen_ai.usage.input_tokens": 812,
        "gen_ai.usage.output_tokens": 47,
    })
    registry.register(infer)

    tool = Span(name="S_tool", parent=infer)
    registry.register(tool)
    # Guardrail applied at creation — the only safe point.
    capture_at_creation(infer, tool, ("gen_ai.request.model", "gen_ai.operation.name"))

    if tool_duration_exceeds_flush:
        # Parent exported and evicted while the tool is still running.
        registry.export(infer)

    # A violating implementation would do this instead of capture_at_creation:
    # model = registry.resolve_genai_attr(tool, "gen_ai.request.model")
    model = tool.attributes.get("gen_ai.request.model")
    if model is None:
        raise SemanticContextEvictionError(
            f"tool span {tool.name!r} has no gen_ai.request.model; cost join "
            f"will drop this subtree"
        )

    registry.export(tool)
    return tool
