# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-adversarial-curricula-from-silently-regressing-below-the-tool-use-failure-frontier.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-adversarial-curricula-from-silently-regressing-below-the-tool-use-failure-frontier.warrant.json
# Markdown SHA-256:   67a41b236f2861663b5710d7baa2e08abfa29d10ee9d73b4c165ad9e30d26e76
# Code AST SHA-256:   3a658abb059691019c5c4e0bf491b710e8653dd726a2fca25936877fa3a765f7
# Verified Classes:   CurriculumCollapseError, RetentionBasis, GeneratorConfig, Candidate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CurriculumCollapseError(RuntimeError):
    """Raised when a curriculum generator's retention decision is gated on
    target response while the target is being patched in-loop, which silently
    prunes hard failure modes and regresses the benchmark below the frontier."""
    pass


class RetentionBasis(Enum):
    TAXONOMY = "taxonomy"      # absolute: node coverage + param diversity
    TARGET_RESPONSE = "target" # relative: accept-rate against current agent


@dataclass
class GeneratorConfig:
    retention_basis: RetentionBasis
    target_patched_in_loop: bool
    per_node_min_samples: int
    taxonomy_nodes: set


@dataclass
class Candidate:
    node: str
    setup_reached_injection_point: bool  # canary-verified
    target_failed: bool                  # agent succumbed (relative signal)


def retain(cfg: GeneratorConfig, cand: Candidate, node_sample_counts: dict) -> bool:
    # Invariant: retention must never be a function of target response when the
    # target is patched in-loop. Accept-rate then measures the moving target,
    # not attack strength, and low-yield hard nodes get pruned silently.
    if cfg.retention_basis is RetentionBasis.TARGET_RESPONSE and cfg.target_patched_in_loop:
        raise CurriculumCollapseError(
            f"retention gated on target.response while target is patched in-loop; "
            f"node={cand.node!r} would be pruned on moving-target accept-rate"
        )

    # Malformed scenarios are repaired, not pruned: setup failure != resistance.
    if not cand.setup_reached_injection_point:
        raise CurriculumCollapseError(
            f"scenario for node={cand.node!r} never reached injection point in canary "
            f"replay; classify as malformed and repair, do not discard"
        )

    if cfg.retention_basis is RetentionBasis.TAXONOMY:
        # Keep for coverage regardless of whether the current agent failed.
        # Failure rate only ranks difficulty within the node.
        if cand.node not in cfg.taxonomy_nodes:
            raise CurriculumCollapseError(
                f"candidate node={cand.node!r} absent from taxonomy; "
                f"cannot retain on coverage basis"
            )
        return True

    # TARGET_RESPONSE basis is admissible only if target is frozen.
    return cand.target_failed


def run_round(cfg: GeneratorConfig, candidates: list, node_sample_counts: dict) -> list:
    kept = []
    for cand in candidates:
        node_sample_counts[cand.node] = node_sample_counts.get(cand.node, 0) + 1
        if retain(cfg, cand, node_sample_counts):
            kept.append(cand)
    # Post-round invariant: every taxonomy node must retain its sampling floor.
    for node in cfg.taxonomy_nodes:
        if node_sample_counts.get(node, 0) < cfg.per_node_min_samples:
            raise CurriculumCollapseError(
                f"node={node!r} sampled {node_sample_counts.get(node, 0)} times, "
                f"below floor {cfg.per_node_min_samples}; curriculum has regressed "
                f"off this node and will report false-negative coverage"
            )
    return kept
