# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-compaction-induced-referential-drift-when-a-lossless-fallback-index-silently-disagrees-with-the-compacted-working-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-compaction-induced-referential-drift-when-a-lossless-fallback-index-silently-disagrees-with-the-compacted-working-context.warrant.json
# Markdown SHA-256:   e9a8ccbcf824d28a8f88546e1cabffa7657295e5126cb43e94bb1b7fcb1864f6
# Code AST SHA-256:   190896705bc6d9fb37cc519e3e6fd2e2e0609d0dcea267f21aadb3cc17f3de4f
# Verified Classes:   ReferentialDriftError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ReferentialDriftError(RuntimeError):
    """Raised when a compacted reference fails to bind uniquely to the object
    the pre-compaction context would have resolved to, despite a successful
    (byte-lossless) retrieval from the fallback index."""


def resolve_compacted_reference(reference, fallback_index, binding_table):
    # A reference surviving compaction must carry an explicit binding recorded
    # at compaction time. Absent binding => we cannot know the intended referent.
    binding = binding_table.get(reference.ref_id)
    if binding is None:
        raise ReferentialDriftError(
            f"reference {reference.ref_id!r} has no recorded binding; "
            f"lossless retrieval cannot recover the intended referent"
        )

    # Unit congruence: the reference addresses objects at `reference.unit`
    # granularity; the index must key at that same unit.
    if binding.unit != fallback_index.key_unit:
        raise ReferentialDriftError(
            f"unit mismatch: reference addresses {binding.unit!r}, "
            f"index keys {fallback_index.key_unit!r}; top-1 retrieval is unsound"
        )

    candidates = fallback_index.lookup(binding.object_id, unit=binding.unit)
    if len(candidates) != 1:
        # Ambiguity is a hard stop, not a ranking problem.
        raise ReferentialDriftError(
            f"reference {reference.ref_id!r} binds to {len(candidates)} objects; "
            f"re-expand the evicted span and re-resolve inline"
        )

    obj = candidates[0]
    if obj.content_hash != binding.content_hash_at_compaction:
        raise ReferentialDriftError(
            f"object {binding.object_id!r} mutated since compaction "
            f"(expected {binding.content_hash_at_compaction}, got {obj.content_hash}); "
            f"binding is stale"
        )
    return obj
