# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-split-trace-context-when-an-mcp-to-a2a-bridge-rewrites-the-caller-identity-mid-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-split-trace-context-when-an-mcp-to-a2a-bridge-rewrites-the-caller-identity-mid-invocation.warrant.json
# Markdown SHA-256:   b39ec7938e40b84141260d0abf2bf40e6b373936817a2393a59f5c215a18c508
# Code AST SHA-256:   90632c256ecedcff89df403528c7cea6806d738144459b704ce09096afa17d85
# Verified Classes:   IdentityTranslationSeam
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class IdentityTranslationSeam(RuntimeError):
    """Raised when a bridge span's identity cannot be derived from its parent
    plus a recorded translation event. Distinguishes telemetry gaps from
    token/span divergence because the remediations are opposite."""
    pass


def verify_bridge_edge(parent_span: dict, child_span: dict, translation_span: dict | None) -> None:
    """Enforce the continuity invariant on one parent->child edge across the
    MCP/A2A boundary. Raises IdentityTranslationSeam on violation."""
    parent_id = parent_span.get("identity", {}).get("namespace")
    child_id = child_span.get("identity", {}).get("namespace")

    # Same namespace: no translation required, identity must match.
    if parent_id == child_id:
        if parent_span["identity"].get("value") != child_span["identity"].get("value"):
            raise IdentityTranslationSeam(
                f"same-namespace identity drift on trace {child_span.get('trace_id')}: "
                f"{parent_span['identity']} -> {child_span['identity']}"
            )
        return

    # Cross-namespace: a translation event is mandatory.
    if translation_span is None:
        raise IdentityTranslationSeam(
            f"forged/leaked trace {child_span.get('trace_id')}: cross-namespace edge "
            f"{parent_id}->{child_id} with no translation span; quarantine trace_id"
        )

    required = {"identity.from", "identity.to", "translation.policy_id", "translation.timestamp"}
    missing = required - set(translation_span.get("attributes", {}))
    if missing:
        raise IdentityTranslationSeam(
            f"translation span {translation_span.get('span_id')} missing {missing}; "
            f"mark child {child_span.get('span_id')} identity.unverified, route to audit"
        )

    claimed_to = translation_span["attributes"]["identity.to"]
    if claimed_to != child_span["identity"].get("value"):
        raise IdentityTranslationSeam(
            f"token/span divergence on trace {child_span.get('trace_id')}: translation claims "
            f"{claimed_to!r} but child span carries {child_span['identity'].get('value')!r}; "
            f"freeze worker credentials and treat as privilege-escalation event"
        )
