# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-it-has-already-partially-consumed-taint-boundary-reclassification-and-the-split-consumption-leak.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-it-has-already-partially-consumed-taint-boundary-reclassification-and-the-split-consumption-leak.warrant.json
# Markdown SHA-256:   d261778d794b783d48ea9f173ec76df223e9d4c4d78ccf6ca3495689763b9ddb
# Code AST SHA-256:   f51e3eef38e65780733c805f66ec9171abfc847dc91286582a3c6ea6a1494aa6
# Verified Classes:   TaintProvenanceError, DerivedArtifact, ResultStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintProvenanceError(RuntimeError):
    """Raised when a derived artifact cannot be safely resolved against a taint verdict."""
    pass


@dataclass
class DerivedArtifact:
    artifact_id: str
    source_result_id: str
    byte_range: tuple[int, int]
    verdict_at_write: str  # "CLEAN" | "PENDING" | "INJECTED"
    payload: str


@dataclass
class ResultStore:
    results: dict[str, bytes] = field(default_factory=dict)
    verdicts: dict[str, str] = field(default_factory=dict)  # result_id -> verdict
    artifacts: dict[str, DerivedArtifact] = field(default_factory=dict)
    # derivation edges: artifact_id -> set of artifact_ids derived from it
    edges: dict[str, set[str]] = field(default_factory=dict)


def write_derived(store: ResultStore, art: DerivedArtifact) -> None:
    if art.source_result_id not in store.results:
        raise TaintProvenanceError(
            f"artifact {art.artifact_id} references unknown result {art.source_result_id}"
        )
    verdict = store.verdicts.get(art.source_result_id, "PENDING")
    art.verdict_at_write = verdict
    store.artifacts[art.artifact_id] = art


def record_verdict(store: ResultStore, result_id: str, verdict: str) -> list[str]:
    """Apply a taint verdict; return artifact IDs that must be invalidated.

    Invalidation predicate is provenance REACHABILITY, not span overlap:
    any artifact whose source_result_id == result_id (directly or via a
    derivation chain) is invalidated, even if its consumed byte_range is
    disjoint from the injected span.
    """
    if result_id not in store.results:
        raise TaintProvenanceError(f"verdict for unknown result {result_id}")
    store.verdicts[result_id] = verdict
    if verdict != "INJECTED":
        return []

    invalidated: list[str] = []
    # direct derivations from the tainted result
    frontier = [
        a.artifact_id
        for a in store.artifacts.values()
        if a.source_result_id == result_id
    ]
    seen: set[str] = set()
    while frontier:
        aid = frontier.pop()
        if aid in seen:
            continue
        seen.add(aid)
        invalidated.append(aid)
        frontier.extend(store.edges.get(aid, set()))
    return invalidated


def executor_step(store: ResultStore, artifact_id: str) -> str:
    art = store.artifacts.get(artifact_id)
    if art is None:
        raise TaintProvenanceError(f"missing artifact {artifact_id}")
    # Re-check against current verdict, not verdict_at_write: a verdict may
    # have landed after this artifact was written.
    current = store.verdicts.get(art.source_result_id, "PENDING")
    if current == "INJECTED":
        raise TaintProvenanceError(
            f"artifact {artifact_id} derived from tainted result "
            f"{art.source_result_id}; must re-derive from clean source"
        )
    if current == "PENDING":
        raise TaintProvenanceError(
            f"artifact {artifact_id} consumed before verdict; blocking execution"
        )
    return art.payload
