# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-loss-after-context-compaction-when-adversarial-recall-probes-disagree-with-the-compaction-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-loss-after-context-compaction-when-adversarial-recall-probes-disagree-with-the-compaction-summary.warrant.json
# Markdown SHA-256:   15224e6cae26eddf218c1a0be399e95a6d135c0f7bffb48bf3a68452d5370562
# Code AST SHA-256:   bfd3891d9ce0786f4500c0fc9a8fe6ff12785c840e4db92050bcb656adca351e
# Verified Classes:   CompactionVerificationError, Probe, PostCompactionContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionVerificationError(RuntimeError):
    """Raised when a recall probe cannot be satisfied by surviving context provenance."""
    pass


@dataclass
class Probe:
    question: str
    required_spans: list[str]          # fact-IDs that MUST survive compaction
    is_negative_control: bool = False  # correct answer is "dropped / unknown"


@dataclass
class PostCompactionContext:
    surviving_fact_ids: set[str] = field(default_factory=set)
    summary_text: str = ""


def verify_probe(probe: Probe, ctx: PostCompactionContext,
                 model_answer: str, cited_spans: list[str]) -> str:
    """
    Provenance-based grading. Plausibility is deliberately ignored.
    Returns one of: PRESERVED_TRACEABLE, PRESERVED_UNTRACEABLE, DROPPED.
    """
    if probe.is_negative_control:
        # Correct behavior is abstention; a confident answer is a failure signal.
        if model_answer and "unknown" not in model_answer.lower() and "dropped" not in model_answer.lower():
            raise CompactionVerificationError(
                f"Negative control answered confidently instead of abstaining: {probe.question!r}"
            )
        return "DROPPED"

    missing = [s for s in probe.required_spans if s not in ctx.surviving_fact_ids]
    if missing:
        # The fact the probe needs did not survive compaction.
        raise CompactionVerificationError(
            f"Probe {probe.question!r} requires spans {missing} that did not survive compaction; "
            f"answer {model_answer!r} is likely confabulated from adjacent context."
        )

    if not cited_spans:
        # Answer may be correct by coincidence but has no provenance -> unsafe.
        raise CompactionVerificationError(
            f"Probe {probe.question!r} produced answer {model_answer!r} with no surviving provenance; "
            f"treat as PRESERVED_UNTRACEABLE and re-derive from tool call, not context."
        )

    return "PRESERVED_TRACEABLE"


def run_compaction_verification(probes: list[Probe], ctx: PostCompactionContext,
                                answers: dict[str, tuple[str, list[str]]]) -> dict:
    results = {}
    failures = []
    for p in probes:
        answer, cited = answers.get(p.question, ("", []))
        try:
            results[p.question] = verify_probe(p, ctx, answer, cited)
        except CompactionVerificationError as e:
            results[p.question] = "FAILED"
            failures.append(str(e))
    if failures:
        raise CompactionVerificationError(
            f"{len(failures)} of {len(probes)} probes failed provenance verification; "
            f"compaction is unsafe for downstream reasoning. First failure: {failures[0]}"
        )
    return results
