# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-redact-a-span-it-cannot-attribute-the-unredactable-span-deadlock-in-cost-attributed-genai-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-redact-a-span-it-cannot-attribute-the-unredactable-span-deadlock-in-cost-attributed-genai-observability-pipelines.warrant.json
# Markdown SHA-256:   d9d8960df6baef0c3424e122eef7226fbd408768d3c8a0c10603c0a13cae9d11
# Code AST SHA-256:   653677377588de277cfa5d1914a018aa6b17f711284edc8414b5a7357bf6e3fe
# Verified Classes:   RedactionOrderingViolation, AttributionMode, Span, TraceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class RedactionOrderingViolation(RuntimeError):
    """Raised when redaction would fire on a span whose descendants still
    require content-dependent attribution, or when a deferred hold expires
    without a valid content-independence proof."""
    pass


class AttributionMode(Enum):
    CONTENT_INDEPENDENT = "content_independent"
    CONTENT_DEPENDENT = "content_dependent"


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_id: Optional[str]
    payload: Optional[str]
    redacted: bool = False
    attributed: bool = False
    redaction_deferred: bool = False


@dataclass
class TraceGraph:
    spans: dict[str, Span] = field(default_factory=dict)
    # sinks that can receive payload-derived bytes; redaction must cover all
    registered_sinks: set[str] = field(default_factory=lambda: {"span_store"})

    def descendants(self, span_id: str) -> list[Span]:
        out, frontier = [], [span_id]
        while frontier:
            cur = frontier.pop()
            for s in self.spans.values():
                if s.parent_id == cur:
                    out.append(s)
                    frontier.append(s.span_id)
        return out


def request_redaction(
    graph: TraceGraph,
    span_id: str,
    attribution_mode: AttributionMode,
    proof_token: Optional[str],
    debug_sink_registered: bool,
) -> None:
    span = graph.spans[span_id]
    open_descendants = [
        d for d in graph.descendants(span_id)
        if not d.redacted and not d.attributed
    ]

    # An unregistered debug sink makes every span look like it has open
    # descendants, because payload bytes can escape through it.
    if not debug_sink_registered:
        open_descendants = open_descendants or [span]

    if not open_descendants:
        span.payload = None
        span.redacted = True
        return

    if attribution_mode is AttributionMode.CONTENT_INDEPENDENT and proof_token:
        span.payload = None
        span.redacted = True
        return

    if attribution_mode is AttributionMode.CONTENT_DEPENDENT:
        span.redaction_deferred = True
        raise RedactionOrderingViolation(
            f"span {span_id} in trace {span.trace_id} has "
            f"{len(open_descendants)} open descendant(s) requiring "
            f"content-dependent attribution; redaction deferred, plaintext held"
        )

    raise RedactionOrderingViolation(
        f"span {span_id}: content-independent attribution asserted without "
        f"a proof token; refusing to redact on unverified claim"
    )
