# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-semantic-recall-when-a-hot-tier-eviction-races-a-warm-tier-promotion.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-semantic-recall-when-a-hot-tier-eviction-races-a-warm-tier-promotion.warrant.json
# Markdown SHA-256:   56549366893f67802d14792d752aeb4c972db2a19df3314a8df3acc3cbdc0230
# Code AST SHA-256:   f6a8a5a936748ea1ff131f2fe45fc7e9bade4f4c55e8f887f3d70fd215e23992
# Verified Classes:   ResidencyInversionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResidencyInversionError(RuntimeError):
    """Raised when an eviction write-back supersedes a causally-later promotion."""
    pass


def commit_residency(register, item_id, op, generation, tier, stamp):
    """Compare-and-swap residency mutation with causal ordering.

    op: 'promote' | 'evict'. Promotion dominates a concurrent eviction.
    """
    current = register.get(item_id)
    if current is not None and current["generation"] != generation:
        # Generation moved under us: a concurrent op committed.
        if op == "promote" and current["tier"] == "WARM":
            # Promotion lost the race to an eviction; evidence must win.
            # Re-issue on top of the eviction's generation with priority.
            register[item_id] = {
                "generation": current["generation"] + 1,
                "tier": "HOT",
                "stamp": stamp,
                "priority": "promotion_retry",
            }
            return register[item_id]
        if op == "evict" and current["tier"] == "HOT":
            # Eviction lost to a promotion; discard the write-back.
            return current
        raise ResidencyInversionError(
            f"unresolvable contention on {item_id}: op={op} "
            f"gen={generation} current_gen={current['generation']}"
        )
    register[item_id] = {
        "generation": (current["generation"] + 1) if current else 1,
        "tier": tier,
        "stamp": stamp,
        "priority": None,
    }
    return register[item_id]


def audit_eviction_batch(register, warm_index, evicted_ids):
    """Post-eviction residency audit: every evicted item must resolve
    in warm tier with a stamp >= its eviction stamp and no pending promotion."""
    for item_id in evicted_ids:
        rec = register.get(item_id)
        warm = warm_index.get(item_id)
        if rec is None or warm is None:
            raise ResidencyInversionError(
                f"{item_id} evicted but not resolvable in warm tier"
            )
        if rec["tier"] == "HOT":
            # A promotion is pending or committed; eviction must not stand.
            raise ResidencyInversionError(
                f"{item_id} evicted while resident HOT (pending promotion)"
            )
        if warm["stamp"] < rec["stamp"]:
            raise ResidencyInversionError(
                f"{item_id} stale warm record: warm_stamp={warm['stamp']} "
                f"< evict_stamp={rec['stamp']}"
            )
    return True
