# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-per-agent-cost-attribution-has-silently-collapsed-under-semantic-convention-resource-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-per-agent-cost-attribution-has-silently-collapsed-under-semantic-convention-resource-drift.warrant.json
# Markdown SHA-256:   a480217b6e0ca10f365e21527c2e11dd6cbd37d2b8bf2fe26965eee2b67cab13
# Code AST SHA-256:   d91d0fc51a41f22d31c9e44548a63413c858a994c42106aa0f7d59da0a2aa817
# Verified Classes:   AttributionCollapseError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttributionCollapseError(RuntimeError):
    """Raised when a token-bearing span's resource identity does not match
    the session/agent that actually issued the call, making per-session
    cost attribution unsound."""
    pass


def attribute_span_cost(span, session_registry):
    """Bind a token-bearing span's cost to its true (session, agent) pair.

    Returns (session_id, agent_id, tokens) or raises AttributionCollapseError
    if the binding invariant cannot be proven call-local.
    """
    usage = span.attributes.get("gen_ai.usage.output_tokens", 0) + \
            span.attributes.get("gen_ai.usage.input_tokens", 0)
    if usage == 0:
        return None

    res_session = span.resource.attributes.get("agent.session.id")
    res_agent = span.resource.attributes.get("gen_ai.agent.id")
    span_agent = span.attributes.get("gen_ai.agent.id")

    # Signal 2: resource/span divergence -> sub-agent inherited parent emitter.
    if span_agent is not None and span_agent != res_agent:
        raise AttributionCollapseError(
            f"resource agent.id={res_agent!r} != span agent.id={span_agent!r} "
            f"on span {span.span_id}; emitter reuse across identity boundary"
        )

    # Signal 3: session-id monotonicity break -> resumed into warm emitter.
    record = session_registry.get(res_session)
    if record is not None and record.get("end_time") is not None \
            and span.start_time > record["end_time"]:
        raise AttributionCollapseError(
            f"token-bearing span {span.span_id} for closed session "
            f"{res_session!r} at {span.start_time}; emitter reuse on resume"
        )

    # Signal 1: emitter shared by multiple agents -> cannot prove call-local.
    if res_session is None or res_agent is None:
        raise AttributionCollapseError(
            f"span {span.span_id} carries {usage} tokens but resource lacks "
            f"session/agent identity; attribution would be ambient, not call-local"
        )

    return (res_session, res_agent, usage)
