# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-invalidate-downstream-claims-when-a-provenance-graph-edge-is-retroactively-retracted-mid-generation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-invalidate-downstream-claims-when-a-provenance-graph-edge-is-retroactively-retracted-mid-generation.warrant.json
# Markdown SHA-256:   029e4bd74ee0f4fa829b29788f0e9c69048ae8c36239f339772beb544e9bd9b5
# Code AST SHA-256:   d5789944474651d4aeee39c307ceb8e4ceef6d1fc485c170cbd1e829244d24e1
# Verified Classes:   EdgeType, ProvenanceLagError, Node, CPG
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set, List


class EdgeType(Enum):
    SUPPORT = "support"            # S -> C: C derived from S
    PARAMETERIZATION = "param"     # C -> tool_call: C drives a side effect
    ASSERTION = "assert"           # C -> final_answer: C is asserted to user


class ProvenanceLagError(RuntimeError):
    """Raised when a claim is committed for parameterization/assertion while
    an ancestor source is retracted or stale, i.e. provenance lag > 0."""
    pass


@dataclass
class Node:
    id: str
    kind: str                      # "source" | "claim" | "tool_call" | "answer"
    valid: bool = True
    supersedes: str | None = None
    gen: int = 0                   # monotonic step at which node was created


@dataclass
class CPG:
    nodes: Dict[str, Node] = field(default_factory=dict)
    edges: List[tuple] = field(default_factory=list)   # (src, dst, EdgeType)
    last_mutation_gen: int = 0

    def add(self, node: Node) -> None:
        self.nodes[node.id] = node
        self.last_mutation_gen = max(self.last_mutation_gen, node.gen)

    def link(self, src: str, dst: str, etype: EdgeType) -> None:
        self.edges.append((src, dst, etype))
        self.last_mutation_gen = max(self.last_mutation_gen, self.nodes[dst].gen)

    def retract(self, source_id: str, gen: int) -> None:
        if source_id not in self.nodes:
            raise ProvenanceLagError(f"retract of unknown node {source_id}")
        self.nodes[source_id].valid = False
        self.last_mutation_gen = max(self.last_mutation_gen, gen)

    def ancestors(self, claim_id: str) -> Set[str]:
        seen: Set[str] = set()
        stack = [claim_id]
        while stack:
            cur = stack.pop()
            for src, dst, etype in self.edges:
                if dst == cur and etype == EdgeType.SUPPORT and src not in seen:
                    seen.add(src)
                    stack.append(src)
        return seen

    def commit(self, claim_id: str, etype: EdgeType, gen: int) -> None:
        """Commit a claim for parameterization or assertion. Pessimistic check:
        every SUPPORT ancestor must be valid AND the check must be fresh
        (no CPG mutation since the claim was created)."""
        if etype == EdgeType.SUPPORT:
            return  # optimistic path is sound for support-only edges
        node = self.nodes[claim_id]
        if self.last_mutation_gen > node.gen:
            raise ProvenanceLagError(
                f"claim {claim_id} committed at gen {gen} but CPG mutated at "
                f"gen {self.last_mutation_gen}; re-ground before {etype.value}"
            )
        for anc in self.ancestors(claim_id):
            if not self.nodes[anc].valid:
                raise ProvenanceLagError(
                    f"claim {claim_id} has retracted ancestor {anc}; "
                    f"cannot add {etype.value} edge"
                )


def issue_migration(cpg: CPG, claim_id: str, gen: int) -> str:
    # Raises before the side effect fires if any ancestor is retracted.
    cpg.commit(claim_id, EdgeType.PARAMETERIZATION, gen)
    return "migration fired"
