# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-a-contract-net-bidder-withhold-an-outcome-attestation-rather-than-sign-it-under-partial-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-a-contract-net-bidder-withhold-an-outcome-attestation-rather-than-sign-it-under-partial-observability.warrant.json
# Markdown SHA-256:   1febba72cd3e70eb1612f32b6ceb148c4cc8be0d624a2f6bfcecf88c425691a9
# Code AST SHA-256:   8df325df24573c1b7585244cae41ee0f7868f07d1629d504be88f7b5b6b22662
# Verified Classes:   UnstableAttestationError, BidContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class UnstableAttestationError(RuntimeError):
    """Raised when a bidder attempts to sign an outcome attestation
    without a stability primitive that establishes a happens-before
    edge to the verifier's acceptance window."""


@dataclass(frozen=True)
class BidContext:
    bid_id: str
    observed_version: int
    expected_version: int
    stability_token: Optional[str]  # fence token / read-lease id, or None
    token_covers_signing_instant: bool = False


def sign_attestation(ctx: BidContext) -> dict:
    if ctx.observed_version != ctx.expected_version:
        raise UnstableAttestationError(
            f"bid {ctx.bid_id}: observed version {ctx.observed_version} "
            f"!= expected {ctx.expected_version}; cannot attest"
        )
    if ctx.stability_token is None:
        raise UnstableAttestationError(
            f"bid {ctx.bid_id}: no stability token; observation is advisory "
            f"and an attestation would be unsound under concurrent writers"
        )
    if not ctx.token_covers_signing_instant:
        raise UnstableAttestationError(
            f"bid {ctx.bid_id}: stability token {ctx.stability_token} does "
            f"not cover the signing instant; happens-before edge to verifier "
            f"is not established"
        )
    return {
        "bid_id": ctx.bid_id,
        "attested_version": ctx.observed_version,
        "stability_token": ctx.stability_token,
        "claim": "post_version_matches_expected",
    }


def handle_bid(ctx: BidContext) -> dict:
    try:
        return {"status": "attested", "claim": sign_attestation(ctx)}
    except UnstableAttestationError as exc:
        # Abstention is a first-class protocol message, not a failure.
        return {
            "status": "abstained",
            "reason": "NO_STABLE_READ",
            "detail": str(exc),
        }
