# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-a-speculative-branch-when-its-rollback-journal-diverges-from-the-reconciler-s-authoritative-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-a-speculative-branch-when-its-rollback-journal-diverges-from-the-reconciler-s-authoritative-ledger.warrant.json
# Markdown SHA-256:   2c51eb79dabffac3d3b9c4cbda8e6f046f0c11cabfc90ae8ccaf5515fd60e4a1
# Code AST SHA-256:   e177e128ce168873732dc6a2a3163e06ae0404d84c6beded325c740e5a74f843
# Verified Classes:   JournalLedgerDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class JournalLedgerDivergence(RuntimeError):
    """Raised when a speculative branch's rollback journal cannot be soundly
    reconciled against the authoritative ledger (UNKNOWN or orphaned keys)."""
    pass


TERMINAL = {"ACK", "FAILED", "COMMITTED"}


def authorize_rollback(journal: dict[str, str], ledger: dict[str, str]) -> list[str]:
    """Return the ordered list of compensation keys the branch may replay.

    journal: {idempotency_key: status} as recorded by the branch's proxy.
    ledger:  {idempotency_key: status} as recorded by the reconciler.

    Soundness invariant: every journal key must be present in the ledger with a
    terminal status, and no journal entry may be UNKNOWN. Anything else is a
    divergence and must block rollback rather than compensate.
    """
    unknown = [k for k, s in journal.items() if s not in TERMINAL]
    if unknown:
        raise JournalLedgerDivergence(
            f"unresolved UNKNOWN entries block rollback: {unknown}"
        )

    orphaned = [k for k in journal if k not in ledger]
    if orphaned:
        raise JournalLedgerDivergence(
            f"journal keys absent from ledger (integrity fault): {orphaned}"
        )

    # Only keys the ledger confirms as terminal may be compensated, and the
    # compensation is keyed off the ledger entry, not the journal entry.
    return [k for k in journal if ledger[k] in TERMINAL]
