# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-trace-span-has-been-privacy-clipped-into-semantic-incoherence-before-it-is-exported-across-a-trust-bounda.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-trace-span-has-been-privacy-clipped-into-semantic-incoherence-before-it-is-exported-across-a-trust-bounda.warrant.json
# Markdown SHA-256:   1a3b302d96d865731cd0dd93fd5782a407924905ac86f12668e5b11c9e10fe40
# Code AST SHA-256:   bdbe94a64b35d89f4be3f0e549f2735727fb4844e91391c0bfc3f7080c3fc6e4
# Verified Classes:   SpanCoherenceError, ClippingManifest, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any

class SpanCoherenceError(RuntimeError):
    """Raised when a span is too incoherent to export as a causal record."""
    pass

@dataclass
class ClippingManifest:
    dropped: list[str] = field(default_factory=list)
    generalized: list[str] = field(default_factory=list)
    noised: dict[str, float] = field(default_factory=dict)  # field -> epsilon

    def digest(self) -> str:
        payload = repr((sorted(self.dropped), sorted(self.generalized),
                        sorted(self.noised.items()))).encode()
        return hashlib.sha256(payload).hexdigest()[:16]

@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    attrs: dict[str, Any]
    manifest: ClippingManifest
    agent_identity: str

BOUNDED_FIELDS = {"latency_ms": (0, None), "result_rows": (0, None),
                  "error_rate": (0.0, 1.0)}

def check_span_coherence(span: Span, exported_ids: set[str],
                         identity_tokens: dict[str, str]) -> None:
    # 1. Range violation after DP noise (the negative-latency canary)
    for f, (lo, hi) in BOUNDED_FIELDS.items():
        if f in span.attrs and f not in span.manifest.dropped:
            v = span.attrs[f]
            if (lo is not None and v < lo) or (hi is not None and v > hi):
                raise SpanCoherenceError(
                    f"span {span.span_id}: field {f}={v} violates bound "
                    f"[{lo},{hi}] after noise eps={span.manifest.noised.get(f)}")

    # 2. Orphaned causality: parent not exported and not declared external
    if span.parent_span_id and span.parent_span_id not in exported_ids:
        if "external_ref" not in span.manifest.generalized:
            raise SpanCoherenceError(
                f"span {span.span_id}: parent {span.parent_span_id} absent "
                f"from export and not declared external_ref — causality broken")

    # 3. Status/attribute contradiction
    if span.attrs.get("status") == "ERROR" and "error.message" in span.manifest.dropped:
        raise SpanCoherenceError(
            f"span {span.span_id}: ERROR status with error.message dropped — "
            f"uninterpretable, must downgrade")

    # 4. Identity collapse within this trace
    tok = identity_tokens.get(span.agent_identity)
    if tok is not None:
        collisions = [i for i, t in identity_tokens.items()
                      if t == tok and i != span.agent_identity]
        if collisions:
            raise SpanCoherenceError(
                f"span {span.span_id}: identity {span.agent_identity} generalized "
                f"to same token as {collisions} — auditor/audited indistinguishable")

def export_span(span: Span, exported_ids: set[str],
                identity_tokens: dict[str, str]) -> dict[str, Any]:
    try:
        check_span_coherence(span, exported_ids, identity_tokens)
    except SpanCoherenceError:
        # Downgrade to opaque reference; never export incoherent semantics
        return {
            "span_id": span.span_id,
            "parent_span_id": span.parent_span_id,
            "coherence": "degraded",
            "manifest_digest": span.manifest.digest(),
        }
    return {
        "span_id": span.span_id,
        "parent_span_id": span.parent_span_id,
        "coherence": "full",
        "attrs": span.attrs,
        "manifest_digest": span.manifest.digest(),
    }
