# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-quorum-under-byzantine-fault-tolerant-consensus-when-its-local-state-vector-is-silently-truncated-by-a-context-windo.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-quorum-under-byzantine-fault-tolerant-consensus-when-its-local-state-vector-is-silently-truncated-by-a-context-windo.warrant.json
# Markdown SHA-256:   ae0563872199ebefd1c78db3874cc28b4ab7b99877d435a065e6c4f1daee75d6
# Code AST SHA-256:   5b5cc4374e6e056009ffa4bdf68b7f399a0395e4e84769866ce217b69bc6cf92
# Verified Classes:   TruncatedVoteError, ProvenanceViolationError, AssembledContext, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

CONSENSUS_CRITICAL_FIELDS: FrozenSet[str] = frozenset(
    {"epoch", "parent_hash", "view", "signer_set", "state_root"}
)

class TruncatedVoteError(RuntimeError):
    """Raised when a replica attempts to vote from a lossy-evicted context."""
    pass

class ProvenanceViolationError(RuntimeError):
    """Raised when a vote's state provenance is context-derived for a critical hash."""
    pass

@dataclass
class AssembledContext:
    fields: dict
    evicted_spans: list  # list of (start, end) token ranges dropped by eviction
    pinned_prefix: list  # field names declared non-evictable

@dataclass
class Vote:
    replica_id: str
    state_hash: str
    provenance: str  # "durable_read" | "context_derived"
    signature: bytes = b""

def assemble_vote(ctx: AssembledContext, durable_state: dict | None) -> Vote:
    # 1. Assert the pinned prefix survived eviction.
    surviving = set(ctx.fields.keys())
    missing_critical = CONSENSUS_CRITICAL_FIELDS - surviving
    if missing_critical:
        raise TruncatedVoteError(
            f"consensus-critical fields evicted from context: {sorted(missing_critical)}; "
            f"evicted_spans={ctx.evicted_spans}; refusing to vote from truncated state"
        )

    # 2. If any eviction span intersects the pinned prefix, the context is unsafe.
    pinned_count = len(ctx.pinned_prefix)
    for (start, end) in ctx.evicted_spans:
        if start < pinned_count:
            raise TruncatedVoteError(
                f"eviction span ({start},{end}) intersects pinned prefix of length "
                f"{pinned_count}; context is lossy over consensus-critical region"
            )

    # 3. Prefer durable read; if unavailable, provenance must be declared.
    if durable_state is not None:
        state = durable_state
        provenance = "durable_read"
    else:
        state = ctx.fields
        provenance = "context_derived"

    state_hash = _hash_state(state)

    # 4. A context-derived hash over consensus-critical state is not admissible.
    if provenance == "context_derived" and _touches_critical(state):
        raise ProvenanceViolationError(
            f"replica {ctx.fields.get('replica_id')} attempted context-derived vote "
            f"over critical state hash {state_hash}; abstain and signal STATE_UNAVAILABLE"
        )

    return Vote(
        replica_id=ctx.fields["replica_id"],
        state_hash=state_hash,
        provenance=provenance,
    )

def _hash_state(state: dict) -> str:
    import hashlib, json
    payload = json.dumps({k: state[k] for k in sorted(state)}, separators=(",", ":"))
    return "0x" + hashlib.sha256(payload.encode()).hexdigest()

def _touches_critical(state: dict) -> bool:
    return bool(CONSENSUS_CRITICAL_FIELDS & set(state.keys()))

def admit_vote(vote: Vote, proposal_hash: str) -> None:
    if vote.provenance == "context_derived" and vote.state_hash == proposal_hash:
        # Even a matching hash from a context-derived vote is untrustworthy:
        # it may have truncated identically to another replica's truncation.
        raise ProvenanceViolationError(
            f"vote from {vote.replica_id} matches proposal but provenance is "
            f"context_derived; reject to avoid silent-fork quorum contamination"
        )
