# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-divergence-across-federated-agent-hops-under-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-divergence-across-federated-agent-hops-under-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   e0888e730929435ed1ed95d5ba7f60298d3abd003a23b5d97bdbb608dead0aa4
# Code AST SHA-256:   8daf05c986a5dfd76cf011f3f3acbcb7d6eac461fee564a9be30097f9792407f
# Verified Classes:   TraceContextDivergence, InboundContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Mapping


class TraceContextDivergence(RuntimeError):
    """Raised when a federation hop would re-derive an inherited GenAI attribute,
    or claim hop-local authority over an attribute the caller owns."""


# Attributes whose authority, once set by the originator, must be inherited
# verbatim across every federation hop. A hop may *read* these but must not
# recompute them; if it needs a differing value it must use a distinct key.
INHERITED_KEYS = frozenset(
    {
        "gen_ai.operation.name",
        "gen_ai.request.model",
        "gen_ai.request.max_tokens",
        "gen_ai.usage.input_tokens",  # prompt size is a property of the logical request
    }
)

# Attributes that are expected to differ per hop and must carry a hop
# discriminator rather than being summed blindly.
HOP_LOCAL_KEYS = frozenset(
    {
        "gen_ai.response.model",
        "gen_ai.usage.output_tokens",
        "gen_ai.server.time_to_first_token",
    }
)


@dataclass
class InboundContext:
    trace_id: str
    parent_span_id: str
    attributes: Mapping[str, object]
    # Declares, per key, whether the value is 'inherited' or 'hop_local'.
    # Absence of a declaration is the failure trigger.
    authority: Mapping[str, str] = field(default_factory=dict)


def admit_federation_hop(
    inbound: InboundContext,
    hop_emitted: Mapping[str, object],
    *,
    is_federation_boundary: bool,
) -> dict[str, object]:
    """Validate that this hop neither re-derives inherited attributes nor
    claims inherited authority over hop-local ones. Returns the merged
    attribute set to emit on this hop's span.
    """
    if not is_federation_boundary:
        # Intra-process parenting: caller context is trusted, no authority check.
        return dict(hop_emitted)

    merged: dict[str, object] = {}

    for key, value in hop_emitted.items():
        declared = inbound.authority.get(key)

        if key in INHERITED_KEYS:
            if declared != "inherited":
                raise TraceContextDivergence(
                    f"hop attempted to emit inherited attribute {key!r} without "
                    f"an 'inherited' authority declaration in inbound context "
                    f"(trace={inbound.trace_id}); refusing to re-derive"
                )
            upstream = inbound.attributes.get(key)
            if upstream is not None and upstream != value:
                raise TraceContextDivergence(
                    f"hop re-derived inherited attribute {key!r}: upstream="
                    f"{upstream!r} hop={value!r} (trace={inbound.trace_id}); "
                    f"emit a hop-local key instead of overwriting"
                )
            merged[key] = upstream if upstream is not None else value

        elif key in HOP_LOCAL_KEYS:
            if declared == "inherited":
                raise TraceContextDivergence(
                    f"hop claimed inherited authority over hop-local attribute "
                    f"{key!r} (trace={inbound.trace_id}); hop-local values must "
                    f"carry a hop discriminator, not be inherited"
                )
            merged[key] = value

        else:
            merged[key] = value

    # Any inherited key the caller declared but this hop silently dropped is
    # also a divergence: downstream joins will see a gap.
    for key, decl in inbound.authority.items():
        if decl == "inherited" and key not in merged and key in inbound.attributes:
            raise TraceContextDivergence(
                f"hop dropped inherited attribute {key!r} declared by caller "
                f"(trace={inbound.trace_id})"
            )

    return merged
