TASK
Implementation
A CRDT merge function must satisfy three properties to guarantee convergence: commutativity, associativity, and idempotency. Proving these for the G-Counter validates it as a correct CRDT.
Commutativity: merge(A, B) == merge(B, A)
- max(A[i], B[i]) == max(B[i], A[i]) for all i. This is true because max is commutative.
Associativity: merge(A, merge(B, C)) == merge(merge(A, B), C)
- max(A[i], max(B[i], C[i])) == max(max(A[i], B[i]), C[i]). True because max is associative.
Idempotency: merge(A, A) == A
- max(A[i], A[i]) == A[i]. True because max(x, x) == x.
These properties form a join semi-lattice: the set of all possible states with merge as the join operation. The system monotonically advances through this lattice, guaranteeing convergence.
Request: {"type": "crdt_verify", "msg_id": 1, "state_a": {"n1": 3, "n2": 1}, "state_b": {"n1": 1, "n2": 5}}
Response: {"type": "crdt_verify_ok", "in_reply_to": 1, "merge_ab": {"n1": 3, "n2": 5}, "merge_ba": {"n1": 3, "n2": 5}, "commutative": true, "idempotent": true}Sample Test Cases
Merge is commutativeTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"crdt_verify","msg_id":2,"state_a":{"n1":3,"n2":1},"state_b":{"n1":1,"n2":5}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Merge is idempotentTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"crdt_verify","msg_id":2,"state_a":{"n1":5,"n2":3},"state_b":{"n1":5,"n2":3}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Hints
Hint 1▾
Commutative: merge(A, B) == merge(B, A) for all states A, B
Hint 2▾
Associative: merge(A, merge(B, C)) == merge(merge(A, B), C)
Hint 3▾
Idempotent: merge(A, A) == A
Hint 4▾
These three properties ensure convergence regardless of message order or duplication
Hint 5▾
The element-wise max operation satisfies all three properties
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
commutativityassociativityidempotencylatticeconvergence proof
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()