# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-cardinality-explosion-from-silently-corrupting-agent-handoff-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-cardinality-explosion-from-silently-corrupting-agent-handoff-traces.warrant.json
# Markdown SHA-256:   f088c31908d66d5128e8855bba64193b56e3bb0d32129664c771555cbd9e14c3
# Code AST SHA-256:   d17319f2e6323f5bac4eaab473470e0c96d725a7ece7d4986930dd198a176d65
# Verified Classes:   HandoffIntegrityError, HandoffSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class HandoffIntegrityError(RuntimeError):
    """Raised when a handoff span's integrity attributes are inconsistent or missing."""
    pass


@dataclass
class HandoffSpan:
    agent_id: str
    target_agent_id: str
    context: Optional[str] = None
    context_hash: Optional[str] = None
    integrity: Optional[str] = None
    attribute_limit: int = 4096


def emit_handoff_span(agent_id: str, target_agent_id: str, state: dict, attribute_limit: int = 4096) -> HandoffSpan:
    serialized = json.dumps(state, sort_keys=True)
    digest = hashlib.sha256(serialized.encode()).hexdigest()

    # Emit integrity attributes FIRST and independently of the content attribute,
    # so a count-based collector limit cannot drop them while keeping content.
    span = HandoffSpan(
        agent_id=agent_id,
        target_agent_id=target_agent_id,
        context_hash=digest,
        integrity="verified",
    )

    if len(serialized) <= attribute_limit:
        span.context = serialized
    else:
        # Content exceeds the limit: do NOT emit truncated content.
        # Mark degraded and omit the content attribute entirely.
        span.context = None
        span.integrity = "degraded"
    return span


def verify_handoff(span: HandoffSpan, received_state: dict) -> None:
    # Fail-closed: any missing or ambiguous integrity attribute is an error.
    if span.integrity not in ("verified", "degraded", "decorative"):
        raise HandoffIntegrityError(
            f"handoff span {span.agent_id}->{span.target_agent_id} has "
            f"unrecognized integrity status {span.integrity!r}"
        )
    if span.integrity == "degraded":
        raise HandoffIntegrityError(
            f"handoff span {span.agent_id}->{span.target_agent_id} is degraded; "
            f"continuity cannot be verified from trace alone"
        )
    if span.integrity == "decorative":
        # Authoritative state travels out-of-band; trace is not evidence.
        return
    if span.context_hash is None:
        raise HandoffIntegrityError(
            f"handoff span {span.agent_id}->{span.target_agent_id} missing context_hash "
            f"despite integrity='verified'"
        )
    actual = hashlib.sha256(json.dumps(received_state, sort_keys=True).encode()).hexdigest()
    if actual != span.context_hash:
        raise HandoffIntegrityError(
            f"handoff state divergence on {span.agent_id}->{span.target_agent_id}: "
            f"trace_hash={span.context_hash} received_hash={actual}"
        )


if __name__ == "__main__":
    big_state = {"tool_results": ["x" * 3000 for _ in range(3)]}
    span = emit_handoff_span("executor", "auditor", big_state, attribute_limit=4096)
    try:
        verify_handoff(span, big_state)
    except HandoffIntegrityError as e:
        print(f"caught as designed: {e}")
