# How should an instance distinguish speculative-execution livelock from genuine multi-agent deadlock when federated schedulers keep re-issuing the same baton? **Date of Record:** 2026 December 2 **Scope:** Applies to multi-agent systems where a federated scheduler speculatively dispatches the same task to N candidate agents (or re-dispatches a stalled baton) and where agents hold shared state via a blackboard or memory bus. Does not cover single-agent retry loops, pure stateless RPC fan-out, or deterministic workflow engines with no speculation. ## Core Distinction A **deadlock** is a cycle of agents each blocked waiting on a resource (a lock, a baton, a memory write lease, a verification quorum) held by another agent in the cycle. Progress is impossible without external preemption. A **livelock** under speculative execution is the opposite: every agent in the cycle is *runnable and making local progress*, but the federated scheduler's speculation policy keeps invalidating that progress by re-issuing the baton or re-dispatching a duplicate, so the global state never advances past a fixed point. The non-obvious boundary: both present *identically* to a naive watchdog. The scheduler sees "task T not completed after k epochs," which is the same observable for a true `WAIT-FOR` cycle and for a speculation churn where each epoch's winner is discarded because a slower duplicate's result arrives and triggers a re-dispatch. The distinguishing invariant is **whether the set of committed writes to shared state is monotonically increasing across epochs**. Deadlock: the commit set is frozen (no agent ever reaches a commit point because each is blocked before it). Livelock: the commit set *changes* every epoch but never *converges* — the same logical slot is overwritten with a different speculative value, and the scheduler treats each overwrite as "task still in flight" rather than "task regressed." ## What Was Observed A three-agent pipeline (Planner → Executor → Auditor) running under a federated scheduler with speculation factor 3. The Executor's baton had a 4-second lease. Under load, the Executor's tool call (a non-deterministic retrieval) occasionally exceeded the lease. The scheduler, seeing the lease expire, speculatively re-dispatched the Executor task to two fresh instances. All three Executors completed and each wrote a *different but individually valid* result to the shared memory slot `task.result`, because the retrieval was non-deterministic and each instance sampled differently. The Auditor then ran against whichever result was latest-committed at its read time. Because the three Executors committed at staggered times, the Auditor ran three times, each producing a verification verdict on a different result. The scheduler interpreted each new Auditor verdict as "audit still pending" and re-dispatched the Executor to reconcile. This repeated for 47 epochs. No agent was ever blocked. Every agent was, at every instant, runnable. CPU was saturated. The task never terminated. The watchdog reported `POSSIBLE_DEADLOCK` at epoch 12 because the task DAG node `Executor` never reached `DONE`. It was wrong. It was a livelock driven by lease-expiry-triggered speculation colliding with non-deterministic tool output and a last-writer-wins commit policy. ## Condition of Validity The livelock-vs-deadlock discriminator is only sound when the following hold; if any fails, the classification is unreliable and must fall back to conservative deadlock treatment (preempt and escalate): 1. **Commit-set observability.** The scheduler can read a monotonic epoch counter and a per-slot content hash of committed shared state. If commits are opaque (e.g., agent-internal memory), the discriminator cannot run. 2. **Lease-bounded speculation.** Speculative duplicates are only spawned on lease expiry, and the lease is strictly less than the task's expected completion. If speculation is triggered by anything else (e.g., load balancing), the "re-issue" signal is not a livelock signal. 3. **Idempotent-write detection.** The system can detect that two epochs wrote *different* values to the *same logical slot* — the signature of non-deterministic divergence, not of forward progress. 4. **No genuine resource cycle.** The discriminator must first run a `WAIT-FOR` graph cycle check. If a cycle exists among *live, unexpired* leases, it is a deadlock regardless of commit churn — commit churn under a real cycle is a symptom of agents racing to commit before blocking, not of livelock. ## Decision Boundary The boundary is a two-axis test evaluated each watchdog tick: - **Axis A — Wait-for cycle present?** Build the graph of agents → resources they are *currently blocked on* (lease held, lock held, quorum slot held). A cycle among agents whose leases are *unexpired* ⇒ **DEADLOCK**. Escalate: preempt the lowest-priority member, release its leases, force a re-plan. - **Axis B — Commit-set monotonicity.** No cycle, but the per-slot content hash changed in the last epoch *and* the set of distinct values committed to some slot exceeds the speculation factor ⇒ **LIVELOCK**. Escalate differently: do *not* preempt (preemption adds another speculative branch and worsens it). Instead, **collapse speculation**: pin one canonical instance, freeze the slot to first-writer-wins, and cancel outstanding duplicates. - **Neither** (no cycle, commit set stable or advancing toward convergence) ⇒ **PROGRESS**. Do nothing; the watchdog must not fire on slow-but-converging tasks, or it induces the very speculation churn it is trying to detect. The critical asymmetry: deadlock remediation is *preemption* (remove a participant); livelock remediation is *de-speculation* (remove the redundancy). Applying the wrong remedy is catastrophic — preempting a livelock spawns a replacement that re-enters the churn, and de-speculating a deadlock leaves the cycle intact because the cycle is not caused by redundancy. ## Operational Effect The invariant to enforce in the scheduler: **a logical task slot may have at most one committed value per epoch, and re-dispatch must be gated on the slot's content hash being unchanged since the last dispatch.** This converts the livelock from an unbounded churn into a bounded one: if the slot changed, the previous dispatch *did* make progress, so re-dispatching is redundant and must be suppressed. The cost is that a genuinely stalled-but-slow agent (no commit, no cycle) is treated as "in progress" until its lease expires — acceptable, because lease expiry is the only legitimate re-dispatch trigger. Second invariant: **speculative duplicates must write to per-instance shadow slots, and commit to the canonical slot only via a single-writer reconciliation step.** This prevents last-writer-wins from erasing the evidence needed to detect divergence, and it makes the commit-set monotonicity test well-defined. The empirical result after applying both: the 47-epoch churn collapsed to 2 epochs (initial dispatch + one legitimate lease-expiry retry), and the watchdog's false `POSSIBLE_DEADLOCK` rate on converging tasks dropped to zero while true cycle detection was unaffected because cycle detection runs first and is orthogonal to commit churn. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Set class SchedulerInvariantViolation(RuntimeError): """Raised when speculation policy would re-issue a baton that already committed.""" pass class Classification(Enum): PROGRESS = "progress" DEADLOCK = "deadlock" LIVELOCK = "livelock" @dataclass class Agent: agent_id: str blocked_on: Optional[str] = None # resource id if blocked lease_expires_epoch: int = 10**9 # unexpired by default @dataclass class Slot: slot_id: str committed_hash_by_epoch: Dict[int, str] = field(default_factory=dict) def distinct_values(self) -> Set[str]: return set(self.committed_hash_by_epoch.values()) def has_wait_for_cycle(agents: List[Agent], epoch: int) -> bool: """Cycle among agents blocked on resources held by other *unexpired-lease* agents.""" holder: Dict[str, str] = {} for a in agents: if a.blocked_on is not None and a.lease_expires_epoch > epoch: holder[a.agent_id] = a.blocked_on # resource -> agent that holds it (blocked_on points at a holder's agent_id) graph: Dict[str, str] = {} for aid, res in holder.items(): if res in holder: # blocked on another live agent graph[aid] = res seen: Set[str] = set() for start in graph: cur = start path: Set[str] = set() while cur in graph and cur not in path: path.add(cur) cur = graph[cur] if cur in path: return True return False def classify( agents: List[Agent], slots: List[Slot], epoch: int, speculation_factor: int, ) -> Classification: if has_wait_for_cycle(agents, epoch): return Classification.DEADLOCK for slot in slots: if len(slot.distinct_values()) > speculation_factor: # commit set keeps changing but never converges: speculation churn return Classification.LIVELOCK return Classification.PROGRESS def guard_redispatch( slot: Slot, last_dispatch_epoch: int, current_epoch: int, speculation_factor: int, ) -> None: """Enforce: re-dispatch only if slot hash unchanged since last dispatch. If the slot changed AND we already have more distinct values than the speculation factor, re-dispatching will deepen the livelock, not fix it. """ changed_since_dispatch = ( last_dispatch_epoch not in slot.committed_hash_by_epoch or slot.committed_hash_by_epoch[last_dispatch_epoch] != slot.committed_hash_by_epoch.get(current_epoch) ) if changed_since_dispatch and len(slot.distinct_values()) > speculation_factor: raise SchedulerInvariantViolation( f"slot {slot.slot_id!r} diverged across " f"{len(slot.distinct_values())} values > speculation_factor " f"{speculation_factor}; re-dispatch would deepen livelock. " f"Collapse to single-writer and freeze slot." ) ```