# The Art of Projection: Zero-Overhead Derivation from a Single State Machine to Multiple Roles
In the world of distributed systems, we often find ourselves caught in a dilemma: a protocol requires the collaboration of multiple roles, yet the behavioral logic of each role must be implemented separately. As a result, the exact same control flow is repeatedly copied, pasted, and modified, eventually devolving into an unmaintainable maze of code. The emergence of Troupe breaks this dilemma in an almost magical way—it models the protocol as a **global state machine**, and then "projects" this state machine onto each role at compile time, allowing each role to automatically obtain its own control flow. This process incurs no runtime overhead, yet it fundamentally changes the way distributed programs are written.
## The Pain of Scattered Control Flow
Imagine a simple three-party protocol: Alice sends a request, Bob processes and forwards it to Charlie, and Charlie finally responds. In a traditional implementation, we need to write three separate pieces of code:
* Alice's code contains the logic for "sending a request, waiting for a response, and handling timeouts."
* Bob's code contains the logic for "receiving the request, forwarding it, waiting for Charlie's response, and sending it back."
* Charlie's code contains the logic for "receiving the request, processing it, and sending a response."
Although these three pieces of code represent different perspectives, they essentially describe the same protocol flow. When the protocol evolves (for example, by adding a retry mechanism), all three pieces of code must be modified synchronously. This repetitive labor is not only inefficient but also a breeding ground for bugs—with the slightest carelessness, one role's state machine falls out of sync with the others, plunging the entire system into chaos.
The root of the problem is this: **control flow is scattered**. Each role independently maintains its own understanding of the protocol, and the overall behavior of the protocol can only be pieced together from these fragmented parts.
## State Machines: A Natural Global Description
If we take a step back, a protocol is essentially a **finite state machine** it has a set of states, transitions between states are triggered by messages, and each state specifies who sends the message, who receives it, and what the next state is. This state machine naturally encompasses the behavior of all roles—it doesn't favor any single party, but rather describes the evolution of the entire protocol from a global perspective.
This file has been truncated. show original