# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-span-s-token-usage-attributes-as-authoritative-across-a-tool-call-boundary-and-when-must-it-recom.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-span-s-token-usage-attributes-as-authoritative-across-a-tool-call-boundary-and-when-must-it-recom.warrant.json
# Markdown SHA-256:   749af72938a2aa214b14aa4efc2fd1ba73dd2b0b9b2cfb9fcb63fe882acfc5e0
# Code AST SHA-256:   eb506de623a972c0d16145bd028f9955a45fd275c80232fe70f5b659b8a2cb37
# Verified Classes:   UsageModeAmbiguityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UsageModeAmbiguityError(RuntimeError):
    """Raised when a GenAI span stream cannot be resolved to a single usage mode."""
    pass


def resolve_step_input_tokens(spans: list[dict], declared_mode: str | None) -> int:
    """Resolve the authoritative input-token count for one agent step.

    spans: ordered LLM spans (each with gen_ai.usage.input_tokens,
           gen_ai.usage.output_tokens, gen_ai.request.model).
    declared_mode: 'attribution' | 'delta' | None (unknown).
    """
    if not spans:
        raise UsageModeAmbiguityError("no LLM spans in step; cannot resolve usage")

    models = {s["gen_ai.request.model"] for s in spans}
    if len(models) > 1:
        raise UsageModeAmbiguityError(
            f"step crosses model boundary {sorted(models)}; split into sub-steps"
        )

    inputs = [s["gen_ai.usage.input_tokens"] for s in spans]

    if declared_mode == "attribution":
        # Invariant: last span's input is a superset of all prior contexts.
        for prev, cur in zip(inputs, inputs[1:]):
            if cur < prev:
                raise UsageModeAmbiguityError(
                    f"non-monotonic input_tokens ({prev} -> {cur}); "
                    "context compaction or delta emitter under attribution mode"
                )
        return inputs[-1]

    if declared_mode == "delta":
        return sum(inputs)

    # Mode unknown: refuse to guess. Heuristic inference is the failure we are bounding.
    raise UsageModeAmbiguityError(
        "usage mode not declared; additive and delta readings diverge by "
        f"{sum(inputs) - inputs[-1]} tokens for this step"
    )
