# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculates-past-a-federated-commit-barrier-cross-org-read-set-drift-under-optimistic-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculates-past-a-federated-commit-barrier-cross-org-read-set-drift-under-optimistic-agent-execution.warrant.json
# Markdown SHA-256:   8ada6fc10524aeb93215124cf8ecd002f2994f98946b98d03444ece1b11591b6
# Code AST SHA-256:   c539e1fea0fdf7044b4847b98ca7bd4ad56e02f939d030212852151f7b6c3b22
# Verified Classes:   ReadSetInvalidated, VersionedValue, SpeculativePlanner
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReadSetInvalidated(RuntimeError):
    """Raised when a speculative instance attempts a dependent dispatch
    after its read-set has been superseded by a federated commit."""
    pass


@dataclass(frozen=True)
class VersionedValue:
    org: str
    version: int
    value: object
    conditional_on: Optional[int] = None  # must not be flattened away


@dataclass
class SpeculativePlanner:
    read_set: list[VersionedValue] = field(default_factory=list)

    def reconciled_floor(self) -> int:
        if not self.read_set:
            return 0
        return max(v.version for v in self.read_set)

    def dispatch_dependent(self, action: str, inputs: list[VersionedValue]) -> str:
        floor = self.reconciled_floor()
        # Invariant: no dependent dispatch below the reconciled version floor,
        # and no conditional input silently treated as unconditional success.
        for v in inputs:
            if v.version < floor:
                raise ReadSetInvalidated(
                    f"dispatch '{action}' blocked: input from {v.org} at "
                    f"v{v.version} < reconciled floor v{floor}; read-set "
                    f"superseded by federated commit"
                )
            if v.conditional_on is not None and v.conditional_on > v.version:
                raise ReadSetInvalidated(
                    f"dispatch '{action}' blocked: input from {v.org} is "
                    f"conditional on v{v.conditional_on} but read at "
                    f"v{v.version}; attestation not yet satisfiable"
                )
        return f"dispatched:{action}@v{floor}"


# Incident replay: planner holds stale v16 belief, peer attestation implies v17.
planner = SpeculativePlanner(
    read_set=[VersionedValue("B", 16, {"free": 42})]
)
attestation = VersionedValue("C", 17, {"reservation": "ok"}, conditional_on=17)
try:
    planner.dispatch_dependent("reserve_5_more", [attestation])
except ReadSetInvalidated as e:
    print(f"GUARDRAIL HELD: {e}")
