# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-invalid-when-the-committed-task-set-is-internally-consistent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-invalid-when-the-committed-task-set-is-internally-consistent.warrant.json
# Markdown SHA-256:   36186cf0bc4e6673051844c87d2997fe5e9cec3882ce48b4fa8c1144b44be6ec
# Code AST SHA-256:   e03ee5c56a92febb72fe289236ff43c071feaec30fe9d463cfe56aef0198fe67
# Verified Classes:   CommitmentInvariantViolation, CertificateRejected, Task, Certificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Callable, Mapping, Sequence


class CommitmentInvariantViolation(RuntimeError):
    """Raised when a quorum certificate authenticates a payload that violates
    the commitment predicate I(S), even though signatures and digest bind."""


class CertificateRejected(RuntimeError):
    """Raised when cryptographic or structural certificate checks fail."""


@dataclass(frozen=True)
class Task:
    task_id: str
    resource: str
    epoch: int
    owner: str


@dataclass(frozen=True)
class Certificate:
    digest: str
    signers: Sequence[str]
    payload: Sequence[Task]


def canonical_digest(tasks: Sequence[Task]) -> str:
    h = hashlib.sha256()
    for t in sorted(tasks, key=lambda x: x.task_id):
        h.update(f"{t.task_id}|{t.resource}|{t.epoch}|{t.owner}".encode())
    return h.hexdigest()


def commitment_invariant(tasks: Sequence[Task]) -> bool:
    """I(S): no two tasks claim the same exclusive resource in the same epoch."""
    seen: dict[tuple[str, int], str] = {}
    for t in tasks:
        key = (t.resource, t.epoch)
        if key in seen and seen[key] != t.owner:
            return False
        seen[key] = t.owner
    return True


def accept_certificate(
    cert: Certificate,
    registered_keys: Mapping[str, str],
    verify_sig: Callable[[str, str, str], bool],
    quorum: int,
) -> Sequence[Task]:
    # 1. threshold soundness
    distinct = {s for s in cert.signers if s in registered_keys}
    if len(distinct) < quorum:
        raise CertificateRejected(f"insufficient signers: {len(distinct)} < {quorum}")
    for signer in distinct:
        if not verify_sig(signer, cert.digest, registered_keys[signer]):
            raise CertificateRejected(f"bad signature from {signer}")

    # 2. digest binding
    if canonical_digest(cert.payload) != cert.digest:
        raise CertificateRejected("digest does not bind payload")

    # 3. invariant closure -- MUST precede application, not follow it.
    if not commitment_invariant(cert.payload):
        raise CommitmentInvariantViolation(
            "certificate authenticates conflicting exclusive claims; "
            "refusing to produce a state transition"
        )

    # 4. only now is a transition produced
    return cert.payload


def apply_commit(cert: Certificate, state: dict, **kw) -> dict:
    tasks = accept_certificate(cert, **kw)
    new_state = dict(state)
    for t in tasks:
        new_state[(t.resource, t.epoch)] = t.owner
    return new_state


if __name__ == "__main__":
    conflicting = [
        Task("Ta", "R", 41, "agent-1"),
        Task("Tb", "R", 41, "agent-2"),
    ]
    digest = canonical_digest(conflicting)
    cert = Certificate(digest=digest, signers=["a", "b", "c"], payload=conflicting)
    keys = {"a": "k", "b": "k", "c": "k"}
    try:
        apply_commit(cert, {}, registered_keys=keys,
                     verify_sig=lambda s, d, k: True, quorum=3)
    except CommitmentInvariantViolation as e:
        print(f"rejected as expected: {e}")
