# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-trace-has-lost-causal-closure-across-sub-agent-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-trace-has-lost-causal-closure-across-sub-agent-fan-out.warrant.json
# Markdown SHA-256:   714703470439397d62c62585ad71f46ac6e06080217097d2197b20ac3c7051aa
# Code AST SHA-256:   92ea731edd20b5cafe9e3e2d6ba7f6244f385a27e578cf9788d5db8d758c2331
# Verified Classes:   CausalClosureError, Span
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalClosureError(RuntimeError):
    """Raised when a reconstructed trace cannot prove causal closure."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    kind: str  # "fanout", "child", "synthesis"
    status: str  # "ok", "error", "cancelled"
    delegation_id: Optional[str] = None
    attempt: int = 1
    retry_of: Optional[str] = None
    cancelled_by: Optional[str] = None
    consumes: list = field(default_factory=list)
    start_time: float = 0.0
    end_time: float = 0.0


def assert_closure(synthesis: Span, children: list, allow_timestamp_fallback: bool = False) -> None:
    if synthesis.kind != "synthesis":
        raise CausalClosureError(
            f"span {synthesis.span_id} is not a synthesis span; closure check inapplicable"
        )

    if not children:
        return  # nothing to close over

    # Invariant 1: retries must be explicitly linked, never inferred.
    for c in children:
        if c.attempt > 1 and c.retry_of is None:
            raise CausalClosureError(
                f"child {c.span_id} has attempt={c.attempt} but no retry_of edge; "
                f"retry provenance lost under fan-out"
            )

    # Invariant 2: cancellations must point at their decider.
    for c in children:
        if c.status == "cancelled" and c.cancelled_by is None:
            raise CausalClosureError(
                f"child {c.span_id} cancelled without cancelled_by edge; "
                f"causal attribution to parent decision lost"
            )

    # Invariant 3: every consumed child must be an explicit edge.
    if not synthesis.consumes:
        if not allow_timestamp_fallback:
            raise CausalClosureError(
                f"synthesis {synthesis.span_id} has {len(children)} child spans "
                f"but zero consumes edges; refusing timestamp-based inference "
                f"(closure unprovable under concurrent fan-out)"
            )
        # Explicit opt-in fallback: infer, but flag it.
        inferred = [c.span_id for c in children if c.end_time <= synthesis.start_time]
        if any(c.status == "cancelled" for c in children if c.span_id in inferred):
            raise CausalClosureError(
                f"timestamp fallback would attribute a cancelled child's output "
                f"to synthesis {synthesis.span_id}; closure inverted"
            )
        return

    # Invariant 4: declared consumption must reference a real, non-cancelled child.
    child_ids = {c.span_id for c in children}
    for cited in synthesis.consumes:
        if cited not in child_ids:
            raise CausalClosureError(
                f"synthesis {synthesis.span_id} consumes unknown span {cited}"
            )
        child = next(c for c in children if c.span_id == cited)
        if child.status == "cancelled":
            raise CausalClosureError(
                f"synthesis {synthesis.span_id} consumes cancelled child {cited}; "
                f"dependency inversion"
            )


# Example trigger: fan-out with a retried child and a cancelled sibling,
# synthesis emitted without consumes edges.
children = [
    Span("s3_a", "fan", "child", "error", delegation_id="d3", attempt=1),
    Span("s3_b", "fan", "child", "ok", delegation_id="d3", attempt=2, retry_of="s3_a"),
    Span("s4", "fan", "child", "cancelled", delegation_id="d4", cancelled_by="decide"),
]
synthesis = Span("syn", "root", "synthesis", "ok", start_time=10.0, end_time=11.0)
try:
    assert_closure(synthesis, children)
except CausalClosureError as e:
    print("closure loss detected:", e)
