# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-provenance-consistent-memory-write-that-contradicts-a-lower-trust-but-higher-recency-store-and-how-is.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-provenance-consistent-memory-write-that-contradicts-a-lower-trust-but-higher-recency-store-and-how-is.warrant.json
# Markdown SHA-256:   5491dd1712dc47f31ceb99175ca7d1cd10e1ec7b06d7db1b9e5c6f7893266edb
# Code AST SHA-256:   362bd279b078c3fd3b4aeb888e93e8e975b4442c670d4bd9ee4c73f1eb6cd95e
# Verified Classes:   Tier, AuthorityClass, ContradictionQuarantine, MemoryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class Tier(Enum):
    LOW = 1
    MID = 2
    HIGH = 3


class AuthorityClass(Enum):
    DERIVED = 1        # tool output, distilled fact
    SCRAPE = 2         # unverified external snapshot
    PRICE_OVERRIDE = 3  # human correction, entity-specific authority


# Partial order over authority classes for a given entity class.
# Returns True iff `a` dominates or equals `b`.
_AUTHORITY_DOMINANCE = {
    "price": {
        AuthorityClass.PRICE_OVERRIDE: {AuthorityClass.PRICE_OVERRIDE,
                                        AuthorityClass.DERIVED,
                                        AuthorityClass.SCRAPE},
        AuthorityClass.DERIVED: {AuthorityClass.DERIVED},
        AuthorityClass.SCRAPE: {AuthorityClass.SCRAPE},
    },
}


class ContradictionQuarantine(RuntimeError):
    """Raised when two provenance-valid entries contradict on a single-valued
    attribute and their authority classes are incomparable. The resolver must
    fail closed rather than default to tier precedence."""


@dataclass(frozen=True)
class MemoryEntry:
    entity: str
    attribute: str
    value: object
    tier: Tier
    authority: AuthorityClass
    provenance: str
    recency_ts: float


def _dominates(a: AuthorityClass, b: AuthorityClass, entity_class: str) -> bool:
    lattice = _AUTHORITY_DOMINANCE.get(entity_class)
    if lattice is None:
        # Unknown entity class: no dominance is provable.
        return False
    return b in lattice.get(a, set())


def resolve_contradiction(
    high: MemoryEntry,
    low: MemoryEntry,
    entity_class: str,
    rederivation_deadline_ts: Optional[float],
    now_ts: float,
) -> MemoryEntry:
    """Resolve a contradiction between a higher-trust, more-recent entry and a
    lower-trust, older entry. Quarantine (raise) when authority classes are
    incomparable; never fall back to tier precedence."""
    if high.entity != low.entity or high.attribute != low.attribute:
        raise ContradictionQuarantine(
            f"mismatched keys: {high.entity}.{high.attribute} vs "
            f"{low.entity}.{low.attribute}"
        )
    if high.value == low.value:
        return high

    high_dom = _dominates(high.authority, low.authority, entity_class)
    low_dom = _dominates(low.authority, high.authority, entity_class)

    if high_dom and not low_dom:
        # Class dominance corroborates tier precedence: safe to resolve.
        return high

    if low_dom and not high_dom:
        # The observed failure: tier says high wins, class says low wins.
        # Tier precedence is actively wrong here; quarantine.
        raise ContradictionQuarantine(
            f"authority inversion on {high.entity}.{high.attribute}: "
            f"tier={high.tier.name} authority={high.authority.name} "
            f"(provenance={high.provenance}) contradicts "
            f"tier={low.tier.name} authority={low.authority.name} "
            f"(provenance={low.provenance}); tier precedence is invalid"
        )

    # Incomparable authority classes: quarantine until re-derivation.
    if rederivation_deadline_ts is not None and now_ts > rederivation_deadline_ts:
        # Deadline passed without re-derivation: fail closed, do NOT resolve.
        raise ContradictionQuarantine(
            f"quarantine expired unresolved on {high.entity}.{high.attribute}; "
            f"refusing tier-precedence fallback (provenance high={high.provenance}, "
            f"low={low.provenance})"
        )
    raise ContradictionQuarantine(
        f"incomparable authority on {high.entity}.{high.attribute}: "
        f"{high.authority.name} vs {low.authority.name}; "
        f"quarantine window open until {rederivation_deadline_ts}"
    )
