# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-then-rehydrates-a-dropped-span-that-was-already-mutated-by-a-later-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-then-rehydrates-a-dropped-span-that-was-already-mutated-by-a-later-tool-call.warrant.json
# Markdown SHA-256:   0405bde53e5feacd6b3c1cbf2377961834aef23f7bb35d90102308d7b627635f
# Code AST SHA-256:   772020ef8d8eed77d457a78a9f473fd4812d7bd6916427e3764c32204ead2c6a
# Verified Classes:   StaleRehydrationError, ArchivedSpan, Mutation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleRehydrationError(RuntimeError):
    """Raised when a rehydrated span is superseded by a later mutation."""
    pass


@dataclass
class ArchivedSpan:
    turn_id: int
    entity: Optional[str]       # what the span is *about*; None = unidentifiable
    content: str
    superseded_by: Optional[int] = None   # turn id of the mutation that invalidated it


@dataclass
class Mutation:
    turn_id: int
    entity: str
    new_value: str


def rehydrate(
    span: ArchivedSpan,
    mutations: list[Mutation],
    current_turn: int,
) -> tuple[str, bool]:
    """
    Return (content, is_authoritative). Never silently returns pre-mutation
    state as authoritative. Raises if the span is unidentifiable and would
    contradict a postdating summary.
    """
    if span.entity is None:
        # Unidentifiable subject: advisory only. Never authoritative.
        return span.content, False

    later = [m for m in mutations if m.entity == span.entity and m.turn_id > span.turn_id]
    if later or span.superseded_by is not None:
        superseding = max(
            [m.turn_id for m in later] + ([span.superseded_by] if span.superseded_by else [])
        )
        if superseding < current_turn:
            # The span predates a mutation the agent has already acted on.
            # Surfacing it as raw evidence would resurrect pre-mutation state.
            raise StaleRehydrationError(
                f"span from turn {span.turn_id} about {span.entity!r} "
                f"superseded by turn {superseding}; re-read that turn before trusting"
            )
        return span.content, False

    return span.content, True
