18/27
Part 5 of 7 · Several counts at onceLearn and do

Keep each count's state under its request id

Level 4 lets the root start a new count while another is running: start(request_id). The write-up's answer for concurrency is to keep the state of each request apart, by request_id (1 report).

Look at the level 3 state: one parent, one replies, one answer. Two counts at once would write into the same fields. Machine 1 would mix count a's answers with count b's, and finish both with one set of numbers, or ignore b's ask as a repeat of a's.

The fix is mechanical. Every message carries the request id second: ("ask", id) and ("answer", id, count, shape). Every piece of state becomes a dict keyed by that id:

  • self.open[id]: the counts in progress here, each with its parent and its replies,
  • self.answers[id]: the answers this machine has sent, kept for repeats,
  • on the root, self.counts[id] and self.trees[id].

A count moves from open to answers when it finishes. tick asks again for every open count. Nothing else changes: each count runs exactly the level 3 protocol, as if it were alone.

open_counts = {"a": {"parent": 0, "replies": {3: (1, "3")}},
               "b": {"parent": 0, "replies": {}}}
print([(rid, sorted(state["replies"])) for rid, state in open_counts.items()])
[('a', [3]), ('b', [])]

The editor holds the level 4 Machine with all its state keyed by request id, and an empty receive. Write receive: answer a repeated ask from self.answers, start a count on a new id, and file each answer under its own id in self.open.