# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-genai-span-attribution-for-a-tool-call-whose-lineage-parent-has-already-been-evicted-from-the-exporter-buffer.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-genai-span-attribution-for-a-tool-call-whose-lineage-parent-has-already-been-evicted-from-the-exporter-buffer.warrant.json
# Markdown SHA-256:   548310ff45c165f78b7d74eecd6de116ce5344e1ceb785686ecac9c05deeba00
# Code AST SHA-256:   eca60be818c3f1c263f5a39c2c604b6f48c90d52ee8e866e6bd6e36771bddeb5
# Verified Classes:   LineageEvictionError, SpanRecord, LineageLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class LineageEvictionError(RuntimeError):
    """Raised when a tool span cannot be attributed to a lineage-viable parent."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    parent_span_id: Optional[str]
    enqueued_at: float
    trace_id: str


@dataclass
class LineageLedger:
    trace_close_grace: float = 30.0
    _last_enqueue: Dict[str, float] = field(default_factory=dict)
    _enqueued: Dict[str, SpanRecord] = field(default_factory=dict)

    def record_enqueue(self, span: SpanRecord) -> None:
        self._enqueued[span.span_id] = span
        self._last_enqueue[span.trace_id] = span.enqueued_at

    def parent_is_lineage_viable(self, parent_span_id: str, trace_id: str, now: float) -> bool:
        parent = self._enqueued.get(parent_span_id)
        if parent is None:
            return False
        last = self._last_enqueue.get(trace_id, 0.0)
        return (now - last) <= self.trace_close_grace


def enqueue_tool_span(
    ledger: LineageLedger,
    span_id: str,
    parent_span_id: str,
    trace_id: str,
    tool_name: str,
    now: Optional[float] = None,
) -> SpanRecord:
    now = time.monotonic() if now is None else now
    if not ledger.parent_is_lineage_viable(parent_span_id, trace_id, now):
        # Parent has been evicted or the trace has been closed past grace.
        # We must not silently emit a dangling child; either re-anchor or orphan.
        raise LineageEvictionError(
            f"tool span {span_id} (tool={tool_name}) cannot attach to parent "
            f"{parent_span_id} in trace {trace_id}: parent not lineage-viable "
            f"at t={now:.3f}; re-anchor or set gen_ai.lineage.orphaned=true"
        )
    span = SpanRecord(span_id=span_id, parent_span_id=parent_span_id,
                      enqueued_at=now, trace_id=trace_id)
    ledger.record_enqueue(span)
    return span
