# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-fan-out-and-roll-back-committed-side-effects-when-a-subagent-s-divergent-result-arrives-after.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-fan-out-and-roll-back-committed-side-effects-when-a-subagent-s-divergent-result-arrives-after.warrant.json
# Markdown SHA-256:   80b31c5a9111dd951f7d002ad5abeda603ce1ea6691d7ba4cd0b64df235402be
# Code AST SHA-256:   69120ec5e22b10417f5a0658ca9fc25d8814a7e6879e225e579e343609a616d4
# Verified Classes:   SpeculativeCommitError, OutputClass, SubagentResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Callable


class SpeculativeCommitError(RuntimeError):
    """Raised when a commit is attempted on an unresolved non-monotone result set."""


class OutputClass(Enum):
    MONOTONE = "monotone"          # can only confirm or abstain
    NON_MONOTONE = "non_monotone"  # can supersede / disambiguate / contradict


@dataclass
class SubagentResult:
    name: str
    output_class: OutputClass
    resolved: bool
    payload: dict


def commit_speculative(
    results: dict[str, SubagentResult],
    commit_predicate: Callable[[dict[str, SubagentResult]], bool],
    effect_emitter: Callable[[dict], None],
    revocation_handle: Callable[[dict], None] | None,
) -> None:
    # Invariant 1: no commit-critical (non-monotone) subagent may be unresolved.
    unresolved_critical = [
        r.name for r in results.values()
        if r.output_class is OutputClass.NON_MONOTONE and not r.resolved
    ]
    if unresolved_critical:
        raise SpeculativeCommitError(
            f"refusing early commit: non-monotone subagents unresolved: "
            f"{unresolved_critical}; timeout is not resolution"
        )

    # Invariant 2: predicate must be evaluated over the complete resolved set.
    if not commit_predicate(results):
        return

    # Invariant 3: if any non-monotone subagent contributed, a revocation
    # handle must exist before the effect is externally observable.
    has_non_monotone = any(
        r.output_class is OutputClass.NON_MONOTONE for r in results.values()
    )
    if has_non_monotone and revocation_handle is None:
        raise SpeculativeCommitError(
            "refusing commit: non-monotone result set present but no revocation "
            "handle to downstream consumers; rollback would orphan dependents"
        )

    effect = {"committed": True, "inputs": list(results)}
    effect_emitter(effect)
    # revocation_handle(effect) is retained by the orchestrator for the
    # lifetime of any downstream consumer that may read the effect.
