# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-rehydrate-compacted-context-without-silently-resurrecting-superseded-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-rehydrate-compacted-context-without-silently-resurrecting-superseded-state.warrant.json
# Markdown SHA-256:   331c0c3c26b126b59f6587600b837b5265dbce0d2e5bbf39611c21551bd65d89
# Code AST SHA-256:   695ca5cf6fbceaa9a48af42d3b8a14aca80aaac583a476c9161929036269efdb
# Verified Classes:   SupersessionUnresolved
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SupersessionUnresolved(RuntimeError):
    """Raised when a resumed session retrieves an entry whose supersession
    status cannot be resolved from the compacted store, and the pending
    task is a write or diagnosis that would act on resurrected state."""
    pass


def rehydrate_for_action(retrieved_entries, task_kind, supersession_index):
    """
    retrieved_entries: list of dicts with keys 'id', 'content', 'similarity'
    task_kind: 'read' | 'write' | 'diagnose'
    supersession_index: dict mapping entry_id -> superseding_entry_id or None
                        (None means the compactor asserted 'supersedes: none';
                         a MISSING key means the edge was lost in compaction)
    """
    if task_kind == "read":
        # Stale facts are tolerable for idempotent reads.
        return retrieved_entries

    unresolved = []
    for entry in retrieved_entries:
        eid = entry["id"]
        if eid not in supersession_index:
            # Edge was dropped at compaction time; status unknown.
            unresolved.append((eid, "missing_edge"))
            continue
        superseder = supersession_index[eid]
        if superseder is not None:
            # Entry is superseded; it must not drive a write or diagnosis.
            unresolved.append((eid, f"superseded_by:{superseder}"))

    if unresolved:
        raise SupersessionUnresolved(
            f"Refusing to act on task_kind={task_kind!r}: "
            f"{len(unresolved)} retrieved entr(ies) have unresolved "
            f"supersession status {unresolved}. Re-derive current state "
            f"from a live source or halt for adjudication."
        )

    # All retrieved entries are confirmed current (supersedes: none).
    return retrieved_entries


def resolve_and_probe(entry, probe_fn, supersession_index):
    """Probe an endpoint only after confirming it is the current target."""
    current = rehydrate_for_action([entry], "diagnose", supersession_index)
    result = probe_fn(current[0]["content"])
    if not result.reachable:
        # A refused probe against a *confirmed current* target is an outage.
        # Against an unresolved target it would have raised above.
        return {"status": "outage", "target": current[0]["id"]}
    return {"status": "healthy", "target": current[0]["id"]}
