# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-freeze-its-speculative-commit-frontier-when-a-rollback-target-s-tool-result-hash-collides-across-divergent-speculat.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-freeze-its-speculative-commit-frontier-when-a-rollback-target-s-tool-result-hash-collides-across-divergent-speculat.warrant.json
# Markdown SHA-256:   9b0f399a37bcc88ee9129eec5beefc4c04bec24caf7ea55464fdb490e6debfdd
# Code AST SHA-256:   4e70203a09d02d18ebde9f9c570c900d4ac2f7c63e551df295ea57b031693688
# Verified Classes:   FrontierCollisionError, Branch, Frontier
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class FrontierCollisionError(RuntimeError):
    """Raised when a speculative frontier would advance on a hash match
    that is not backed by effect-log agreement for a non-injective tool."""
    pass


@dataclass
class Branch:
    branch_id: str
    result_hash: str
    effect_log: tuple = field(default_factory=tuple)


@dataclass
class Frontier:
    step: int
    lca_hash: str
    committed: bool = False


NON_INJECTIVE_TOOLS = {"read_config", "mutate_config", "list_keys", "validate"}


def advance_frontier(frontier: Frontier, branches: list[Branch], tool: str) -> Frontier:
    hashes = {b.result_hash for b in branches}
    if len(hashes) > 1:
        # genuine divergence: rollback to LCA is safe
        return Frontier(step=frontier.step, lca_hash=frontier.lca_hash, committed=False)

    if tool in NON_INJECTIVE_TOOLS:
        effect_logs = {b.effect_log for b in branches}
        if len(effect_logs) > 1:
            # hash agrees but effect logs disagree -> collision case
            raise FrontierCollisionError(
                f"frontier step {frontier.step} on non-injective tool '{tool}': "
                f"result hash {next(iter(hashes))} matches across branches "
                f"{[b.branch_id for b in branches]} but effect logs diverge; "
                f"quarantine and re-execute serially from LCA {frontier.lca_hash}"
            )

    return Frontier(step=frontier.step + 1, lca_hash=next(iter(hashes)), committed=True)
