# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-lineage-when-opentelemetry-genai-spans-batch-token-accounting-across-a-mid-execution-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-lineage-when-opentelemetry-genai-spans-batch-token-accounting-across-a-mid-execution-context-compaction.warrant.json
# Markdown SHA-256:   45460e4733c8e2213026e93aed59b1edecb8100d8d6da37d30537b8ae9d5d0a7
# Code AST SHA-256:   44afa5f206f011b8594e51708961801036490918f5a30057263d31e92f6509c9
# Verified Classes:   LineageAccountingError, CompactionEvent, RunLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class LineageAccountingError(RuntimeError):
    """Raised when a GenAI span would be emitted across an unrecorded compaction boundary."""


@dataclass
class CompactionEvent:
    evicted_tool_call_ids: set[str]
    input_tokens: int
    output_tokens: int
    recorded: bool = True


@dataclass
class RunLedger:
    live_tool_call_ids: set[str] = field(default_factory=set)
    compaction: CompactionEvent | None = None
    billed_input_tokens: int = 0

    def emit_tool_span(self, call_id: str, referenced_ids: list[str], input_tokens: int) -> None:
        # A referenced ID that is neither live nor explained by a compaction event
        # produces a dangling lineage edge we cannot reconcile.
        for ref in referenced_ids:
            if ref not in self.live_tool_call_ids:
                if self.compaction is None or not self.compaction.recorded:
                    raise LineageAccountingError(
                        f"tool span {call_id} references {ref}, which is not live and "
                        f"has no recorded compaction event to explain its eviction"
                    )
                if ref not in self.compaction.evicted_tool_call_ids:
                    raise LineageAccountingError(
                        f"tool span {call_id} references {ref}, evicted-set does not "
                        f"contain it; lineage edge is unreconstructable"
                    )
        self.billed_input_tokens += input_tokens
        self.live_tool_call_ids.add(call_id)

    def compact(self, evicted: set[str], in_tok: int, out_tok: int) -> None:
        # The compaction itself must be billed and its evictions declared, or
        # every later span that re-sends the retained tail double-counts.
        self.compaction = CompactionEvent(evicted_tool_call_ids=evicted,
                                          input_tokens=in_tok, output_tokens=out_tok)
        self.billed_input_tokens += in_tok + out_tok
        self.live_tool_call_ids -= evicted

    def run_total(self) -> int:
        if self.compaction is not None and not self.compaction.recorded:
            raise LineageAccountingError("cannot publish run total across unrecorded compaction")
        return self.billed_input_tokens


# Misuse: compaction happened but was never recorded, then a later span re-sends history.
ledger = RunLedger()
ledger.live_tool_call_ids = {"call_a"}
ledger.live_tool_call_ids.discard("call_a")          # evicted without a CompactionEvent
ledger.emit_tool_span("call_b", ["call_a"], 4200)    # raises LineageAccountingError
