# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-context-compaction-from-silently-corrupting-an-agent-s-task-state-during-retrieval-backed-rehydration.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-context-compaction-from-silently-corrupting-an-agent-s-task-state-during-retrieval-backed-rehydration.warrant.json
# Markdown SHA-256:   eae16bc5b5463ab59919280566624d74f995e766479a95143bd8be9d3c593963
# Code AST SHA-256:   32fd756fc0df5980199c827d2cfc0db877c08d80c8ac94273cbef1854dcd6291
# Verified Classes:   CompactionRehydrationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionRehydrationError(RuntimeError):
    """Raised when a rehydrated span cannot be proven to be the antecedent of a summary assertion."""
    pass


def rehydrate(summary_assertion, retrieved_span):
    """
    summary_assertion: dict with keys 'entity', 'predicate', 'value', 'provenance' (set of span_ids)
    retrieved_span:   dict with keys 'span_id', 'entity', 'predicate', 'value'
    Returns the span as authoritative ONLY if provenance and entity both match.
    """
    if retrieved_span["span_id"] not in summary_assertion["provenance"]:
        # Retrieval returned a semantic neighbor, not the source span.
        raise CompactionRehydrationError(
            f"span {retrieved_span['span_id']} is not in provenance "
            f"{sorted(summary_assertion['provenance'])}; treat as advisory, re-fetch from source"
        )

    if retrieved_span["entity"] != summary_assertion["entity"]:
        # The dangerous case: summary fused across an entity boundary.
        raise CompactionRehydrationError(
            f"entity mismatch: summary bound predicate to {summary_assertion['entity']!r} "
            f"but retrieved span belongs to {retrieved_span['entity']!r}; "
            f"summary likely fused spans across entities — do not act, re-fetch"
        )

    return retrieved_span


def safe_act(summary_assertion, retrieved_span, action):
    try:
        antecedent = rehydrate(summary_assertion, retrieved_span)
    except CompactionRehydrationError:
        # Fall back to live source; never act on advisory reconstruction.
        return action.refetch_and_verify(summary_assertion["entity"])
    return action.execute(antecedent)
