# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-plan-commitment-under-3f-1-quorum-when-the-committing-agent-s-own-tool-call-ledger-diverges-from-the-peer-observed-ledge.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-plan-commitment-under-3f-1-quorum-when-the-committing-agent-s-own-tool-call-ledger-diverges-from-the-peer-observed-ledge.warrant.json
# Markdown SHA-256:   d9ae94b597316b3d6bf79ad29fbc20694005fc7654d952fcd574e71a8817c30c
# Code AST SHA-256:   434d9389497f7d2020b9afe75529fa8237758e3476c675b92175d770f01f8409
# Verified Classes:   StaleCommitmentError, ReadSetEntry, PlanCommitment, ExecutionGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Callable, Dict, List


class StaleCommitmentError(RuntimeError):
    """Raised when a quorum-certified plan's read set has diverged from the
    state observed at PREPARE time. The certificate is valid; the world is not."""


@dataclass
class ReadSetEntry:
    resource: str
    value_hash: str
    observed_at: float


@dataclass
class PlanCommitment:
    plan_id: str
    step_list: List[str]
    preconditions: List[str]
    read_set: Dict[str, ReadSetEntry] = field(default_factory=dict)
    quorum_signers: List[str] = field(default_factory=list)

    def read_set_root(self) -> str:
        h = hashlib.sha256()
        for key in sorted(self.read_set):
            entry = self.read_set[key]
            h.update(f"{key}:{entry.value_hash}".encode())
        return h.hexdigest()

    def certificate_hash(self) -> str:
        # NOTE: read_set_root MUST be inside the signed hash. Excluding it is
        # the precondition-binding gap this record documents.
        h = hashlib.sha256()
        h.update("|".join(self.step_list).encode())
        h.update("|".join(self.preconditions).encode())
        h.update(self.read_set_root().encode())
        return h.hexdigest()


class ExecutionGate:
    def __init__(self, quota: int, required_quorum: int, total_nodes: int):
        self.quota = quota
        self.required_quorum = required_quorum
        self.total_nodes = total_nodes

    def recompute_read_set_root(self, plan: PlanCommitment) -> str:
        h = hashlib.sha256()
        for key in sorted(plan.read_set):
            # Re-read the live value of each open precondition resource.
            live_value = self._observe(key)
            h.update(f"{key}:{live_value}".encode())
        return h.hexdigest()

    def _observe(self, resource: str) -> str:
        if resource == "api_quota_remaining":
            return hashlib.sha256(str(self.quota).encode()).hexdigest()
        if resource.startswith("file:"):
            # Simulated absence/presence observation.
            return hashlib.sha256(b"absent").hexdigest()
        raise StaleCommitmentError(f"unobservable resource in open read set: {resource}")

    def validate_and_execute(
        self,
        plan: PlanCommitment,
        execute_fn: Callable[[PlanCommitment], None],
    ) -> None:
        # Phase A: certificate must carry 2f+1 distinct signers.
        distinct = set(plan.quorum_signers)
        if len(distinct) < self.required_quorum:
            raise StaleCommitmentError(
                f"insufficient quorum: {len(distinct)} < {self.required_quorum}"
            )
        if len(distinct) > self.total_nodes:
            raise StaleCommitmentError("quorum larger than node set; forged signers")

        # Phase B: read-set re-validation. This is the gate whose absence
        # produced the corrupted-artifact incident.
        certified_root = plan.read_set_root()
        live_root = self.recompute_read_set_root(plan)
        if live_root != certified_root:
            changed = [
                k for k in plan.read_set
                if self._observe(k) != plan.read_set[k].value_hash
            ]
            raise StaleCommitmentError(
                f"plan {plan.plan_id} stale: read-set diverged at {changed}; "
                f"certified={certified_root[:12]} live={live_root[:12]}. "
                f"Re-propose required; do not execute."
            )

        execute_fn(plan)


# --- Demonstration of the boundary failure ---
if __name__ == "__main__":
    gate = ExecutionGate(quota=5, required_quorum=3, total_nodes=6)

    plan = PlanCommitment(
        plan_id="plan-7f3a",
        step_list=["write:/work/out.json", "call:summarize"],
        preconditions=[
            "file:/work/out.json absent",
            "api_quota_remaining >= 5",
        ],
        read_set={
            "file:/work/out.json": ReadSetEntry(
                "file:/work/out.json",
                hashlib.sha256(b"absent").hexdigest(),
                time.time(),
            ),
            "api_quota_remaining": ReadSetEntry(
                "api_quota_remaining",
                hashlib.sha256(b"5").hexdigest(),
                time.time(),
            ),
        },
        quorum_signers=["A", "B", "C", "D"],  # 2f+1 = 3 satisfied, valid cert
    )

    # Adversarial peer consumes quota between PREPARE and execution-start.
    gate.quota = 2

    try:
        gate.validate_and_execute(plan, lambda p: print(f"EXECUTING {p.plan_id}"))
    except StaleCommitmentError as exc:
        print(f"ABORTED: {exc}")
