# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-execution-when-idempotency-keys-outlive-compensating-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-execution-when-idempotency-keys-outlive-compensating-rollback.warrant.json
# Markdown SHA-256:   147306f0e89a9e98c88cf079a9c343d570c5a0f173bec5dd4a8c7f9b8fbcb5c8
# Code AST SHA-256:   e03cbd26e941be9d56e29f1fa961be56dc1350b38565e6445cfe785ec4088548
# Verified Classes:   SpeculativeReplayAfterCompensation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeReplayAfterCompensation(RuntimeError):
    """Raised when a cached idempotent success is observed for a transaction
    that has already been compensated. The effect is dead; the plan segment
    must not advance."""
    pass


def interpret_speculative_response(
    response: dict,
    compensation_ledger: dict[str, str],  # txn_id -> compensation_key
    request_key: str,
) -> str:
    """
    Classify a tool response on a speculative path.

    Returns 'executed' or 'replayed_live'.
    Raises if the response is a replay of a compensated transaction.
    """
    if response.get("status") != 200:
        raise SpeculativeReplayAfterCompensation(
            f"non-200 on speculative call key={request_key}: {response}"
        )

    txn_id = response.get("transaction_id")
    if txn_id is None:
        raise SpeculativeReplayAfterCompensation(
            f"200 without transaction_id on key={request_key}; "
            f"cannot establish liveness"
        )

    replayed = response.get("idempotent_replay", False) or response.get(
        "cached", False
    )

    if txn_id in compensation_ledger:
        # The effect was reversed under a different key. A 200 here is a
        # cached claim about a dead execution. Do not advance.
        raise SpeculativeReplayAfterCompensation(
            f"cached success for txn={txn_id} key={request_key} is stale: "
            f"compensated by {compensation_ledger[txn_id]}. "
            f"Re-enter branch with a fresh key."
        )

    if replayed:
        # Replay of a non-compensated txn: effect is still live, but the
        # caller must know it did not execute now.
        return "replayed_live"

    return "executed"


def advance_plan_segment(
    response: dict,
    compensation_ledger: dict[str, str],
    request_key: str,
) -> None:
    verdict = interpret_speculative_response(
        response, compensation_ledger, request_key
    )
    if verdict not in ("executed", "replayed_live"):
        # Defensive: interpret_speculative_response should have raised.
        raise SpeculativeReplayAfterCompensation(
            f"unexpected verdict {verdict!r} for key={request_key}"
        )
    # ... proceed to next segment only after liveness is established ...
