# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-speculative-branch-before-commit-when-cross-org-consistency-checks-depend-on-non-monotonic-confl.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-speculative-branch-before-commit-when-cross-org-consistency-checks-depend-on-non-monotonic-confl.warrant.json
# Markdown SHA-256:   da559c003f635f6dec11af55dd848746ca73cc6f9ab8a5b71229248e081adbec
# Code AST SHA-256:   adcafc6772bcaee1c62ac79f50107898fc2e9acfef249c2b9f635e285020e4c1
# Verified Classes:   ToolClass, ResolverPolicy, SpecRead, SpecBranch, FederationResolver, RetractionAncestryError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ToolClass(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"
    COMPENSABLE = "compensable"


class ResolverPolicy(Enum):
    MONOTONIC = "monotonic"
    PRIORITY_WEIGHTED = "priority_weighted"
    QUORUM_VETO = "quorum_veto"
    ESCALATION = "escalation"


@dataclass(frozen=True)
class SpecRead:
    resource: str
    value: object
    owning_org: str
    resolver_priority: int
    irrevocable: bool


@dataclass
class SpecBranch:
    branch_id: str
    org: str
    reads: list[SpecRead] = field(default_factory=list)
    effects: list[str] = field(default_factory=list)


class FederationResolver(Protocol):
    policy: ResolverPolicy

    def retractable_reads(self, read: SpecRead) -> bool:
        """True if any admissible resolution can retract this read's value."""
        ...


class RetractionAncestryError(RuntimeError):
    """Raised when an irreversible effect would be grounded in a retractable read."""


def _is_non_monotonic(policy: ResolverPolicy) -> bool:
    return policy in (
        ResolverPolicy.PRIORITY_WEIGHTED,
        ResolverPolicy.QUORUM_VETO,
        ResolverPolicy.ESCALATION,
    )


def pre_execution_ancestry_gate(
    branch: SpecBranch,
    tool_class: ToolClass,
    resolver: FederationResolver,
    has_registered_compensator: bool = False,
) -> None:
    """
    Must be called immediately before invoking a tool. Rejects the branch if an
    irreversible effect would rest on a retractable speculative read.
    """
    if tool_class is ToolClass.REVERSIBLE:
        return
    if tool_class is ToolClass.COMPENSABLE and has_registered_compensator:
        return

    if not _is_non_monotonic(resolver.policy):
        return

    tainted = [
        r for r in branch.reads
        if not r.irrevocable and resolver.retractable_reads(r)
    ]
    if tainted:
        raise RetractionAncestryError(
            f"branch {branch.branch_id} (org={branch.org}) cannot emit "
            f"{tool_class.value} effect: {len(tainted)} retractable ancestor(s) "
            f"under {resolver.policy.value}; "
            f"resources={[r.resource for r in tainted]}. "
            f"Defer until resolver marks reads IRREVOCABLE or escalate."
        )


def execute_speculative_tool(
    branch: SpecBranch,
    tool_name: str,
    tool_class: ToolClass,
    resolver: FederationResolver,
    compensator: str | None = None,
) -> None:
    pre_execution_ancestry_gate(
        branch, tool_class, resolver,
        has_registered_compensator=compensator is not None,
    )
    branch.effects.append(tool_name)
