# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-pruning-when-its-own-relevance-scores-are-computed-against-the-context-it-is-about-to-delete.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-pruning-when-its-own-relevance-scores-are-computed-against-the-context-it-is-about-to-delete.warrant.json
# Markdown SHA-256:   fd86dadf036cf888aa191c5321a6bed7e2ed067e4c229c07e9814d97171ed163
# Code AST SHA-256:   7481a351bddb7e9cb6ec721ef67c0915e3b7fa95f3479b4fc4ee837bd8b9bae7
# Verified Classes:   PruningBoundaryViolation, Message, PruningCycle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class PruningBoundaryViolation(RuntimeError):
    """Raised when a self-pruning cycle would evict pinned content or re-score survivors."""


@dataclass
class Message:
    content: str
    partition: str  # "pinned" | "working"

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()[:16]


@dataclass
class PruningCycle:
    window: list[Message]
    budget_tokens: int
    scorer: Callable[[str, list[Message]], list[float]]
    evicted_log: list[dict] = field(default_factory=list)

    def prune(self, query: str, utilization: float) -> list[Message]:
        # Invariant 1: pinned partition is never scored or evicted.
        working = [m for m in self.window if m.partition == "working"]
        pinned = [m for m in self.window if m.partition == "pinned"]
        if utilization <= 0.70:
            return self.window

        # Invariant 2: score once, against the full pre-eviction working set.
        scores = self.scorer(query, working)
        if len(scores) != len(working):
            raise PruningBoundaryViolation(
                f"scorer returned {len(scores)} scores for {len(working)} messages"
            )

        # Invariant 3: eviction fraction is budget-derived, not survivor-derived.
        target_fraction = min(0.30, max(0.0, utilization - 0.70) + 0.10)
        n_evict = int(len(working) * target_fraction)

        ranked = sorted(zip(scores, working), key=lambda p: p[0])
        to_evict = [m for _, m in ranked[:n_evict]]

        # Boundary check: a pinned message scoring low against a narrow query
        # is a signal the query is too narrow, not that the message is dead.
        pinned_scores = self.scorer(query, pinned) if pinned else []
        if pinned and min(pinned_scores) < 0.15:
            raise PruningBoundaryViolation(
                "pinned message scored below 0.15 against active query; "
                "query too narrow — fall back to external compaction"
            )

        # Invariant 4: witnessed, reversible eviction.
        for m in to_evict:
            self.evicted_log.append(
                {"digest": m.digest, "score": dict(zip([x.digest for x in working], scores))[m.digest],
                 "query": query}
            )

        survivors = [m for m in self.window if m not in to_evict]
        # Invariant 2 (enforced): do NOT re-score survivors in this cycle.
        return survivors
