# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-reconcile-a-speculative-commit-fork-when-optimistic-multi-agent-execution-outruns-byzantine-commit-ordering.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-reconcile-a-speculative-commit-fork-when-optimistic-multi-agent-execution-outruns-byzantine-commit-ordering.warrant.json
# Markdown SHA-256:   5169b560ac809b2ddda509cb2bb282a8fa661039420eee6c2ef6a3be7b1b18b2
# Code AST SHA-256:   a7be08c8dcb9a887ec450484b71dd5e4c7a9a6296dec2217d679e9370e1dc56a
# Verified Classes:   SpeculativeForkError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeForkError(RuntimeError):
    """Raised when a commit's parent edge references an unfinalized or absent hash."""
    pass


def validate_commit(commit, finalized_nodes, provisional_ok=False):
    """
    Enforce causal-finality: every parent edge must reference a finalized node
    unless the commit is explicitly provisional.
    """
    for parent_hash in commit.parent_hashes:
        if parent_hash not in finalized_nodes:
            if commit.provisional and provisional_ok:
                # Provisional commits may reference unfinalized parents,
                # but must not contribute to downstream quorums.
                continue
            raise SpeculativeForkError(
                f"Commit {commit.node_id} references parent {parent_hash} "
                f"absent from finalized set; speculative-commit fork detected."
            )
    return True


def reconcile_fork(commit, finalized_nodes, replay_fn):
    """
    Attempt to re-parent a forked commit onto the finalized parent.
    Returns a re-parented commit, or raises if replay diverges.
    """
    missing = [h for h in commit.parent_hashes if h not in finalized_nodes]
    if not missing:
        return commit
    canonical_parent = finalized_nodes[commit.parent_node]
    replayed = replay_fn(commit.node_id, canonical_parent)
    if replayed.output_hash != commit.output_hash:
        raise SpeculativeForkError(
            f"Replay of {commit.node_id} diverged: speculative output "
            f"{commit.output_hash} != replayed {replayed.output_hash}; "
            f"discarding {len(commit.signatures)} signatures."
        )
    return replayed.with_parent(canonical_parent.hash)
