# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tier-promotion-races-from-corrupting-the-semantic-store-when-episodic-consolidation-runs-concurrently-with-retrieval-arbitrat.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tier-promotion-races-from-corrupting-the-semantic-store-when-episodic-consolidation-runs-concurrently-with-retrieval-arbitrat.warrant.json
# Markdown SHA-256:   627da5047b7096170b39cac801d067308d139720bbca142139fdd532f2fa79d4
# Code AST SHA-256:   61e615bda9a8e488309eaa314ed66ee8b2365141838f7aaff91c7bcb72677c79
# Verified Classes:   PromotionInvariantError, State, SemanticRecord, TieredStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class PromotionInvariantError(RuntimeError):
    """Raised when a semantic record would become retrievable with an open
    provenance set, an unfenced epoch, or a silently collapsed conflict."""
    pass


class State(Enum):
    PENDING = "pending"
    COMMITTED = "committed"


@dataclass
class SemanticRecord:
    subject: str
    predicate: str
    obj: str
    confidence: float
    provenance_ids: list[str]
    epoch: int
    state: State = State.PENDING
    conflicts: list[dict] = field(default_factory=list)


class TieredStore:
    """Minimal model of the invariant-bearing tiered store."""

    def __init__(self, committed_epoch: int = 0):
        self._records: dict[tuple[str, str], list[SemanticRecord]] = {}
        self._committed_epoch = committed_epoch

    def _key(self, subject: str, predicate: str) -> tuple[str, str]:
        return (subject, predicate)

    def promote(
        self,
        subject: str,
        predicate: str,
        obj: str,
        confidence: float,
        provenance_ids: list[str],
        epoch: int,
    ) -> SemanticRecord:
        if epoch < self._committed_epoch:
            raise PromotionInvariantError(
                f"epoch {epoch} is behind committed_epoch {self._committed_epoch}; "
                "a superseded consolidation pass may not commit"
            )
        if not provenance_ids:
            raise PromotionInvariantError(
                "refusing to promote a fact with an empty provenance set"
            )

        key = self._key(subject, predicate)
        bucket = self._records.setdefault(key, [])

        # Provenance-before-visibility: build the full record in PENDING first.
        record = SemanticRecord(
            subject=subject,
            predicate=predicate,
            obj=obj,
            confidence=confidence,
            provenance_ids=list(provenance_ids),
            epoch=epoch,
            state=State.PENDING,
        )

        # Conflict-preserving dedup: same (subject, predicate) with a different
        # object value must be retained as a conflict, never overwritten.
        for existing in bucket:
            if existing.state is State.COMMITTED and existing.obj != obj:
                record.conflicts.append(
                    {
                        "obj": existing.obj,
                        "confidence": existing.confidence,
                        "provenance_ids": existing.provenance_ids,
                    }
                )

        bucket.append(record)
        return record

    def commit(self, record: SemanticRecord, source_marked: bool) -> None:
        """Flip PENDING -> COMMITTED only after sources are durably marked."""
        if not source_marked:
            raise PromotionInvariantError(
                "cannot commit semantic record before source episodes are marked consolidated"
            )
        if record.state is not State.PENDING:
            raise PromotionInvariantError(f"record in unexpected state {record.state}")
        if not record.provenance_ids:
            raise PromotionInvariantError("commit attempted with empty provenance")
        record.state = State.COMMITTED
        self._committed_epoch = max(self._committed_epoch, record.epoch)

    def arbitrate(self, subject: str, predicate: str) -> Optional[SemanticRecord]:
        """Retriever query: only committed, epoch-fenced records are visible."""
        bucket = self._records.get(self._key(subject, predicate), [])
        visible = [
            r
            for r in bucket
            if r.state is State.COMMITTED and r.epoch <= self._committed_epoch
        ]
        if not visible:
            return None
        return max(visible, key=lambda r: (r.confidence, r.epoch))


def consolidate_and_retrieve(store: TieredStore, crash_after_promote: bool) -> Optional[SemanticRecord]:
    """Simulates the race: promote, optionally crash before source-marking,
    then retrieve. The invariant must make the poisoned fact invisible."""
    rec = store.promote(
        subject="user",
        predicate="timezone",
        obj="UTC+2",
        confidence=0.7,
        provenance_ids=["e17"],
        epoch=1,
    )
    if crash_after_promote:
        # Crash between semantic write and source-consolidation flag.
        # Record stays PENDING; retriever must NOT see it.
        return store.arbitrate("user", "timezone")
    store.commit(rec, source_marked=True)
    return store.arbitrate("user", "timezone")
