# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-conflicts-before-they-commit-in-a-concurrent-agent-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-conflicts-before-they-commit-in-a-concurrent-agent-swarm.warrant.json
# Markdown SHA-256:   1d54fc728e613c5b1dccd80e06ea3dd15a958817c6597594f1578bb25bf45814
# Code AST SHA-256:   e970596552e620d1583ec8718ab71b56576a7f3e4578587c77fe5731ed731c84
# Verified Classes:   ReadSetConflict, IncompleteReadSetError, SpeculativeTxn, Store
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class ReadSetConflict(RuntimeError):
    """Raised when a speculative commit's read-set intersects a peer write
    committed within the agent's (base_version, commit_version] window."""


class IncompleteReadSetError(RuntimeError):
    """Raised when a tool's read-set was not captured at transitive-key
    granularity, making read-set validation unsound."""


@dataclass
class SpeculativeTxn:
    agent_id: str
    base_version: int
    read_set: Set[str]
    write_intent: Dict[str, object]
    effects_buffered: bool = True
    read_set_complete: bool = True


@dataclass
class Store:
    version: int = 0
    data: Dict[str, object] = field(default_factory=dict)
    # version -> set of keys written at that version
    write_log: Dict[int, Set[str]] = field(default_factory=dict)

    def commit(self, txn: SpeculativeTxn) -> int:
        if not txn.read_set_complete:
            raise IncompleteReadSetError(
                f"agent {txn.agent_id}: read-set not captured at transitive "
                f"key granularity; read-set validation is unsound"
            )
        if not txn.effects_buffered:
            raise ReadSetConflict(
                f"agent {txn.agent_id}: speculative effects already emitted; "
                f"cannot abort safely on read-set conflict"
            )

        # Validate read-set UNION write-intent against every write committed
        # in (base_version, current_version]. Write-set-only diff is insufficient.
        touched = txn.read_set | set(txn.write_intent.keys())
        for v in range(txn.base_version + 1, self.version + 1):
            peer_writes = self.write_log.get(v, set())
            overlap = touched & peer_writes
            if overlap:
                raise ReadSetConflict(
                    f"agent {txn.agent_id}: read-set/write-intent {sorted(overlap)} "
                    f"intersects peer write at version {v} "
                    f"(base={txn.base_version}, commit={self.version}); "
                    f"aborting speculative commit to preserve premise consistency"
                )

        self.version += 1
        for k, val in txn.write_intent.items():
            self.data[k] = val
        self.write_log[self.version] = set(txn.write_intent.keys())
        return self.version


def reconcile_inventory(store: Store, agent_id: str,
                        snapshot_version: int) -> SpeculativeTxn:
    # Speculative read: plan derived from on_hand and pending_count.
    on_hand = store.data["on_hand"]
    pending = store.data["pending_count"]
    # Read-set MUST include both keys the plan depended on, not just the
    # entity being written.
    return SpeculativeTxn(
        agent_id=agent_id,
        base_version=snapshot_version,
        read_set={"on_hand", "pending_count"},
        write_intent={"on_hand": on_hand - pending},
        effects_buffered=True,
        read_set_complete=True,
    )


if __name__ == "__main__":
    s = Store()
    s.data = {"on_hand": 100, "pending_count": 3}
    s.version = 41
    txn = reconcile_inventory(s, "executor", snapshot_version=41)

    # Peer planner commits a write to a key the executor READ but did not WRITE.
    s.version += 1
    s.data["pending_count"] = 5
    s.write_log[s.version] = {"pending_count"}

    try:
        s.commit(txn)
    except ReadSetConflict as e:
        print(f"BLOCKED: {e}")
        # Correct recovery: re-read at commit version and re-derive.
        txn = reconcile_inventory(s, "executor", snapshot_version=s.version)
        s.commit(txn)
        assert s.data["on_hand"] == 95, s.data["on_hand"]
        print(f"re-derived on_hand={s.data['on_hand']} (correct)")
