# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-abort-speculative-tool-call-fan-out-when-compensation-is-non-commutative-the-idempotency-key-shadowing-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-abort-speculative-tool-call-fan-out-when-compensation-is-non-commutative-the-idempotency-key-shadowing-failure.warrant.json
# Markdown SHA-256:   8087cedaaa65ee72a87b4b9f4cbbc7c5dbc5d5d7685ccb544ecfd9de19d3364b
# Code AST SHA-256:   d9cc72c183edfe4369a87ec30eeb40099508ca616d097012fa93cfbf3dffc931
# Verified Classes:   SpeculativeCompensationError, EffectLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Set


class SpeculativeCompensationError(RuntimeError):
    """Raised when speculative fan-out would violate key-alignment or compensation ordering."""
    pass


@dataclass
class EffectLedger:
    applied: Dict[str, str] = field(default_factory=dict)      # idem_key -> logical_op_id
    compensated: Set[str] = field(default_factory=set)
    pending_compensations: Dict[str, str] = field(default_factory=dict)  # logical_op_id -> key


def mint_key(logical_op_id: str, plan_uuid: str) -> str:
    # Key derived from immutable operation identity + plan UUID minted at materialization.
    # NOT from attempt / step_index / retry counter.
    return hashlib.sha256(f"{plan_uuid}:{logical_op_id}".encode()).hexdigest()[:16]


def assert_speculation_safe(
    ledger: EffectLedger,
    logical_op_id: str,
    tool_idempotent: bool,
    compensation_order_sensitive: bool,
    key_derivable_from_immutable_identity: bool,
) -> str:
    if logical_op_id in ledger.pending_compensations:
        raise SpeculativeCompensationError(
            f"Refusing speculative dispatch for {logical_op_id}: "
            f"compensation for key {ledger.pending_compensations[logical_op_id]} still pending. "
            f"New attempt would mint a parallel key and shadow the unflushed compensation."
        )
    if not key_derivable_from_immutable_identity:
        raise SpeculativeCompensationError(
            f"Refusing speculative dispatch for {logical_op_id}: idempotency key would be "
            f"re-derived from plan shape (attempt/step), breaking key-alignment across retries."
        )
    if (not tool_idempotent) and compensation_order_sensitive:
        raise SpeculativeCompensationError(
            f"Refusing speculative dispatch for {logical_op_id}: non-idempotent tool with "
            f"order-sensitive compensation requires serial execution with reverse-order flush."
        )
    return mint_key(logical_op_id, plan_uuid="plan-uuid-immutable")


def reconcile(ledger: EffectLedger) -> None:
    shadowed = ledger.compensated - set(ledger.applied)
    if shadowed:
        raise SpeculativeCompensationError(
            f"Compensation ledger references keys never applied: {sorted(shadowed)}. "
            f"Fingerprint of idempotency-key shadowing across speculative branches."
        )
