# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-discard-a-speculative-tool-call-whose-pre-execution-result-was-already-tainted-by-a-sibling-commit-a-taint-verified-commit-disca.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-discard-a-speculative-tool-call-whose-pre-execution-result-was-already-tainted-by-a-sibling-commit-a-taint-verified-commit-disca.warrant.json
# Markdown SHA-256:   cf9e437d40e710ef7c27e97543070d387bf1da1546b2bf2bbd545b6093f81c9d
# Code AST SHA-256:   751babbc22081573eaabfff15c2d9a51fcb5db2f623bbf2b3c56fbb5839e935e
# Verified Classes:   TaintCommitViolation, Provenance, SpeculativeCall, TaintVerifiedCommitter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import threading
from dataclasses import dataclass, field
from typing import FrozenSet, Set


class TaintCommitViolation(RuntimeError):
    """Raised when a speculative MCP result is committed despite provenance invalidation."""
    pass


@dataclass(frozen=True)
class Provenance:
    """Immutable set of source node ids that a value transitively derives from."""
    nodes: FrozenSet[str]

    def is_subset_of(self, other: "Provenance") -> bool:
        return self.nodes.issubset(other.nodes)

    def minus(self, other: "Provenance") -> "Provenance":
        return Provenance(self.nodes - other.nodes)


@dataclass
class SpeculativeCall:
    call_id: str
    args_provenance_at_dispatch: Provenance
    reach: Provenance  # transitive closure of nodes the args depend on
    result: object = None
    committed: bool = False
    discarded: bool = False


class TaintVerifiedCommitter:
    """Serializes speculative commits against sibling commits on one MCP session."""

    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._committed: Set[str] = set()

    def commit_or_discard(
        self,
        call: SpeculativeCall,
        current_args_provenance: Provenance,
        committed_since_dispatch: Provenance,
    ) -> str:
        with self._lock:  # clause 3: revalidate inside the session commit lock
            # clause 1: provenance snapshot monotonicity
            added = current_args_provenance.minus(call.args_provenance_at_dispatch)
            if added.nodes:
                call.discarded = True
                return "discard:provenance-drift"

            # clause 2: no sibling commit touched the args' transitive closure
            overlap = committed_since_dispatch.nodes & call.reach.nodes
            if overlap:
                call.discarded = True
                return f"discard:sibling-commit-in-reach:{sorted(overlap)}"

            # value-stable + provenance-stable + no in-window sibling commit
            if call.result is None:
                raise TaintCommitViolation(
                    f"call {call.call_id!r} has no result to commit"
                )
            call.committed = True
            self._committed.add(call.call_id)
            return "commit"


# --- minimal trace of the incident -----------------------------------------
committer = TaintVerifiedCommitter()

s3 = SpeculativeCall(
    call_id="S3",
    args_provenance_at_dispatch=Provenance(frozenset({"user_url"})),
    reach=Provenance(frozenset({"user_url", "kb.allowlist"})),
    result={"posted": True, "channel": "X"},
)

# S2 committed a hot-swapped resource body between S3's dispatch and commit.
committed_since_dispatch = Provenance(frozenset({"kb.allowlist"}))
current_args_provenance = Provenance(frozenset({"user_url"}))  # bytes unchanged

disposition = committer.commit_or_discard(
    s3, current_args_provenance, committed_since_dispatch
)
assert disposition.startswith("discard:"), disposition
assert s3.discarded and not s3.committed
