# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-episodic-to-semantic-promotion-from-silently-overwriting-contradictory-session-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-episodic-to-semantic-promotion-from-silently-overwriting-contradictory-session-memory.warrant.json
# Markdown SHA-256:   1ca7690cef2f01b7977db2a83dddc368e699dec473fa0b1446650f7c7c243266
# Code AST SHA-256:   60a7343410d67e3342d9d025f06474475d247d1f3584956ea72d076192e2c630
# Verified Classes:   SemanticValue, PromotionConflictError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

@dataclass
class SemanticValue:
    value: str
    evidence_ts: float      # when the observation occurred
    ingestion_ts: float     # when it was written to semantic store
    source: str             # "live" | "distill"
    source_seq: int         # monotonic token from episodic append

class PromotionConflictError(RuntimeError):
    """Raised when a promotion would shadow a live value with older evidence."""
    pass

def promote(key: str, incoming: SemanticValue, current: Optional[SemanticValue]) -> SemanticValue:
    if current is None:
        return incoming

    # Invariant: evidence order dominates; ingestion order is never the tiebreaker.
    if incoming.evidence_ts < current.evidence_ts:
        raise PromotionConflictError(
            f"promotion for {key!r} rejected: incoming evidence_ts="
            f"{incoming.evidence_ts} predates current evidence_ts="
            f"{current.evidence_ts} (source={current.source}); "
            f"must be recorded as ConflictRecord, not applied."
        )

    # Equal evidence with different values is a contradiction, not a win.
    if incoming.evidence_ts == current.evidence_ts and incoming.value != current.value:
        raise PromotionConflictError(
            f"contradiction on {key!r}: equal evidence_ts={incoming.evidence_ts} "
            f"with values {current.value!r} vs {incoming.value!r}; "
            f"requires reconciliation, not recency resolution."
        )

    # Guard against stale promotion that already carries a newer ingestion_ts
    # than the live value it would shadow (the exact observed failure).
    if (incoming.source == "distill"
            and current.source == "live"
            and incoming.ingestion_ts > current.ingestion_ts
            and incoming.evidence_ts < current.evidence_ts):
        raise PromotionConflictError(
            f"lagging distillation would shadow live value on {key!r}; "
            f"ingestion_ts newer but evidence older — refuse upsert."
        )

    return incoming
