# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-quorum-attestation-but-its-local-state-diverges-before-the-commit-is-durably-witnessed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-quorum-attestation-but-its-local-state-diverges-before-the-commit-is-durably-witnessed.warrant.json
# Markdown SHA-256:   d759ada35b3006dff4aa1a70223f102cc3c5a41f58d6c95ec72625f41b56efd5
# Code AST SHA-256:   3495e28ac18fe7ca2cad630d24425ae4d5f2e4f9856d96125a9b895439691ccd
# Verified Classes:   CommitmentStateDivergence, TaskSlot, Attestation, QuorumCertificate, CommittingAgent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CommitmentStateDivergence(RuntimeError):
    """Raised when an agent observes a quorum certificate for a task whose
    local state no longer matches the snapshot the agent signed at attest time.

    This is an honest-agent signal, not a Byzantine signal: it means the agent
    caught its own state drift before acting on a stale or missing commitment.
    The coordinator must respond with a state re-push, not a re-attestation.
    """
    pass


@dataclass
class TaskSlot:
    task_id: str
    priority: int
    definition: dict

    def snapshot_hash(self) -> str:
        payload = f"{self.task_id}|{self.priority}|{sorted(self.definition.items())}"
        return hashlib.sha256(payload.encode()).hexdigest()[:16]


@dataclass
class Attestation:
    agent_id: str
    task_id: str
    epoch: int
    slot_snapshot: str


@dataclass
class QuorumCertificate:
    task_id: str
    epoch: int
    # Per-agent signed snapshots. Without this field, condition 5 is broken
    # and the observation boundary cannot detect divergence.
    signed_snapshots: Dict[str, str] = field(default_factory=dict)


class CommittingAgent:
    def __init__(self, agent_id: str):
        self.agent_id = agent_id
        # Id-keyed table: slot collisions cannot overwrite a committed task.
        self.task_table: Dict[str, TaskSlot] = {}
        self.committed: set[str] = set()

    def attest(self, slot: TaskSlot, epoch: int) -> Attestation:
        self.task_table[slot.task_id] = slot
        return Attestation(
            agent_id=self.agent_id,
            task_id=slot.task_id,
            epoch=epoch,
            slot_snapshot=slot.snapshot_hash(),
        )

    def observe_certificate(self, qc: QuorumCertificate) -> None:
        """Enforce attestation-observation atomicity.

        If the current snapshot for qc.task_id does not match the snapshot this
        agent signed, raise CommitmentStateDivergence. Do NOT silently drop.
        """
        signed = qc.signed_snapshots.get(self.agent_id)
        if signed is None:
            # This agent is not in the certificate; nothing to observe.
            return

        slot = self.task_table.get(qc.task_id)
        if slot is None:
            raise CommitmentStateDivergence(
                f"agent={self.agent_id} task={qc.task_id} epoch={qc.epoch}: "
                f"certificate references task absent from local table; "
                f"signed_snapshot={signed}; recovery=state_repush"
            )

        current = slot.snapshot_hash()
        if current != signed:
            raise CommitmentStateDivergence(
                f"agent={self.agent_id} task={qc.task_id} epoch={qc.epoch}: "
                f"signed_snapshot={signed} current_snapshot={current}; "
                f"local state drifted between attest and observe; "
                f"recovery=state_repush"
            )

        self.committed.add(qc.task_id)


def run_observation(agent: CommittingAgent, qc: QuorumCertificate) -> None:
    """Driver that demonstrates the failure and its guardrail."""
    agent.observe_certificate(qc)


if __name__ == "__main__":
    a3 = CommittingAgent("A_3")
    t42 = TaskSlot(task_id="T_42", priority=3, definition={"op": "reindex", "shard": 7})

    att = a3.attest(t42, epoch=118)
    qc = QuorumCertificate(
        task_id="T_42",
        epoch=118,
        signed_snapshots={"A_3": att.slot_snapshot, "A_1": "deadbeef", "A_2": "cafef00d"},
    )

    # Simulate the concurrent scheduler overwriting the slot with T_43.
    # With an id-keyed table this appends rather than replaces, but the
    # slot for T_42 can still be mutated in place (e.g., priority bump).
    a3.task_table["T_42"].priority = 4

    # Observation must now raise, not silently drop.
    run_observation(a3, qc)
