# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-retention-policy-tombstone-has-been-silently-resurrected-by-an-embedding-reindex.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-retention-policy-tombstone-has-been-silently-resurrected-by-an-embedding-reindex.warrant.json
# Markdown SHA-256:   9284cedda54862ad640eaa0c6d5fc4e0121685364862ef564abc6707f8db1c51
# Code AST SHA-256:   7a3be7a845b82e869df17f8860630f39a98ebe962daa82f74e3b53a136b9e240
# Verified Classes:   ResurrectionDetected, Episode, Embedding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class ResurrectionDetected(RuntimeError):
    """Raised when a reindex produces a vector for a tombstoned record."""
    pass


@dataclass
class Episode:
    id: str
    payload: Optional[str]
    title: str
    tags: list
    forgotten_at: Optional[float] = None
    forgotten_reason: Optional[str] = None


@dataclass
class Embedding:
    source_record_id: str
    vector: list
    embedding_created_at: float


def reindex_batch(episodes, embedder, watermark: float, tombstone_aware: bool):
    """Rebuild embeddings for records past the watermark.

    INVARIANT: no embedding may be created for an episode whose
    forgotten_at is set, regardless of watermark position.
    """
    out = []
    for ep in episodes:
        selected = ep.forgotten_at is None or ep.forgotten_at > watermark
        if not selected:
            continue
        # Tombstone-wins guard: this is the line whose absence caused the incident.
        if tombstone_aware and ep.forgotten_at is not None:
            # Skip silently in production; assert in canary mode.
            continue
        text = ep.payload
        if text is None:
            # The dangerous fallback. Only legal if selection excluded tombstones.
            if ep.forgotten_at is not None:
                raise ResurrectionDetected(
                    f"embedder fallback reached tombstoned record {ep.id} "
                    f"(forgotten_at={ep.forgotten_at}); reindex selection "
                    f"is not tombstone-aware"
                )
            text = f"{ep.title} {' '.join(ep.tags)}"
        vec = embedder(text)
        out.append(Embedding(ep.id, vec, time.time()))
    return out


def verify_no_resurrection(index: list, episodes_by_id: dict) -> None:
    """Post-reindex canary: any vector newer than its tombstone is a failure."""
    for emb in index:
        ep = episodes_by_id.get(emb.source_record_id)
        if ep is None or ep.forgotten_at is None:
            continue
        if emb.embedding_created_at > ep.forgotten_at:
            raise ResurrectionDetected(
                f"record {ep.id} tombstoned at {ep.forgotten_at} but has "
                f"embedding created at {emb.embedding_created_at}; "
                f"derived-state erasure invariant violated"
            )
