# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-token-accounting-attributes-are-internally-consistent-but-semantically-orphaned-by-to.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-token-accounting-attributes-are-internally-consistent-but-semantically-orphaned-by-to.warrant.json
# Markdown SHA-256:   1913afac17677b493a8bc1dd40d9ceedfb2a5e2919987ac05958adf1abba8387
# Code AST SHA-256:   a8b6d304ca9a012ee1de01860819f6515f67562ea32b6654d9f42cdf9e6bee40
# Verified Classes:   OrphanedTokenAttributionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class OrphanedTokenAttributionError(RuntimeError):
    """Raised when a GenAI model span fans out to multiple tool calls
    without a token partition or an aggregate marker, making per-tool
    attribution ambiguous to span-at-a-time consumers."""


def validate_genai_turn(
    output_tokens: int,
    tool_call_ids: list[str],
    partition: dict[str, int] | None,
    attribution_marker: str | None,
) -> str:
    """Return the attribution mode to emit, or raise if the span set is orphaned.

    Invariant: for n > 1 children, either a partition summing to the parent
    figure exists, or an explicit 'aggregate' marker must be set. Otherwise
    the span is internally consistent but semantically orphaned.
    """
    n = len(tool_call_ids)
    if n == 0:
        return "none"
    if n == 1:
        return "single"

    if partition is not None:
        if set(partition) != set(tool_call_ids):
            raise OrphanedTokenAttributionError(
                f"partition keys {sorted(partition)} do not match "
                f"tool calls {sorted(tool_call_ids)}"
            )
        if sum(partition.values()) != output_tokens:
            raise OrphanedTokenAttributionError(
                f"partition sum {sum(partition.values())} != "
                f"parent output_tokens {output_tokens} across {n} calls"
            )
        return "partitioned"

    if attribution_marker == "aggregate":
        return "aggregate"

    raise OrphanedTokenAttributionError(
        f"model span fans out to {n} tool calls with output_tokens="
        f"{output_tokens} but no partition and no aggregate marker; "
        f"consumers will duplicate the figure {n}x. Refusing to emit "
        f"ambiguous telemetry."
    )
