# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-policy-negotiated-capability-grant-is-narrower-at-execution-time-than-at-negotiation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-policy-negotiated-capability-grant-is-narrower-at-execution-time-than-at-negotiation-time.warrant.json
# Markdown SHA-256:   c70aed0493ec77cdad6c8ae64258adf9a2ea1c44c08c18a8730f4499d8553fac
# Code AST SHA-256:   2ce3ce9f171e6f22a1c915d4369d9edc52e500a0a5ad2c29d3509bf4081e8ea2
# Verified Classes:   GrantDriftError, Grant, Result
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class GrantDriftError(RuntimeError):
    """Raised when a host result violates the delegate's cached grant.

    The result must be quarantined and the task halted; it must NOT be
    appended to delegate state or fed to any distillation sink.
    """


# Refinement order for residency: EU is narrower than GLOBAL.
_RESIDENCY_RANK = {"EU": 1, "GLOBAL": 2}


@dataclass(frozen=True)
class Grant:
    max_rows: int
    residency: str          # "EU" | "GLOBAL"
    retention: str          # "ephemeral" | "persistent"


@dataclass
class Result:
    rows: list[dict[str, Any]]
    residency: str
    retention: str


def _dominates(result: Result, grant: Grant) -> tuple[bool, str]:
    """True iff every result attribute is within the cached grant."""
    if len(result.rows) > grant.max_rows:
        return False, f"rows {len(result.rows)} > grant max_rows {grant.max_rows}"
    if _RESIDENCY_RANK[result.residency] > _RESIDENCY_RANK[grant.residency]:
        return False, f"residency {result.residency} exceeds grant {grant.residency}"
    if result.retention != grant.retention:
        return False, f"retention {result.retention} != grant {grant.retention}"
    return True, ""


def admit_result(result: Result, grant: Grant, working_set: list[dict[str, Any]]) -> None:
    """Ingress gate: the ONLY path by which a host result may enter delegate state.

    Runs BEFORE any append or distillation. On drift, halts the task and
    raises; the caller must transition to GRANT_DRIFT and re-negotiate.
    """
    ok, reason = _dominates(result, grant)
    if not ok:
        # Do not partially admit. The batch is atomic; discard and halt.
        raise GrantDriftError(
            f"host result violates cached grant: {reason}; "
            f"task halted, working_set preserved at {len(working_set)} rows for discard"
        )
    working_set.extend(result.rows)


def run_enumeration(pages: list[Result], grant: Grant) -> list[dict[str, Any]]:
    working_set: list[dict[str, Any]] = []
    for i, page in enumerate(pages):
        try:
            admit_result(page, grant, working_set)
        except GrantDriftError as e:
            # Re-raise with page context; caller re-negotiates. No partial state escapes.
            raise GrantDriftError(f"page {i}: {e}") from e
    return working_set


# --- reproduction of the observed failure ---
if __name__ == "__main__":
    grant = Grant(max_rows=10000, residency="EU", retention="ephemeral")
    # Page 13 post-reclassification: 500 rows, 200 now GLOBAL-resident.
    drifted_page = Result(rows=[{"id": n} for n in range(500)],
                          residency="GLOBAL", retention="ephemeral")
    try:
        run_enumeration([drifted_page], grant)
    except GrantDriftError as e:
        print(f"HALTED before write: {e}")
