# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-context-mid-task-and-the-rehydration-retrieval-cannot-distinguish-a-superseded-fact-from-its-replacement.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-context-mid-task-and-the-rehydration-retrieval-cannot-distinguish-a-superseded-fact-from-its-replacement.warrant.json
# Markdown SHA-256:   dd943164efcccb41eada54456857ced198024c818fe767c928ace02d5ba646db
# Code AST SHA-256:   582f3aa361d8d6da5d43b7854f1a47f136c73b92d07c462807f4c782d7ca0d00
# Verified Classes:   SupersededRehydrationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SupersededRehydrationError(RuntimeError):
    """Raised when rehydration returns a span that a later span supersedes."""
    pass


def rehydrate(
    query: str,
    retrieved: list[dict],
    supersession_index: dict[str, list[str]],
) -> dict:
    """
    retrieved: list of {"key": str, "value": str, "turn": int, "span_id": str}
    supersession_index: key -> ordered list of span_ids, oldest first.
    Returns the single authoritative span for the query's target key,
    or raises if ordering cannot be established.
    """
    if not retrieved:
        raise SupersededRehydrationError(
            f"rehydration for {query!r} returned no spans; cannot proceed on memory"
        )

    # Group by key; a query may match spans across several keys.
    by_key: dict[str, list[dict]] = {}
    for span in retrieved:
        by_key.setdefault(span["key"], []).append(span)

    resolved: dict[str, dict] = {}
    for key, spans in by_key.items():
        order = supersession_index.get(key)
        if order is None:
            # No supersession metadata survived compaction: unsafe to trust.
            raise SupersededRehydrationError(
                f"key {key!r} has no supersession index; "
                f"retrieved spans cannot be ordered, must re-execute live"
            )
        # Keep only spans whose span_id appears in the index, then take latest.
        ranked = [s for s in spans if s["span_id"] in order]
        if not ranked:
            raise SupersededRehydrationError(
                f"key {key!r} retrieved spans {[s['span_id'] for s in spans]} "
                f"are all absent from supersession index {order}"
            )
        latest = max(ranked, key=lambda s: order.index(s["span_id"]))
        # Reject if any retrieved span for this key is newer than the one
        # the caller is about to trust — the caller must reconcile.
        newer = [s for s in ranked if order.index(s["span_id"]) > order.index(latest["span_id"])]
        if newer:
            raise SupersededRehydrationError(
                f"key {key!r}: span {latest['span_id']} is superseded by "
                f"{[s['span_id'] for s in newer]}"
            )
        resolved[key] = latest

    return resolved
