# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-rewrite-that-is-locally-valid-but-globally-non-monotonic.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-rewrite-that-is-locally-valid-but-globally-non-monotonic.warrant.json
# Markdown SHA-256:   d09c5b1eeea67a9f9e0d8eab719ab44cc22b6907df370c6ab00589e982e4ddd0
# Code AST SHA-256:   1ab018b950041d55e9b0fc6022abba21535143995b7a597d1aec5905633d8078
# Verified Classes:   NonMonotonicRewriteError, Tombstone, RewriteProposal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class NonMonotonicRewriteError(RuntimeError):
    """Raised when a model-driven context rewrite is locally valid but
    would break global monotonicity of the window's decision history."""


@dataclass(frozen=True)
class Tombstone:
    fact_id: str
    source_span: str
    prune_reason: str
    re_fetch_handle: str | None


@dataclass
class RewriteProposal:
    retained_spans: list[str]
    pruned_spans: list[str]
    summary_facts: set[str]
    tombstones: list[Tombstone] = field(default_factory=list)
    rewrite_depth: dict[str, int] = field(default_factory=dict)


MAX_REWRITE_DEPTH = 3


def _resolve(handle: str | None) -> bool:
    # A real implementation consults the retrieval layer; here we treat
    # any non-empty handle as resolvable and None/"" as dangling.
    return bool(handle)


def validate_rewrite(
    proposal: RewriteProposal,
    source_facts: dict[str, set[str]],
    open_dependencies: Iterable[str],
) -> None:
    """Enforce the four conditions of validity. Raises on the first failure."""
    # Condition 1: tombstone completeness for every pruned span.
    tombstoned_spans = {t.source_span for t in proposal.tombstones}
    for span in proposal.pruned_spans:
        if span not in tombstoned_spans:
            raise NonMonotonicRewriteError(
                f"pruned span {span!r} has no tombstone; deletion without record"
            )
    for t in proposal.tombstones:
        if not _resolve(t.re_fetch_handle):
            raise NonMonotonicRewriteError(
                f"tombstone for fact {t.fact_id!r} has dangling re-fetch handle "
                f"{t.re_fetch_handle!r}; prune is a deletion, not a compression"
            )

    # Condition 2: no net assertion gain without a new source.
    source_fact_union: set[str] = set()
    for span in proposal.retained_spans + proposal.pruned_spans:
        source_fact_union |= source_facts.get(span, set())
    hallucinated = proposal.summary_facts - source_fact_union
    if hallucinated:
        raise NonMonotonicRewriteError(
            f"summary asserts facts absent from all source spans: {sorted(hallucinated)}"
        )

    # Condition 3: dependency closure for every tombstoned fact.
    tombstoned_facts = {t.fact_id for t in proposal.tombstones}
    live = set(open_dependencies)
    unclosed = tombstoned_facts & live
    if unclosed:
        raise NonMonotonicRewriteError(
            f"tombstoned facts still have live dependents: {sorted(unclosed)}"
        )

    # Condition 4: bounded rewrite depth per logical span.
    for span, depth in proposal.rewrite_depth.items():
        if depth > MAX_REWRITE_DEPTH:
            raise NonMonotonicRewriteError(
                f"span {span!r} rewritten {depth} times without re-fetch; "
                f"provenance no longer reconstructible (bound {MAX_REWRITE_DEPTH})"
            )


def apply_or_refuse(
    proposal: RewriteProposal,
    source_facts: dict[str, set[str]],
    open_dependencies: Iterable[str],
) -> RewriteProposal:
    validate_rewrite(proposal, source_facts, open_dependencies)
    return proposal
