ARCHIVED from builddistributedsystem.com on 2026-04-28 — URL: https://builddistributedsystem.com/tracks/identifier/tasks/task-2-3-4-happened-before
TASK

Implementation

With vector clocks, you can determine the exact causal relationship between any two events:

  • A -> B (A happened before B): A[i] <= B[i] for all i, and strict < for at least one
  • B -> A (B happened before A): B[i] <= A[i] for all i, and strict < for at least one
  • A || B (concurrent): neither dominates

Implement a compare handler:

Request:  {"type": "compare", "msg_id": 1, 
           "vc_a": {"n1": 2, "n2": 1}, 
           "vc_b": {"n1": 1, "n2": 3}}
Response: {"type": "compare_ok", "in_reply_to": 1, "relation": "concurrent"}

Possible relations: "a_before_b", "b_before_a", "concurrent", "equal".

Sample Test Cases

A before BTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"compare","msg_id":2,"vc_a":{"n1":1,"n2":0},"vc_b":{"n1":2,"n2":1}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "compare_ok", "relation": "a_before_b", "in_reply_to": 2, "msg_id": 1}}
Concurrent eventsTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"compare","msg_id":2,"vc_a":{"n1":2,"n2":1},"vc_b":{"n1":1,"n2":3}}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "compare_ok", "relation": "concurrent", "in_reply_to": 2, "msg_id": 1}}

Hints

Hint 1
A -> B if A[i] <= B[i] for all i, and A[j] < B[j] for at least one j
Hint 2
A || B (concurrent) if neither A -> B nor B -> A
Hint 3
Compare vectors element-wise across all nodes
Hint 4
Store events with their vector clock snapshots for later comparison
Hint 5
This is the foundation for conflict detection in databases like Riak
OVERVIEW

Theoretical Hub

Concept overview coming soon

Key Concepts

happened-beforeconcurrent eventsvector comparisonconflict detection
main.py
python
Implement Happened-Before Detector with Vector Clocks - The Identifier | Build Distributed Systems