# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-execution-from-corrupting-cross-org-reconciliation-in-federated-multi-agent-workflows.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-execution-from-corrupting-cross-org-reconciliation-in-federated-multi-agent-workflows.warrant.json
# Markdown SHA-256:   08ab8b999d9c5b1718ccf76b51588810e50262be7ada15539e02cfa996c3f423
# Code AST SHA-256:   74c27c95e54944a12aa59c4f7e9e514dc01a4e1548405de4961c7dcff3776168
# Verified Classes:   SupersededReadTokenError, ReadToken
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SupersededReadTokenError(RuntimeError):
    """Raised when a speculative commit depends on a read token that is retained
    but no longer authoritative at the counterparty's commit epoch."""
    pass


class ReadToken:
    def __init__(self, token_id: str, retained_until_epoch: int, authoritative_through_epoch: int):
        self.token_id = token_id
        self.retained_until_epoch = retained_until_epoch
        self.authoritative_through_epoch = authoritative_through_epoch


def assert_commit_legal(read_tokens, counterparty_commit_epoch: int) -> None:
    """Counterparty-side check, executed inside the durable commit write.
    The speculator's local revalidation is NOT consulted here."""
    for tok in read_tokens:
        if counterparty_commit_epoch > tok.authoritative_through_epoch:
            raise SupersededReadTokenError(
                f"read token {tok.token_id} superseded: commit epoch "
                f"{counterparty_commit_epoch} exceeds authoritative_through_epoch "
                f"{tok.authoritative_through_epoch} (retained_until_epoch="
                f"{tok.retained_until_epoch} grants drain, not commit rights)"
            )


def reconcile_speculative_commit(read_tokens, counterparty_commit_epoch: int) -> str:
    # Byte-identical reads do not license skipping the check.
    assert_commit_legal(read_tokens, counterparty_commit_epoch)
    return "committed"
