# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-phantom-tool-call-spans-when-opentelemetry-genai-token-accounting-diverges-from-the-provider-s-billing-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-phantom-tool-call-spans-when-opentelemetry-genai-token-accounting-diverges-from-the-provider-s-billing-ledger.warrant.json
# Markdown SHA-256:   9c5f0ff2a23dba62cef006867d7757072ef373f86e07ba62ed71dbffd812500d
# Code AST SHA-256:   2188616bac30843a2978d382b071dac2f93294431245bffc3ccef34480ba9dd1
# Verified Classes:   PhantomToolSpanError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from collections import defaultdict
from dataclasses import dataclass


class PhantomToolSpanError(RuntimeError):
    """Raised when a tool span claims a unique call id but its parent chat span
    has no settled usage record, or when call-id cardinality exceeds one
    without a reuse marker."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    kind: str  # "chat" or "tool"
    response_id: str | None
    tool_call_id: str | None
    input_tokens: int | None
    output_tokens: int | None
    finish_reason: str | None
    reuse_marker: bool


def detect_phantom_tool_spans(
    spans: list[Span],
    ledger: dict[str, int],  # response_id -> billed total tokens
    charge_on_open: bool,
) -> list[str]:
    """Return list of trace_ids with phantom tool spans. Raise on hard violations."""
    by_trace: dict[str, list[Span]] = defaultdict(list)
    for s in spans:
        by_trace[s.trace_id].append(s)

    phantoms: list[str] = []
    for trace_id, trace_spans in by_trace.items():
        chat_by_id = {s.span_id: s for s in trace_spans if s.kind == "chat"}
        tool_spans = [s for s in trace_spans if s.kind == "tool"]

        call_id_counts: dict[str, int] = defaultdict(int)
        for t in tool_spans:
            if t.tool_call_id is None:
                continue
            call_id_counts[t.tool_call_id] += 1

        for t in tool_spans:
            parent = chat_by_id.get(t.parent_span_id or "")
            if parent is None:
                # Orphaned tool span: cannot attribute, but not a phantom by itself.
                continue

            parent_settled = (
                parent.response_id is not None
                and parent.response_id in ledger
                and parent.output_tokens is not None
            )

            if not parent_settled and charge_on_open:
                # Parent was charged at stream open but usage chunk never arrived.
                # A tool span here is a phantom unless it carries the reuse marker.
                if not t.reuse_marker:
                    raise PhantomToolSpanError(
                        f"trace {trace_id}: tool span {t.span_id} "
                        f"(call_id={t.tool_call_id}) has parent {parent.span_id} "
                        f"with finish_reason={parent.finish_reason!r} but no "
                        f"output_tokens and no reuse marker; provider charges on "
                        f"open, so this tool span is unbilled-adjacent."
                    )
                phantoms.append(trace_id)

            if t.tool_call_id is not None and call_id_counts[t.tool_call_id] > 1:
                # Duplicate call id: legitimate only if at most one instance
                # lacks the reuse marker (the settled retry).
                unmarked = [
                    x for x in tool_spans
                    if x.tool_call_id == t.tool_call_id and not x.reuse_marker
                ]
                if len(unmarked) > 1:
                    raise PhantomToolSpanError(
                        f"trace {trace_id}: call_id {t.tool_call_id} appears "
                        f"{call_id_counts[t.tool_call_id]} times with "
                        f"{len(unmarked)} unmarked instances; uniqueness "
                        f"invariant violated."
                    )

    return sorted(set(phantoms))


def reconcile_trace(
    spans: list[Span],
    ledger: dict[str, int],
    charge_on_open: bool,
) -> None:
    phantoms = detect_phantom_tool_spans(spans, ledger, charge_on_open)
    if phantoms:
        # Surface but do not raise: phantoms are expected under retry-after-reset.
        print(f"phantom tool spans in traces: {phantoms}")


if __name__ == "__main__":
    trace = "trace-001"
    spans = [
        Span(trace, "chat-7f3a", None, "chat", "resp_A", None, 1841, None, "tool_calls", False),
        Span(trace, "tool-7f3a-1", "chat-7f3a", "tool", None, "call_abc123", None, None, None, False),
        Span(trace, "chat-7f3b", None, "chat", "resp_B", None, 1841, 47, "tool_calls", False),
        Span(trace, "tool-7f3b-1", "chat-7f3b", "tool", None, "call_abc123", None, None, None, True),
    ]
    ledger = {"resp_A": 1841, "resp_B": 1888}
    # charge_on_open=True: chat-7f3a billed at open; tool-7f3a-1 lacks marker -> raises.
    try:
        detect_phantom_tool_spans(spans, ledger, charge_on_open=True)
    except PhantomToolSpanError as e:
        print(f"detected: {e}")
