# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-speculative-tool-call-divergence-before-commit-in-an-optimistic-concurrency-agent-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-speculative-tool-call-divergence-before-commit-in-an-optimistic-concurrency-agent-swarm.warrant.json
# Markdown SHA-256:   d6b33a9eb24ee134aae5fc38df347a8956158719f9906c22ed9443e49c75805b
# Code AST SHA-256:   32d9670319fe7cb1ce14f009c430bc189d3d4d0c8f971010facd6957af919fce
# Verified Classes:   SpeculativeDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeDivergenceError(RuntimeError):
    """Raised when a derived artifact's read-set depends on a speculative
    branch that did not commit before the artifact, making version-guarded
    commit unsound."""
    pass


def commit_artifact(artifact, durable_state, committed_branches):
    """
    artifact: {
        'id': str,
        'read_set': {key: {'observed_value': Any, 'version': int,
                           'speculative_branch': str | None}},
        'derived_from_branch': str | None,
    }
    durable_state: {key: current_value}
    committed_branches: set[str] of branch IDs that have durably committed
    """
    for key, read in artifact['read_set'].items():
        branch = read['speculative_branch']
        if branch is not None and branch not in committed_branches:
            # The premise this artifact was derived from was never made durable.
            raise SpeculativeDivergenceError(
                f"artifact {artifact['id']} read {key!r} from speculative "
                f"branch {branch!r} which did not commit; version guard on "
                f"v{read['version']} is unsound because the observed value "
                f"{read['observed_value']!r} reflects an uncommitted sibling "
                f"effect. Abort and recompute from durable state."
            )
        if durable_state.get(key) != read['observed_value']:
            raise SpeculativeDivergenceError(
                f"artifact {artifact['id']} observed {key!r}="
                f"{read['observed_value']!r} but durable value is "
                f"{durable_state.get(key)!r}; read-set drifted despite "
                f"version match. Recompute required."
            )
    return apply(artifact, durable_state)


def apply(artifact, durable_state):
    # durable write path (omitted); returns new state
    return durable_state
