# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-sampling-as-a-state-continuity-hazard-rather-than-a-telemetry-cost-lever-in-long-running-agent-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-sampling-as-a-state-continuity-hazard-rather-than-a-telemetry-cost-lever-in-long-running-agent-sessions.warrant.json
# Markdown SHA-256:   156e014e027b7e860bf7e2036ed73e4c1a93505e147cf874f46998f17ef7ba92
# Code AST SHA-256:   0ceda50ec7c00b5dcb13840193add7893cbc87dc8da3a415f852c6de3f33b99f
# Verified Classes:   ContinuityClass, TraceContinuityError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ContinuityClass(Enum):
    ANCHOR = "anchor"      # writes durable state / negotiates contracts; never dropped
    DERIVED = "derived"    # reasons over anchors; retained if any dependency is retained
    LEAF = "leaf"          # terminal, no downstream readers; freely samplable


class TraceContinuityError(RuntimeError):
    """Raised when a trace marked replayable has unresolved causal references."""


@dataclass
class Span:
    span_id: str
    continuity_class: ContinuityClass
    depends_on: list[str] = field(default_factory=list)   # causal antecedents, not just parent
    retained: bool = False
    summary_of: list[str] = field(default_factory=list)   # span_ids this summary stands in for


def enforce_chain_closure(spans: list[Span], *, replayable: bool) -> list[Span]:
    """Retain the minimal causally-closed set, or reject a replayable trace that isn't closed.

    Invariant: for every retained span S and every dependency D in S.depends_on,
    D is retained OR covered by a retained summary span. Retention probability is a
    property of the causal edge, so a DERIVED span is retained iff any dependency is.
    """
    by_id = {s.span_id: s for s in spans}

    # Anchors are unconditionally retained.
    for s in spans:
        if s.continuity_class is ContinuityClass.ANCHOR:
            s.retained = True

    # Fixpoint: retain DERIVED spans whose any dependency is retained.
    changed = True
    while changed:
        changed = False
        for s in spans:
            if s.retained or s.continuity_class is not ContinuityClass.DERIVED:
                continue
            if any(by_id.get(d) and by_id[d].retained for d in s.depends_on):
                s.retained = True
                changed = True

    if not replayable:
        return [s for s in spans if s.retained]

    # Replayable traces must have zero unresolved causal references.
    covered = set()
    for s in spans:
        if s.retained:
            covered.add(s.span_id)
            covered.update(s.summary_of)

    unresolved = []
    for s in spans:
        if not s.retained:
            continue
        for d in s.depends_on:
            if d not in covered:
                unresolved.append((s.span_id, d))

    if unresolved:
        raise TraceContinuityError(
            f"replayable trace has {len(unresolved)} unresolved causal references; "
            f"first: retained span {unresolved[0][0]} depends on dropped span "
            f"{unresolved[0][1]}. Refusing to emit a trace that asserts continuity "
            f"it cannot substantiate — retain the anchor or add a summary span."
        )

    return [s for s in spans if s.retained]
