# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-graph-corruption-when-observability-pipelines-retroactively-re-parent-spans-across-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-graph-corruption-when-observability-pipelines-retroactively-re-parent-spans-across-agent-handoffs.warrant.json
# Markdown SHA-256:   21a700d1ae33eb4ac46b3d1f0fd15539a5b79fcee47ff6aca214b0e71d2ad957
# Code AST SHA-256:   11883d53726cceb19e80b1e454630eb44a9d5249f25f628a3b754883c700faf9
# Verified Classes:   UnsealedEpochError, TraceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsealedEpochError(RuntimeError):
    """Raised when a consumer reads a trace epoch whose handoff parent has not been observed."""
    pass


class TraceGraph:
    def __init__(self):
        self.spans = {}            # span_id -> {parent, epoch, sealed}
        self.mutations = []        # first-class re-parent records
        self.pending = {}          # claimed_parent_id -> [child span_ids]

    def admit(self, span_id, claimed_parent, epoch):
        # Provisional attachment is tagged with epoch; never silently re-rooted.
        self.spans[span_id] = {"parent": claimed_parent, "epoch": epoch, "sealed": False}
        if claimed_parent not in self.spans:
            self.pending.setdefault(claimed_parent, []).append(span_id)

    def observe_parent(self, parent_id):
        # Late-arriving parent: re-parent waiting children, but record the mutation.
        for child in self.pending.pop(parent_id, []):
            old = self.spans[child]["parent"]
            self.spans[child]["parent"] = parent_id
            self.mutations.append(
                {"child": child, "old_parent": old, "new_parent": parent_id,
                 "epoch": self.spans[child]["epoch"]}
            )

    def seal_epoch(self, epoch):
        for s in self.spans.values():
            if s["epoch"] == epoch:
                s["sealed"] = True

    def read_for_verifier(self, span_id):
        s = self.spans.get(span_id)
        if s is None:
            raise UnsealedEpochError(f"span {span_id} unknown")
        if not s["sealed"]:
            raise UnsealedEpochError(
                f"span {span_id} belongs to unsealed epoch {s['epoch']}; "
                f"handoff parent not yet observed — refusing to let verifier act on mutable topology"
            )
        return s
