# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-redacts-spans-before-federating-otel-genai-traces-and-silently-destroys-the-parent-child-causal-chain-auditors-need-to-r.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-redacts-spans-before-federating-otel-genai-traces-and-silently-destroys-the-parent-child-causal-chain-auditors-need-to-r.warrant.json
# Markdown SHA-256:   891d2723f206aaf25f70a6c7be1ca177a5fd61dc39609084d7c15d89dc36c75a
# Code AST SHA-256:   67cd999f011e0c7cf65ea919829258e00794474e374e2712c525e0f9fe8f347c
# Verified Classes:   TraceFederationIntegrityError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceFederationIntegrityError(RuntimeError):
    """Raised when a federated OTel GenAI trace violates causal-linkage invariants
    after redaction (deletion/re-parenting instead of tombstoning)."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    span_kind: str
    start_ns: int
    end_ns: int
    service_name: str
    redacted: bool = False
    redaction_policy_id: Optional[str] = None


def assert_federatable(spans: list[Span], topology_integrity: str = "strict") -> None:
    """Enforce the tombstone invariant before spans leave the trust domain.

    In 'strict' mode, every non-root span MUST have a parent present in the
    emitted set (tombstones count as present). Re-parenting to a surviving
    ancestor is a violation because it rewrites causality.
    """
    by_id = {s.span_id: s for s in spans}
    if len(by_id) != len(spans):
        raise TraceFederationIntegrityError("duplicate span_id in federated batch")

    for s in spans:
        if s.parent_span_id is None:
            continue
        parent = by_id.get(s.parent_span_id)
        if parent is None:
            if topology_integrity == "strict":
                raise TraceFederationIntegrityError(
                    f"span {s.span_id} references missing parent "
                    f"{s.parent_span_id}; redaction must tombstone, not delete"
                )
            continue
        # Causal timing check: a child must not start before its parent starts.
        if s.start_ns < parent.start_ns:
            raise TraceFederationIntegrityError(
                f"span {s.span_id} (start={s.start_ns}) precedes parent "
                f"{parent.span_id} (start={parent.start_ns}): "
                f"linkage likely rewritten by re-parenting"
            )
        # A redacted child must carry a policy marker so the auditor can
        # distinguish 'opaque by policy' from 'absent by corruption'.
        if s.redacted and not s.redaction_policy_id:
            raise TraceFederationIntegrityError(
                f"redacted span {s.span_id} missing redaction_policy_id"
            )


def redact_span(span: Span, policy_id: str) -> Span:
    """Tombstone a span: keep structure and identity, drop gen_ai payload."""
    if not policy_id:
        raise TraceFederationIntegrityError("redaction requires a policy_id")
    return Span(
        span_id=span.span_id,               # preserved
        parent_span_id=span.parent_span_id, # preserved — never re-parented
        span_kind=span.span_kind,
        start_ns=span.start_ns,
        end_ns=span.end_ns,
        service_name=span.service_name,
        redacted=True,
        redaction_policy_id=policy_id,
    )


# --- demonstration of the failure the guardrail catches ---
planner = Span("p", None, "SERVER", 100, 900, "planner")
executor = Span("e", "p", "CLIENT", 200, 600, "executor")
verifier = Span("v", "e", "CLIENT", 650, 850, "verifier")

# Correct: tombstone the executor, keep its edge.
safe = [planner, redact_span(executor, "pii-v3"), verifier]
assert_federatable(safe)  # passes; DAG intact

# Broken: executor deleted, verifier re-parented to planner.
broken = [planner, Span("v", "p", "CLIENT", 650, 850, "verifier")]
try:
    assert_federatable(broken)
except TraceFederationIntegrityError as exc:
    print("caught:", exc)
