# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-evict-a-cached-prefix-that-is-still-warm-the-compaction-reuse-race-in-kv-cache-aware-context-scheduling.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-evict-a-cached-prefix-that-is-still-warm-the-compaction-reuse-race-in-kv-cache-aware-context-scheduling.warrant.json
# Markdown SHA-256:   29dd6e9b86365178bda5337d890777c7f4494373d5d6f8e85c50029ea6c2b9c3
# Code AST SHA-256:   76bf4b663c5b65974fc99a778655e162c5d66312a75a2ab53fc82038d3c17eea
# Verified Classes:   PrefixEvictionViolation, CacheBlock, CommittedTurn, ContextScheduler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class PrefixEvictionViolation(RuntimeError):
    """Raised when a compaction would evict a span still depended on by a committed turn."""
    pass


@dataclass
class CacheBlock:
    start: int          # byte offset of block start in the context
    end: int
    content_hash: str   # content-addressed key, NOT positional


@dataclass
class CommittedTurn:
    turn_id: str
    first_block_offset: int   # byte offset of the earliest cache block this turn reads


@dataclass
class ContextScheduler:
    blocks: list[CacheBlock] = field(default_factory=list)
    committed: list[CommittedTurn] = field(default_factory=list)
    compaction_in_flight: bool = False

    def dependency_frontier(self) -> int:
        if not self.committed:
            return float("inf")
        return min(t.first_block_offset for t in self.committed)

    def assert_eviction_safe(self, evict_start: int, evict_end: int, replacement: str) -> None:
        if self.compaction_in_flight:
            raise PrefixEvictionViolation(
                "re-entrant compaction: a compaction is already in flight; "
                "suppress trigger to avoid thrash loop"
            )
        dep = self.dependency_frontier()
        # Equality is unsafe: a committed turn beginning exactly at the frontier
        # would lose its first block. Require strict ordering.
        if evict_start < dep:
            raise PrefixEvictionViolation(
                f"eviction [{evict_start},{evict_end}) crosses dependency frontier "
                f"{dep}; defer or tail-compact instead"
            )
        # Content-addressed check: an equal-length replacement still changes bytes,
        # so any block whose span overlaps the eviction must be re-keyed.
        new_hash = hashlib.sha256(replacement.encode()).hexdigest()
        for b in self.blocks:
            if b.start < evict_end and b.end > evict_start:
                if b.content_hash != new_hash:
                    raise PrefixEvictionViolation(
                        f"block [{b.start},{b.end}) content changed under warm key; "
                        f"positional reuse would serve stale KV"
                    )

    def compact(self, evict_start: int, evict_end: int, summary: str) -> None:
        self.assert_eviction_safe(evict_start, evict_end, summary)
        self.compaction_in_flight = True
        try:
            # Append-and-tombstone: summary goes after the warm region, original span
            # is marked superseded rather than deleted in place.
            self.blocks.append(
                CacheBlock(start=evict_end, end=evict_end + len(summary),
                           content_hash=hashlib.sha256(summary.encode()).hexdigest())
            )
        finally:
            self.compaction_in_flight = False
