# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-tool-call-after-optimistic-pre-execution-reveals-a-conflicting-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-tool-call-after-optimistic-pre-execution-reveals-a-conflicting-side-effect.warrant.json
# Markdown SHA-256:   7512bfedfb938a232d4db131f2386b56c06a1df153499464bb6694e04f92d9bd
# Code AST SHA-256:   a79ce193dc12d73be45cadada080b87ec49fff9f206e09e8e8c347e283e0510c
# Verified Classes:   SpeculativeCommitConflict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeCommitConflict(RuntimeError):
    """Raised when a speculative tool call cannot be safely committed.

    Distinguishes clean aborts (no external effect) from aborts that
    leaked an externally observable side effect requiring compensation.
    """
    pass


def commit_speculative_call(call, read_set, committed_version, external_dispatched):
    # 1. Provenance check: reject results computed against rolled-back versions,
    #    even if the value coincidentally matches the committed version.
    for entry in read_set:
        if entry.source_version not in committed_version.committed_ancestors:
            raise SpeculativeCommitConflict(
                f"dirty speculative read: {entry.key} sourced from "
                f"rolled-back version {entry.source_version}"
            )

    # 2. Value revalidation against the committed snapshot.
    for entry in read_set:
        if committed_version.value_of(entry.key) != entry.value:
            if external_dispatched:
                raise SpeculativeCommitConflict(
                    f"write-skew on {entry.key} after external dispatch; "
                    f"compensation required for call {call.id}"
                )
            raise SpeculativeCommitConflict(
                f"write-skew on {entry.key}; safe to abort and re-dispatch "
                f"call {call.id}"
            )

    # 3. Effect-class gate: non-commutative tools must not be externally
    #    dispatched before this point.
    if call.effect_class == "non_commutative" and external_dispatched:
        raise SpeculativeCommitConflict(
            f"non-commutative tool {call.tool} dispatched before validation"
        )

    return call.commit()
