# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-certificate-equivocation-in-bft-agent-task-commitment-before-the-safety-violation-becomes-observable.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-certificate-equivocation-in-bft-agent-task-commitment-before-the-safety-violation-becomes-observable.warrant.json
# Markdown SHA-256:   39417c373b9c195c9c2835e170aa6ada4bfc46c8369fca3c7d95d8fb75d74941
# Code AST SHA-256:   b07d39960e7ba678cdc54d61c9c5b62a7e4072fe5c98e5716d736af0d298e4ae
# Verified Classes:   EquivocalCertificateError, StaleConflictLogError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EquivocalCertificateError(RuntimeError):
    """Raised when two distinct, validly-signed QCs exist at the same height."""
    pass


class StaleConflictLogError(RuntimeError):
    """Raised when checkpoint restore cannot prove conflict-log continuity."""
    pass


def validate_and_commit(
    height: int,
    qc_digest: bytes,
    qc_value: bytes,
    conflict_log: dict,          # height -> set[qc_digest]
    committed_height: int,
    state_root_height: int,
) -> None:
    # Guardrail 3: conflict log must be at least as fresh as the state root.
    if state_root_height > committed_height and height not in conflict_log:
        # We are about to act on a height the conflict log has never seen.
        # Fail closed rather than risk committing an equivocal certificate.
        raise StaleConflictLogError(
            f"conflict log has no entry for height {height} but "
            f"state_root_height={state_root_height} > committed_height={committed_height}; "
            f"refusing to commit without conflict-log continuity"
        )

    seen = conflict_log.setdefault(height, set())

    # Guardrail 4: any second distinct digest at the same height is a portable
    # conflict proof. Halt; do not commit.
    if seen and qc_digest not in seen:
        raise EquivocalCertificateError(
            f"equivocation at height {height}: already hold "
            f"{len(seen)} distinct QC digest(s) {[d.hex()[:8] for d in seen]}, "
            f"now seeing {qc_digest.hex()[:8]} for value {qc_value.hex()[:8]}; "
            f"broadcast conflict proof and halt"
        )

    seen.add(qc_digest)
    # ... apply qc_value to shared state, advance committed_height ...
