# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-call-return-values-as-tainted-until-proven-otherwise-the-read-after-unauthorized-write-trust-inversion.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-call-return-values-as-tainted-until-proven-otherwise-the-read-after-unauthorized-write-trust-inversion.warrant.json
# Markdown SHA-256:   f52017b68c9796f12445f81d18731400e1ca73f8d7f34fda15f0033eeafb5613
# Code AST SHA-256:   c6a45dc7d5d84dd44f800c470767d187862c212886301bbbea963df51381ea93
# Verified Classes:   TaintViolation, TaintClass, LedgerEntry, WriteLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TaintViolation(RuntimeError):
    """Raised when a tainted read is about to cross a side-effect boundary."""
    pass


class TaintClass(Enum):
    CLEAN = "clean"
    SELF_AUTHORED = "self_authored"
    UNVERIFIED = "unverified"
    TAINTED = "tainted"


@dataclass
class LedgerEntry:
    resource_id: str
    session_seq: int
    taint: TaintClass
    cleared: bool = False


@dataclass
class WriteLedger:
    entries: list[LedgerEntry] = field(default_factory=list)
    seq: int = 0

    def record_write(self, resource_id: str, body_taint: TaintClass) -> LedgerEntry:
        self.seq += 1
        entry = LedgerEntry(resource_id, self.seq, body_taint)
        self.entries.append(entry)
        return entry

    def uncleared_writes_touching(self, dependency_set: set[str]) -> list[LedgerEntry]:
        return [
            e for e in self.entries
            if e.resource_id in dependency_set
            and not e.cleared
            and e.taint in (TaintClass.SELF_AUTHORED, TaintClass.UNVERIFIED)
        ]


def classify_read(
    ledger: WriteLedger,
    dependency_set: set[str],
    read_is_ranked: bool,
) -> TaintClass:
    """Decide whether a read is clean given the session write history.

    A read is tainted if any uncleared write touches its dependency set, OR
    if the read is a ranking/search operation and *any* uncleared write
    occurred in-session (ranking is a global function of corpus state).
    """
    if read_is_ranked and ledger.entries:
        # Retrieval-side-channel coupling: any write perturbs ranking.
        if any(not e.cleared for e in ledger.entries):
            return TaintClass.TAINTED

    touching = ledger.uncleared_writes_touching(dependency_set)
    if not touching:
        return TaintClass.CLEAN
    if any(e.taint is TaintClass.UNVERIFIED for e in touching):
        return TaintClass.TAINTED
    return TaintClass.SELF_AUTHORED


def guarded_side_effect(
    ledger: WriteLedger,
    dependency_set: set[str],
    read_is_ranked: bool,
    action: str,
) -> None:
    """Gate a side-effect tool call on the taint class of its inputs."""
    taint = classify_read(ledger, dependency_set, read_is_ranked)
    if taint is TaintClass.TAINTED:
        raise TaintViolation(
            f"Refusing side-effect '{action}': input read is tainted by "
            f"uncleared in-session write touching {sorted(dependency_set)} "
            f"(or by ranking perturbation). De-taint via immutable re-read "
            f"or checkpoint before proceeding."
        )
    # SELF_AUTHORED may proceed only if the action cannot re-enter the
    # read path of a later step; otherwise escalate to de-taint as well.
    if taint is TaintClass.SELF_AUTHORED:
        raise TaintViolation(
            f"Side-effect '{action}' consumes self-authored data with no "
            f"checkpoint; provenance is circular. Require independent "
            f"verification of the write target before acting."
        )
    # taint is CLEAN: proceed.
