TASK
Implementation
Implement 2PC: Phase 1 sends PREPARE, collects votes. Phase 2 sends COMMIT if all YES, else ABORT.
Sample Test Cases
All participants vote yesTimeout: 5000ms
Input
{
"src": "c0",
"dest": "n1",
"body": {
"type": "init",
"msg_id": 1,
"node_id": "n1",
"node_ids": [
"n1"
]
}
}Expected Output
{"src":"n1","dest":"c0","body":{"type":"init_ok","in_reply_to":1,"msg_id":0}}Hints
Hint 1▾
Phase 1: Prepare - ask all participants
Hint 2▾
Phase 2: Commit/Abort based on votes
Hint 3▾
Log decisions for recovery
OVERVIEW
Theoretical Hub
Two-Phase Commit
2PC ensures all-or-nothing across nodes. The blocking problem: if coordinator crashes after PREPARE, participants are stuck.
Key Concepts
2PCatomic commitprepare-commit
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python3
class Coordinator:
def __init__(self, participants):
self.participants = participants
self.tx_log = {}
def prepare(self, tx_id, operations):
votes = [p.prepare(tx_id, operations.get(p.id, [])) for p in self.
participants]
return votes
def commit_or_abort(self, tx_id, votes):
# TODO: If all YES, commit; else abort
pass
class Participant:
def __init__(self, id):
self.id = id
self.state = {}
self.locks = {}
def prepare(self, tx_id, ops):
# TODO: Lock resources, vote YES or NO
pass
def commit(self, tx_id):
# TODO: Apply changes, release locks
pass