# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-cancel-a-speculative-tool-call-whose-taint-has-already-propagated-into-a-committed-reasoning-step.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-cancel-a-speculative-tool-call-whose-taint-has-already-propagated-into-a-committed-reasoning-step.warrant.json
# Markdown SHA-256:   3bf60be78a857c5b61b4946f03437a6006c61fb18c77cab5107c5f2773416399
# Code AST SHA-256:   2671be08962e3c2bea5151f61e4ed187681e005bef21d6d8103a5af7ccdc744d
# Verified Classes:   TaintCancellationError, SpecEntry, Artifact, TaintAwareCanceller
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Optional


class TaintCancellationError(RuntimeError):
    """Raised when a speculative result is cancelled after its taint
    has propagated into committed reasoning state that cannot be safely
    retracted or proven non-influential."""
    pass


@dataclass
class SpecEntry:
    spec_id: str
    precondition_hash: str
    status: str = "PENDING_COMMIT"   # PENDING_COMMIT | COMMITTED | CANCELLED_STALE
    changed_fields: Set[str] = field(default_factory=set)


@dataclass
class Artifact:
    artifact_id: str
    spec_id: str
    precondition_hash: str
    fields_read: Set[str]


class TaintAwareCanceller:
    def __init__(self):
        self.specs: Dict[str, SpecEntry] = {}
        self.artifacts: Dict[str, Artifact] = {}

    def commit_artifact(self, art: Artifact) -> None:
        # Enforce precondition binding at commit time.
        spec = self.specs.get(art.spec_id)
        if spec is None:
            raise TaintCancellationError(
                f"artifact {art.artifact_id} depends on unknown spec {art.spec_id}"
            )
        if spec.precondition_hash != art.precondition_hash:
            raise TaintCancellationError(
                f"artifact {art.artifact_id} bound to stale precondition "
                f"{art.precondition_hash} != live {spec.precondition_hash}"
            )
        if not art.fields_read:
            raise TaintCancellationError(
                f"artifact {art.artifact_id} has no field-level provenance; "
                f"cannot prove non-influence on cancellation"
            )
        self.artifacts[art.artifact_id] = art

    def cancel_stale(self, spec_id: str, changed_fields: Set[str]) -> Set[str]:
        """Cancel a speculative call and perform the backward taint walk.
        Returns the set of artifact ids that must be retracted."""
        spec = self.specs[spec_id]
        spec.status = "CANCELLED_STALE"
        spec.changed_fields = changed_fields

        retract: Set[str] = set()
        for art in self.artifacts.values():
            if art.spec_id != spec_id:
                continue
            if not art.fields_read:
                # No provenance: cannot prove non-influence. Hard fail.
                raise TaintCancellationError(
                    f"artifact {art.artifact_id} lacks field provenance; "
                    f"taint from {spec_id} cannot be bounded"
                )
            if art.fields_read & changed_fields:
                retract.add(art.artifact_id)

        for aid in retract:
            del self.artifacts[aid]
        return retract
