# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-prefetch-failures-from-poisoning-swarm-state-during-concurrent-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-prefetch-failures-from-poisoning-swarm-state-during-concurrent-verification.warrant.json
# Markdown SHA-256:   0957194f359a777ace8edfcf854e63de82f8b020c63e122ad922883dc9652995
# Code AST SHA-256:   a4fa7b2767e051754365883e4634e295940843ffe65ee4dec2a6657b9908035f
# Verified Classes:   StalePrefetchPromotionError, Observation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StalePrefetchPromotionError(RuntimeError):
    """Raised when a prefetched observation is promoted to shared state
    without a freshness witness, or when reconciliation is attempted
    across observations with incomparable witnesses."""
    pass


@dataclass(frozen=True)
class Observation:
    surface: str
    value: object
    witness: Optional[int]  # monotonic version / ETag / logical clock

    def is_witnessed(self) -> bool:
        return self.witness is not None


def promote_prefetch(obs: Observation, shared_state: dict) -> None:
    """Promote a speculative observation into shared state.

    Invariant: promotion requires a freshness witness. A prefetched value
    without a witness cannot be compared against a later auditor check
    and therefore cannot be safely consumed by another agent's reasoning.
    """
    if not obs.is_witnessed():
        raise StalePrefetchPromotionError(
            f"refusing to promote unwitnessed prefetch on surface "
            f"{obs.surface!r}: no version/ETag/logical clock to compare "
            f"against auditor checks"
        )
    shared_state[obs.surface] = obs


def reconcile(speculator: Observation, auditor: Observation) -> str:
    """Reconcile a speculator's prefetched observation against an
    auditor's independent check on the same surface.

    Returns one of: 'proceed', 'retract', 'halt'.
    """
    if speculator.surface != auditor.surface:
        raise StalePrefetchPromotionError(
            f"cannot reconcile observations on different surfaces: "
            f"{speculator.surface!r} vs {auditor.surface!r}"
        )
    if not (speculator.is_witnessed() and auditor.is_witnessed()):
        raise StalePrefetchPromotionError(
            f"cannot reconcile {speculator.surface!r}: missing freshness "
            f"witness on one or both observations"
        )

    if speculator.witness < auditor.witness:
        # Speculator's premise is superseded; plan must be retracted,
        # not reconciled. Internal consistency of the speculator's
        # reasoning is NOT a tiebreaker.
        return "retract"
    if speculator.witness > auditor.witness:
        # Auditor's check is stale/concurrent; speculator's observation
        # is current. Log auditor as superseded, not as mismatch.
        return "proceed"

    # Equal witnesses with divergent values => non-deterministic surface
    # or witness collision. Neither is recoverable by reconciliation.
    if speculator.value != auditor.value:
        raise StalePrefetchPromotionError(
            f"equal-witness divergence on {speculator.surface!r} "
            f"(witness={speculator.witness}): surface is not a function "
            f"of its witness; halt and require non-speculative read"
        )
    return "proceed"
