# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-plan-fragments-when-a-federated-quorum-commits-a-byzantine-peer-s-stale-proposal-as-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-plan-fragments-when-a-federated-quorum-commits-a-byzantine-peer-s-stale-proposal-as-shared-state.warrant.json
# Markdown SHA-256:   4463b9235c05911da50947d9f8c3a1b9009473efc53f4cda42f77679c7e25e14
# Code AST SHA-256:   d8eed32f111d9c7bdb6240b33406dcd30e5a3b1c461d1f60f174ee7cd8915de2
# Verified Classes:   StaleFragmentRejected, PlanFragment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleFragmentRejected(RuntimeError):
    """Raised when a committed plan fragment's bound epoch is older than
    the instance's last-observed epoch, indicating a replay of a stale but
    internally-valid proposal that passed Byzantine quorum."""
    pass


@dataclass(frozen=True)
class PlanFragment:
    fragment_id: str
    observed_at_epoch: int      # bound at proposal time, must be monotonic
    freshness_proof: bytes      # threshold sig over epoch from read-quorum
    payload: dict


def admit_fragment(
    fragment: PlanFragment,
    last_observed_epoch: int,
    verify_freshness_proof,
) -> PlanFragment:
    # Currency check FIRST: a validly-signed fragment can still be stale.
    if fragment.observed_at_epoch < last_observed_epoch:
        raise StaleFragmentRejected(
            f"fragment {fragment.fragment_id} bound to epoch "
            f"{fragment.observed_at_epoch} < last observed "
            f"{last_observed_epoch}; possible Byzantine replay"
        )
    if not verify_freshness_proof(fragment.observed_at_epoch, fragment.freshness_proof):
        raise StaleFragmentRejected(
            f"fragment {fragment.fragment_id} lacks valid freshness proof "
            f"for epoch {fragment.observed_at_epoch}"
        )
    # Only now does content-consistency verification run.
    return fragment


def commit_fragment(fragment: PlanFragment, quorum, last_observed_epoch: int) -> PlanFragment:
    admitted = admit_fragment(fragment, last_observed_epoch, quorum.verify_freshness_proof)
    quorum.commit(admitted)  # epoch-monotonicity already enforced above
    return admitted
