# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-fork-a-speculative-branch-when-its-parent-s-tool-call-log-contains-an-unresolved-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-fork-a-speculative-branch-when-its-parent-s-tool-call-log-contains-an-unresolved-side-effect.warrant.json
# Markdown SHA-256:   7c8e1085da99f6b6851ffb99fe28d47c946c5238c56996d550b1f9225cf019f2
# Code AST SHA-256:   9f49ffc324241ce0d31767bfae021d144687f2a34de5553d73e9f60dbbdfce10
# Verified Classes:   UnfencedSpeculativeFork
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnfencedSpeculativeFork(RuntimeError):
    """Raised when a branch is forked from a parent with unresolved effects
    and no effect fence is bound to the branch's tool wrapper."""
    pass


def fork_branch(parent, checkpoint, branch_id, effect_fence=None):
    pending = [
        e for e in parent.effect_log
        if e.status == "PENDING" and e.emitted_before(checkpoint)
    ]
    if pending and effect_fence is None:
        raise UnfencedSpeculativeFork(
            f"parent {parent.id} has {len(pending)} unresolved effect(s) "
            f"{[e.call_id for e in pending]} at checkpoint {checkpoint}; "
            f"fork of branch {branch_id} requires an effect fence or "
            f"quiescent parent"
        )
    # Key root must be parent-derived so re-issues collapse at the substrate.
    key_root = parent.id
    return Branch(
        id=branch_id,
        context=parent.context.snapshot(checkpoint),
        effect_log=parent.effect_log.snapshot(checkpoint),
        idempotency_root=key_root,
        fence=effect_fence,
    )


def emit(branch, call):
    if branch.fence is not None:
        for ancestor_id in call.causal_preconditions:
            if branch.effect_log.status_of(ancestor_id) == "PENDING":
                raise UnfencedSpeculativeFork(
                    f"branch {branch.id} attempted {call.intent} whose "
                    f"precondition {ancestor_id} is unresolved in inherited log"
                )
    return branch.substrate.dispatch(call, key_root=branch.idempotency_root)
