# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mutates-its-trace-graph-mid-span-and-orphans-the-retrieval-ancestors-of-a-tool-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mutates-its-trace-graph-mid-span-and-orphans-the-retrieval-ancestors-of-a-tool-side-effect.warrant.json
# Markdown SHA-256:   ebf392cf5eda77df838ffbe059e3128adffec91a2660af5e60d0f33be544daa7
# Code AST SHA-256:   063f433f666f54bfeb1c5c86eb3f42913837f080bf36655facf83a8d9313b1a8
# Verified Classes:   OrphanedProvenanceError, Span, TraceGraph
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class OrphanedProvenanceError(RuntimeError):
    """Raised when a side-effecting span's ancestor path cannot be resolved
    to at least one live-or-tombstoned retrieval span with a resolvable hash."""
    pass


@dataclass
class Span:
    span_id: str
    kind: str  # "retrieval" | "prompt" | "tool" | "reasoning"
    parent_span_id: Optional[str]
    content_hash: Optional[str] = None
    payload: Optional[str] = None
    side_effecting: bool = False
    tombstoned: bool = False


class TraceGraph:
    def __init__(self) -> None:
        self._spans: dict[str, Span] = {}
        self._content_store: dict[str, str] = {}

    def commit(self, span: Span) -> None:
        if span.content_hash and span.payload is not None:
            self._content_store[span.content_hash] = span.payload
        self._spans[span.span_id] = span

    def evict_payload(self, span_id: str) -> None:
        """Evict payload to a tombstone, preserving the causal edge."""
        span = self._spans[span_id]
        span.payload = None
        span.tombstoned = True
        # content_hash is deliberately retained; the edge stays traversable.

    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_span_id == cur:
                    out.append(s)
                    frontier.append(s.span_id)
        return out

    def assert_attributable(self, tool_span_id: str) -> None:
        tool = self._spans.get(tool_span_id)
        if tool is None or not tool.side_effecting:
            return
        # Walk ancestry; require a resolvable retrieval root.
        cur: Optional[Span] = tool
        resolved_retrieval = False
        seen: set[str] = set()
        while cur is not None and cur.parent_span_id is not None:
            if cur.parent_span_id in seen:
                raise OrphanedProvenanceError(
                    f"cycle detected at {cur.parent_span_id}"
                )
            seen.add(cur.parent_span_id)
            parent = self._spans.get(cur.parent_span_id)
            if parent is None:
                raise OrphanedProvenanceError(
                    f"dangling edge: {cur.span_id} -> {cur.parent_span_id}; "
                    f"side effect {tool_span_id} is unattributable"
                )
            if parent.kind == "retrieval":
                if not parent.content_hash:
                    raise OrphanedProvenanceError(
                        f"retrieval {parent.span_id} lacks content hash"
                    )
                if parent.content_hash not in self._content_store:
                    raise OrphanedProvenanceError(
                        f"retrieval {parent.span_id} hash "
                        f"{parent.content_hash} unresolvable at audit time"
                    )
                resolved_retrieval = True
            cur = parent
        if not resolved_retrieval:
            raise OrphanedProvenanceError(
                f"side effect {tool_span_id} has no retrieval ancestor"
            )


def plan_eviction(graph: TraceGraph, candidate_id: str) -> str:
    """Return 'free' or 'tombstone' for a payload eviction candidate."""
    descendant_effects = [
        s for s in graph._descendants(candidate_id) if s.side_effecting
    ]
    if descendant_effects:
        return "tombstone"
    return "free"
