# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-consolidation-replay-from-resurrecting-stale-facts-during-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-consolidation-replay-from-resurrecting-stale-facts-during-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   a1f4022c91cc6e83fb503d0b7b0adf83edd0b9a47db9348bd93de6690a3b019e
# Code AST SHA-256:   e02404cc92c0de12bb3c4c6453987ff6a4d240391d5f03c280b3066b049884b0
# Verified Classes:   StaleWriteError, SemanticRecord, SemanticStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class StaleWriteError(RuntimeError):
    """Raised when a consolidation write would supersede a newer observation
    with an older one, laundering staleness into apparent recency."""
    pass

@dataclass
class SemanticRecord:
    key: str
    value: str
    source_observed_at: int   # monotonic clock, from the episodic trace
    source_trace_id: str
    distilled_at: int         # wall clock of the distillation pass

class SemanticStore:
    def __init__(self):
        self._records: dict[str, SemanticRecord] = {}

    def reconcile(self, key: str, value: str,
                  observed_at: int, trace_id: str,
                  distilled_at: int) -> SemanticRecord:
        # Invariant 1: distilled_at must not outrun its source observation.
        if distilled_at < observed_at:
            raise StaleWriteError(
                f"distilled_at={distilled_at} precedes observed_at={observed_at} "
                f"for {key}; watermark inversion"
            )
        existing = self._records.get(key)
        # Invariant 2: a write may only supersede an equal-or-older observation.
        if existing is not None and observed_at < existing.source_observed_at:
            raise StaleWriteError(
                f"rejecting stale write for {key}: incoming observed_at={observed_at} "
                f"(trace {trace_id}) is older than stored observed_at="
                f"{existing.source_observed_at} (trace {existing.source_trace_id}); "
                f"late-arrival reconciliation required, not blind append"
            )
        rec = SemanticRecord(key, value, observed_at, trace_id, distilled_at)
        self._records[key] = rec
        return rec

    def get(self, key: str) -> Optional[SemanticRecord]:
        return self._records.get(key)

# Demonstration of the replay hazard:
store = SemanticStore()
store.reconcile("service.region", "eu-west-1", observed_at=30, trace_id="B", distilled_at=30)
# Late-arriving trace C (observed_at=20) replayed on day 6 (distilled_at=60):
try:
    store.reconcile("service.region", "us-east-1", observed_at=20, trace_id="C", distilled_at=60)
except StaleWriteError as e:
    print(f"blocked: {e}")
    # Correct handling: log reconciliation event, re-evaluate key, do NOT overwrite.
