# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-bind-its-audit-trail-to-a-delegated-warrant-before-replaying-a-federated-transaction.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-bind-its-audit-trail-to-a-delegated-warrant-before-replaying-a-federated-transaction.warrant.json
# Markdown SHA-256:   06fdeaaad19de0b89b6d2d12bf41a1ed559152073e6e50d93e198d61f903f3c4
# Code AST SHA-256:   8da6d8c2a0b257e6f55d8dce38403a235b0c1d4e4b9b691d07194e7801262842
# Verified Classes:   WarrantAuditDecouplingError, Warrant, AuditEntry
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantAuditDecouplingError(RuntimeError):
    """Raised when a replay cannot bind an audit log to exactly one live warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    tx_id: str
    grantee: str
    scope: frozenset
    signature_digest: str
    committed_root: str
    revoked: bool


@dataclass(frozen=True)
class AuditEntry:
    warrant_id: str
    step: int
    tool: str
    args_digest: str
    prev_link: str
    link: str


def resolve_single_warrant(warrants: list[Warrant], tx_id: str) -> Warrant:
    live = [w for w in warrants if w.tx_id == tx_id and not w.revoked]
    if len(live) == 0:
        raise WarrantAuditDecouplingError(
            f"no live warrant for tx_id={tx_id!r}; replay has no anchor"
        )
    if len(live) > 1:
        # Identifier equality is NOT uniqueness. Two live warrants for one tx_id
        # means the issuance path lacks revocation-by-signature.
        raise WarrantAuditDecouplingError(
            f"ambiguous warrant set for tx_id={tx_id!r}: "
            f"{[w.signature_digest for w in live]} — refuse, do not pick latest"
        )
    return live[0]


def recompute_chain_root(entries: list[AuditEntry], warrant: Warrant) -> str:
    if not entries:
        raise WarrantAuditDecouplingError("empty audit log cannot attest to a warrant")
    if any(e.warrant_id != warrant.warrant_id for e in entries):
        # A log carrying entries from a foreign warrant cannot be re-parented.
        raise WarrantAuditDecouplingError(
            "audit log contains entries bound to a different warrant_id"
        )
    ordered = sorted(entries, key=lambda e: e.step)
    expected_prev = warrant.signature_digest
    for e in ordered:
        if e.prev_link != expected_prev:
            raise WarrantAuditDecouplingError(
                f"chain break at step {e.step}: prev_link mismatch"
            )
        expected_prev = e.link
    return expected_prev


def replay_transaction(
    warrants: list[Warrant],
    entries: list[AuditEntry],
    dedup_drops: int,
    tx_id: str,
) -> bool:
    if dedup_drops != 0:
        # Silent dedup on (warrant_id, step) is indistinguishable from tampering.
        raise WarrantAuditDecouplingError(
            f"audit store dropped {dedup_drops} entries during replay window"
        )
    warrant = resolve_single_warrant(warrants, tx_id)
    head = recompute_chain_root(entries, warrant)
    if head != warrant.committed_root:
        raise WarrantAuditDecouplingError(
            "recomputed chain root does not match issuer commitment; "
            "steps were added, dropped, or reordered after issuance"
        )
    for e in entries:
        if e.tool not in warrant.scope:
            raise WarrantAuditDecouplingError(
                f"step {e.step} tool {e.tool!r} outside warrant scope"
            )
    return True
