# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-consolidate-an-episodic-trace-whose-semantic-summary-has-already-been-invalidated-by-a-downstream-correction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-consolidate-an-episodic-trace-whose-semantic-summary-has-already-been-invalidated-by-a-downstream-correction.warrant.json
# Markdown SHA-256:   632796fe8172d5e587fc2ff343e889ffb66971e6969694d83abe7faab27b3bd6
# Code AST SHA-256:   6a74111617de2d4e6c6a0d6df4b244b98f79a689a2d6bbefa08f6ffa07232afd
# Verified Classes:   ConsolidationInvariantError, PromoteDecision, Episode, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ConsolidationInvariantError(RuntimeError):
    """Raised when a consolidation promote would violate the tombstone-join invariant."""


class PromoteDecision(Enum):
    PROMOTE = "promote"
    QUARANTINE = "quarantine"
    REJECT = "reject"


@dataclass(frozen=True)
class Episode:
    episode_id: str
    derived_key: str
    recorded_at: int


@dataclass(frozen=True)
class Tombstone:
    key: str
    written_at: int
    has_replacement: bool


def decide_promotion(
    episode: Episode,
    tombstones: list[Tombstone],
    promote_at: int,
    tombstone_retention_horizon: int,
) -> PromoteDecision:
    # If tombstones may have been GC'd before the episode could be checked,
    # the join is unverifiable and we must not promote.
    if promote_at - episode.recorded_at > tombstone_retention_horizon:
        raise ConsolidationInvariantError(
            f"episode {episode.episode_id} predates tombstone retention horizon; "
            f"join unverifiable (lag={promote_at - episode.recorded_at}, "
            f"horizon={tombstone_retention_horizon})"
        )

    relevant = [t for t in tombstones if t.key == episode.derived_key]

    # Correction predates the episode: the episode itself is suspect.
    if any(t.written_at < episode.recorded_at for t in relevant):
        return PromoteDecision.REJECT

    # Correction falls inside [recorded_at, promote_at]: the episode is stale.
    retroactive = [
        t for t in relevant if episode.recorded_at <= t.written_at <= promote_at
    ]
    if retroactive:
        if all(t.has_replacement for t in retroactive):
            return PromoteDecision.REJECT
        return PromoteDecision.QUARANTINE

    return PromoteDecision.PROMOTE


def consolidate(episode: Episode, tombstones: list[Tombstone], promote_at: int,
                tombstone_retention_horizon: int, semantic_store: dict) -> None:
    decision = decide_promotion(
        episode, tombstones, promote_at, tombstone_retention_horizon
    )
    if decision is PromoteDecision.REJECT:
        raise ConsolidationInvariantError(
            f"refusing to consolidate {episode.episode_id}: "
            f"key {episode.derived_key} has a retraction tombstone"
        )
    if decision is PromoteDecision.QUARANTINE:
        semantic_store.setdefault("__quarantine__", []).append(episode)
        return
    semantic_store[episode.derived_key] = episode.episode_id
