# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-branch-state-after-speculative-multi-agent-rollback-without-corrupting-the-causal-commit-log.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-branch-state-after-speculative-multi-agent-rollback-without-corrupting-the-causal-commit-log.warrant.json
# Markdown SHA-256:   277943f3f9e0e6a200aa8d5d1d68805a9f7a28a23515745e896922f0b8060145
# Code AST SHA-256:   75ee797d0a8be5801c37cc2c40a21f6bf0478252efe4d8f83c259d650859b77c
# Verified Classes:   DanglingCausalEdgeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DanglingCausalEdgeError(RuntimeError):
    """Raised when a speculative branch commits against a parent commit
    that is not reachable in the reconciled history."""
    pass


def validate_branch_commit(branch, reconciled_log, substrate):
    """Validate a speculative branch's intent edges against reachability
    in the final reconciled history, not mere existence at commit time.

    Returns True if the branch may commit. Raises DanglingCausalEdgeError
    if any recorded parent is unreachable (rolled back but still present
    in the substrate's retained-commit set).
    """
    for parent_id in branch.intent_edges:
        if not reconciled_log.contains(parent_id):
            # Parent was never committed at all -> ordinary invalid branch.
            raise DanglingCausalEdgeError(
                f"branch {branch.id} references unknown parent {parent_id}"
            )
        if not reconciled_log.is_reachable(parent_id):
            # Parent exists in the substrate (rolled back, not yet GC'd)
            # but is NOT in the reconciled history. This is the boundary
            # failure: value-equality validation would pass here.
            raise DanglingCausalEdgeError(
                f"branch {branch.id} commits against rolled-back parent "
                f"{parent_id}; reachability check failed"
            )
    # Also verify read-dependencies produced by other speculative branches
    # are still reachable, since their effects may have been reverted.
    for read_dep in branch.read_dependencies:
        producing_commit = substrate.producing_commit(read_dep.key, read_dep.version)
        if producing_commit is not None and not reconciled_log.is_reachable(
            producing_commit
        ):
            raise DanglingCausalEdgeError(
                f"branch {branch.id} read {read_dep.key}@{read_dep.version} "
                f"produced by unreachable commit {producing_commit}; "
                f"abort and re-dispatch from base"
            )
    return True


def reconcile(branch, reconciled_log, substrate):
    if not validate_branch_commit(branch, reconciled_log, substrate):
        # Unreachable given the raise above, but kept explicit for callers
        # that catch and continue.
        raise DanglingCausalEdgeError(f"branch {branch.id} failed reconciliation")
    return reconciled_log.append(branch)
