# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-truncation-is-corrupting-token-accounting-in-opentelemetry-genai-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-truncation-is-corrupting-token-accounting-in-opentelemetry-genai-agent-traces.warrant.json
# Markdown SHA-256:   444d7664df35a19184bc824b9d83328330921ffc0929f4e1426468f02ce9329e
# Code AST SHA-256:   241b396d9a3d1eb2e84871b58a001cb136538eab210b84b1d4808f075d06d77e
# Verified Classes:   TelemetryAccountingFault, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class TelemetryAccountingFault(RuntimeError):
    """Raised when a GenAI span's token counters cannot be trusted for accounting."""
    pass


@dataclass
class GenAISpan:
    name: str
    attributes: dict
    input_tokens: int
    output_tokens: int
    status_code: str = "UNSET"


def validate_span_for_accounting(
    span: GenAISpan,
    tool_output_schema: dict,
    provider_input_tokens: int,
    attribute_byte_cap: int,
    reconciliation_tolerance: float = 0.05,
) -> str:
    """
    Classify a GenAI tool-call span as valid or invalid for token accounting.
    Returns 'valid' or raises TelemetryAccountingFault with the reason.
    """
    result = span.attributes.get("gen_ai.tool.call.result")
    if result is None:
        return "valid"  # no tool payload on this span; nothing to clip

    result_bytes = len(result.encode("utf-8"))
    at_cap = result_bytes >= attribute_byte_cap

    if not at_cap:
        return "valid"

    # At the cap: determine whether clipping happened before or after counting.
    schema_ok = True
    try:
        json.loads(result)
    except json.JSONDecodeError:
        schema_ok = False

    if schema_ok:
        required = tool_output_schema.get("required", [])
        parsed = json.loads(result)
        schema_ok = all(k in parsed for k in required)

    if schema_ok:
        # Payload survived intact enough to satisfy schema: clip was cosmetic.
        return "valid"

    # Payload is clipped. Use provider counter to decide the branch.
    if span.input_tokens == 0:
        raise TelemetryAccountingFault(
            f"span {span.name}: clipped tool result with zero input_tokens; "
            f"counter was never computed from the real payload"
        )

    drift = abs(span.input_tokens - provider_input_tokens) / max(provider_input_tokens, 1)
    if drift > reconciliation_tolerance:
        raise TelemetryAccountingFault(
            f"span {span.name}: clipped result at {result_bytes} bytes (cap "
            f"{attribute_byte_cap}); input_tokens={span.input_tokens} vs provider="
            f"{provider_input_tokens} (drift {drift:.1%}). Span invalid for "
            f"accounting; clip-before-count ordering detected."
        )

    # Reconciles despite clipping: clip happened after counting; mark truncated
    # but keep the span in the accounting pipeline.
    span.attributes["gen_ai.tool.call.result.truncated"] = True
    return "valid"


def finalize_batch(spans, schema, provider_totals, cap):
    accepted, rejected = [], []
    for sp in spans:
        try:
            validate_span_for_accounting(
                sp, schema, provider_totals[sp.name], cap
            )
            accepted.append(sp)
        except TelemetryAccountingFault as e:
            rejected.append((sp.name, str(e)))
    if not accepted and spans:
        raise TelemetryAccountingFault(
            f"all {len(spans)} spans failed accounting validation: {rejected}"
        )
    return accepted, rejected
