# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-revoke-capability-grants-when-taint-propagation-crosses-a-turn-boundary-in-tool-sandboxing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-revoke-capability-grants-when-taint-propagation-crosses-a-turn-boundary-in-tool-sandboxing.warrant.json
# Markdown SHA-256:   f633e8572154eab49db18cd0856b5cd596888be0c0a6790ec7edde5874244b37
# Code AST SHA-256:   391e4b1ecc599d12aecb599ee0f8fc083961b657efd49e381e5daf33a0d24633
# Verified Classes:   Taint, TaintLaunderingError, GrantTable, Lattice
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Set


class Taint(IntEnum):
    CLEAN = 0
    INTERNAL = 1
    EXTERNAL_UNTRUSTED = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a capability grant survives a turn boundary without a live
    taint justification, or when a memory write drops the join of its inputs."""
    pass


@dataclass
class GrantTable:
    # grant name -> taint label that justified it at negotiation time
    grants: Dict[str, Taint] = field(default_factory=dict)


@dataclass
class Lattice:
    labels: Dict[str, Taint] = field(default_factory=dict)

    def join_into(self, key: str, label: Taint) -> None:
        self.labels[key] = max(self.labels.get(key, Taint.CLEAN), label)


def rotate_turn(
    grants: GrantTable,
    old_lattice: Lattice,
    new_lattice: Lattice,
    memory_writes: Dict[str, Set[str]],
) -> GrantTable:
    """Rotate a turn boundary. Revoke grants whose justification label is not
    re-established in the new lattice. Refuse to drop taint on memory writes."""
    surviving = GrantTable()
    for grant, justification in grants.grants.items():
        if not _label_reachable(justification, new_lattice):
            # justification vanished at rotation: revoke, do not carry forward
            continue
        surviving.grants[grant] = justification

    for summary_key, source_keys in memory_writes.items():
        joined = Taint.CLEAN
        for src in source_keys:
            joined = max(joined, old_lattice.labels.get(src, Taint.EXTERNAL_UNTRUSTED))
        stored = new_lattice.labels.get(summary_key, Taint.CLEAN)
        if stored < joined:
            raise TaintLaunderingError(
                f"memory write '{summary_key}' stored label {stored.name} "
                f"but inputs join to {joined.name}; distillation dropped taint"
            )
    return surviving


def authorize(grant: str, grant_table: GrantTable, lattice: Lattice) -> None:
    if grant not in grant_table.grants:
        raise TaintLaunderingError(f"grant '{grant}' not present; request re-negotiation")
    justification = grant_table.grants[grant]
    if not _label_reachable(justification, lattice):
        raise TaintLaunderingError(
            f"grant '{grant}' justified by {justification.name} but lattice "
            f"no longer carries that label; grant is unbacked"
        )


def _label_reachable(label: Taint, lattice: Lattice) -> bool:
    if label == Taint.CLEAN:
        return True
    return any(v >= label for v in lattice.labels.values())
