# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-orphaning-in-genai-observability-when-agent-tool-call-attribution-outlives-its-parent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-orphaning-in-genai-observability-when-agent-tool-call-attribution-outlives-its-parent-span.warrant.json
# Markdown SHA-256:   31c2b40439522de7b47ef884f835dde4076fd00bbebf39134ef69aee2920801b
# Code AST SHA-256:   90d4afd3ea86ce9a601570c9d3aa300bce2fa99a666134a6ed293d9aefcfffcf
# Verified Classes:   SpanOrphanedError, ParentAggregate, AttributionEngine
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Tuple


class SpanOrphanedError(RuntimeError):
    """Raised when a child tool-call span closes into a parent that is already finalized."""
    pass


@dataclass
class ParentAggregate:
    trace_id: str
    parent_span_id: str
    cost_usd: float = 0.0
    latency_ms: float = 0.0
    declared_children: int = 0
    closed_children: int = 0
    finalized: bool = False
    finalized_at: float = 0.0


class AttributionEngine:
    def __init__(self, grace_seconds: float, orphan_ledger: Dict[Tuple[str, str, str], float]):
        self.grace = grace_seconds
        self.ledger = orphan_ledger
        self.parents: Dict[Tuple[str, str], ParentAggregate] = {}

    def open_parent(self, trace_id: str, parent_span_id: str, declared_children: int) -> ParentAggregate:
        agg = ParentAggregate(trace_id, parent_span_id, declared_children=declared_children)
        self.parents[(trace_id, parent_span_id)] = agg
        return agg

    def close_parent(self, trace_id: str, parent_span_id: str) -> ParentAggregate:
        agg = self.parents[(trace_id, parent_span_id)]
        # Commit barrier: refuse to finalize until all declared children closed,
        # or the grace window (>= p99 tool latency) has elapsed.
        if agg.closed_children < agg.declared_children:
            if time.monotonic() - agg.finalized_at < self.grace:
                raise SpanOrphanedError(
                    f"parent {parent_span_id} closed with "
                    f"{agg.declared_children - agg.closed_children} children outstanding "
                    f"within grace window"
                )
        agg.finalized = True
        agg.finalized_at = time.monotonic()
        return agg

    def close_child(self, trace_id: str, parent_span_id: str, child_span_id: str,
                    cost_usd: float, latency_ms: float) -> None:
        key = (trace_id, parent_span_id)
        agg = self.parents.get(key)
        if agg is None:
            # Parent never opened in this window: orphan to ledger, never silently drop.
            self.ledger[(trace_id, parent_span_id, child_span_id)] = cost_usd
            raise SpanOrphanedError(
                f"child {child_span_id} has no live parent {parent_span_id}; "
                f"routed to orphan ledger (cost={cost_usd})"
            )
        if agg.finalized:
            # Parent already committed before child closed: the structural orphan case.
            self.ledger[(trace_id, parent_span_id, child_span_id)] = cost_usd
            raise SpanOrphanedError(
                f"child {child_span_id} closed after parent {parent_span_id} finalized; "
                f"cost={cost_usd} moved to ledger for reconciliation"
            )
        agg.cost_usd += cost_usd
        agg.latency_ms = max(agg.latency_ms, latency_ms)
        agg.closed_children += 1

    def child_parent_ratio(self, trace_id: str) -> float:
        parent_cost = sum(p.cost_usd for (t, _), p in self.parents.items() if t == trace_id)
        ledger_cost = sum(c for (t, _, _), c in self.ledger.items() if t == trace_id)
        total = parent_cost + ledger_cost
        if total == 0.0:
            return 1.0
        return parent_cost / total  # must converge to 1.0 under production concurrency
