# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-model-driven-pruning-of-low-salience-reasoning-traces-has-crossed-into-invariant-violation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-model-driven-pruning-of-low-salience-reasoning-traces-has-crossed-into-invariant-violation.warrant.json
# Markdown SHA-256:   aafe787d5c806a50a258aa65b0b235cf27386c4fef9ff03e302734235bbc8a3d
# Code AST SHA-256:   373bb4d23923bbfeb1a587e95366f17a03721d99c227009d4c607aeea63a24c0
# Verified Classes:   PruningInvariantViolation, ReasoningBlock, PrunePolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PruningInvariantViolation(RuntimeError):
    """Raised when a model-driven prune would sever a decision-relevant edge."""
    pass


@dataclass
class ReasoningBlock:
    turn: int
    salience: float
    text: str
    contains_guard: bool = False      # conditional / rejection / "do not do X"
    contains_counter: bool = False    # retry or attempt counters
    entailed_by_surviving: bool = False  # mechanical entailment check result


@dataclass
class PrunePolicy:
    utilization_threshold: float = 0.70
    progress_history: list = field(default_factory=list)

    def record_progress(self, distinct_successes: int) -> None:
        self.progress_history.append(distinct_successes)

    def progress_frozen(self) -> bool:
        h = self.progress_history
        return len(h) >= 2 and h[-1] == h[-2]

    def select_prunable(self, blocks: list) -> list:
        if self.progress_frozen():
            raise PruningInvariantViolation(
                "C3 violated: forward progress flat across pruning cycles; "
                "amputation likely. Freeze pruner, escalate to external compaction."
            )
        prunable = []
        for b in blocks:
            if b.salience >= 0.5:
                continue
            if b.contains_guard or b.contains_counter:
                raise PruningInvariantViolation(
                    f"C2 violated at turn {b.turn}: block carries a guard/counter "
                    f"and must be promoted to a state record before pruning."
                )
            if not b.entailed_by_surviving:
                raise PruningInvariantViolation(
                    f"C1 violated at turn {b.turn}: low salience ({b.salience}) but "
                    f"no surviving artifact entails its decision content; "
                    f"pruning would amputate a dependency edge."
                )
            prunable.append(b)
        return prunable


def apply_prune(policy: PrunePolicy, blocks: list, utilization: float) -> list:
    if utilization <= policy.utilization_threshold:
        return blocks
    prunable = policy.select_prunable(blocks)
    doomed = {id(b) for b in prunable}
    return [b for b in blocks if id(b) not in doomed]


# --- failure trace reproduced from the record ---
policy = PrunePolicy()
policy.record_progress(3)
policy.record_progress(3)  # flat: two cycles, zero forward progress

blocks = [
    ReasoningBlock(3, salience=0.18,
                   text="409 means missing idempotency key; retrying without one loops.",
                   contains_guard=True, entailed_by_surviving=False),
    ReasoningBlock(5, salience=0.91, text="tool output: HTTP 409 Conflict"),
]

try:
    apply_prune(policy, blocks, utilization=0.72)
except PruningInvariantViolation as e:
    print("HALTED:", e)
