# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-trace-graph-edges-when-memory-mutations-are-observed-out-of-causal-order-relative-to-the-llm-call-that-motivat.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-causal-trace-graph-edges-when-memory-mutations-are-observed-out-of-causal-order-relative-to-the-llm-call-that-motivat.warrant.json
# Markdown SHA-256:   ffb4ae196bafed0d61b906a25dd573706c69896e041f8fcccdbe147b886e778b
# Code AST SHA-256:   31a28561f1420dccf2eee044cba8b4a001bb5470c89beb024a05f1b95f5c383e
# Verified Classes:   CausalAttributionError, Span, TraceGraph
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class CausalAttributionError(RuntimeError):
    """Raised when a memory mutation cannot be validly attributed to a motivating LLM span."""


@dataclass
class Span:
    span_id: str
    kind: str  # "llm" | "tool" | "memory_mutation"
    closed: bool = False


@dataclass
class TraceGraph:
    spans: dict[str, Span] = field(default_factory=dict)
    parent_of: dict[str, str] = field(default_factory=dict)
    pending: dict[str, list[str]] = field(default_factory=dict)  # motivating_span_id -> [child_ids]

    def open_span(self, span_id: str, kind: str) -> None:
        self.spans[span_id] = Span(span_id=span_id, kind=kind)

    def close_span(self, span_id: str) -> None:
        self.spans[span_id].closed = True
        # Reconcile any mutations that were deferred waiting on this parent.
        for child in self.pending.pop(span_id, []):
            self.parent_of[child] = span_id

    def observe_mutation(self, span_id: str, motivating_span_id: Optional[str]) -> None:
        self.spans[span_id] = Span(span_id=span_id, kind="memory_mutation", closed=True)

        if motivating_span_id is None:
            # No out-of-band context: MUST NOT infer parent from adjacency.
            raise CausalAttributionError(
                f"mutation {span_id} has no motivating_span_id; "
                "refusing nearest-open-span attribution (would corrupt causal walk)"
            )

        parent = self.spans.get(motivating_span_id)
        if parent is None:
            # Parent not yet observed at all: defer, do not orphan silently.
            self.pending.setdefault(motivating_span_id, []).append(span_id)
            return
        if not parent.closed:
            # Parent still streaming (the streaming-tool-call window): defer.
            self.pending.setdefault(motivating_span_id, []).append(span_id)
            return

        self.parent_of[span_id] = motivating_span_id


def walk_backward(graph: TraceGraph, from_span: str) -> list[str]:
    """Return the causal chain from a memory mutation back to its motivating LLM span."""
    chain: list[str] = []
    cur: Optional[str] = from_span
    while cur is not None:
        chain.append(cur)
        cur = graph.parent_of.get(cur)
    root = graph.spans[chain[-1]]
    if root.kind == "memory_mutation":
        raise CausalAttributionError(
            f"walk from {from_span} terminated at unattributed mutation {root.span_id}; "
            "trace is structurally valid but semantically corrupt"
        )
    return chain


def demo() -> None:
    g = TraceGraph()
    g.open_span("llm#7", "llm")
    # Mutation observed mid-stream, before llm#7 closes.
    g.observe_mutation("mem#7", motivating_span_id="llm#7")
    assert "mem#7" not in g.parent_of  # deferred, not mis-attributed to llm#6
    g.close_span("llm#7")
    assert g.parent_of["mem#7"] == "llm#7"
    assert walk_backward(g, "mem#7") == ["mem#7", "llm#7"]

    # Demonstrating the guardrail: context-less mutation is rejected, not guessed.
    try:
        g.observe_mutation("mem#8", motivating_span_id=None)
    except CausalAttributionError:
        pass
    else:
        raise CausalAttributionError("guardrail failed: adjacency attribution was permitted")


if __name__ == "__main__":
    demo()
