# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branches-when-optimistic-multi-agent-rollback-produces-non-commuting-reconciliation-conflicts.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branches-when-optimistic-multi-agent-rollback-produces-non-commuting-reconciliation-conflicts.warrant.json
# Markdown SHA-256:   34b4195304165b56c50bd6ad98dbe7253e9b965dc3c923ec2e798f831647738e
# Code AST SHA-256:   82caa7fac5220e30d78f65a847913564e57e7f932b58844b057425d367573707
# Verified Classes:   NonCommutingSpeculativeMerge
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class NonCommutingSpeculativeMerge(RuntimeError):
    """Raised when a speculative branch set cannot be merged under any
    serialization order without changing the committed result."""
    pass


def reconcile(branches, snapshot):
    """
    branches: list of dicts {id, patch, reads, guards}
      patch:  {key: ("abs", value) | ("delta", value)}
      reads:  frozenset of keys read from snapshot
      guards: list of (key, predicate) evaluated pre-merge
    snapshot: pre-branch state S0

    Returns committed state, or raises NonCommutingSpeculativeMerge.
    """
    committed = dict(snapshot)
    committed_ids = []

    def writes(b):
        return set(b["patch"].keys())

    for b in branches:
        for prev in branches:
            if prev["id"] in committed_ids:
                continue
            # stale-read absolute clobber: both write same key absolutely,
            # both read it from S0, neither sees the other.
            shared = writes(b) & writes(prev)
            for k in shared:
                b_abs = b["patch"][k][0] == "abs"
                p_abs = prev["patch"][k][0] == "abs"
                if b_abs and p_abs and k in b["reads"] and k in prev["reads"]:
                    raise NonCommutingSpeculativeMerge(
                        f"stale-read clobber on {k!r}: {b['id']} and "
                        f"{prev['id']} both wrote absolute values read from S0"
                    )
            # TOCTOU: b's guard reads a key prev writes, evaluated pre-merge
            for (gkey, _pred) in b["guards"]:
                if gkey in writes(prev) and gkey not in committed_ids:
                    raise NonCommutingSpeculativeMerge(
                        f"TOCTOU guard on {gkey!r}: {b['id']} validated "
                        f"against S0 but {prev['id']} mutates it in-window"
                    )

        # apply only after passing commutativity/serialization checks
        for k, (kind, v) in b["patch"].items():
            if kind == "delta":
                committed[k] = committed.get(k, 0) + v
            else:
                committed[k] = v
        committed_ids.append(b["id"])

    return committed


def safe_commit(branches, snapshot):
    try:
        return reconcile(branches, snapshot)
    except NonCommutingSpeculativeMerge:
        # set-level failure: roll back whole window, re-dispatch serially
        raise NonCommutingSpeculativeMerge(
            "aborting speculative set; re-dispatch serially against refreshed S0"
        )
