Simulate two-phase commit with a coordinator and 3 participant classes. Implement prepare and commit phases and handle coordinator failure where if it crashes after sending prepare, participants must query each other to decide whether to abort or commit.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Implementing two-phase commit simulation with failure handling
A Python simulation is designed with Coordinator and Participant classes, implementing prepare and commit phases. It handles coordinator failure after sending prepare by having participants query each other’s states to decide safely whether to commit or abort based on peers’ votes.
Here's a self–contained toy simulation of 2‑phase commit with a coordinator and three participants. It models the normal prepare/commit rounds and adds a simple termination protocol the participants run if the coordinator disappears after sending PREPARE:
python
from enum import Enum
class State(Enum):
INIT = "INIT"
READY = "READY" # voted YES and waiting for decision
COMMITTED = "COMMITTED"
ABORTED = "ABORTED"
class Participant:
def __init__(self, name, will_vote_yes=True):
self.name = name
self.state = State.INIT
self.will_vote_yes = will_vote_yes
def on_prepare(self, txid):
"""
Invoked by the coordinator during the prepare phase.
"""
if self.will_vote_yes:
print(f"{self.name}: voting YES for {txid}")
self.state = State.READY
return True
else:
print(f"{self.name}: voting NO for {txid}")
self.state = State.ABORTED
return False
def on_commit(self, txid):
print(f"{self.name}: COMMIT {txid}")
self.state = State.COMMITTED
def on_abort(self, txid):
print(f"{self.name}: ABORT {txid}")
self.state = State.ABORTED
def decide_without_coordinator(self, peers):
"""
Run when we have timed out waiting for the coordinator.
We ask our peers what state they're in.
"""
print(f"{self.name}: timeout waiting for coordinator, querying peers")
peer_states = {p.name: p.state for p in peers}
print(f"{self.name}: peer states: {peer_states}")
# Termination rule:
# - if any peer has already aborted or was never READY -> abort
# - if any peer has committed -> commit
# - if all peers are READY (voted YES) -> we can safely commit
if any(s == State.ABORTED or s == State.INIT for s in peer_states.values()):
self.on_abort("<unknown>")
elif any(s == State.COMMITTED for s in peer_states.values()):
self.on_commit("<unknown>")
elif all(s == State.READY for s in peer_states.values()):
# All voted yes, coordinator could only decide COMMIT
self.on_commit("<unknown>")
def __repr__(self):
return f"<{self.name} state={self.state.value}>"
class Coordinator:
def __init__(self, participants):
self.participants = participants
def two_phase_commit(self, txid, crash_after_prepare=False):
print(f"Coordinator: starting 2PC for {txid}")
# Phase 1: prepare
votes = []
for p in self.participants:
vote = p.on_prepare(txid)
votes.append(vote)
if crash_after_prepare:
# Simulate a crash: do not send the decision
print("Coordinator: *** CRASHED after sending PREPARE! ***")
return
# Phase 2: decide
if all(votes):
print("Coordinator: all YES, sending COMMIT")
for p in self.participants:
p.on_commit(txid)
else:
print("Coordinator: got a NO, sending ABORT")
for p in self.participants:
p.on_abort(txid)
# Demo 1: normal flow
p1, p2, p3 = Participant("P1"), Participant("P2"), Participant("P3")
coord = Coordinator([p1, p2, p3])
coord.two_phase_commit("T1")
print(p1, p2, p3, "\n")
# Demo 2: coordinator crashes after PREPARE, all voted YES
q1, q2, q3 = Participant("Q1"), Participant("Q2"), Participant("Q3")
coord2 = Coordinator([q1, q2, q3])
coord2.two_phase_commit("T2", crash_after_prepare=True)
# participants time out and run termination protocol
for q in (q1, q2, q3):
q.decide_without_coordinator([peer for peer in (q1, q2, q3) if peer is not q])
print(q1, q2, q3, "\n")
# Demo 3: coordinator crashes after PREPARE, one NO vote
r1, r2, r3 = Participant("R1"), Participant("R2", will_vote_yes=False), Participant("R3")
coord3 = Coordinator([r1, r2, r3])
coord3.two_phase_commit("T3", crash_after_prepare=True)
for r in (r1, r2, r3):
r.decide_without_coordinator([peer for peer in (r1, r2, r3) if peer is not r])
print(r1, r2, r3)
Sample output:
code
Coordinator: starting 2PC for T1
P1: voting YES for T1
P2: voting YES for T1
P3: voting YES for T1
Coordinator: all YES, sending COMMIT
P1: COMMIT T1
P2: COMMIT T1
P3: COMMIT T1
<P1 state=COMMITTED> <P2 state=COMMITTED> <P3 state=COMMITTED>
Coordinator: starting 2PC for T2
Q1: voting YES for T2
Q2: voting YES for T2
Q3: voting YES for T2
Coordinator: *** CRASHED after sending PREPARE! ***
Q1: timeout waiting for coordinator, querying peers
Q1: peer states: {'Q2': <State.READY: 'READY'>, 'Q3': <State.READY: 'READY'>}
Q1: COMMIT <unknown>
Q2: timeout waiting for coordinator, querying peers
Q2: peer states: {'Q1': <State.COMMITTED: 'COMMITTED'>, 'Q3': <State.READY: 'READY'>}
Q2: COMMIT <unknown>
Q3: timeout waiting for coordinator, querying peers
Q3: peer states: {'Q1': <State.COMMITTED: 'COMMITTED'>, 'Q2': <State.COMMITTED: 'COMMITTED'>}
Q3: COMMIT <unknown>
<Q1 state=COMMITTED> <Q2 state=COMMITTED> <Q3 state=COMMITTED>
Coordinator: starting 2PC for T3
R1: voting YES for T3
R2: voting NO for T3
R3: voting YES for T3
Coordinator: *** CRASHED after sending PREPARE! ***
R1: timeout waiting for coordinator, querying peers
R1: peer states: {'R2': <State.ABORTED: 'ABORTED'>, 'R3': <State.READY: 'READY'>}
R1: ABORT <unknown>
R2: timeout waiting for coordinator, querying peers
R2: peer states: {'R1': <State.ABORTED: 'ABORTED'>, 'R3': <State.READY: 'READY'>}
R2: ABORT <unknown>
R3: timeout waiting for coordinator, querying peers
R3: peer states: {'R1': <State.ABORTED: 'ABORTED'>, 'R2': <State.ABORTED: 'ABORTED'>}
R3: ABORT <unknown>
<R1 state=ABORTED> <R2 state=ABORTED> <R3 state=ABORTED>
In the crash cases the participants notice the coordinator's failure, exchange their local state, and either all commit (when everyone had voted YES) or abort (when any participant had already aborted).