# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-poisoned-episodic-memory-when-the-poison-s-only-symptom-is-a-shift-in-retrieval-rank-not-content-falsity.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-poisoned-episodic-memory-when-the-poison-s-only-symptom-is-a-shift-in-retrieval-rank-not-content-falsity.warrant.json
# Markdown SHA-256:   127a286050fc863f1aa082bb442adc2f3a3648cd5cbcebaf83055f0e3e4bc972
# Code AST SHA-256:   09440b19ea6c552d0042ebc523a14420b89e7bdfed6916038e601a4f0dc6cab2
# Verified Classes:   RankDisplacementViolation, Episode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass
from typing import Sequence


class RankDisplacementViolation(RuntimeError):
    """Raised when an outcome-inconsistent, unattributable entry displaces
    the outcome-consistent episode for a task signature past top_k."""


@dataclass(frozen=True)
class Episode:
    episode_id: str
    signature: str
    outcome_class: str
    writer_id: str
    writer_authenticated: bool
    embedding_score: float  # cosine sim to query, pre-computed
    importance: float       # READER-computed, not self-assigned


def rank_of(episodes: Sequence[Episode], target_id: str) -> int:
    """1-indexed rank by descending retrieval weight."""
    def weight(e: Episode) -> float:
        return e.embedding_score + 0.1 * e.importance
    ordered = sorted(episodes, key=weight, reverse=True)
    for i, e in enumerate(ordered, start=1):
        if e.episode_id == target_id:
            return i
    raise RankDisplacementViolation(f"target {target_id} absent from candidate set")


def check_displacement(
    signature: str,
    dominant_outcome: str,
    episodes: Sequence[Episode],
    top_k: int,
    prior_rank: int,
) -> None:
    consistent = [e for e in episodes if e.outcome_class == dominant_outcome]
    if not consistent:
        raise RankDisplacementViolation(
            f"signature {signature}: no outcome-consistent episode survives"
        )
    target = consistent[0]
    current_rank = rank_of(episodes, target.episode_id)

    if current_rank <= top_k or prior_rank <= top_k:
        return  # no boundary crossing; nothing to attribute

    displacers = [e for e in episodes if rank_of(episodes, e.episode_id) < current_rank]
    for d in displacers:
        outcome_inconsistent = d.outcome_class != dominant_outcome
        unattributable = not d.writer_authenticated
        if outcome_inconsistent and unattributable:
            raise RankDisplacementViolation(
                f"signature={signature} target={target.episode_id} "
                f"rank {prior_rank}->{current_rank} (top_k={top_k}) "
                f"displaced by unauthenticated writer={d.writer_id} "
                f"outcome={d.outcome_class} != {dominant_outcome}; "
                f"escalate to unlearn(episode_id={d.episode_id})"
            )
    # displacement exists but is attributable or outcome-consistent:
    # legitimate memory evolution, do not unlearn.
