# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-tool-call-sandboxing-when-replay-determinism-cannot-be-reconstructed-from-the-audit-log.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-tool-call-sandboxing-when-replay-determinism-cannot-be-reconstructed-from-the-audit-log.warrant.json
# Markdown SHA-256:   f9e30f04404bd3985e9e4a9939d88bf3e36591d7d488a6b55fc18d61393bd915
# Code AST SHA-256:   75773aa6fbbafd16e6402cdba397f5dbf82d6d0fb7cd638467996149a2cdb1d0
# Verified Classes:   UnverifiableSpeculativeBranch, ToolCall, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnverifiableSpeculativeBranch(RuntimeError):
    """Raised when a speculative branch cannot be certified by deterministic replay."""
    pass


class ToolCall:
    def __init__(self, tool_name, args, returned_value, resource_version=None, input_snapshot=None):
        self.tool_name = tool_name
        self.args = args
        self.returned_value = returned_value
        self.resource_version = resource_version
        self.input_snapshot = input_snapshot

    def reads_mutable_state(self):
        # Tools that read external mutable resources must declare it.
        return self.tool_name in {"fetch_account_balance", "read_ledger", "get_peer_state"}


class SpeculativeBranch:
    def __init__(self, branch_id, tool_calls, siblings=None, replay_mode="RECOMPUTE"):
        self.branch_id = branch_id
        self.tool_calls = tool_calls
        self.siblings = siblings or []
        self.replay_mode = replay_mode

    def shares_read_dependency(self, other):
        mine = {c.tool_name for c in self.tool_calls if c.reads_mutable_state()}
        theirs = {c.tool_name for c in other.tool_calls if c.reads_mutable_state()}
        return bool(mine & theirs)

    def input_snapshots_disjoint(self, other):
        my_versions = {c.resource_version for c in self.tool_calls if c.resource_version}
        their_versions = {c.resource_version for c in other.tool_calls if c.resource_version}
        return not (my_versions & their_versions)


def certify_branch_for_audit(branch):
    """Return True only if the branch is a faithful audit artifact."""
    # Condition 1: input completeness.
    for call in branch.tool_calls:
        if call.reads_mutable_state():
            if call.resource_version is None and call.input_snapshot is None:
                raise UnverifiableSpeculativeBranch(
                    f"branch {branch.branch_id}: tool {call.tool_name} reads mutable "
                    f"state but transcript lacks resource_version/input_snapshot; "
                    f"replay cannot force a unique reconstruction"
                )

    # Condition 2: replay by recomputation, never short-circuit.
    if branch.replay_mode != "RECOMPUTE":
        raise UnverifiableSpeculativeBranch(
            f"branch {branch.branch_id}: replay_mode={branch.replay_mode}; "
            f"short-circuit replay is tautological and cannot certify faithfulness"
        )

    # Condition 3: correlated siblings sharing a mutable read dependency.
    for sibling in branch.siblings:
        if branch.shares_read_dependency(sibling) and not branch.input_snapshots_disjoint(sibling):
            raise UnverifiableSpeculativeBranch(
                f"branch {branch.branch_id} shares a mutable read dependency with "
                f"sibling {sibling.branch_id} and input snapshots overlap; "
                f"cross-branch agreement is not evidence of faithfulness"
            )

    return True


def commit_or_hold(branch, downstream_commit_fn):
    try:
        certify_branch_for_audit(branch)
    except UnverifiableSpeculativeBranch:
        # Demote to advisory hint; hold downstream state for canonical re-validation.
        return {"status": "PENDING_CANONICAL", "branch_id": branch.branch_id}
    return downstream_commit_fn(branch)
