# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-leakage-when-compensation-rollback-collides-with-idempotency-key-reuse-across-a-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-leakage-when-compensation-rollback-collides-with-idempotency-key-reuse-across-a-handoff.warrant.json
# Markdown SHA-256:   57e949d4eb526042cdcb97983b87851b1916464e40c2bb7faaba5a2a1eae507c
# Code AST SHA-256:   c42421fa6f72620605ad6a0327dd2ceb02ebd0860eeee2b574bcc414e16e31b9
# Verified Classes:   CompensationKeyLineageError, LedgerTerminalStateConflict
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CompensationKeyLineageError(RuntimeError):
    """Raised when a compensation cannot be tied to the original speculation key."""


class LedgerTerminalStateConflict(RuntimeError):
    """Raised when a key receives a second terminal write (race between abort and retry)."""


TERMINAL_STATES = {"committed", "rolled_back"}


def apply_compensation(
    ledger: dict,
    original_key: str,
    compensation_key: str,
    remote_txn_log: dict,
) -> None:
    entry = ledger.get(original_key)
    if entry is None:
        raise CompensationKeyLineageError(
            f"no ledger entry for original key {original_key!r}; "
            f"cannot verify compensation lineage"
        )

    # Lineage gate: compensation must be keyed to the original, or a
    # documented transform the remote also implements. A fresh key is invalid.
    if compensation_key != original_key and not compensation_key.startswith(f"{original_key}::"):
        raise CompensationKeyLineageError(
            f"compensation key {compensation_key!r} is not derived from "
            f"original key {original_key!r}; amount-matching fallback is forbidden"
        )

    # Single-valued terminal state: reject a second terminal write.
    if entry.get("status") in TERMINAL_STATES and entry["status"] != "rolled_back":
        raise LedgerTerminalStateConflict(
            f"key {original_key!r} already terminal as {entry['status']!r}; "
            f"refusing to overwrite with 'rolled_back'"
        )

    # Reconciliation gate: the remote must show the transaction as reversed.
    remote = remote_txn_log.get(original_key)
    if remote is None:
        raise CompensationKeyLineageError(
            f"remote log has no record for {original_key!r}; "
            f"compensation would act on an unknown side effect"
        )
    if remote.get("state") != "reversed":
        raise CompensationKeyLineageError(
            f"remote still shows {original_key!r} as {remote.get('state')!r}; "
            f"compensation did not take effect on the original key"
        )

    entry["status"] = "rolled_back"
    entry["compensation_key"] = compensation_key
