Distributed Tree Traversal and Reliable Neighbor Messaging Protocol
Trees & GraphsModel answerLast updated
Design a reliable message passing protocol across adjacent tree nodes, then compute total network size and discover paths under network faults.
You are building an algorithm for a distributed network of nodes arranged in a graph structure. Initially, assume the network forms a rooted tree, where every node only knows the identifier of its parent and its children, and can only communicate directly with these immediate neighbors.
Your task is to design and implement a protocol that answers the following requirements:
-
Reliable Neighbor Link Layer (
sendMessage): Implement a reliable messaging interface between adjacent nodes over an asynchronous, lossy link layer that may drop, duplicate, or reorder packets. -
Network Node Counter: Using only asynchronous neighbor-to-neighbor message passing, calculate the total number of nodes in the entire network. State all assumptions, and analyze the message and time complexity. Explain how to generalize this step if the topology is an arbitrary connected graph rather than a tree.
-
Path Routing Discovery: Design protocols to compute and return:
- (a) The sequential path of node IDs from any starting node $u$ up to the root.
- (b) The sequential path of node IDs between two arbitrary nodes $u$ and $v$.
-
Fault Tolerance & Edge Handling: Explain how your protocol handles message loss, duplicate delivery, packet reordering, and node timeouts. Discuss how termination detection is guaranteed.
Hints
Hint 1
Think about standard networking protocols: how do sequence numbers and ACKs solve packet loss, duplicates, and reordering across a single hop?
Hint 2
To count nodes in a tree, combine top-down broadcast with bottom-up aggregation (convergecast). Every leaf node can easily report its subtree count as 1.
Hint 3
For routing between arbitrary nodes u and v in a tree, think about how finding each node's path to the root lets you determine their Lowest Common Ancestor (LCA).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture & Protocol Design
This problem spans low-level reliable link transport up to high-level distributed algorithms on graph structures.
Part 1: Reliable Adjacent-Node Messaging
To handle loss, duplication, and reordering across direct physical links, we implement a Stop-and-Wait (or Sliding Window) protocol with Sequence Numbers and Acknowledgments (ACKs) per neighbor channel.
Channel Mechanism
- Sequence Numbers: Each directed link $(u \to v)$ maintains a monotonic sequence counter
seq_num. - Packet Structure: Frames take the form
(type="DATA"|"ACK", src_id, dst_id, seq_num, payload). - Deduplication: Receiver $v$ tracks
expected_seq(or a fixed sliding window of seen sequence IDs) for each neighbor $u$. Duplicates are immediately ACKed with their sequence number but discarded at the application layer. - Retransmissions: Sender $u$ retains unacknowledged packets in an
unacked_bufferpaired with a expiration timer (RTO- Retransmission Timeout). If no ACK arrives before the timeout expires, the frame is retransmitted.
Part 2: Network Size Counting (Tree & General Graph)
Tree Topology (Broadcast + Convergecast)
If the topology is guaranteed to be a tree:
- Initiation: The root sends a
COUNT_REQUEST(req_id)message to all its children. - Propagation: Non-leaf nodes forward
COUNT_REQUESTto all their children and initialize a counterreceived_replies = 0andtotal_nodes = 1(counting themselves). - Leaf Processing: Leaf nodes (nodes with no children) immediately return
COUNT_RESPONSE(req_id, count=1)back to their parent. - Aggregation (Echo / Convergecast): When an internal node receives answers from all its children, it sends
COUNT_RESPONSE(req_id, count = 1 + sum(child_counts))up to its parent. - Termination: The root receives answers from all its children and outputs
total_nodes.
Complexity (Tree)
- Message Complexity: Exactly $2(N - 1)$ messages (1 request down each edge, 1 response up each edge).
- Time Complexity: $O(\text{depth})$ parallel message hops from root down to leaves and back.
General Graph Topology (Echo Algorithm / Spanning Tree Construction)
If the network contains cycles, naive flooding causes infinite loops. We use the Segall's Echo Algorithm:
- When a node sees
COUNT_REQUESTfor the first time from neighbor $p$, it marks $p$ as its parent in the dynamic spanning tree. - It forwards
COUNT_REQUESTto all other neighbors. - If a node receives a
COUNT_REQUESTfrom a neighbor that is not its parent, it immediately replies with aREJECT(req_id, count=0). - Once a node has received either a valid count or a
REJECTfrom all non-parent neighbors, it sendsCOUNT_RESPONSE(req_id, count = 1 + sum(valid_counts))back to its designated parent.
- Message Complexity (Graph): $O(E)$, where $E$ is the number of edges (at most $2E$ total messages).
- Time Complexity (Graph): $O(D)$, where $D$ is the network diameter.
Part 3: Path Discovery
3(a) Path from Node $u$ to Root
- Node $u$ generates a
PATH_TO_ROOT_REQ(req_id, current_path=[u]). - Every intermediate node $w$ appends its own ID (
current_path.append(w)) and forwards the message toparent. - Upon reaching the root, the complete path $[u, w_1, w_2, \dots, \text{root}]$ is assembled.
- The root can source-route the complete list back down to $u$ using the inverse of the path.
- Message/Time Complexity: $O(\text{depth}(u))$ messages and rounds.
3(b) Path Between Arbitrary Nodes $u$ and $v$
Because nodes lack global routing tables, finding an arbitrary node $v$ requires a coordinated search:
- Node $u$ triggers path collection to the root, generating
path_u = [u, ..., root]. - The root initiates a downstream search (or flood) for node $v$. When node $v$ is reached, its path to the root
path_v = [v, ..., root]is sent back to the root. - The root finds the Lowest Common Ancestor (LCA) by comparing
path_uandpath_vfrom the root backward until they diverge. - Combining the two segments yields the path: $$\text{Path}(u, v) = \text{reverse}(\text{path}_u[u \dots \text{LCA}]) + \text{path}_v[\text{LCA} \dots v]$$
- The result is returned along the path to $u$.
- Message Complexity: $O(N)$ due to flooding for $v$ without global routing indices ($O(\text{depth})$ if subtree location indices are known).
- Time Complexity: $O(\text{height})$.
Part 4: Fault Tolerance & Edge Cases
| Issue | Mitigation |
|---|---|
| Packet Loss | Sender holds unACKed messages and retries after RTO expiration. |
| Duplicates | Receiver tracks seen_seq per neighbor link. Duplicate sequence IDs are acknowledged but suppressed. |
| Reordering | Frames strictly carry sequence numbers; link handlers order or process idempotently. |
| Node Failures / Crashes | Heartbeat ticks detect link drops. If a child crashes mid-convergecast, the parent times out and excludes that subtree (or flags an error state). |
| Termination Detection | Achieved naturally via Dijkstra-Scholten convergecast tree signaling: internal nodes do not respond until all dependent subtrees have completed. |
Python Implementation
Below is a complete simulation including lossy links, duplicate packet generation, reordering, reliable neighbor messaging, network counting, and path resolution.
import random
from collections import defaultdict
class Frame:
def __init__(self, f_type, src, dst, seq, payload):
self.f_type = f_type # "DATA" or "ACK"
self.src = src
self.dst = dst
self.seq = seq
self.payload = payload
class LossyNetwork:
"""Simulates an asynchronous lossy network with delay, duplication, and drop."""
def __init__(self, loss_rate=0.1, dup_rate=0.05, seed=42):
self.nodes = {}
self.queue = [] # List of tuples: (delivery_time, Frame)
self.current_time = 0
self.loss_rate = loss_rate
self.dup_rate = dup_rate
self.rng = random.Random(seed)
def register_node(self, node):
self.nodes[node.node_id] = node
node.network = self
def send_frame(self, frame):
# Model loss
if self.rng.random() < self.loss_rate:
return # Packet dropped
# Model duplication
copies = 2 if self.rng.random() < self.dup_rate else 1
for _ in range(copies):
delay = self.rng.randint(1, 4)
self.queue.append((self.current_time + delay, frame))
def step(self, max_ticks=1000):
while self.current_time < max_ticks:
# Deliver scheduled frames
due_frames = [f for t, f in self.queue if t == self.current_time]
self.queue = [(t, f) for t, f in self.queue if t != self.current_time]
for frame in due_frames:
if frame.dst in self.nodes:
self.nodes[frame.dst].on_receive_frame(frame)
# Trigger timers on all nodes
for node in self.nodes.values():
node.tick(self.current_time)
self.current_time += 1
# Stop early if network is idle
if not self.queue and all(len(n.unacked) == 0 for n in self.nodes.values()):
break
class DistributedNode:
def __init__(self, node_id, parent=None, children=None, rto=5):
self.node_id = node_id
self.parent = parent
self.children = children if children else []
self.network = None
self.rto = rto
# Reliable Link State per Neighbor
self.next_tx_seq = defaultdict(int)
self.expected_rx_seq = defaultdict(int)
self.unacked = {} # (dst, seq) -> (Frame, send_time)
# Counting & Query State
self.pending_counts = {} # req_id -> {received: dict, total_children: int}
self.path_results = {} # req_id -> path result
# --- Part 1: Reliable Neighbor Messaging ---
def send_neighbor_message(self, dst_id, payload):
assert dst_id == self.parent or dst_id in self.children, "Can only send to direct neighbors"
seq = self.next_tx_seq[dst_id]
self.next_tx_seq[dst_id] += 1
frame = Frame("DATA", self.node_id, dst_id, seq, payload)
self.unacked[(dst_id, seq)] = (frame, self.network.current_time)
self.network.send_frame(frame)
def on_receive_frame(self, frame):
if frame.f_type == "ACK":
key = (frame.src, frame.seq)
if key in self.unacked:
del self.unacked[key]
return
if frame.f_type == "DATA":
# Send ACK back immediately
ack_frame = Frame("ACK", self.node_id, frame.src, frame.seq, None)
self.network.send_frame(ack_frame)
# Check sequence for duplicate suppression
if frame.seq == self.expected_rx_seq[frame.src]:
self.expected_rx_seq[frame.src] += 1
self.on_receive_payload(frame.src, frame.payload)
def tick(self, now):
# Retransmit unacked messages whose timer expired
for (dst, seq), (frame, send_time) in list(self.unacked.items()):
if now - send_time >= self.rto:
self.unacked[(dst, seq)] = (frame, now)
self.network.send_frame(frame)
# --- Application Payload Processing ---
def on_receive_payload(self, src_id, payload):
p_type = payload.get("type")
# --- Part 2: Network Counting Protocol ---
if p_type == "COUNT_REQ":
req_id = payload["req_id"]
if not self.children:
# Leaf node answers immediately
self.send_neighbor_message(src_id, {"type": "COUNT_RESP", "req_id": req_id, "count": 1})
else:
self.pending_counts[req_id] = {"received": {}, "expected": len(self.children)}
for child in self.children:
self.send_neighbor_message(child, {"type": "COUNT_REQ", "req_id": req_id})
elif p_type == "COUNT_RESP":
req_id = payload["req_id"]
count = payload["count"]
state = self.pending_counts[req_id]
state["received"][src_id] = count
if len(state["received"]) == state["expected"]:
total = 1 + sum(state["received"].values())
if self.parent is not None:
self.send_neighbor_message(self.parent, {"type": "COUNT_RESP", "req_id": req_id, "count": total})
else:
self.path_results[req_id] = total # Root completes counting
# --- Part 3(a): Path to Root ---
elif p_type == "PATH_ROOT_REQ":
req_id = payload["req_id"]
path = payload["path"] + [self.node_id]
if self.parent is None:
# Root reached
self.path_results[req_id] = path
else:
self.send_neighbor_message(self.parent, {"type": "PATH_ROOT_REQ", "req_id": req_id, "path": path})
def start_count(self, req_id):
"""Initiated by Root Node"""
self.pending_counts[req_id] = {"received": {}, "expected": len(self.children)}
for child in self.children:
self.send_neighbor_message(child, {"type": "COUNT_REQ", "req_id": req_id})
def start_path_to_root(self, req_id):
"""Initiated by any node u"""
if self.parent is None:
self.path_results[req_id] = [self.node_id]
else:
self.send_neighbor_message(self.parent, {"type": "PATH_ROOT_REQ", "req_id": req_id, "path": [self.node_id]})
# Execution Example
if __name__ == "__main__":
net = LossyNetwork(loss_rate=0.15, dup_rate=0.10)
# Tree: Node 1 (Root) -> Node 2, Node 3; Node 2 -> Node 4, Node 5
n4 = DistributedNode(4, parent=2)
n5 = DistributedNode(5, parent=2)
n2 = DistributedNode(2, parent=1, children=[4, 5])
n3 = DistributedNode(3, parent=1)
n1 = DistributedNode(1, parent=None, children=[2, 3])
for node in [n1, n2, n3, n4, n5]:
net.register_node(node)
# 1. Count network nodes from root
n1.start_count("query_1")
net.step(max_ticks=500)
print("Total Node Count Output at Root:", n1.path_results.get("query_1")) # Output: 5
# 2. Get Path to Root from Node 5
n5.start_path_to_root("query_2")
net.step(max_ticks=500)
print("Path to Root from Node 5:", n1.path_results.get("query_2")) # Output: [5, 2, 1]