# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-compaction-rehydration-as-a-provenance-problem-not-a-retrieval-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-compaction-rehydration-as-a-provenance-problem-not-a-retrieval-problem.warrant.json
# Markdown SHA-256:   cec0222f20e42d3a8409c402b0b7fd38737e9d9a2b85e01d0b8dbf52f9c71bc3
# Code AST SHA-256:   4024239e1954608a70bc3cc491ff719db517a97dc01719871eba6f7173fcc942
# Verified Classes:   AmbiguousRehydrationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AmbiguousRehydrationError(RuntimeError):
    """Raised when a rehydration handle resolves to more than one artifact
    and the instance cannot disambiguate from live context."""
    pass


def rehydrate(handle: str, store, live_context: dict) -> dict:
    """
    Resolve a summary-emitted handle against the artifact store.

    Invariant: a handle may be consumed only if it resolves to exactly one
    artifact, OR if a discriminator in live_context selects one. Rank-1
    consumption of an ambiguous handle is forbidden.
    """
    candidates = store.match(handle)  # ranked, may be empty or many

    if not candidates:
        raise AmbiguousRehydrationError(
            f"handle {handle!r} resolved to zero artifacts; "
            f"summarizer emitted a dangling reference"
        )

    if len(candidates) == 1:
        return candidates[0]

    # cardinality > 1: must disambiguate against live context
    discriminator = live_context.get("discriminator_for", {}).get(handle)
    if discriminator is None:
        raise AmbiguousRehydrationError(
            f"handle {handle!r} is non-injective: {len(candidates)} candidates "
            f"and no discriminator in live context; compaction dropped the "
            f"selector. Refusing rank-1 consumption."
        )

    selected = [c for c in candidates if c.matches(discriminator)]
    if len(selected) != 1:
        raise AmbiguousRehydrationError(
            f"handle {handle!r} discriminator {discriminator!r} selected "
            f"{len(selected)} artifacts; expected exactly 1"
        )
    return selected[0]


def compact_step(summary_handle: str, store, live_context: dict) -> dict:
    """Wrapper demonstrating the guarded path an agent loop must use."""
    try:
        return rehydrate(summary_handle, store, live_context)
    except AmbiguousRehydrationError:
        # escalate: do not silently proceed with a plausible-but-wrong artifact
        raise
