# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-task-result-before-the-quorum-s-view-of-the-tool-call-log-converges.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-task-result-before-the-quorum-s-view-of-the-tool-call-log-converges.warrant.json
# Markdown SHA-256:   d73255c1734b373ce2e3e5e12574c3e7a498f3c8d858f186a64d35fbafe9bbf9
# Code AST SHA-256:   8b2aaa6a2ecf0c7e8c08b13bcb3c78d1c90efb717d9a7422d010d7de3975b1da
# Verified Classes:   ResultCommitDivergence, LogCertificate, ResultCertificate
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ResultCommitDivergence(RuntimeError):
    """Raised when an instance attempts to emit a task result on the strength
    of a log-quorum certificate without a matching result-agreement certificate."""
    pass


@dataclass(frozen=True)
class LogCertificate:
    block_index: int
    block_hash: str
    quorum_signatures: tuple


@dataclass(frozen=True)
class ResultCertificate:
    task_id: str
    result_hash: str
    determinism_witness: tuple  # (model_hash, tokenizer_hash, seed, tool_in_hash, tool_out_hash)
    quorum_signatures: tuple


def derive_result_hash(log_segment: bytes, witness: tuple) -> str:
    h = hashlib.sha256()
    h.update(log_segment)
    for part in witness:
        h.update(str(part).encode())
    return h.hexdigest()


def emit_task_result(
    task_id: str,
    log_segment: bytes,
    log_cert: LogCertificate,
    result_cert: ResultCertificate | None,
    local_witness: tuple,
    quorum_size: int,
) -> str:
    # A valid log certificate is necessary but NOT sufficient to emit.
    if len(log_cert.quorum_signatures) < quorum_size:
        raise ResultCommitDivergence(
            f"log certificate for block {log_cert.block_index} lacks quorum"
        )

    # The boundary: refuse to emit on log-quorum alone.
    if result_cert is None:
        raise ResultCommitDivergence(
            f"task {task_id}: log committed at index {log_cert.block_index} "
            f"but no result-agreement certificate present; refusing to emit "
            f"derived result on log-quorum strength alone"
        )

    if result_cert.task_id != task_id:
        raise ResultCommitDivergence(
            f"result certificate task_id {result_cert.task_id} != {task_id}"
        )

    if len(result_cert.quorum_signatures) < quorum_size:
        raise ResultCommitDivergence(
            f"task {task_id}: result certificate lacks quorum "
            f"({len(result_cert.quorum_signatures)} < {quorum_size})"
        )

    # Determinism witness must match the local derivation path, or the
    # replica is deriving under artifact/model skew and must not emit.
    if tuple(result_cert.determinism_witness) != tuple(local_witness):
        raise ResultCommitDivergence(
            f"task {task_id}: local determinism witness {local_witness} "
            f"does not match committed witness {result_cert.determinism_witness}; "
            f"possible tokenizer/model/artifact skew"
        )

    local_hash = derive_result_hash(log_segment, local_witness)
    if local_hash != result_cert.result_hash:
        raise ResultCommitDivergence(
            f"task {task_id}: local result hash {local_hash} != "
            f"committed result hash {result_cert.result_hash}"
        )

    return local_hash
