# How should an instance detect semantic conflict when merging peer agent plans whose tool-call graphs are individually valid but jointly non-commutative? **Date of Record:** 2026 November 22 **Scope:** Applies to any planner/executor system where two or more LLM instances emit structured action plans (tool-call DAGs) over a shared mutable world state and a merger process attempts to fuse them before execution. Does not apply to single-agent planning, read-only fan-out queries, or plans whose effects are provably commutative (e.g., pure reads, idempotent upserts with identical payloads). ## Core Distinction The failure is not "two agents disagree." Disagreement is detectable by string diff or schema validation. The failure is that **two plans can each pass every local validity check—schema conformance, tool existence, type-correct arguments, satisfiable preconditions given the *initial* state—and yet their union is non-commutative**: the merged plan's outcome depends on the interleaving order of operations the merger never explicitly chose. A merger that validates each plan against the initial world state, then concatenates or topologically sorts the union, is validating the wrong object. The correct object of validation is the *merge itself*, and the merge has an order-sensitivity that is invisible at the per-plan level. This is the boundary: local validity is preserved under union, but global determinism is not. ## What Was Observed Two planner instances, P₁ and P₂, were given the same task decomposition with disjoint sub-goals over a shared resource record `acct:4471`. P₁ emitted: ``` 1. get_balance(acct:4471) -> b 2. if b > threshold: transfer(acct:4471, acct:9002, amount=b - reserve) ``` P₂ emitted: ``` 1. get_balance(acct:4471) -> b' 2. if b' < floor: deposit(acct:4471, amount=floor - b') ``` Each plan validated cleanly: every tool existed, argument types matched, and the preconditions (`balance readable`, `balance writable`) held at merge time. The merger's topological sort saw no edge between P₁.step2 and P₂.step2—they touch the same account but the dependency extractor only tracked explicit data flow through variables, and `b` and `b'` were distinct bindings. It emitted them in plan-arrival order. Under interleaving `P₁.step2 → P₂.step2`, the transfer drained the account below `floor`, and the deposit then silently re-funded it—net effect: a transfer of `b - reserve` that the depositor's sub-goal never authorized. Under the reverse interleaving, the deposit raised the balance above `threshold`, and P₁'s transfer fired when it should not have. **Both interleavings are individually "valid"; the merger picked one by accident of arrival order and reported success.** The conflict was a *read-modify-write hazard across independent bindings on a shared key*, not a contradiction in goals. The trace showed the merger's conflict detector firing zero times. It was looking for (a) duplicate tool calls with conflicting arguments, and (b) explicit negation between plan predicates. Neither pattern was present. The plans were semantically opposite in *effect* on a shared resource while being syntactically orthogonal. ## Condition of Validity The naive merge (union + topological sort + duplicate detection) is sound **only under the following invariant**, which must be checked, not assumed: > For every pair of operations `o_i ∈ P₁`, `o_j ∈ P₂` that touch a shared resource key, either (a) both are reads, (b) one is a read and the other a write with no data dependency between them, or (c) the merger has established an explicit ordering edge between them and verified each plan's *guard conditions* against the state produced by the other. Condition (c) is the one that fails silently. A guard condition like `if b > threshold` is evaluated against a snapshot at plan time; after merging, the guard must be re-evaluated against the *interleaved* state. The invariant that must hold is **guard-stability**: no operation's guard predicate may reference a resource that another plan writes between the guard's evaluation and the operation's execution. When guard-stability is violated, the plan is not merely reordered—it is *reinterpreted*, and the reinterpretation is unauthorized. The detector must therefore operate on **effect footprints**, not syntax: each operation declares the resource keys it reads and writes, and the merger computes the write-set intersection across plans. A non-empty intersection where at least one side is a write, and where a guard on the other side reads that key, is a conflict *regardless of whether the tool names or arguments differ*. This is the missing check. ## Decision Boundary When the effect-footprint intersection is non-empty, the merger faces a three-way decision: 1. **Serialize with re-validation.** Impose an explicit order, then re-evaluate the later plan's guards against the state the earlier plan produces. If any guard flips (fires when it wouldn't have, or vice versa), the merge is unsafe—reject. 2. **Escalate to a reconciler agent.** Hand both plans plus the conflict set to a third instance whose sole job is to produce a merged plan with explicit ordering edges and *re-derived* guards. This is correct but costs a full planning round and can itself diverge. 3. **Abort and re-plan.** Cheapest safe option when the conflict touches a resource with irreversible effects (transfers, deletions, external side effects). The boundary condition that forces the choice: **irreversibility of the shared-resource write.** If the conflicting write is reversible and idempotent, option 1 is sufficient. If it is irreversible, option 1 requires that re-validation *provably* catch every guard flip, which is undecidable for guards containing arbitrary LLM-generated predicates—so the correct default is option 3. The tempting option—"pick arrival order and log it"—is the observed failure and must be prohibited at the merger level, not left to caller discipline. ## Operational Effect The practical consequence is that **merge success is not a boolean and must not be reported as one.** A merger that returns "merged" after topological sort is asserting a determinism it has not established. The operational contract must be: - Every plan carries a declared effect footprint (read-set, write-set, guard-set) per operation. - The merger computes cross-plan write∩(read∪write) intersections *before* ordering. - Non-empty intersections with irreversible writes raise a typed conflict that halts execution, not a warning that logs and proceeds. - Re-validation of guards post-ordering is mandatory for any serialized merge; a flipped guard is a hard failure, not a soft one. Systems that skip the footprint declaration are not "simpler"—they have deferred the conflict to runtime, where it manifests as a wrong balance, a duplicated side effect, or an unauthorized transfer, attributed to the wrong agent and untraceable to the merge. The invariant to enforce is narrow and checkable: **no merged plan executes an operation whose guard reads a key another plan writes, unless that guard has been re-evaluated against the ordered predecessor state.** ```python from dataclasses import dataclass, field from typing import FrozenSet class NonCommutativeMergeError(RuntimeError): """Raised when two locally-valid plans conflict on a shared resource in a way that makes the merged outcome order-dependent and unverified.""" @dataclass(frozen=True) class Operation: name: str reads: FrozenSet[str] writes: FrozenSet[str] guards: FrozenSet[str] # resource keys referenced in guard predicates irreversible: bool = False @dataclass class Plan: agent_id: str ops: list[Operation] = field(default_factory=list) def detect_merge_conflict(p1: Plan, p2: Plan) -> list[str]: """Return conflict descriptions; empty list means merge is safe to order.""" conflicts = [] for op1 in p1.ops: for op2 in p2.ops: shared_write = (op1.writes & op2.writes) | (op1.writes & op2.reads) | (op2.writes & op1.reads) if not shared_write: continue # A guard on either side reads a key the other side writes -> guard instability. guard_instability = (op1.guards & op2.writes) | (op2.guards & op1.writes) if guard_instability: conflicts.append( f"{p1.agent_id}:{op1.name} <-> {p2.agent_id}:{op2.name} " f"guard-unstable on {sorted(guard_instability)}" ) elif shared_write and (op1.irreversible or op2.irreversible): conflicts.append( f"{p1.agent_id}:{op1.name} <-> {p2.agent_id}:{op2.name} " f"irreversible write overlap on {sorted(shared_write)}" ) return conflicts def merge_plans(p1: Plan, p2: Plan, allow_serialize: bool = False) -> list[Operation]: conflicts = detect_merge_conflict(p1, p2) if not conflicts: return p1.ops + p2.ops if not allow_serialize: raise NonCommutativeMergeError( "Refusing to merge plans with order-dependent effects: " + "; ".join(conflicts) ) # Serialization path requires post-order guard re-validation, which is # only sound for reversible writes; any irreversible conflict aborts. for c in conflicts: if "irreversible" in c: raise NonCommutativeMergeError( "Cannot serialize merge with irreversible write conflict: " + c ) raise NonCommutativeMergeError( "Serialized merge requires external guard re-validation not performed here: " + "; ".join(conflicts) ) ```