# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-opentelemetry-genai-span-trees-have-silently-dropped-a-tool-call-child-span-during-agent-handoff-invalidating-token-a.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-opentelemetry-genai-span-trees-have-silently-dropped-a-tool-call-child-span-during-agent-handoff-invalidating-token-a.warrant.json
# Markdown SHA-256:   53dacb6053eabba16ca7a39a8455be17262bc549e52fd1da596e386c78470dc4
# Code AST SHA-256:   a02ade67d2d937d766aede405c4c9f6c493c7f6062fbb6884f18872fc2833a68
# Verified Classes:   OrphanedTokenBearingSpanError, ReceivedSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import logging
from dataclasses import dataclass
from typing import Optional

logger = logging.getLogger("genai.trace.integrity")

# GenAI semantic-convention operation names that carry token accounting.
TOKEN_BEARING_OPS = frozenset({"chat", "invoke_agent"})
# Operations whose loss is structurally detectable but economically inert.
INERT_OPS = frozenset({"execute_tool"})


class OrphanedTokenBearingSpanError(RuntimeError):
    """Raised when a received span's parent is unresolved AND the span carries
    gen_ai.usage.* attributes, meaning trace-level token accounting is corrupt."""


@dataclass
class ReceivedSpan:
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str
    input_tokens: int = 0
    output_tokens: int = 0

    @property
    def total_tokens(self) -> int:
        return self.input_tokens + self.output_tokens


def validate_trace_integrity(
    spans: list[ReceivedSpan],
    external_ledger_tokens: int,
    loss_tolerance: int,
) -> int:
    """Validate parent-child graph completeness and token reconciliation.

    Returns the reconciled trace token sum. Raises if a token-bearing span is
    orphaned or if the trace sum diverges from the external ledger beyond
    tolerance.
    """
    known_ids = {s.span_id for s in spans}
    trace_sum = 0

    for span in spans:
        trace_sum += span.total_tokens

        if span.parent_span_id is None:
            continue  # legitimate root

        if span.parent_span_id in known_ids:
            continue  # edge intact

        # Parent unresolved. Classify by whether the span bears tokens.
        if span.operation_name in TOKEN_BEARING_OPS:
            raise OrphanedTokenBearingSpanError(
                f"span {span.span_id} ({span.operation_name}) has unresolved "
                f"parent {span.parent_span_id} and carries "
                f"{span.total_tokens} tokens; trace token accounting is corrupt"
            )
        elif span.operation_name in INERT_OPS:
            logger.warning(
                "trace-hygiene: orphaned inert span %s (%s), parent %s missing",
                span.span_id,
                span.operation_name,
                span.parent_span_id,
            )
        else:
            logger.warning(
                "trace-hygiene: orphaned span %s with unknown op %r",
                span.span_id,
                span.operation_name,
            )

    divergence = abs(trace_sum - external_ledger_tokens)
    if divergence > loss_tolerance:
        raise OrphanedTokenBearingSpanError(
            f"trace token sum {trace_sum} diverges from external ledger "
            f"{external_ledger_tokens} by {divergence} > tolerance "
            f"{loss_tolerance}; a token-bearing span was likely dropped "
            f"at an async handoff boundary"
        )

    return trace_sum


def force_flush_or_fail(batch_processor, timeout_ms: int = 5000) -> None:
    """Handoff-scoped flush barrier. Must be called before context teardown."""
    if not batch_processor.force_flush(timeout_millis=timeout_ms):
        raise OrphanedTokenBearingSpanError(
            f"batch span processor failed to flush within {timeout_ms}ms; "
            f"queued GenAI spans will be dropped on process teardown"
        )
