# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-demote-a-semantic-memory-to-episodic-before-retrieval-and-why-does-the-write-time-classifier-fail-to-detect-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-demote-a-semantic-memory-to-episodic-before-retrieval-and-why-does-the-write-time-classifier-fail-to-detect-it.warrant.json
# Markdown SHA-256:   6f05fd71b1db9c212d629852db097bd77bf71338cdbfe223026291dc873e3fb8
# Code AST SHA-256:   d3ebb9fe94060990a5f565c0bb7dca0b615f2b2703da1af2a5a49bd77c227d79
# Verified Classes:   SemanticDemotionError, MemoryItem
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SemanticDemotionError(RuntimeError):
    """Raised when a semantic memory cannot be safely demoted or resolved."""
    pass


@dataclass
class MemoryItem:
    item_id: str
    text: str
    tier: str                      # "semantic" | "episodic"
    subject: Optional[str] = None
    attribute: Optional[str] = None
    superseded_by: Optional[str] = None
    embedding_score: float = 0.0


def resolve_co_referent(item: MemoryItem, existing: list[MemoryItem]) -> Optional[MemoryItem]:
    """Return the most recent existing item sharing (subject, attribute), if any."""
    if item.subject is None or item.attribute is None:
        return None
    matches = [
        m for m in existing
        if m.subject == item.subject
        and m.attribute == item.attribute
        and m.superseded_by is None
    ]
    if not matches:
        return None
    return max(matches, key=lambda m: m.item_id)


def write_with_demotion(item: MemoryItem, store: list[MemoryItem],
                        durability_score: float, threshold: float = 0.62) -> None:
    """
    Enforce the demotion invariant: a later co-referent write demotes the
    older semantic item to episodic before the new item is committed.
    """
    if item.subject is None or item.attribute is None:
        raise SemanticDemotionError(
            f"item {item.item_id} has no (subject, attribute) key; "
            "co-reference detection cannot run and a stale semantic item "
            "could silently outrank its correction"
        )

    prior = resolve_co_referent(item, store)
    if prior is not None and prior.tier == "semantic":
        # Demote before writing the new item, so the tier prior never
        # applies to a contradicted fact.
        prior.tier = "episodic"
        prior.superseded_by = item.item_id

    # Only promote the new item if it passes the durability classifier;
    # otherwise it enters as episodic and the pair remains re-rankable.
    item.tier = "semantic" if durability_score >= threshold else "episodic"
    store.append(item)


def retrieve(query_score: dict[str, float], store: list[MemoryItem],
             tier_prior: float = 1.4) -> list[MemoryItem]:
    """Rank with tier prior applied only to non-superseded items."""
    ranked = []
    for m in store:
        base = query_score.get(m.item_id, 0.0)
        weight = 1.0 if m.superseded_by is not None else (
            tier_prior if m.tier == "semantic" else 1.0
        )
        m.embedding_score = base * weight
        ranked.append(m)
    ranked.sort(key=lambda m: m.embedding_score, reverse=True)
    return ranked


# --- observed failure reproduction ---
store: list[MemoryItem] = []
write_with_demotion(
    MemoryItem("m1", "staging cluster failover target is node-7", "semantic",
               subject="staging_cluster", attribute="failover_target"),
    store, durability_score=0.80,
)
# 26 days later, topology change is written; co-reference fires, m1 demoted.
write_with_demotion(
    MemoryItem("m2", "failover target moved to node-9", "episodic",
               subject="staging_cluster", attribute="failover_target"),
    store, durability_score=0.40,
)

assert store[0].tier == "episodic" and store[0].superseded_by == "m2"

ranked = retrieve({"m1": 0.58, "m2": 0.45}, store)
if ranked[0].item_id != "m2":
    raise SemanticDemotionError(
        "demotion invariant violated: stale semantic item outranked its "
        "correction; tier prior was applied to a superseded memory"
    )
