# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-span-collapse-when-genai-agent-traces-cross-a-sampling-or-batching-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-span-collapse-when-genai-agent-traces-cross-a-sampling-or-batching-boundary.warrant.json
# Markdown SHA-256:   69a8b30c7332ba190c16b8d3ab77518173b8b833cc0e29b0ea5dc9b9be2f1612
# Code AST SHA-256:   302ddba257e77182417b2e01f78238341df219f9c2214fb7957475d8fdf3b150
# Verified Classes:   AggregateProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AggregateProvenanceError(RuntimeError):
    """Raised when a GenAI agent span's token aggregate has no closed descendant set."""
    pass


def seal_agent_span(span_attrs: dict, child_span_ids: set[str]) -> dict:
    """Attach a provenance seal to a closing invoke_agent span."""
    declared = span_attrs.get("gen_ai.usage.descendant_span_ids", set())
    if declared != child_span_ids:
        raise AggregateProvenanceError(
            f"declared descendants {declared} != observed {child_span_ids}"
        )
    span_attrs["gen_ai.usage.descendant_count"] = len(child_span_ids)
    return span_attrs


def admit_root_span(root: dict, observed_child_ids: set[str]) -> dict:
    """Collector-side gate: only admit aggregate as authoritative if sealed set is closed."""
    declared = root.get("gen_ai.usage.descendant_span_ids", set())
    if declared != observed_child_ids:
        root["gen_ai.usage.classification"] = "partial_trace"
        root["gen_ai.usage.unattributed_tokens"] = root.get("gen_ai.usage.total_tokens", 0)
        # quarantine from cost/budget pipelines; do not raise here, classify instead
        return root
    root["gen_ai.usage.classification"] = "authoritative"
    return root


def enforce_conservation(root: dict, child_usage: list[int]) -> None:
    """Hard check used by audit/replay; raises on unreconciled aggregate."""
    if root.get("gen_ai.usage.classification") != "authoritative":
        raise AggregateProvenanceError(
            f"cannot reconcile non-authoritative aggregate: "
            f"{root.get('gen_ai.usage.unattributed_tokens')} unattributed tokens"
        )
    total = root.get("gen_ai.usage.total_tokens", 0)
    if sum(child_usage) > total:
        raise AggregateProvenanceError(
            f"child usage {sum(child_usage)} exceeds parent aggregate {total}"
        )
