# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-pre-executes-a-tool-call-whose-optimistic-concurrency-token-is-invalidated-by-a-concurrent-sibling-agent-b.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-pre-executes-a-tool-call-whose-optimistic-concurrency-token-is-invalidated-by-a-concurrent-sibling-agent-b.warrant.json
# Markdown SHA-256:   f75944fd4b4fc257064ce7c94380546b3bf86ede321bc68a37258702930f717b
# Code AST SHA-256:   d1eebf9d6f9005fe5e0a7babcd0000f2095380483cd8a2ec316c1003d2a8dfa2
# Verified Classes:   StaleSpeculativeDerivation, SpeculativeArtifact, Resource
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleSpeculativeDerivation(RuntimeError):
    """Raised when a speculative artifact is reconciled against a token it was not derived from."""
    pass


@dataclass(frozen=True)
class SpeculativeArtifact:
    delta: dict
    derived_from: str  # the concurrency token read at plan time


@dataclass(frozen=True)
class Resource:
    token: str
    state: dict


def reconcile(
    artifact: SpeculativeArtifact,
    current: Resource,
    *,
    delta_is_commutative: bool = False,
) -> dict:
    """
    Reconcile a speculative artifact against the current committed resource.

    Invariant: a speculative artifact may only be committed against the token it
    was derived from, unless the delta is provably commutative with all
    intervening commits. A 409-on-speculative must NOT be retried with the
    stale delta; it must be discarded and re-planned.
    """
    if artifact.derived_from == current.token:
        merged = dict(current.state)
        merged.update(artifact.delta)
        return merged

    if delta_is_commutative:
        # Safe only when the tool surface exposes the intervening commit log
        # and the delta provably commutes with every intervening write.
        merged = dict(current.state)
        merged.update(artifact.delta)
        return merged

    # Non-commutative delta against an advanced token: the speculative
    # derivation is orphaned. Retrying it here is the lost-update bug.
    raise StaleSpeculativeDerivation(
        f"speculative artifact derived_from={artifact.derived_from!r} "
        f"cannot be committed against current token={current.token!r}; "
        f"delta is non-commutative — discard and re-plan, do not retry"
    )


def commit_speculative(
    artifact: SpeculativeArtifact,
    current: Resource,
    *,
    delta_is_commutative: bool = False,
) -> Resource:
    merged_state = reconcile(
        artifact, current, delta_is_commutative=delta_is_commutative
    )
    # Token advances only on a validated commit.
    next_token = f"v{int(current.token.lstrip('v')) + 1}"
    return Resource(token=next_token, state=merged_state)
