# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-warrant-divergence-in-federated-multi-agent-execution-when-cross-org-reconciliation-commits-a-loser-branc.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-warrant-divergence-in-federated-multi-agent-execution-when-cross-org-reconciliation-commits-a-loser-branc.warrant.json
# Markdown SHA-256:   580cfe9902b8ab63630492a876617fa0011dae835cb7d0a6bb63ed9c19c82461
# Code AST SHA-256:   8eff2b1f9e41fdfd657955227c9edb4f60da4d980231e67fdbee68272d3131ab
# Verified Classes:   WarrantDiscardError, WarrantState, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class WarrantDiscardError(RuntimeError):
    """Raised when a reconciler attempts to discard a warrant that has been
    observed by a non-participant party, violating observation isolation."""


class WarrantState(Enum):
    PENDING = "pending"
    COMMITTED = "committed"
    DISCARDED = "discarded"
    COMPENSATED = "compensated"


@dataclass
class Warrant:
    warrant_id: str
    org: str
    generation: int
    state: WarrantState = WarrantState.PENDING
    # Parties contractually bound to honor DISCARD (participants in reconciliation).
    bound_participants: FrozenSet[str] = frozenset()
    # Parties that have actually read this warrant, participant or not.
    observed_by: set = field(default_factory=set)

    def record_observation(self, party: str) -> None:
        self.observed_by.add(party)

    def unbound_observers(self) -> set:
        return self.observed_by - set(self.bound_participants)


def reconcile_discard(
    warrant: Warrant,
    reconciler_org: str,
    bound_participants: FrozenSet[str],
) -> None:
    """
    Attempt to discard a losing speculative branch's warrant.

    Safe only when every observer of the warrant is a bound participant that
    will honor the DISCARD. Any unbound observer (a downstream planner, a
    scheduler, a webhook consumer) means the warrant is actionable by a party
    outside the reconciliation protocol, and release would orphan an
    observation. In that case the caller must compensate instead.
    """
    if warrant.state is not WarrantState.PENDING:
        raise WarrantDiscardError(
            f"warrant {warrant.warrant_id} not in PENDING state: {warrant.state}"
        )

    warrant.bound_participants = bound_participants
    unbound = warrant.unbound_observers()

    if unbound:
        # The boundary crossing: a non-participant has seen this warrant and
        # may have initiated irreversible downstream action against it.
        raise WarrantDiscardError(
            f"cannot discard warrant {warrant.warrant_id} from org {warrant.org}: "
            f"observed by non-participants {sorted(unbound)} at generation "
            f"{warrant.generation}; compensate with a superseding generation "
            f"instead of release"
        )

    warrant.state = WarrantState.DISCARDED


def compensate_warrant(warrant: Warrant, next_generation: int) -> Warrant:
    """
    Supersede a warrant that cannot be safely discarded. Downstream parties
    bound to re-validate on generation change will treat the new warrant as
    authoritative and abandon the stale one.
    """
    if next_generation <= warrant.generation:
        raise WarrantDiscardError(
            f"compensation generation {next_generation} does not exceed "
            f"warrant {warrant.warrant_id} generation {warrant.generation}"
        )
    superseding = Warrant(
        warrant_id=warrant.warrant_id,
        org=warrant.org,
        generation=next_generation,
        bound_participants=warrant.bound_participants,
    )
    warrant.state = WarrantState.COMPENSATED
    return superseding
