# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-opentelemetry-genai-span-tree-has-silently-desynchronized-from-its-agent-s-actual-token-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-opentelemetry-genai-span-tree-has-silently-desynchronized-from-its-agent-s-actual-token-ledger.warrant.json
# Markdown SHA-256:   ec885376a596d8d84218221e26b07a4a32654471002f0580c3d0fb016d6beadc
# Code AST SHA-256:   4f0daa70f145f303693f7b75bb3faad928b283d1d3c07d15452dd031b532aa18
# Verified Classes:   TelemetryLedgerDesync
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TelemetryLedgerDesync(RuntimeError):
    """Raised when a GenAI span subtree cannot be reconciled to a true token ledger."""
    pass


def validate_agent_token_ledger(chat_spans: list[dict]) -> dict:
    """
    chat_spans: ordered list of dicts, each with keys
      'input_tokens' (int), 'has_cumulative_context' (bool), 'tool_loop_active' (bool)
    Returns an aggregate ONLY if the tree is provably independent or cumulative.
    """
    if not chat_spans:
        raise TelemetryLedgerDesync("no chat spans; cannot validate ledger")

    inputs = [s["input_tokens"] for s in chat_spans]
    monotonic = all(b >= a for a, b in zip(inputs, inputs[1:]))
    any_cumulative = any(s["has_cumulative_context"] for s in chat_spans)
    tool_loop = any(s["tool_loop_active"] for s in chat_spans)

    # Delta-reporting signature: flat input counts across an active tool loop.
    flat_under_loop = tool_loop and not monotonic and len(set(inputs)) <= 2

    if flat_under_loop:
        raise TelemetryLedgerDesync(
            f"delta-reporting loop detected: inputs={inputs[:5]}... "
            "per-span sum is uninvertible; refuse to aggregate."
        )
    if tool_loop and not any_cumulative and not monotonic:
        raise TelemetryLedgerDesync(
            "ambiguous tree: no monotonic growth and no cumulative-context attribute; "
            "treat as delta-reporting by default."
        )

    # Provably cumulative or independent: sum is meaningful.
    return {
        "aggregate_input_tokens": sum(inputs),
        "reconcilable": True,
        "mode": "cumulative" if monotonic else "independent",
    }
