# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-a-causal-span-before-a-reflection-loop-re-enters-planning-or-the-decision-trace-silently-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-a-causal-span-before-a-reflection-loop-re-enters-planning-or-the-decision-trace-silently-forks.warrant.json
# Markdown SHA-256:   0c0179adfa19a19651e379f3eb9b15b0ad0cec53adb3b4b1a2512ce734d42fea
# Code AST SHA-256:   ba47ea405c2231a09fc6fa665b2e678275b0e75e797db7514c6c35a001998c11
# Verified Classes:   ForkedDecisionTraceError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ForkedDecisionTraceError(RuntimeError):
    """Raised when a non-terminal reflection verdict produced no causal edge
    to the re-entrant planning span (no parent edge and no effect edge)."""


TERMINAL_VERDICTS = frozenset({"ACCEPT", "ABORT"})


@dataclass
class Span:
    span_id: str
    kind: str                      # "plan" | "tool" | "reflect"
    parent_id: Optional[str]
    verdict: Optional[str] = None  # set on reflect spans
    caused_by: Optional[str] = None  # effect edge: this span was caused by X
    caused_span_id: Optional[str] = None  # effect edge: this span caused Y
    children: list = field(default_factory=list)


def validate_reflection_loop_edges(spans: dict[str, Span]) -> None:
    """Enforce: every non-terminal reflection span has a downstream edge.

    A downstream edge is satisfied by EITHER:
      (a) a planning span whose parent_id == reflection.span_id, or
      (b) the reflection span declaring caused_span_id (effect edge).
    Otherwise the trace is forked and causal attribution is unsound.
    """
    children_by_parent: dict[Optional[str], list[str]] = {}
    for s in spans.values():
        children_by_parent.setdefault(s.parent_id, []).append(s.span_id)

    for s in spans.values():
        if s.kind != "reflect":
            continue
        if s.verdict is None:
            raise ForkedDecisionTraceError(
                f"reflection span {s.span_id} has no verdict; "
                f"loop-back causality is unobservable"
            )
        if s.verdict in TERMINAL_VERDICTS:
            continue  # no re-entry expected; sibling/silence is legal

        # Non-terminal verdict: require a causal edge.
        has_parent_edge = any(
            spans[cid].kind == "plan"
            for cid in children_by_parent.get(s.span_id, [])
        )
        has_effect_edge = s.caused_span_id is not None and (
            s.caused_span_id in spans
            and spans[s.caused_span_id].caused_by == s.span_id
        )

        if not (has_parent_edge or has_effect_edge):
            raise ForkedDecisionTraceError(
                f"reflection span {s.span_id} returned {s.verdict!r} but "
                f"emitted no loop-back edge: no planning child and no "
                f"caused_span_id effect edge. Decision trace is forked; "
                f"causal queries over this episode are unsound."
            )


# --- observed failing episode ---
episode = {
    "root": Span("root", "plan", None),
    "P1": Span("P1", "plan", "root"),
    "T2": Span("T2", "tool", "P1"),
    "R1": Span("R1", "reflect", "root", verdict="REVISE"),
    "P2": Span("P2", "plan", "root"),  # sibling of P1 — the fork
    "T3": Span("T3", "tool", "P2"),
    "R2": Span("R2", "reflect", "root", verdict="ACCEPT"),
}

validate_reflection_loop_edges(episode)  # raises ForkedDecisionTraceError
