# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-links-causal-spans-across-a-mid-trace-context-eviction-and-re-derives-parent-ids-from-a-lossy-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-links-causal-spans-across-a-mid-trace-context-eviction-and-re-derives-parent-ids-from-a-lossy-summary.warrant.json
# Markdown SHA-256:   eaa277649e9f3b17b8e7f0d747401c7371ef6e251e96934a655f158496215452
# Code AST SHA-256:   061d374badb7f4bb3e11a6397c695e7764d144663317a4b5c2e1791683c290be
# Verified Classes:   CausalEdgeViolation, SpanContext, Instance
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalEdgeViolation(RuntimeError):
    """Raised when a span attempts to parent to a handle that was not
    carried live across the instance's own context boundary."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str


@dataclass
class Instance:
    name: str
    live: Optional[SpanContext] = None
    # Handles this instance actually held live (not inferred from summary).
    carried: set = field(default_factory=set)

    def adopt(self, ctx: SpanContext) -> None:
        self.live = ctx
        self.carried.add(ctx.span_id)

    def resume_from_summary(self, summary_parent_hint: str,
                            new_span: SpanContext) -> None:
        """Resume after eviction. The hint is prose-derived and NOT a handle.
        We open a fresh span; we never adopt the hinted id as live."""
        self.live = new_span
        self.carried.add(new_span.span_id)
        # The hint is recorded as a non-structural link only.
        self._resumed_from = summary_parent_hint

    def emit_child(self, child_span_id: str,
                   proposed_parent: str) -> dict:
        if proposed_parent not in self.carried:
            # Reconstructive edge: the instance is interpreting a summary.
            # Downgrade: re-root to the live span, record resumed_from.
            if self.live is None:
                raise CausalEdgeViolation(
                    f"{self.name}: no live span; cannot emit "
                    f"{child_span_id} with reconstructive parent "
                    f"{proposed_parent}"
                )
            return {
                "span_id": child_span_id,
                "parent_span_id": self.live.span_id,
                "resumed_from": proposed_parent,
                "reconstructed": True,
            }
        return {
            "span_id": child_span_id,
            "parent_span_id": proposed_parent,
            "reconstructed": False,
        }
