# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-conformance-drift-from-silently-corrupting-agent-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-conformance-drift-from-silently-corrupting-agent-observability-pipelines.warrant.json
# Markdown SHA-256:   889b2a7ea88e182c35fb40e41fdcaa2d8e60b8d6367c0797f054974a57fb23d6
# Code AST SHA-256:   be4992e02025c581439e2fc34bcd4df45041994e0f6bf2c5b162e75fc3c2cea1
# Verified Classes:   ConformanceArithmeticMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ConformanceArithmeticMismatch(RuntimeError):
    """Raised when a parent span's usage attributes do not equal the sum of its children's,
    indicating inherited or defaulted values rather than measured aggregation."""
    pass


def validate_usage_provenance(span, children, tolerance=0):
    """
    Enforce the provenance-binding invariant for GenAI usage attributes.

    A parent span carrying gen_ai.usage.* must either:
      (a) carry no usage attributes (consumer sums children), or
      (b) declare gen_ai.usage.aggregation == 'sum_of_children' AND
          equal the sum of its children's usage within tolerance.

    Context-inherited values (the failure mode) violate (b) and are rejected.
    """
    parent_input = span.attributes.get("gen_ai.usage.input_tokens")
    parent_output = span.attributes.get("gen_ai.usage.output_tokens")

    if parent_input is None and parent_output is None:
        return  # mode (a): no usage on parent, safe

    # If any usage is present, aggregation mode must be declared explicitly.
    mode = span.attributes.get("gen_ai.usage.aggregation")
    if mode != "sum_of_children":
        raise ConformanceArithmeticMismatch(
            f"span {span.span_id} carries usage {parent_input}/{parent_output} "
            f"but declares aggregation={mode!r}; inherited values are not permitted"
        )

    child_input = sum(
        c.attributes.get("gen_ai.usage.input_tokens", 0) for c in children
    )
    child_output = sum(
        c.attributes.get("gen_ai.usage.output_tokens", 0) for c in children
    )

    if abs((parent_input or 0) - child_input) > tolerance or abs(
        (parent_output or 0) - child_output
    ) > tolerance:
        raise ConformanceArithmeticMismatch(
            f"span {span.span_id} aggregation mismatch: "
            f"parent=({parent_input},{parent_output}) "
            f"sum_of_children=({child_input},{child_output}); "
            f"likely inherited from context rather than measured"
        )
