TASK
Implementation
Implement a basic grow-only counter that handles add and read operations. Multiple nodes share counter state, but your initial implementation will lose updates under concurrency.
This task intentionally demonstrates the lost update problem. Your counter will work for sequential operations but fail verification under concurrent updates from multiple nodes.
Sample Test Cases
Basic counter addTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"add","msg_id":2,"delta":5}}
{"src":"c1","dest":"n1","body":{"type":"read","msg_id":3}}
Expected Output
{"src":"n1","dest":"c0","body":{"type":"init_ok","in_reply_to":1,"msg_id":0}}
{"src":"n1","dest":"c1","body":{"type":"add_ok","in_reply_to":2,"msg_id":1}}
{"src":"n1","dest":"c1","body":{"type":"read_ok","in_reply_to":3,"msg_id":2,"value":5}}
Sequential increments workTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"add","msg_id":2,"delta":3}}
{"src":"c2","dest":"n1","body":{"type":"add","msg_id":3,"delta":2}}
{"src":"c3","dest":"n1","body":{"type":"read","msg_id":4}}
Expected Output
{"src":"n1","dest":"c0","body":{"type":"init_ok","in_reply_to":1,"msg_id":0}}
{"src":"n1","dest":"c1","body":{"type":"add_ok","in_reply_to":2,"msg_id":1}}
{"src":"n1","dest":"c2","body":{"type":"add_ok","in_reply_to":3,"msg_id":2}}
{"src":"n1","dest":"c3","body":{"type":"read_ok","in_reply_to":4,"msg_id":3,"value":5}}
Hints
Hint 1▾
Start with a simple counter
Hint 2▾
Notice what happens with concurrent updates
Hint 3▾
This task is meant to fail
OVERVIEW
Theoretical Hub
The Lost Update Problem
When multiple nodes read, modify, and write state, updates can be lost. Node A reads 5, Node B reads 5, both increment to 6, both write 6. One increment is lost. This is why distributed counters need special handling.
Key Concepts
lost updatesrace conditionsnaive replication
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python3
import sys
import json
class Node:
def __init__(self):
self.node_id = None
self.counter = 0
# TODO: Implement add and read handlers
# Notice that concurrent updates will be lost
if __name__ == "__main__":
pass