# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-model-driven-context-rewriting-when-the-eviction-gate-and-the-rewrite-gate-disagree-on-token-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-model-driven-context-rewriting-when-the-eviction-gate-and-the-rewrite-gate-disagree-on-token-provenance.warrant.json
# Markdown SHA-256:   eb44d0b148de0b96e7601f73f06a462a02d4248ba082100e9f7ba5b49ae1fee8
# Code AST SHA-256:   3f3357f3b88fc7510251294f9f7c544b97348977ef2d1447f30e6df73fd87b95
# Verified Classes:   ContextRewriteViolation, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ContextRewriteViolation(RuntimeError):
    """Raised when a model-driven rewrite would launder discriminator loss via eviction."""
    pass


@dataclass
class Span:
    span_id: str
    content: str
    provenance: str            # "user" | "tool_result" | "model_inference" | "injected_doc"
    parents: tuple[str, ...] = ()
    discriminators: frozenset[str] = frozenset()
    content_hash: str = ""

    def __post_init__(self):
        if not self.content_hash:
            self.content_hash = hashlib.sha256(self.content.encode()).hexdigest()[:16]


def extract_discriminators(text: str, known_tokens: set[str]) -> frozenset[str]:
    # Mechanical extraction: numbers, units, error codes, negations, temporal qualifiers.
    found = set()
    for tok in known_tokens:
        if tok in text:
            found.add(tok)
    return frozenset(found)


def commit_rewrite(
    parent_spans: list[Span],
    proposed_summary: str,
    known_discriminators: set[str],
    reconstructible_from_external: bool,
    saturation: float,
    saturation_threshold: float = 0.90,
    recursive_depth: int = 0,
) -> Span:
    """Two-phase rewrite commit. Model proposes; this checker disposes."""

    if recursive_depth > 1:
        raise ContextRewriteViolation(
            f"recursive rewrite depth {recursive_depth} exceeds ceiling 1; "
            "provenance no longer constrains content"
        )

    parent_discriminators: set[str] = set()
    for p in parent_spans:
        parent_discriminators |= set(p.discriminators)

    summary_discriminators = extract_discriminators(proposed_summary, known_discriminators)
    lost = parent_discriminators - summary_discriminators

    has_tool_parent = any(p.provenance == "tool_result" for p in parent_spans)
    if lost and has_tool_parent and not reconstructible_from_external:
        raise ContextRewriteViolation(
            f"rewrite drops discriminators {sorted(lost)} from a tool_result parent "
            "with no live external source; refusing to commit"
        )

    if lost and saturation > saturation_threshold:
        raise ContextRewriteViolation(
            f"rewrite proposed under token pressure (saturation={saturation:.2f}) "
            f"and drops discriminators {sorted(lost)}; pressure rewrites are presumed lossy"
        )

    if lost and not reconstructible_from_external:
        raise ContextRewriteViolation(
            f"rewrite drops discriminators {sorted(lost)} and originals are not reconstructible; "
            "eviction would launder the loss"
        )

    return Span(
        span_id=f"derived::{parent_spans[0].span_id}",
        content=proposed_summary,
        provenance="model_inference",
        parents=tuple(p.span_id for p in parent_spans),
        discriminators=frozenset(summary_discriminators),
    )


def evict(span: Span, live_derived_parents: set[str], relevance: float, min_relevance: float) -> bool:
    """Eviction gate: relevance necessary, reconstructibility sufficient."""
    if span.span_id in live_derived_parents:
        raise ContextRewriteViolation(
            f"cannot evict {span.span_id}: it is a live parent of a derived span; "
            "eviction would orphan the summary from its source"
        )
    return relevance >= min_relevance
