# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-detect-that-a-speculative-branch-has-already-been-reconciled-by-a-sibling-before-replaying-its-own-effect-log-and-why-does-the.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-detect-that-a-speculative-branch-has-already-been-reconciled-by-a-sibling-before-replaying-its-own-effect-log-and-why-does-the.warrant.json
# Markdown SHA-256:   067413e7c1dc7f0cd23e276ff0e9c3e79e729525be5d29b993948468ad0c3479
# Code AST SHA-256:   d8fbb1923ba6f745613d4294b62c7abf919267f1cc294720e74eb87fc6469d88
# Verified Classes:   StaleReplayError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleReplayError(RuntimeError):
    """Raised when a branch is replayed after a sibling already reconciled its effects."""
    pass


# Effect idempotency classes: only ABSOLUTE is replay-safe under merge.
MERGE_IDEMPOTENT = {"read", "absolute_write"}
TERMINAL_DISPOSITIONS = {"satisfied-by-merge", "superseded", "inverted-by-sibling"}


def guard_replay(branch, merged_state):
    # 1. Terminal disposition gate: satisfied-by-merge must be in the branch ledger.
    if branch.ledger_disposition in TERMINAL_DISPOSITIONS:
        raise StaleReplayError(
            f"branch {branch.id}: disposition={branch.ledger_disposition} "
            f"is terminal; sibling already reconciled these effects"
        )

    # 2. Idempotency gate: any non-merge-idempotent effect needs a reconciliation token.
    for effect in branch.effect_log:
        if effect.cls not in MERGE_IDEMPOTENT:
            if not effect.reconciliation_token \
               or effect.reconciliation_token not in merged_state.tokens:
                raise StaleReplayError(
                    f"branch {branch.id}: effect {effect.id} class={effect.cls} "
                    f"is not merge-idempotent and lacks a reconciliation token; "
                    f"replay would double-apply or invert a sibling commit"
                )

    # 3. Lineage gate: only now is ancestry decisive.
    if branch.ancestor not in merged_state.committed_checkpoints:
        raise StaleReplayError(
            f"branch {branch.id}: ancestor {branch.ancestor} not committed"
        )
    return True
