# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-relevance-scored-context-eviction-has-silently-orphaned-a-live-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-relevance-scored-context-eviction-has-silently-orphaned-a-live-constraint.warrant.json
# Markdown SHA-256:   fc5999a13722d351d9f78e0f416bbd2626445626598d9720e68f1e9e485b3be2
# Code AST SHA-256:   233d70aa78ff086927ec2c9372a1af80223c8b3f3bd9d282a53f209493338c87
# Verified Classes:   OrphanedConstraintError, Segment
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

CONSTRAINT_GRAMMAR = [
    r"\bdo not\b", r"\bnever\b", r"\bavoid\b", r"\bread[- ]only\b",
    r"\bpropose only\b", r"\bonly\b", r"\bexcept\b", r"\brequires? auth\b",
    r"\bunauthenticated\b", r"\bin (milliseconds|seconds|utc|base64)\b",
    r"\bISO-?8601\b", r"\bSCOPE:", r"\bUNIT:",
]
_CONSTRAINT_RE = re.compile("|".join(CONSTRAINT_GRAMMAR), re.IGNORECASE)


class OrphanedConstraintError(RuntimeError):
    """Raised when a model-scored eviction would drop a structurally binding segment."""


@dataclass
class Segment:
    id: str
    text: str
    relevance_score: float


def is_binding(seg: Segment) -> bool:
    return bool(_CONSTRAINT_RE.search(seg.text))


def evict_by_score(segments: list[Segment], threshold: float) -> list[Segment]:
    """Return surviving segments. Refuses to evict binding segments regardless of score."""
    survivors: list[Segment] = []
    for seg in segments:
        if seg.relevance_score >= threshold:
            survivors.append(seg)
            continue
        if is_binding(seg):
            # Structural veto: keep the segment, but surface the near-miss.
            # Do NOT silently retain; log so constraint density stays observable.
            survivors.append(seg)
            continue
        # safe to evict
    return survivors


def commit_compaction(segments: list[Segment], threshold: float) -> list[Segment]:
    survivors = evict_by_score(segments, threshold)
    binding_before = sum(is_binding(s) for s in segments)
    binding_after = sum(is_binding(s) for s in survivors)
    if binding_after < binding_before:
        raise OrphanedConstraintError(
            f"compaction would orphan {binding_before - binding_after} binding "
            f"segment(s); structural veto failed. Abort and fall back to pinned eviction."
        )
    return survivors
