# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-signs-an-attestation-over-a-result-it-never-recomputed-quorum-signed-commitment-with-attestation-replay-against-a-diverg.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-signs-an-attestation-over-a-result-it-never-recomputed-quorum-signed-commitment-with-attestation-replay-against-a-diverg.warrant.json
# Markdown SHA-256:   1f7eefa9e54dce382a83cb023a4ecb9df70066cfb0a4606c88337bd8cb5e97f3
# Code AST SHA-256:   4a4a4ead982f09519ad9164f914a159ea35633704fb1b02ca2ada75828bc189b
# Verified Classes:   AttestationWithoutCommitmentError, Commitment, ExecutionRecord, InstanceLedger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class AttestationWithoutCommitmentError(RuntimeError):
    """Raised when an instance is asked to attest a result for a commitment
    it does not hold in its persisted ledger, or whose execution record is
    missing or expired. Signing in this state would make the instance a
    Byzantine signer under the quorum's threat model."""


@dataclass
class Commitment:
    commitment_id: str
    task_digest: str
    deadline_epoch: int


@dataclass
class ExecutionRecord:
    commitment_id: str
    output_digest: str
    completed_epoch: int


@dataclass
class InstanceLedger:
    commitments: Dict[str, Commitment] = field(default_factory=dict)
    executions: Dict[str, ExecutionRecord] = field(default_factory=dict)
    reconciled: bool = False

    def reconcile_after_resume(self, fetched_commitments: Dict[str, Commitment]) -> None:
        # Resume path: working memory may be stale; ledger must be re-fetched
        # before any signing is permitted.
        self.commitments = dict(fetched_commitments)
        self.reconciled = True


def sign_attestation(
    ledger: InstanceLedger,
    commitment_id: str,
    claimed_output_digest: str,
    now_epoch: int,
) -> str:
    if not ledger.reconciled:
        raise AttestationWithoutCommitmentError(
            f"ledger not reconciled after resume; refusing to sign {commitment_id}"
        )
    commitment = ledger.commitments.get(commitment_id)
    if commitment is None:
        raise AttestationWithoutCommitmentError(
            f"commitment {commitment_id} absent from ledger; "
            f"attestation would be a signature over an unknown string"
        )
    if now_epoch > commitment.deadline_epoch:
        raise AttestationWithoutCommitmentError(
            f"commitment {commitment_id} expired at {commitment.deadline_epoch}; "
            f"late attestation may originate from a stale-resume state"
        )
    execution = ledger.executions.get(commitment_id)
    if execution is None:
        raise AttestationWithoutCommitmentError(
            f"no execution record for {commitment_id}; "
            f"cannot attest a digest this instance did not compute"
        )
    if execution.output_digest != claimed_output_digest:
        raise AttestationWithoutCommitmentError(
            f"claimed digest {claimed_output_digest} does not match "
            f"local execution {execution.output_digest} for {commitment_id}"
        )
    payload = f"{commitment.task_digest}|{claimed_output_digest}|{commitment_id}"
    return hashlib.sha256(payload.encode()).hexdigest()


def collect_quorum(
    attestations: Dict[str, str],
    auditor_dissent: bool,
    threshold: int,
) -> bool:
    if auditor_dissent:
        # A disputed digest with a satisfied signature threshold is a
        # contradiction: suspend, do not commit.
        raise AttestationWithoutCommitmentError(
            "auditor dissent present; quorum suspended pending re-execution"
        )
    return len(attestations) >= threshold
