# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-tool-call-whose-compensating-transaction-is-itself-non-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-tool-call-whose-compensating-transaction-is-itself-non-idempotent.warrant.json
# Markdown SHA-256:   ca5e083189b8fdad9b308ef4975b3a69771908f48604c8506b420d428da4fff1
# Code AST SHA-256:   7b3f14933b43c680d00361629b4977f4dd170273df26405a0876890ca36dedda
# Verified Classes:   IncompleteEffectLedger, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class IncompleteEffectLedger(RuntimeError):
    """Raised when compensation is attempted but the agent's durable effect
    ledger cannot be proven to be a superset of the tool's actual effect set."""


@dataclass
class EffectLedger:
    # Durable: survives context truncation. Keyed by (plan_id, step_index).
    forward: dict = field(default_factory=dict)   # key -> set(effect_id)
    compensated: dict = field(default_factory=dict)  # key -> set(effect_id)

    def key(self, plan_id: str, step_index: int, tool: str, args: dict) -> str:
        canon = f"{plan_id}|{step_index}|{tool}|{sorted(args.items())}"
        return hashlib.sha256(canon.encode()).hexdigest()

    def record_forward(self, key: str, effect_id: str) -> None:
        self.forward.setdefault(key, set()).add(effect_id)


def compensate(ledger: EffectLedger, tool, plan_id: str, step_index: int,
               tool_name: str, args: dict) -> None:
    key = ledger.key(plan_id, step_index, tool_name, args)
    ledgered = ledger.forward.get(key, set())

    # Reconciliation: ask the tool what effects actually exist for this key.
    actual = set(tool.list_effects(idempotency_prefix=key))

    if ledgered != actual:
        # The agent's memory of what it did is not the truth. Do not guess.
        missing = actual - ledgered
        raise IncompleteEffectLedger(
            f"effect ledger for {tool_name} step {step_index} is incomplete: "
            f"tool reports {len(missing)} effect(s) the agent never recorded "
            f"({sorted(missing)}). Refusing to compensate; escalate or let TTL expire."
        )

    for effect_id in sorted(actual - ledger.compensated.get(key, set())):
        tool.undo(effect_id)  # must be idempotent, keyed by effect_id
        ledger.compensated.setdefault(key, set()).add(effect_id)


def speculative_step(ledger: EffectLedger, tool, plan_id: str, step_index: int,
                     tool_name: str, args: dict, remaining_budget_s: int) -> str:
    key = ledger.key(plan_id, step_index, tool_name, args)
    # Guardrail: only speculate if the tool can enumerate effects by prefix,
    # or the effect is TTL-bounded below the remaining budget.
    if not tool.supports_effect_enumeration and tool.ttl_s >= remaining_budget_s:
        raise IncompleteEffectLedger(
            f"refusing speculative call to {tool_name}: no effect enumeration "
            f"and ttl={tool.ttl_s}s >= remaining budget {remaining_budget_s}s; "
            f"un-compensated residue would outlive the workflow."
        )
    effect_id = tool.forward(idempotency_key=key, **args)
    ledger.record_forward(key, effect_id)
    return effect_id
