TASK
Implementation
Implement an apply channel that feeds committed log entries to the state machine. The state machine is a simple key-value store that processes Put, Get, and Delete commands.
Request: {"type": "apply_entries", "msg_id": 1, "entries": [
{"index": 1, "term": 1, "command": {"op": "put", "key": "x", "value": "1"}},
{"index": 2, "term": 1, "command": {"op": "put", "key": "y", "value": "2"}},
{"index": 3, "term": 1, "command": {"op": "get", "key": "x"}}
]}
Response: {"type": "apply_entries_ok", "in_reply_to": 1, "results": [
{"index": 1, "result": "ok"},
{"index": 2, "result": "ok"},
{"index": 3, "result": "1"}
], "last_applied": 3}
Request: {"type": "get_state", "msg_id": 2}
Response: {"type": "get_state_ok", "in_reply_to": 2, "state": {"x": "1", "y": "2"}, "last_applied": 3}Sample Test Cases
Apply put entries builds stateTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"apply_entries","msg_id":2,"entries":[{"index":1,"term":1,"command":{"op":"put","key":"x","value":"hello"}}]}}
{"src":"c1","dest":"n1","body":{"type":"get_state","msg_id":3}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Apply get returns current valueTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"apply_entries","msg_id":2,"entries":[{"index":1,"term":1,"command":{"op":"put","key":"x","value":"42"}},{"index":2,"term":1,"command":{"op":"get","key":"x"}}]}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Hints
Hint 1▾
Committed entries flow into an apply channel in order
Hint 2▾
The state machine reads from the channel and applies commands sequentially
Hint 3▾
Applied entries must never be re-applied (track lastApplied index)
Hint 4▾
The state machine must be deterministic: same commands = same state
Hint 5▾
Commands flow: client -> leader log -> replicated -> committed -> applied
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
apply channelstate machinecommitted entriesdeterministic replay
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
import sys
import json
def main():
# Your implementation here
for line in sys.stdin:
msg = json.loads(line)
print(json.dumps(msg), flush=True)
if __name__ == "__main__":
main()