Docs · Context Runtime

Inside the Context Runtime.

The runtime is a small set of cooperating managers inside one process per node. This page names each one, says what it owns, and follows a task through them. It describes structure, not APIs; for the calls themselves see the API reference, and for the reasoning behind the mechanisms see the Design section.

Process
one per node
Core pieces
config, IPC, module, pool, work orchestrator, viz
Threads
runtime.num_threads workers + monitor + dashboard pool

The pieces at a glance

ONE RUNTIME PROCESS (clio-run start) Config managerclio.yaml, hostfile Module managerfinds, dlopens ChiMods Pool managerpools, containers, routing Viz serverdashboard, REST routes IPC manager shared-memory queues (same machine) ZeroMQ TCP / Unix socket (clients) run-to-run TCP (other nodes) GPU-to-CPU device rings Work orchestrator + scheduler maps each task to a worker lane monitor thread: rescue, steal, grow, retire learned per-method cost models pluggable: runtime.local_sched WORKERS (runtime.num_threads) Worker 0scheduler workerlane + coroutines Workers 1..kgeneral poolelastic GPU workerpolls device rings Net sendDEALER sockets Net recvROUTER sockets Containers (one per pool on this node)module code: coroutine handlers per method, cost model, Expand / Migrate / Recover, dashboard routes
The managers are process-wide singletons. Workers execute container handlers; the IPC manager moves tasks in and out of the process; the scheduler decides which worker runs each task.

The managers

Config manager
Reads ~/.clio/clio.yaml (or the file named by the environment), the hostfile and the compose list, and applies environment overrides. Everything else asks it for settings such as the thread count, the scheduler name and the ports.
Module manager
At startup, scans the runtime's own library directory, CLIO_REPO_PATH, LD_LIBRARY_PATH and default paths for shared libraries whose names contain _runtime, opens each one, and records its factory functions. It can then construct a container of any loaded module by name. On load it also builds a throwaway prototype container so the module can register its dashboard pages before any pool exists.
Pool manager
Owns the table of pools and their local containers. It creates and destroys pools on request from the admin module, resolves a task's pool id and PoolQuery to a container (here or on another node), saves and restores each container's learned cost model, and hands containers to workers through a lightweight handle cached at routing time.
IPC manager
Owns every way a task can enter or leave the process, described below, plus node identity, peer liveness and the heartbeat clients use to notice a restarted runtime.
Work orchestrator
Spawns and owns the worker threads and their lanes, holds the active scheduler, and runs the monitor thread that calls the scheduler's load-balancing hook every 100 ms.
Viz server
A small HTTP server with its own thread pool. It serves the dashboard, a registry of REST routes that modules add, and static assets a module ships in a viz/ directory.

Tasks and futures

A task is a C++ struct with input and output fields plus a header: its pool, method, PoolQuery, flags and return code. Submitting a task returns a future. The future's completion flag lives in memory both sides can see, so a caller in another process or on a GPU can wait for it without a message. Only inputs travel toward the container and only outputs travel back: tasks are serialized at every process boundary and are never shared objects.

Inside the runtime a handler that submits a subtask passes it by pointer, with no serialization, and co_awaits its future. When the subtask completes, the parent coroutine is put back on its worker's queue.

Transports and queues

The IPC manager picks a transport for each direction a task can travel. Every transport has the same four steps: send the input, receive the input, send the output, receive the output.

PathMechanismUsed by
Runtime to itselfPointer handed to a worker lane; no copySubtasks from handlers, periodic tasks
Client to runtime, same machineShared-memory ring buffers and a shared data segment per clientDefault for local clients
Client to runtime, socketZeroMQ over a Unix socket or TCP, read by a dedicated receive thread. A worker queues the reply; the network receive worker writes itContainers, remote clients, or when shared memory is unavailable. Probed fastest-first unless CLIO_IPC_MODE forces one
Runtime to runtimeZeroMQ TCP: DEALER sockets per peer for sends, one ROUTER for receives; messages carry an incarnation numberAny task whose PoolQuery resolves to another node
GPU to runtimeA device-memory ring per GPU. The kernel fills a pre-allocated task, the GPU worker copies it in, runs it, and writes the output backMemory expansion and GPU kernels

Worker lanes are multi-producer, single-consumer ring buffers: any thread may push, and only the owning worker pops. A worker that would push onto its own full lane is redirected to another worker, so a full queue becomes back-pressure instead of a deadlock.

Inside the process: lanes, workers and queues

ONE RUNTIME PROCESS · runtime.num_threads: 4 (the default) SHM clientsone shard ring per worker;worker w runs shard w inline Socket clientsTCP or Unix socket, readby the chi-client-recv thread Other runtimesTCP, read by thechi-peer-recv thread GPU kernelsone ring per GPU, polledby the GPU worker Worker lanes: one TaskLane per workerring of Future<Task>; any thread pushes, only its worker pops; runtime.queue_depth 1024 Worker 0 · schedulerruns handlers (pool member)flushes collective batchesGPU worker below 5 threads Worker 1 · generalruns handlers (pool member)pool grows by a worker whennone has 100 µs of room Worker 2 · net sendSend periodic, every 25 µs:SendIn, SendOut to peers,latency lanes before I/O Worker 3 · net recvClientSend periodic:replies to socket clients Monitor threadevery 100 ms; a worker inone task over 1 s gets areplacement; its lane moves Net queue · 6 lanesSendIn, SendOut × latency (< 4 KiB) or I/O (≥ 4 KiB); ClientSend TCP, ClientSend IPCfilled by RouteGlobal and by EndTask of a task from another nodenever blocks a producer: a full lane spills to an overflow list Inside every workerone pass of its loop, left to right; it sleeps when a pass finds nothing SHM shardclient requests,routed and runinline, up to 256per pass Event queuefinished subtasks;each resumes theparent coroutinethat awaits it Lanenew tasks; each isrouted, then runhere or pushed toanother lane GPU ringstasks submittedby kernels; onlythe GPU workerhas any Parked queuesperiodic, by period:≤ 50 µs, ≤ 200 µs,≤ 50 ms, longer;retry: 1 pass in 32 A handler that co_awaits a subtask records the future it waits on and returns to the loop. It sits in no queue. The subtask's EndTask puts that future on this worker's event queue and wakes it; the next pass resumes the parent. co_await yield(t), with t > 0, parks the task in the periodic queue for t, so other tasks run in the meantime. A task in memory header: pool_id_, task_id_, pool_query_, method_,task_flags_; then the method's IN and OUT fieldsfut_.is_complete_: the flag its waiter pollsrun_ctx_ (runtime side only): coroutine, container,lane, event queue, awaited future, predicted cost A container (one per pool per node) the module's state; Run(method, task) startsthat method's handler coroutinea learned cost model per method, saved between runsplus one static container per pool with no state,used for ScheduleTask and (de)serializing tasks
With the default four threads, workers 0 and 1 run handlers and workers 2 and 3 serve the network; messages from other nodes and socket clients are read by two dedicated threads. Every worker owns one lane and loops over it together with its own shard, event queue and parked queues. A coroutine waiting on a subtask holds no thread and occupies no queue: the subtask's completion event brings it back.

Workers, coroutines and the scheduler

Each worker loops over its shared-memory shard, its event queue (completions of subtasks its handlers await), its lane, its GPU rings, and its periodic and retry queues. Running a task means resuming its handler coroutine until it finishes or suspends. Handlers are C++20 stackless coroutines; with CLIO_CORE_ENABLE_BOOST_COROUTINES they are Boost.Context fibers behind the same macros, which allows suspending from nested ordinary functions at the price of a stack per task.

Roles are fixed by position. Worker 0 is the scheduler worker. With three or more threads the last two are the network send worker, which drains the outbound network queue, and the network receive worker, which writes replies to socket clients. Messages from other runtimes and from socket clients are read by two dedicated threads that are not workers, so send-side back-pressure never stops incoming replies and probes from draining. A GPU worker is carved out before the network pair when there are five or more threads, and otherwise shares the scheduler worker. The rest are general workers.

The scheduler is an object behind a small interface, chosen by runtime.local_sched. The default one predicts how long each task will hold a worker, using a per-method linear model that each container learns from measured run times and that the pool manager saves to disk between runs. It keeps each worker below about 100 µs of booked work: a task stays on the submitting worker when it fits, otherwise it goes to the least-loaded worker, and when nothing fits the pool grows by one thread. Every 100 ms the monitor thread treats a worker stuck in one task for over a second as stalled, starts a replacement and moves its backlog, lets idle workers steal, and retires idle extra threads. The local scheduler maps tasks by a hash of the submitting process and thread and never rebalances. Write a scheduler describes the interface.

Pools, containers and routing

A pool has one container per node, and the container id is the node id. When a task is routed, its PoolQuery selects containers: the local one, one by id or hash, a range, all of them, a physical node, or a collective. Tasks for this node go to a worker lane; tasks for another node go to the network send worker. A module that holds data receives Expand when a node joins, so it can re-partition, and Recover when a container is rebuilt on another node.

Collectives. A ManyToOne or AllToOne query sends each submitter's task to a leader, where the batch manager parks it, grouped by pool, method, target and batch key. When the batch window closes, it builds one aggregate task by folding each member's inputs in through the container's AggregateIn, runs it once, and copies the output back into every member. A thousand ranks asking for the same thing cost one execution.

A task's trip to another node and back

NODE 0 · the PutBlob arrives here NODE 1 PoolInfo for pool 512.0 (CTE core)containers_ on this node: 0address_map_: container 0 → node 0, 1 → node 1static container: ScheduleTask, (de)serialize PoolInfo for pool 512.0 (CTE core)containers_ on this node: 1address_map_: the same table on every nodestatic container: ScheduleTask, (de)serialize 1 · RouteTask on the worker that took itDynamic → the static container's ScheduleTaskreturns DirectHash(BlobHash(tag, blob name))container hash % 2 = 1 is remote → DirectId(1) 2 · RouteGlobalonto the net queue's SendIn lane (I/O if ≥ 4 KiB)the task is marked routed; the worker moves on 3 · SendIn on the net send workersend_map_[origin] = task; one copy per targetnode; inputs serialized and sent to node 1 Meanwhile, the submitter waitsa client polls its future; a handler's coroutineis suspended and holds no worker 7 · RecvOut on the chi-peer-recv threadoutputs loaded into the copy, folded into the originorigin completes: reply to client, or wake the parent A task that arrives from another node is alreadymarked routed, so RouteTask runs it on this nodewithout resolving its query again. Every resolvedquery carries ret_node, the node to answer. 4 · RecvIn on the chi-peer-recv threadinputs loaded; flagged TASK_REMOTE and routed;kept in recv_map_; pushed to a worker's lane 5 · A worker runs PutBlob on container 1EndTask sees TASK_REMOTE and puts the task onthe net queue's SendOut lane (latency if < 4 KiB) 6 · SendOut on the net send workeroutputs serialized and sent to ret_node 0;the recv_map_ entry is dropped HOW EACH POOLQUERY RESOLVES (ResolvePoolQuery, on the node that routes the task) Localthis node's container; the scheduler picks a worker lane, often the caller's own DirectHash(h)container h % num_containers: Local if it lives here, otherwise DirectId of that container DirectId(c)Local if container c is here, otherwise Physical(the node address_map_ gives for c) Range, Broadcastone query per container; Broadcast is Range(0, num_containers) Dynamicthe pool's ScheduleTask picks a mode (admin create: Local if the pool exists, else Broadcast) ManyToOne, AllToOnesent to the neighborhood leader, where the batch manager merges matching tasks
A client's PutBlob is sent with PoolQuery::Dynamic(). On node 0 the CTE's ScheduleTask turns it into a hash of the blob's tag and name, which names container 1 on node 1, so the task goes to the network queue instead of a worker lane. Node 1 runs it like any local task and sends only the outputs back, where they are folded into the waiting origin task.

What persists

  • The restart log is an append-only log of the compose files that should be re-composed at the next clio-run start. Pools created with restart: true are recorded the same way. --fresh discards it.
  • Cost models are saved per module, pool, node and container, flushed about once a second while they change and on shutdown, and restored when the container is recreated, so a restarted runtime schedules well from the first task.
  • Module state is the module's own business: the CTE keeps its metadata log, a block device its allocation log. A container's recovery callback is where it reloads them.

The dashboard

The viz server answers built-in routes such as /api/health, /api/topology, /api/pools, /api/config, /api/chimods and /api/routes (the list of every registered route). Module routes and asset directories are added at load time. Handlers run on the server's own threads, not on workers, so a slow page never delays a task; they may submit a task and wait for it.

Costs of this design

DecisionBuysCosts
Everything is a moduleOne mechanism for built-in and custom codeA new library needs a runtime restart to be found; online code swap is not yet enabled
Serialized tasks at process boundariesCrash isolation between clients and runtimeInputs and outputs are copied once per crossing
Cooperative coroutinesThousands of waiting tasks on a few threadsA handler that blocks without yielding holds its worker until the monitor rescues the queue behind it
Learned hold-time schedulingFew threads, low latency, no manual classesPredictions are only as good as a module's reported task size
Fixed network workersReceives never wait behind sendsTwo workers and two receive threads per node reserved for networking

The Runtime and block devices design page discusses failure detection, membership and the block-device allocator in more depth.