3. An amusement park

So far the “customers” in our models were anonymous: a number in a container. Many questions need individuals. How long did this visitor spend in the park? Did gold-card holders wait less? How many people gave up and left a line? For that, each visitor needs its own data and its own behavior. And visitors come and go during the day, so they can’t be built up front like the rest of the model.

This chapter introduces dynamic models: model instances created with cb.spawn while a trial runs and removed with cb.release. Along the way we meet priority queues you can leave, process timers, and suspend/resume.

The scenario, from the C library’s tutorial 3:

  • Visitors arrive at the park entrance and wander between nine attractions, choosing the next one from a transition matrix and walking a PERT-distributed time between them.

  • Each attraction has one or more priority lines, served by batch-loading ride servers. A quarter of visitors hold gold cards and queue at a higher priority.

  • Each visitor has a patience factor that drives three behaviors:

    • balking: refusing to join if the shortest line is too long;

    • jockeying: switching to a shorter line after waiting a while;

    • reneging: giving up and walking away after waiting too long.

The full script is tutorial/tut_3_1.py. Here is its process graph. The park spawns visitors; each visitor may join, and leave, any of the eleven ride lines and records its day in the park’s datasets. Each line feeds its ride servers.

        ---
config:
  layout: elk
---
flowchart LR
  subgraph g0["park: Park"]
    n0[/"arrival_gap · exponential"/]
    n1["d_park · Dataset"]
    n2["d_riding · Dataset"]
    n3["d_waiting · Dataset"]
    n4["d_walking · Dataset"]
    n5["d_rides · Dataset"]
    n6(["arrivals"])
  end
  subgraph g1["park.ride_queues[0]: RideQueue"]
    n7["line · PriorityStore[Visitor]"]
    n8[/"duration · pert"/]
    n9(["server"])
  end
  subgraph g2["park.ride_queues[1]: RideQueueThree"]
    n10["line · PriorityStore[Visitor]"]
    n11[/"duration · pert"/]
    n12(["server ×3"])
  end
  subgraph g3["park.ride_queues[2]: RideQueueTwo"]
    n13["line · PriorityStore[Visitor]"]
    n14[/"duration · pert"/]
    n15(["server ×2"])
  end
  subgraph g4["park.ride_queues[3]: RideQueue"]
    n16["line · PriorityStore[Visitor]"]
    n17[/"duration · pert"/]
    n18(["server"])
  end
  subgraph g5["park.ride_queues[4]: RideQueue"]
    n19["line · PriorityStore[Visitor]"]
    n20[/"duration · pert"/]
    n21(["server"])
  end
  subgraph g6["park.ride_queues[5]: RideQueue"]
    n22["line · PriorityStore[Visitor]"]
    n23[/"duration · pert"/]
    n24(["server"])
  end
  subgraph g7["park.ride_queues[6]: RideQueue"]
    n25["line · PriorityStore[Visitor]"]
    n26[/"duration · pert"/]
    n27(["server"])
  end
  subgraph g8["park.ride_queues[7]: RideQueue"]
    n28["line · PriorityStore[Visitor]"]
    n29[/"duration · pert"/]
    n30(["server"])
  end
  subgraph g9["park.ride_queues[8]: RideQueue"]
    n31["line · PriorityStore[Visitor]"]
    n32[/"duration · pert"/]
    n33(["server"])
  end
  subgraph g10["park.ride_queues[9]: RideQueue"]
    n34["line · PriorityStore[Visitor]"]
    n35[/"duration · pert"/]
    n36(["server"])
  end
  subgraph g11["park.ride_queues[10]: RideQueue"]
    n37["line · PriorityStore[Visitor]"]
    n38[/"duration · pert"/]
    n39(["server"])
  end
  subgraph g12["Visitor (spawned)"]
    n40[["new Visitor"]]
    n41(["visit"])
  end
  n0 -->|next| n6
  n6 -->|spawn| n40
  n7 -->|get| n9
  n8 -->|next| n9
  n10 -->|get| n12
  n11 -->|next| n12
  n13 -->|get| n15
  n14 -->|next| n15
  n16 -->|get| n18
  n17 -->|next| n18
  n19 -->|get| n21
  n20 -->|next| n21
  n22 -->|get| n24
  n23 -->|next| n24
  n25 -->|get| n27
  n26 -->|next| n27
  n28 -->|get| n30
  n29 -->|next| n30
  n31 -->|get| n33
  n32 -->|next| n33
  n34 -->|get| n36
  n35 -->|next| n36
  n37 -->|get| n39
  n38 -->|next| n39
  n41 -->|enqueue| n16
  n41 -->|enqueue| n34
  n41 -->|enqueue| n19
  n41 -->|enqueue| n22
  n41 -->|enqueue| n13
  n41 -->|enqueue| n28
  n41 -->|enqueue| n25
  n41 -->|enqueue| n10
  n41 -->|enqueue| n37
  n41 -->|enqueue| n7
  n41 -->|enqueue| n31
  n41 -->|cancel| n16
  n41 -->|cancel| n34
  n41 -->|cancel| n19
  n41 -->|cancel| n22
  n41 -->|cancel| n13
  n41 -->|cancel| n28
  n41 -->|cancel| n25
  n41 -->|cancel| n10
  n41 -->|cancel| n37
  n41 -->|cancel| n7
  n41 -->|cancel| n31
  n41 -->|record| n1
  n41 -->|record| n2
  n41 -->|record| n3
  n41 -->|record| n4
  n41 -->|record| n5
    

A visitor is a model too

There is exactly one concept for “a thing with data and behavior” in Cimba Python, and that is Model. A visitor is declared the same way as the park:

class Visitor(cb.Model):
    park: cb.Ref["Park"]
    patience: float
    priority: int
    entry_park: float
    process_pointer: int = 0
    entry_queue: float = 0.0
    riding: float = 0.0
    waiting: float = 0.0
    walking: float = 0.0
    rides: int = 0

What makes it dynamic is how it is created. The park’s arrival process spawns one per arriving guest:

@cb.process
def arrivals(self):
    while True:
        cb.hold(self.arrival_gap.next())
        if cb.now() >= self.closing:
            break
        priority = 5 if cb.random.bernoulli(PERCENT_GOLDCARDS) else 0
        cb.spawn(Visitor, park=self,
                 priority=priority,
                 patience=cb.random.triangular(0.5, 1.0, 1.5),
                 entry_park=cb.now())
    while True:
        cb.suspend()

cb.spawn(Visitor, field=value, ...) allocates a new Visitor for this trial, sets its fields from the keyword arguments, runs its on_start hooks, and schedules its processes to start at the current time. It returns a handle to the new model, so you can put it in a store or set more fields.

The keyword arguments must cover every field without a default. Here that’s the park reference and the patience, priority and entry_park fields. Fields with a class default, like rides = 0, take it.

What a dynamic model may contain

Spawned models hold values and behavior: plain, Param, Output and Ref fields, inputs, processes and hooks. They can’t own entities or child models. Put shared queues and resources on a static model and give the spawned model a Ref to it, as Visitor does with park.

To give a spawned model an input, pass one of the spawner’s inputs: cb.spawn(Order, lead_time=self.lead_time). The new model gets its own cursor and its own random stream, derived deterministically from the trial seed and the spawn order.

When the visitor reaches the exit, it records its statistics and releases itself:

    self.park.d_park.record(cb.now() - self.entry_park)
    self.park.d_riding.record(self.riding)
    self.park.d_waiting.record(self.waiting)
    self.park.d_walking.record(self.walking)
    self.park.d_rides.record(float(self.rides))
    cb.release(self)

cb.release(model) stops the model’s processes. When a process releases its own model, as here, that process ends at the call. Memory is reclaimed when the trial ends.

Note

At the end of the cooldown the window stops every process, including those of spawned models, so a spawned process that loops forever can’t keep a trial alive. With Window.until_idle() there is no such stop: make sure spawned processes finish or block.

Lines you can leave: priority stores

Each ride line is a PriorityStore of visitors:

class RideQueue(cb.Model):
    attraction: cb.Param[int]
    line: cb.PriorityStore[Visitor]
    duration: cb.Input[float] = inputs.dist.pert(low=3.0, mode=4.0, high=5.0)

    def __init__(self, attraction: int):
        self.attraction = attraction
        self.duration = inputs.dist.pert(
            low=float(MIN_DUR[attraction]),
            mode=float(MODE_DUR[attraction]),
            high=float(MAX_DUR[attraction]),
        )

    @cb.process
    def server(self):
        while True:
            visitor = self.line.get()
            visitor.waiting += cb.now() - visitor.entry_queue
            visitor_process = cb.Process(visitor.process_pointer)
            visitor_process.timers_clear()
            duration = self.duration.next()
            cb.hold(duration)
            visitor.riding += duration
            visitor_process.resume(0)

cb.PriorityStore[Visitor] is typed: it holds Visitor handles, and putting anything else in it is a compile-time error. get() returns the highest-priority item that has waited longest, blocking while the store is empty. So in the ride server, visitor is a full view of the visitor model, and the server can update its waiting and riding fields directly.

Joining a line with put(item, priority) is fire-and-forget. A visitor who may leave the line needs a ticket, so model-valued priority stores offer three more calls:

  • ticket = line.enqueue(item, priority) joins and returns a ticket;

  • line.position(ticket) tells how many are ahead;

  • line.cancel(ticket) leaves the line. It returns False if the item was already taken.

Waiting with timers

Here is the clever part of the visitor. After joining a line, it sets two alarms on its own process and goes to sleep:

        chosen = self.park.shortest_line(at)
        shortest = self.park.ride_queues[chosen].line.length()
        if shortest > self.patience * BALKING_THRESHOLD:
            self.park.n_balks += 1
            continue

        line = self.park.ride_queues[chosen].line
        self.entry_queue = cb.now()
        ticket = line.enqueue(self, self.priority)
        me.timer_set(self.patience * JOCKEYING_THRESHOLD, TIMER_JOCKEYING)
        me.timer_set(self.patience * RENEGING_THRESHOLD, TIMER_RENEGING)
        while True:
            signal = cb.suspend()
            if signal == TIMER_JOCKEYING:
                replacement = self.park.shortest_line(at)
                replacement_length = self.park.ride_queues[replacement].line.length()
                if replacement != chosen and (
                    replacement_length < line.position(ticket)
                ):
                    if line.cancel(ticket):
                        chosen = replacement
                        line = self.park.ride_queues[chosen].line
                        ticket = line.enqueue(self, self.priority + 1)
                        self.park.n_jockeys += 1
            elif signal == TIMER_RENEGING:
                if line.cancel(ticket):
                    self.park.n_reneges += 1
                me.timers_clear()
                break
            else:
                self.rides += 1
                break

me.timer_set(delay, signal) arranges for the process to be woken with signal after delay time units, unless something wakes it first. cb.suspend() blocks until something does: a timer, an interrupt or a resume. It returns the signal, so the visitor knows why it woke:

  • TIMER_JOCKEYING (17): look for a shorter line, and switch if it is shorter than our position in this one;

  • TIMER_RENEGING (42): give up, leave the line, clear the remaining timers and walk on;

  • anything else: the ride server resumed us after the ride.

On the other side, the ride server boards the visitor, cancels the visitor’s pending alarms and resumes it when the ride is over:

visitor_process = cb.Process(visitor.process_pointer)
visitor_process.timers_clear()
...
visitor_process.resume(0)

This pattern of enqueue, arm timers, suspend, and let whoever finishes first decide is how you model patience, timeouts and service-level deadlines in Cimba.

Sharing logic with a function

The visitor needs the shortest line serving an attraction twice: once to join a line and again, when the jockeying timer fires, to look for a better one. That search belongs to the park, so it’s written once, as a @cb.function on Park:

@cb.function
def shortest_line(self, attraction: int) -> int:
    """Index of the shortest line serving ``attraction``."""
    chosen = 0
    shortest = 1_000_000
    for index in range(len(self.ride_queues)):
        ride = self.ride_queues[index]
        if ride.attraction == attraction:
            length = ride.line.length()
            if length < shortest:
                chosen = index
                shortest = length
    return chosen

The visitor calls it through its reference, self.park.shortest_line(at), exactly as you would call a method in Python. A @cb.function is compiled with its class and can be called from processes, hooks, events, predicates and other functions. It can even block. Its parameters and return value are annotated (int, float, bool or a model class). As you’ll see in Compare policies with polymorphic functions, that is also what lets a subclass override it.

Several servers per line

Some attractions run two or three ride vehicles off the same line. A process can run in several copies, each an independent coroutine over the same model:

class RideQueueTwo(RideQueue):
    @cb.process(copies=2)
    def server(self):
        while True:
            visitor = self.line.get()
            visitor.waiting += cb.now() - visitor.entry_queue
            visitor_process = cb.Process(visitor.process_pointer)
            visitor_process.timers_clear()
            duration = self.duration.next()
            cb.hold(duration)
            visitor.riding += duration
            visitor_process.resume(0)

@cb.process(copies=2) starts two server processes for every RideQueueTwo. Because RideQueueTwo subclasses RideQueue, it inherits all the fields and only overrides the process declaration. The park builds a heterogeneous list, with some lines of each class:

def __init__(self, closing: float = PARK_OPEN):
    self.closing = closing
    self.ride_queues = [
        (RideQueue if SERVERS_PER_Q[attraction] == 1 else
         RideQueueTwo if SERVERS_PER_Q[attraction] == 2 else
         RideQueueThree)(attraction)
        for attraction in range(1, NUM_ATTRACTIONS + 1)
        for _ in range(int(NUM_QUEUES[attraction]))
    ]

ride_queues: list[RideQueue] accepts any subclass. In compiled code, self.park.ride_queues[index] is seen through the base class, so the visitor can read attraction and line on every item regardless of its subclass. Each class is compiled once, however many instances there are.

A park that closes

The park stops admitting visitors at closing time, but people already inside should finish their day. That’s what the cooldown is for:

def main() -> None:
    park = Park()
    start = time.perf_counter()
    results = cb.Experiment(
        park, replications=20,
        window=cb.Window(duration=PARK_OPEN, cooldown=2_000.0),
        seed=20260613,
    ).run()

Arrivals stop at PARK_OPEN. For the next 2,000 minutes of cooldown the remaining visitors ride, walk and leave. Datasets keep collecting during the cooldown, so every visitor’s time in the park is recorded. Time-weighted statistics, such as a resource’s utilization, stop at the end of duration.

$ uv run python tutorial/tut_3_1.py
cimba 3.0.0; 9 attractions, 11 queues, 14 ride servers
20 trials in 1.88 s
n_visitors: 476.350
avg_rides: 2.493
avg_time_in_park: 58.854
avg_riding: 16.821
avg_waiting: 4.737
avg_walking: 33.450
n_balks: 0.000
n_jockeys: 0.000
n_reneges: 195.500

About 476 visitors a day, each riding two or three attractions and spending most of their hour walking. Nobody balks or jockeys at these patience settings, but reneging is common. That’s a hint that some ride lines move slowly relative to visitors’ patience. Try raising ARRIVAL_RATE or lowering RENEGING_THRESHOLD and watch the behaviors change.

What you learned

  • cb.spawn(ModelClass, field=value, ...) creates a model during a trial; cb.release(model) removes it. Spawned models hold values, refs, inputs and behavior, but no entities or children.

  • PriorityStore[M] holds typed model handles; enqueue, position and cancel let items leave a line.

  • timer_set, suspend, resume and timers_clear express patience and deadlines.

  • @cb.function shares logic between processes; it’s called like a method.

  • @cb.process(copies=n) runs several identical processes; subclasses can override processes; list[Base] holds mixed subclasses.

  • The cooldown lets in-flight work finish after the measurement window.

In 4. A weather-gated harbor we assemble a model from several cooperating sub-models and learn to wait on arbitrary conditions.