Tallying a Tree of Message-Passing Processes
Trees & GraphsModel answerLast updated
Each tree node is an isolated process with only async send and blocking receive. Design a protocol so the root learns the tree size, tolerates lost and duplicate messages, and returns a structured result.
A rooted tree is deployed so that every node is a separate process. Processes have no shared memory. They interact only through these two primitives:
send_async(to_id, message) # returns at once; delivery happens later
receive() # blocks until something arrives; returns (sender_id, message)
Each process knows its own id, its parent's id (the root has none) and its children's ids. It knows nothing else about the tree.
Design the program that every node runs so that the root finds out how many nodes the tree contains. Then make it robust to an unreliable network, and finally decide what shape the result should take if a caller wants more than a single integer.
Before you start, state your assumptions: how the computation is triggered, whether per-pair message ordering is guaranteed, whether receive can time out, and whether processes can crash or only messages can be lost.
Part 1 - Reliable delivery. Every message arrives exactly once, after an arbitrary delay and possibly out of order. Write the per-node logic and explain why the root's total is right. Give the message count and the completion time in terms of the number of nodes n and the tree depth d.
Part 2 - Unreliable delivery. Any message may be lost, and any message may be delivered more than once. Adapt the protocol so the root still gets the correct count when it can. Cover how duplicates are neutralised, who retries and when, how a node reacts to a repeated request it has already answered, and what happens if a subtree never responds.
Part 3 - Richer result. The caller needs more than one integer. Define what each reply carries and what the root returns. Discuss how message size grows with subtree size, and how the result expresses that the count may be incomplete.
Hints
Hint 1
Think of it as a two-phase wave: a request travels down, and answers travel back up. A node should answer its parent only when every child has answered, and it should track children by id rather than relying on arrival order.
Hint 2
For unreliable networks, make every handler idempotent. Store each child's reply in a map keyed by child id so a second copy overwrites or is ignored, and have the parent (the side that is waiting) retry requests on a timer.
Hint 3
For the richer result, return something like a status plus a count plus the list of unreachable child ids, and compare a full per-node listing (message size O(subtree)) with a compact summary (O(1) per message).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Only the root is triggered by the caller. A node starts working when it receives a
COUNT_REQUESTfrom its parent, so the request flows down the tree. - No ordering guarantee between messages, even for a single pair of processes. The design must not depend on it.
- For Part 1, delivery is reliable. For Part 2, messages may be lost or duplicated, but processes do not crash. A crash is treated like a subtree that never answers.
receivehas a timeout option, or a local timer can inject aTIMEOUTevent. Without some timer, a lost message would block forever, and no protocol could detect it.
Part 1: Convergecast
This is a broadcast down followed by a convergecast up.
Per-node logic:
def run_node(my_id, parent, children):
if parent is None:
pass # root starts on the caller's trigger
else:
receive_until_request() # wait for COUNT_REQUEST from parent
for c in children:
send_async(c, ("REQ",))
total = 1 # count self
pending = set(children)
while pending:
sender, msg = receive()
if msg[0] == "REPLY" and sender in pending:
total += msg[1]
pending.remove(sender)
if parent is None:
return total
send_async(parent, ("REPLY", total))
A leaf has no children, so it replies with 1 immediately. Tracking the pending set by child id means the node knows it has heard from everyone regardless of arrival order.
Correctness (induction on height): a leaf reports 1. An internal node reports 1 plus the sum of its children's reported sizes, each of which is correct by induction. Every node lies in exactly one child subtree of its parent, so nothing is double counted or skipped. The root's total is n.
Cost: one request and one reply per edge, so 2(n-1) messages. Time is about 2d message delays, since the request travels d hops down and the replies d hops up. Each node holds O(number of children) state.
Part 2: Loss and duplication
Two problems appear: duplicates must not inflate the count, and losses must not hang the computation.
Duplicates. Keep replies = {} keyed by child id. A REPLY from a child already in the map is ignored (or overwritten with the same value). Summing from the map, not from a running counter, makes the handler idempotent. A duplicate REQ must not restart the subtree computation. The node keeps a state (idle, waiting, done) and a cached answer.
Losses. The waiting side retries, because it is the one that notices the silence. The parent re-sends REQ to each child still missing, with a timeout and exponential backoff, up to a maximum number of attempts:
def on_timeout():
for c in pending:
send_async(c, ("REQ",))
Repeated request after answering. If a child has finished and gets another REQ, it just resends its cached REPLY. This covers the case where its first reply was lost. It does not recompute, and it does not re-ask its own children. If the child is still waiting, it ignores the duplicate request, or optionally nudges its own pending children, since its own retry timer is already running.
Why the parent retries, not the child: a child that sent a reply cannot know whether it arrived without an acknowledgment. Having the parent re-ask means the parent's request itself serves as the "not received yet" signal. Optionally the parent can send a short ACK, but it is not required, and the child must retain its cached answer anyway because a later REQ might still arrive.
Dead subtrees. After the retry budget is exhausted for a child, mark it unreachable and stop waiting. The node then replies with what it has, flagged as partial. Trade-off: a short timeout makes the answer fast but risks marking a slow subtree as missing; a long timeout is accurate but slow. Timeouts should scale with the depth below a node (a node near the root should wait longer than one near the leaves), otherwise a parent might give up on a child that is itself still legitimately retrying.
Request identity. Tag every request with a request_id. Otherwise a delayed reply from an earlier run could be mistaken for the current one.
Part 3: Result structure
A bare int cannot say "I am not sure." Use a result type such as:
@dataclass
class Result:
count: int # nodes confirmed
complete: bool # False if any subtree was unreachable
unreachable: list[int] # ids of children given up on (their subtrees unknown)
Each node merges its children's results: counts add, complete is the AND of all children and itself, and unreachable lists are concatenated. The root then returns "count is at least X, and these subtrees are missing" rather than a number that looks final. A count from an incomplete run is a lower bound.
Message size. With the structure above, a reply carries a count, a flag and the unreachable ids, so it is O(1) when everything works and O(number of failures) otherwise. If the caller also wants the set of node ids, or a per-subtree breakdown, each reply grows to O(size of subtree) and the root receives O(n) data, with total traffic O(n·d) in the worst case (a path), since ids are re-sent at every level. Choose the smallest payload that satisfies the caller. Aggregates (count, max depth, per-level counts) are cheap; full listings are not.
Common mistakes
- Relying on message order or on "the next message is from my last child".
- Adding to a running counter on every reply, so duplicates double count.
- Re-running the whole subtree computation on each duplicate request.
- Retrying without a bound, or without any timeout at all.
- Returning a partial count as if it were exact.
- Forgetting a request id, so stale replies pollute a new run.
Open limitations
If a node crashes after receiving the request, the system can only report its subtree as unreachable; it cannot distinguish a crash from a slow network. A truly exact answer in the presence of crashes would need a membership service or a consensus mechanism, which is beyond this design.