22. The router

Why this layer exists

A llama-server process serves the model it was started with. An agent stack uses several: chapter 28 routes by role, with a primary model, a fallback, delegated subagents, an auxiliary model for small jobs and a vision model, and each can be a different set of weights. Memory holds only so many of them at once. Something has to decide which models are resident, start and stop their servers, and send each request to the one that serves the model it names. Without that layer every client has to know which port serves which model and whether it is loaded, and a request for a model that is not loaded fails.

The reader’s fleet already runs such a layer: llama-server in router mode. On straylight, the systemd unit starts it with --models-preset (a models.ini catalog), --models-max 3 and --metrics, with no model of its own. Its /props (read 2026-09-30 20:40 PDT, a request that names no model) reports build b10964-b29c606, role router, max_instances 3 and models_autoload true; dixie’s reports the same build and max_instances 2. This chapter builds aec-router, a Go program with the same interface: it reads the same models.ini, routes POST requests by the body’s model and GET requests by ?model=, starts one llama-server child per loaded model, evicts the least recently used idle model when it needs room, and loads a model on demand unless told not to. Every statement about llama.cpp in this chapter is as of llama.cpp b29c606 (2026-09-14), the build both routers run. In the finished system, chapter 51’s module runs aec-router beside aecd in its VM test and on any host without a router of its own (straylight and dixie keep llama.cpp’s), and Part IV’s client (chapter 24) addresses either router by model id, like any OpenAI-compatible endpoint.

straylight’s preset records why a count of models is not enough. A comment above its disabled Laguna section reads: “DISABLED 2026-09-19: resident beside Ornith 35B it left ~15 GB free, and a third model load then hit the 104 GiB TTM cap and OOM-killed the desktop session.” --models-max 3 was satisfied; memory was not. A limit on the number of models does not bound their bytes, because one model can be four times the size of another. aec-router therefore adds a memory budget: before it loads a model it estimates, from the model’s GGUF header, the bytes the loaded model will hold, and it evicts until both the count and the bytes fit. That is its one addition to llama.cpp’s design. Its other departures are smaller. Two are forced by running stock llama-server binaries, health checks over HTTP and the way children die with their parent, and the Mechanism says why. The rest are choices about the router’s own endpoints, how /models/load and /models/unload answer and which refusals are 400 and which 503, and the Walkthrough states each where it arises.

Mechanism

Budgeting memory

Chapter 14 split a model’s cost in two: memory must hold the total parameters, and a decoding step reads only the active ones. A router needs the first as a number of bytes per model, before the model is loaded, from what it can read cheaply. A GGUF file’s header (chapter 14) holds the metadata and the tensor directory at the front of the file: the largest among the 26 GGUF files on straylight, scanned on 2026-09-30, is 15.8 MB, in front of model files such as straylight’s three local ones, of 15.9 to 21.2 GB. The estimate is built from that header, from the options in the model’s preset section, and from nothing else.

Weights. Every tensor in the file is resident, every expert included, because the next token may route to any expert (chapter 11). The header does not give each tensor’s size in bytes. It gives the tensor’s type and dimensions, from which the size follows only with a table of ggml’s block formats, and the offset of its data within the data section. The offsets are enough. GGUF places each tensor’s data at an offset that is a multiple of the alignment aa (general.alignment, default 32), padding between tensors with zeros, and the data section ends at the end of the file. Sort the tensors by offset, o(1)<o(2)<⋯<o(T)o_{(1)} < o_{(2)} < \cdots < o_{(T)}, and let o(T+1)o_{(T+1)} be the data section’s length, the file size less the offset at which the data begins. Tensor (i)(i) occupies [o(i),o(i+1))[o_{(i)}, o_{(i+1)}), so take its size to be

b(i)=o(i+1)−o(i). b_{(i)} = o_{(i+1)} - o_{(i)} .

If its true size is s(i)s_{(i)}, the next tensor starts at the first multiple of aa at or after o(i)+s(i)o_{(i)} + s_{(i)}, so o(i+1)−o(i)−s(i)o_{(i+1)} - o_{(i)} - s_{(i)} is the padding, between 00 and a−1a - 1. Each b(i)b_{(i)} overstates its tensor by at most a−1a - 1 bytes, and the sum W=∑ib(i)W = \sum_i b_{(i)} is the data section’s length exactly, overstating the tensors by at most T(a−1)T(a - 1). For straylight’s ornith-1.5-35b-a3b file (the header of straylight’s file, read on talos, 2026-09-30): 753 tensors, the data at offset 10,990,848 of a 21,713,463,040-byte file, so W=21,713,463,040−10,990,848=21,702,472,192W = 21{,}713{,}463{,}040 - 10{,}990{,}848 = 21{,}702{,}472{,}192 bytes, at most 753×31=23,343753 \times 31 = 23{,}343 of them padding.

Active bytes. Chapter 14 wrote the weights a token is multiplied by as Nactive=Ns+LmneN_{\text{active}} = N_s + L m n_e: the shared weights, plus mm of the EE experts in each of LL MoE layers. In bytes, let WeW_e be the bytes of the expert tensors (the _exps tensors, each of which stacks one layer’s EE experts of equal size). A token reads mm of each layer’s EE equal parts, so it reads Wem/EW_e\, m / E of them. Two tensors outside the experts are not read whole. The token embedding token_embd, of bembdb_{\text{embd}} bytes, is a lookup: a step reads one row of it, r=bembd/nvocabr = b_{\text{embd}} / n_{\text{vocab}}, unless the model has no separate output.weight, in which case the output head is tied to the embedding and multiplies by all of it, so r=bembdr = b_{\text{embd}}. And the multi-token-prediction blocks (below) are resident but not run by a step of the main model. With SS the bytes of every other tensor of the trunk,

A=S+r+WemE. A = S + r + W_e \frac{m}{E} .

For ornith (E=256E = 256, m=8m = 8; the same header, read on talos, 2026-09-30): S=1,366,190,592S = 1{,}366{,}190{,}592 (the output head’s 417,177,600 among them), token_embd is 286,064,640 bytes over 248,320 rows so r=1,152r = 1{,}152, and We=19,503,513,600W_e = 19{,}503{,}513{,}600, giving

A=1,366,190,592+1,152+19,503,513,600×8256=1,366,190,592+1,152+609,484,800=1,975,676,544, A = 1{,}366{,}190{,}592 + 1{,}152 + 19{,}503{,}513{,}600 \times \frac{8}{256} = 1{,}366{,}190{,}592 + 1{,}152 + 609{,}484{,}800 = 1{,}975{,}676{,}544 ,

9.1% of WW. Left out are the other 286,063,488 bytes of token_embd and the 546,703,360-byte MTP block (522,190,848 of them its own experts). AA bounds decoding by chapter 14’s tokens/s≤R/A\text{tokens/s} \le R / A, a property of the model that matters to whoever chooses a model for a role, such as chapter 28’s routing, and aec-router reports it. It is not a cost of residency, since the bytes not read in a step still occupy memory, and the budget never charges it.

The KV cache per position. A full-attention layer ll with hlh_l KV heads of widths dkd_k and dvd_v stores, per cached position, one key of hldkh_l d_k numbers and one value of hldvh_l d_v. With βk\beta_k and βv\beta_v bytes per number for the cache types (cache-type-k, cache-type-v), a cache of CC cells holds

C(hldkβk+hldvβv) C\,(h_l d_k \beta_k + h_l d_v \beta_v)

bytes for that layer. β\beta is 2 for f16. The block formats store numbers in groups of 32 with a scale: q8_0 is 32 signed bytes and one f16 scale, 34 bytes per 32 numbers, so β=34/32=1.0625\beta = 34/32 = 1.0625; q4_0 is 16 bytes of 4-bit numbers and the scale, β=18/32\beta = 18/32. Ornith has 10 full-attention layers, each with h=2h = 2 and dk=dv=256d_k = d_v = 256, so a position costs

10×2×(256+256)×2=20,480 10 \times 2 \times (256 + 256) \times 2 = 20{,}480

bytes at f16, chapter 14’s figure, and 10×2×512×1.0625=10,88010 \times 2 \times 512 \times 1.0625 = 10{,}880 bytes at q8_0.

Cells. llama.cpp sizes the cache from ctx-size, not from the requests it will serve. It rounds the context up to a multiple of 256 (src/llama-context.cpp, lines 288–301), n=pad256(ctx-size)n = \mathrm{pad}_{256}(\text{ctx-size}) with pad256(x)=256⌈x/256⌉\mathrm{pad}_{256}(x) = 256 \lceil x / 256 \rceil. With kv-unified the cache is one stream of nn cells that all PP slots (parallel) share. Without it, each slot has a stream of its own of pad256(⌊n/P⌋)\mathrm{pad}_{256}(\lfloor n / P \rfloor) cells. Either way the total is nn cells, give or take the second rounding, so the cache is set by ctx-size and PP only divides it; chapter 19’s slots split one budget of positions, they do not multiply it. straylight’s preset says the same in a comment: “llama.cpp splits ctx-size across parallel slots: 262144 / 2 = 131072 per slot.” When parallel is left out, llama-server chooses 4 slots and forces a unified cache. When ctx-size is left out, it uses the model’s training context, or, with kv-unified-per-slot NN, a pool of PNP N positions (tools/server/server.cpp, lines 160–169); the estimate does the same.

Sliding windows. A sliding-window layer attends only to the last ww positions of its sequence, so it needs no more than those, plus room for the micro-batch uu being written past them: ubatch-size, 512 by default, capped by batch-size, 2,048 by default (src/llama-context.cpp, lines 245–247). llama.cpp gives the sliding layers their own cache (src/llama-kv-cache-iswa.cpp, line 73):

uint32_t size_swa = GGML_PAD(std::min(size_base, hparams.n_swa*(unified ? n_seq_max : 1) + n_ubatch), 256);

Per stream, a sliding layer holds pad256(min(c,wP+u))\mathrm{pad}_{256}(\min(c, wP + u)) cells in a unified cache, where one stream serves PP sequences, and pad256(min(c,w+u))\mathrm{pad}_{256}(\min(c, w + u)) in each of the PP streams of a per-slot cache, with cc the stream’s cells; swa-full turns this off and gives sliding layers the full stream. Which layers slide is in the header: {arch}.attention.sliding_window_pattern is either an array of 0s and 1s per layer or a period pp, meaning llama.cpp’s set_swa_pattern(p), under which layer ii slides when imodp<p−1i \bmod p < p - 1.

straylight’s gemma4-26b-a4b file (header of straylight’s file, read on talos, 2026-09-30) has 30 layers and a pattern array marking 25 of them as sliding, with window w=1,024w = 1{,}024. Its full layers have 2 KV heads of width 512, its sliding layers 8 heads of width 256 (key_length_swa). At straylight’s [*] settings (ctx-size 262,144, parallel 2, no kv-unified, q8_0), each of the 2 streams has pad256(131,072)=131,072\mathrm{pad}_{256}(131{,}072) = 131{,}072 cells, and a sliding layer holds pad256(min(131,072,1,024+512))=1,536\mathrm{pad}_{256}(\min(131{,}072, 1{,}024 + 512)) = 1{,}536 per stream, 3,072 in all. The cache is

5×262,144×2×1,024×1.0625+25×3,072×8×512×1.0625=2,852,126,720+334,233,600=3,186,360,320 5 \times 262{,}144 \times 2 \times 1{,}024 \times 1.0625 + 25 \times 3{,}072 \times 8 \times 512 \times 1.0625 = 2{,}852{,}126{,}720 + 334{,}233{,}600 = 3{,}186{,}360{,}320

bytes, 2.97 GiB. An estimator that did not read the pattern would size all 30 layers as full layers, with the full layers’ width of 512: 25×262,144×8×1,024×1.0625+2,852,126,720=59,894,661,12025 \times 262{,}144 \times 8 \times 1{,}024 \times 1.0625 + 2{,}852{,}126{,}720 = 59{,}894{,}661{,}120 bytes, 55.78 GiB, 18.8 times too much. A header-only estimator has to know the architecture’s layer map, and where the header leaves part of it to code, the estimate is wrong. aec-router errs large there, by taking every attention layer to be full when no pattern key is present. Exercise (d) shows that this is what happens with straylight’s trinity-mini.

Recurrent state. Chapter 15’s Mamba-family layers keep, per sequence, a convolution state and an SSM state whose sizes do not depend on the context. llama.cpp sizes them per layer (llama_hparams::n_embd_r and n_embd_s in src/llama-hparams.cpp) as (k−1)(dinner+2gdstate)(k - 1)(d_{\text{inner}} + 2 g\, d_{\text{state}}) and dstatedinnerd_{\text{state}}\, d_{\text{inner}} f32 numbers, where kk is the convolution kernel and gg the number of groups: the convolution keeps the last k−1k - 1 inputs of its dinnerd_{\text{inner}} value channels and its 2gdstate2 g\, d_{\text{state}} B and C channels. For ornith, k=4k = 4, dinner=4,096d_{\text{inner}} = 4{,}096, dstate=128d_{\text{state}} = 128, g=16g = 16:

3(4,096+2⋅16⋅128)+128⋅4,096=24,576+524,288=548,864 3\,(4{,}096 + 2 \cdot 16 \cdot 128) + 128 \cdot 4{,}096 = 24{,}576 + 524{,}288 = 548{,}864

numbers per layer. These are chapter 15’s two figures, its 96 KiB and 2 MiB. Over 30 recurrent layers at 4 bytes this is 548,864×30×4=65,863,680548{,}864 \times 30 \times 4 = 65{,}863{,}680 bytes, 62.8 MiB, per slot, and chapter 15’s “a slot’s memory is known in advance” is this product. The state is allocated for every slot, PP rows per layer. With speculative decoding by a draft that can be rolled back (spec-type draft-mtp, draft-eagle3, draft-dflash or draft-dspark), an architecture that supports rolling its state back keeps spec-draft-n-max extra rows per slot, P(1+D)P(1 + D) in all with DD drafts (llm_arch_supports_rs_rollback in src/llama-arch.cpp).

The MTP layer. Ornith’s header says block_count 41 and nextn_predict_layers 1. The last block is a multi-token-prediction head, which drafts tokens for speculative decoding, and llama.cpp’s layer count for the main model excludes it (src/llama-hparams.cpp, line 348):

    return n_layer_all - n_layer_nextn;

The hybrid cache’s filter for ornith’s architecture admits only the layers below that count (src/llama-model.cpp, lines 2552–2554):

                        filter_attn = [&](uint32_t il) {
                            return il < hparams.n_layer() && !hparams.is_recr(il);
                        };

so the main context gives block 40 neither a cache nor a state. This settles chapter 15’s parenthesis about the multi-token-prediction layer: its weights are resident and counted in WW, and it adds nothing to the main context’s cache. When a draft-MTP context runs it, that context has a cache of its own, which the next paragraph’s exclusions name.

The host prompt cache. llama-server keeps evicted conversations’ KV state in host memory, up to cache-ram MiB, 8,192 by default (common/common.h), and the limit is per child: straylight’s preset says, above cache-ram = 2048 in [*], “This limit is PER RESIDENT MODEL, not global”. straylight’s memory is unified, 125 GiB shared by the CPU and GPU, so the host cache and the GPU’s buffers come out of one pool, the pool that ran out on 2026-09-19. aec-router charges each model its cache-ram at the limit. The cache fills to the limit under a long-running agent load, and an estimate that counts less invites the same OOM.

The footprint. Adding the parts, with SrecS_{\text{rec}} the recurrent state per layer per sequence and LrecL_{\text{rec}} the recurrent layers:

F=W+KV+4P(1+D)LrecSrec+Cram. F = W + \mathrm{KV} + 4\,P\,(1 + D)\,L_{\text{rec}}\,S_{\text{rec}} + C_{\text{ram}} .

At straylight’s settings for ornith-1.5-35b-a3b (ctx-size 262,144, parallel 4, kv-unified, q8_0, cache-ram 16,384, no draft), from its header (read on talos, 2026-09-30): KV 262,144×10,880=2,852,126,720262{,}144 \times 10{,}880 = 2{,}852{,}126{,}720 bytes (2.66 GiB), state 4×65,863,680=263,454,7204 \times 65{,}863{,}680 = 263{,}454{,}720 (251.25 MiB), weights 21,702,472,192 and the host cache 16,384×220=17,179,869,18416{,}384 \times 2^{20} = 17{,}179{,}869{,}184, for a total of 41,997,922,816 bytes, 39.11 GiB. Without the host cache, the parts that live on the GPU side come to 24,818,053,632 bytes, 23.11 GiB. The preset’s comment on the same section estimates “this model ~26” GiB, by hand, “before any cache at all”. The difference is what the header cannot show: the projector hf-repo downloads beside the model, and the compute buffers. The estimate’s doc comment, in the ch22-footprint listing below, names what it leaves out by design: compute buffers, context checkpoints (up to 32 per slot), the KV cache of a draft model’s own context (an MTP, EAGLE3, DFlash or DSpark draft), and llama-server’s fitting, which may shrink a context the preset leaves unset, so that the estimate is then high. A budget set to the machine’s limit has no headroom for those, so set it below the limit: a budget is a ceiling on the estimates, not on the process’s resident memory.

Some architectures keep memory this model cannot size from a header. RWKV’s token-shift and WKV state, LFM2’s short convolution, the KDA and lightning-attention states, falcon-h1’s attention and recurrent state in every layer, and the indexer and compressed caches of qwen4exp, deepseek4 and minimax-m3 all differ from the Mamba-family state, and graniteswitch adds an attention layer beyond block_count. An estimate that missed them would be low, which a budget must never be, so the estimator refuses all fifteen architectures, by name, with what it would miss (the unmodelled table in the ch22-shape listing below): gguf: cannot estimate architecture minimax-01: the memory model leaves out lightning-attention state (head_dim^2 per head), with no ssm keys in its header. Under a budget such a model is refused; without one, it loads unbudgeted.

aec-router -footprints prints every model’s estimate and starts nothing. Run on straylight against its own preset on 2026-09-30 at 20:37 PDT, reading the GGUF headers from disk and touching no service, it printed:

2026/09/30 20:37:49 qwen3.6-35b-a3b-abliterated: 24.48 GiB resident (weights 19.70, KV 2.66, state 0.123, cache-ram 2.00), 1.84 GiB read per token
2026/09/30 20:37:49 gemma4-26b-a4b-abliterated: 20.83 GiB resident (weights 15.86, KV 2.97, state 0.000, cache-ram 2.00), 2.42 GiB read per token
2026/09/30 20:37:49 trinity-mini: 25.33 GiB resident (weights 14.83, KV 8.50, state 0.000, cache-ram 2.00), 1.91 GiB read per token
2026/09/30 20:37:49 ornith-1.0-35b: size unknown: [ornith-1.0-35b]: no local model file to read
2026/09/30 20:37:49 ornith-1.5-9b-uncensored: size unknown: [ornith-1.5-9b-uncensored]: no local model file to read
2026/09/30 20:37:49 qwen3-vl-8b-abliterated: size unknown: [qwen3-vl-8b-abliterated]: no local model file to read
2026/09/30 20:37:49 ornith-1.5-35b-a3b: size unknown: [ornith-1.5-35b-a3b]: no local model file to read
2026/09/30 20:37:49 qwen3.8-27b-uncensored: size unknown: [qwen3.8-27b-uncensored]: no local model file to read
2026/09/30 20:37:49 qwen3.8-flash-next-uncensored: size unknown: [qwen3.8-flash-next-uncensored]: no local model file to read

gemma4’s weights include its 251,937,728-byte MTP draft file (model-draft), and its 2.42 GiB per token includes all 605,552,640 bytes of token_embd, since its head is tied. Its KV is the 2.97 GiB derived above. trinity-mini’s 8.50 GiB is the overestimate exercise (d) takes apart. The six hf-repo entries have no local file the router can read, because llama-server downloads them on first load.

Admission and eviction

With a budget, a model’s footprint must be known before it may load. A catalog entry then needs model = <path> to a local file; for a model fetched by hf-repo, point model at the file in the Hugging Face cache, which is an ordinary readable file. Otherwise the entry is refused with “size unknown”, as six of straylight’s would be.

Let RR be the running set: every model whose child is loading or loaded, and every model asked to stop whose process has not yet exited. A model still exiting holds its memory and its slot until its process is gone, so llama.cpp counts it (stopping_models in server-models.h, line 134) and so does aec-router. A new model may start only if both

∣R∣+1≤Mmaxand∑r∈RFr+Fnew≤B |R| + 1 \le M_{\max} \qquad \text{and} \qquad \sum_{r \in R} F_r + F_{\text{new}} \le B

hold, where MmaxM_{\max} is models-max and BB the budget (either may be 0, meaning no limit). If they do not, the router evicts. A model whose footprint alone exceeds BB can never satisfy the second inequality, so it is refused at once, and nothing is evicted for it. The refusal is 400 with an error that names the budget, as is the refusal of a model whose size is unknown under a budget: both are permanent for the request as sent, and a client that retries 503s, as chapter 24’s does, would spend its whole attempt budget on every such request for nothing. The router’s 503s are kept for what can change, and each carries Retry-After.

The victim is chosen as llama.cpp’s pick_victim chooses it (server-models.cpp, lines 268–288): among loaded models, one with no request in flight, that no queued request wants, and that is not already stopping, the least recently used. Each condition is there because something breaks without it:

  • Idle. A model with a request in flight is in the middle of a stream; stopping it cuts the stream off.
  • Unwanted. Suppose Mmax=1M_{\max} = 1, model aa loaded and idle, and requests for aa and bb queued. Without this condition, bb’s request evicts aa, then aa’s request evicts bb before bb’s request has used it, and so on: two models loading in turn for ever, a livelock. A model that a queued request is waiting for is never a victim.
  • Loaded. A model still loading has no request to finish, but evicting it throws away the load in progress. llama.cpp also passes over a model that is not ready or asleep (is_ready_or_sleep), with the comment “one still coming up has no request to finish”.
  • Not already stopping. Its memory is already on its way back and is counted as freed.

“Recently” is measured by a counter, not wall time. Each use takes the next value of a counter that only the pool advances, so the order is total and deterministic: no two uses tie, as two stamps of llama.cpp’s millisecond clock can. A use is a load, which llama.cpp stamps as use when it starts one (server_models::load, line 1151), and a POST routed to the model (proxy_request updates last_used only when its caller asks, and only proxy_post does, lines 1549–1551). A GET routed by ?model= is not use, so a monitor that reads /props?model=X or /metrics?model=X every few seconds does not renew a running X. That alone does not keep a monitor from holding X resident: with autoload on, a GET for an evicted X loads it again, as llama.cpp’s proxy_get does (lines 1948–1960), and the load counts as use. A monitor must send ?autoload=false, or the router run with --no-models-autoload; then its GET reaches a running model without renewing it, and is refused with 400 “model is not loaded” for one that is not. Exercise (c) works through both.

The optimal policy, from Belady’s 1966 study of replacement algorithms, evicts the item whose next use lies farthest in the future. It needs the future. Least recently used is the practical stand-in when the recent past predicts the near future, and the router assumes an agent’s traffic is of that kind: a loop calls the same model turn after turn.

The queue

llama.cpp loads a model at once when a slot is free and nobody is queued (ensure_model_ready, lines 1449–1453). A request that would need an eviction, or that arrives while others wait, joins a queue instead (join, leave, try_claim and tick, lines 291–386), “else they starve” (line 1455). aec-router keeps these rules but one, and adds the budget. Requests for one model share one entry: five requests for a loading model need one load, not five. A model that fits loads at once, even while another model that waited in the queue is loading; llama.cpp makes it wait, because a model that has claimed a slot keeps its entry at the head of the queue until its requests have left, and only the head may claim (try_claim, lines 321–331). The first model in the queue that does not fit holds back every model behind it, even one that would fit, so a large model is not starved by a stream of small ones. For each model that does not fit, idle models are asked to exit until it would, as llama.cpp’s tick evicts while the queued entries outnumber the free slots. A model with requests waiting for it is never a victim, which keeps a model that has just loaded for waiting requests from being evicted before those requests have used it.

A load can fail: the child exits before it answers /health with 200, or it does not answer in time. llama.cpp tells every request that saw the attempt that the model “failed to load” (ensure_model_ready, line 1494). aec-router numbers the load attempts. A waiting request records the attempt it waits for: the one in progress, if the model is loading, or the next one. When attempt kk fails, every request waiting for attempt kk or an earlier one gets the error. The scheduler does not respawn the model while any of those requests is still in the queue. Without that rule, a model that fails at once would be respawned for the very requests that are being told it failed, and since each respawn fails too, it would loop for as long as they wait. A request that arrives later waits for the next attempt, which is the retry.

An unload interrupts waiting requests from the other side. Unload moves the model to a new epoch and drops the requests waiting for it from the queue: each is told that the model was unloaded, with 503 and Retry-After, and the scheduler does not load the model for them, so an operator’s unload is not undone by the requests it interrupted. A request that arrives afterwards loads it again, as any request for an unloaded model does. llama.cpp gets the same effect another way: it force-kills a loading child (lines 1250–1256), and its waiters, seeing the model unloaded rather than failed, give up with “not running” (lines 1490–1497).

Supervision specific to model servers

Supervising a llama-server differs from supervising an ordinary daemon in three ways. A model takes from seconds to minutes to load, and /health answers 503 with “Loading model” until it is ready (the server README). A 503 at startup is therefore normal, and the load timeout is long: straylight’s unit sets TimeoutStartSec=600 (read with systemctl cat, 2026-09-30), and aec-router allows 10 minutes. A hung GPU driver or a wedged kernel leaves a process that is alive and a server that does not answer, so waiting on the process is not enough: the router keeps polling /health after the load, and kills a child that fails a few checks in a row. And a child holds tens of GiB of GPU memory, so a child that outlives its router is a leak the next load runs into.

llama.cpp’s router and its children are two modes of one binary, and they talk over pipes (server-models.cpp, lines 44–45):

#define CMD_ROUTER_TO_CHILD_EXIT  "cmd_router_to_child:exit"
#define CMD_CHILD_TO_ROUTER_STATE "cmd_child_to_router:state:" // followed by json string

A child reports its state (loaded, sleeping and so on) as a line on stdout starting with cmd_child_to_router:state: (line 1793), which the router picks out of the child’s log (line 184). The router asks a child to exit by writing cmd_router_to_child:exit to its stdin. And each child runs a thread that reads stdin until EOF (lines 1757–1781), so a router that dies, closing the pipe, takes its children with it:

        if (eof) {
            SRV_INF("%s", "EOF on stdin detected, forcing shutdown...\n");
            exit(1);
        }

A stock llama-server started with a model speaks none of this; it enters child mode only when the router starts it so. aec-router uses what the stock binary offers: it polls GET /health (503 while loading, 200 when ready), stops a child with SIGTERM, on which llama-server shuts down cleanly, then SIGKILL after the preset’s stop-timeout (default 10 s, llama.cpp’s DEFAULT_STOP_TIMEOUT), and on Linux starts each child with Pdeathsig set to SIGKILL, so that the kernel kills the child when the router dies.

Each choice has a cost. Polling sees a state change up to one interval late (1 s by default, visible in the Walkthrough’s log), and it cannot see that a child has gone to sleep under --sleep-idle-seconds. llama.cpp’s router knows (SLEEPING arrives over stdout), and it still counts a sleeping child as running (is_running, server-models.h, lines 94–96), so the count is the same in both routers. Pdeathsig is Linux-only, is tied to the thread that forked the child rather than the process, and is cleared when the child executes a set-user-ID binary or one with file capabilities (prctl(2)). The stdin protocol works everywhere but needs the child’s cooperation, which only the same binary in child mode provides.

Walkthrough

The package is go/internal/router: the catalog, the GGUF reader, the memory model, the pool and the HTTP handler. go/internal/router/fakellama is a stand-in for llama-server used by the tests, and go/cmd/aec-router is the program.

The catalog

--models-preset takes an INI file. ParsePreset follows llama.cpp’s grammar (common/preset.cpp): comments start with ; or # anywhere on a line, so a value ends at the first of them, keys must match the grammar’s identifier rule (keyRE), version is skipped, and a repeated key keeps its last value (setOption).

// ParsePreset reads llama-server's --models-preset format as llama.cpp's INI
// grammar does: [name] headers, key = value lines, and comments that start
// with ; or # anywhere, so a value ends at the first ; or #. A version key is
// skipped wherever it appears; a repeated key in one section keeps its last
// value.
func ParsePreset(r io.Reader) (*Preset, error) {
    p := &Preset{}
    var cur *[]Option // the option list the next key = value goes to
    sc := bufio.NewScanner(r)
    for n := 1; sc.Scan(); n++ {
        line := strings.TrimSpace(sc.Text())
        if !strings.HasPrefix(line, "[") { // a section name may hold ; or #
            line, _, _ = strings.Cut(line, ";")
            line, _, _ = strings.Cut(line, "#")
            line = strings.TrimSpace(line)
        }
        switch {
        case line == "":
            continue
        case line[0] == '[':
            name, rest, ok := strings.Cut(line[1:], "]")
            name, rest = strings.TrimSpace(name), strings.TrimSpace(rest)
            if !ok || name == "" || rest != "" && rest[0] != ';' && rest[0] != '#' {
                return nil, fmt.Errorf("preset line %d: bad section header %q", n, line)
            }
            if name == "*" {
                cur = &p.Global
                continue
            }
            for _, s := range p.Sections {
                if s.Name == name {
                    return nil, fmt.Errorf("preset line %d: duplicate section [%s]", n, name)
                }
            }
            p.Sections = append(p.Sections, Section{Name: name})
            cur = &p.Sections[len(p.Sections)-1].Options
        default:
            key, value, ok := strings.Cut(line, "=")
            key, value = strings.TrimSpace(key), strings.TrimSpace(value)
            if !ok || !keyRE.MatchString(key) {
                return nil, fmt.Errorf("preset line %d: want key = value, got %q", n, line)
            }
            if key == "version" {
                continue // reserved by llama.cpp
            }
            if cur == nil {
                return nil, fmt.Errorf("preset line %d: %q outside a section", n, key)
            }
            *cur = setOption(*cur, key, value)
        }
    }
    return p, sc.Err()
}

Models’ doc comment gives its rules; three things it does not say. Before a section’s options override [*], each key is brought to its canonical long form by canonical: short spellings and environment names (c, LLAMA_ARG_CTX_SIZE) become the long key (ctx-size) through the aliases table, and a negated key with a boolean value (no-mmap = true) becomes the positive key with the value inverted. Where two spellings of one option appear in one section, merge keeps the one whose key sorts last, because llama.cpp reads a section’s keys in sorted order. And the names are llama.cpp’s: reserved is what its unset_reserved_args removes, the rendering of true and false is its common_preset::to_args, with the 23 flags it cannot negate in flagOnly, and truthy and falsey are its words for booleans: on, enabled, true, 1 and their opposites.

// Models turns the preset into catalog entries. Each section's options
// override [*] option by option; the router keeps load-on-startup,
// stop-timeout and dedup-cache-models for itself, sets host, port and alias
// per child, and drops the router's own options (models-max, api-key and the
// like). The preset's alias, a comma-separated list, gives the model other
// names that requests may use; its tags are listed and passed to the child
// but never routed by. A name or alias that collides with an earlier model's
// is an error, as in llama.cpp's server_models::add_model. A value of true
// renders as --key and false as --no-key, or as nothing for a flag
// llama-server cannot negate (swa-full, metrics, no-host and the rest of
// flagOnly), as llama.cpp does. So a flag must be written true or false, and
// every key other than the ones the router reads (ctx-size, parallel, the
// cache types, kv-unified, swa-full, cache-ram, spec-type, spec-draft-n-max,
// batch-size, ubatch-size, kv-unified-per-slot and the model files) must be
// the long option name.
func (p *Preset) Models() ([]Model, error) {
    var out []Model
    for _, s := range p.Sections {
        m := Model{Name: s.Name, StopTimeout: DefaultStopTimeout}
        merged := merge(merge(nil, p.Global), s.Options)
        for _, o := range merged {
            switch {
            case o.Key == "alias":
                m.Aliases = splitList(o.Value)
            case o.Key == "tags":
                m.Tags = splitList(o.Value)
                m.Args = append(m.Args, "--tags", o.Value)
            case o.Key == "load-on-startup":
                if !truthy(o.Value) && !falsey(o.Value) {
                    return nil, fmt.Errorf("[%s] load-on-startup: want true or false, got %q", s.Name, o.Value)
                }
                m.LoadOnStartup = truthy(o.Value)
            case o.Key == "stop-timeout":
                secs, err := strconv.Atoi(o.Value)
                if err != nil || secs < 0 {
                    return nil, fmt.Errorf("[%s] stop-timeout: want seconds, got %q", s.Name, o.Value)
                }
                m.StopTimeout = time.Duration(secs) * time.Second
            case routerOnly[o.Key] || controlled[o.Key] || reserved[o.Key]:
                // not the child's to see
            case flagOnly[o.Key]:
                if !falsey(o.Value) {
                    m.Args = append(m.Args, "--"+o.Key)
                }
            case o.Value == "true":
                m.Args = append(m.Args, "--"+o.Key)
            case o.Value == "false":
                m.Args = append(m.Args, "--no-"+o.Key)
            default:
                m.Args = append(m.Args, "--"+o.Key, o.Value)
            }
            if !routerOnly[o.Key] && !controlled[o.Key] && !reserved[o.Key] {
                m.Options = append(m.Options, o)
            }
        }
        if _, ok := m.Option("model"); !ok {
            if _, ok := m.Option("hf-repo"); !ok {
                return nil, fmt.Errorf("[%s] needs model or hf-repo", s.Name)
            }
        }
        for _, prev := range out {
            if slices.Contains(prev.Aliases, m.Name) {
                return nil, fmt.Errorf("model name %q conflicts with alias of model %q", m.Name, prev.Name)
            }
            for _, a := range m.Aliases {
                if a == prev.Name {
                    return nil, fmt.Errorf("alias %q for model %q conflicts with existing model name", a, m.Name)
                }
                if slices.Contains(prev.Aliases, a) {
                    return nil, fmt.Errorf("alias %q for model %q conflicts with alias of model %q", a, m.Name, prev.Name)
                }
            }
        }
        out = append(out, m)
    }
    return out, nil
}

straylight’s live preset meets the doc comment’s restriction, and TestLivePresetRendersOnlyAcceptedOptions renders every model in it to arguments that llama-server b29c606 accepts. hf-repo passes through to the child, which then downloads the model itself, as chapter 16 found update_args does.

Aliases and tags follow llama.cpp’s server_models::add_model (server-models.cpp, lines 605–660). A section’s alias is a comma-separated list of other names a request may use for the model; splitList splits it, strips each name and drops empty ones, as llama.cpp does, and keeps them sorted, as its std::set does. A model’s name may not equal an earlier model’s alias, and an alias may not equal an earlier model’s name or alias; each collision is an error with llama.cpp’s wording. A request that names an alias is served by the model, as llama.cpp’s get_meta resolves it (lines 1038–1056) for routing, /models/load and /models/unload. The child’s own --alias is always the section name (update_args, lines 527–543). tags are listed in /v1/models and passed to the child, where they are informational (“not used for routing”, says the option’s help in common/arg.cpp); aec-router never routes by them. straylight’s and dixie’s /v1/models (read 2026-09-30 20:40 PDT) carry aliases and tags for every model, all empty.

The header and the shape

ReadHeader parses a GGUF header from a reader that may hold only a prefix of the file, given the file’s size. Its decoder (d.u32, d.u64, d.str, d.value) remembers the first error and returns zero values after it, so the parse reads straight through and checks once. The bounds at the top keep a damaged or hostile file from claiming a gigabyte-long string or a billion-entry array. The tensor sizes come from sorted offsets, as derived above.

// Bounds on what a header may claim, so a damaged or hostile file is an error
// rather than a huge allocation. The largest real values in straylight's 26
// GGUF files (read 2026-09-30, later shards of split models skipped) are a
// 17,336-byte string (Gemma 4's chat template), a 514,906-entry array (Gemma
// 4's tokenizer merges) and about 4 MiB of retained numbers and strings (two
// vocabulary-sized arrays); the bounds leave ample room above all three. ggml
// tensors have at most four dimensions (GGML_MAX_DIMS).
const (
    maxString   = 1 << 20 // bytes in one string
    maxArray    = 1 << 22 // entries in one array
    maxRetained = 1 << 26 // bytes of strings and numbers kept from one header
    maxDims     = 4
    maxAlign    = 1 << 20
)

// ReadHeader parses the GGUF header from r. fileSize is the size of the whole
// file, needed to size the last tensor; r may hold only a prefix of the file,
// as long as the prefix covers the header.
func ReadHeader(r io.Reader, fileSize int64) (*Header, error) {
    d := &decoder{r: bufio.NewReaderSize(r, 1<<20)}
    if magic := d.bytes(4); string(magic) != "GGUF" {
        return nil, fmt.Errorf("gguf: bad magic %q", magic)
    }
    h := &Header{Version: d.u32(), KV: map[string]any{}}
    if d.err == nil && h.Version != 2 && h.Version != 3 {
        return nil, fmt.Errorf("gguf: version %d, want 2 or 3", h.Version)
    }
    nTensors, nKV := d.u64(), d.u64()
    for i := uint64(0); i < nKV && d.err == nil; i++ {
        key := d.str()
        h.KV[key] = d.value(d.u32())
    }
    for i := uint64(0); i < nTensors && d.err == nil; i++ {
        t := Tensor{Name: d.str()}
        nDims := d.u32()
        if nDims > maxDims {
            return nil, fmt.Errorf("gguf: tensor %s has %d dimensions, at most %d allowed", t.Name, nDims, maxDims)
        }
        for j := uint32(0); j < nDims && d.err == nil; j++ {
            t.Dims = append(t.Dims, d.u64())
        }
        t.Type, t.Offset = d.u32(), d.u64()
        h.Tensors = append(h.Tensors, t)
    }
    if d.err != nil {
        return nil, fmt.Errorf("gguf: %w", d.err)
    }
    align := int64(32) // GGUF_DEFAULT_ALIGNMENT
    if a, ok := h.KV["general.alignment"]; ok {
        n, _ := a.(int64)
        if n <= 0 || n > maxAlign || n&(n-1) != 0 {
            return nil, fmt.Errorf("gguf: general.alignment %v is not a power of two up to %d", a, maxAlign)
        }
        align = n
    }
    h.DataOffset = (d.n + align - 1) / align * align
    if fileSize < h.DataOffset {
        return nil, fmt.Errorf("gguf: file of %d bytes is shorter than its header", fileSize)
    }
    // Tensor sizes from offset differences: no table of ggml type sizes needed.
    order := make([]int, len(h.Tensors))
    for i := range order {
        order[i] = i
    }
    sort.Slice(order, func(a, b int) bool { return h.Tensors[order[a]].Offset < h.Tensors[order[b]].Offset })
    end := uint64(fileSize - h.DataOffset)
    for k := len(order) - 1; k >= 0; k-- {
        t := &h.Tensors[order[k]]
        if t.Offset > end {
            return nil, fmt.Errorf("gguf: tensor %s starts past the end of the file", t.Name)
        }
        t.Bytes, end = end-t.Offset, t.Offset
    }
    return h, nil
}

ShapeOf takes the layer map from the evidence its doc comment lists, in that order. swaFlags reads the sliding pattern, blockIndex finds a tensor’s block number so that MTP blocks can be told apart, and Header.Int and Header.Ints read a scalar or a per-layer array. Every product and sum of header values goes through a sizer, which records an overflow or a negative operand, so impossible numbers in a header are an error rather than a wrapped size.

// unmodelled are the architectures whose memory at llama.cpp b29c606 this
// estimator cannot size from the header, with what it would miss. ShapeOf
// refuses them, because an estimate below what llama.cpp allocates is never
// acceptable under a budget. The list is every recurrent and hybrid
// architecture (llm_arch_is_recurrent, llm_arch_is_hybrid in
// src/llama-arch.cpp) whose state is not the Mamba-family size, plus those
// whose cache llama.cpp builds beyond what the header's layers describe.
var unmodelled = map[string]string{
    "rwkv6":         "RWKV token-shift and wkv state",
    "rwkv6qwen2":    "RWKV token-shift and wkv state",
    "rwkv7":         "RWKV token-shift and wkv state",
    "arwkv7":        "RWKV token-shift and wkv state",
    "lfm2":          "short-convolution state",
    "lfm2moe":       "short-convolution state",
    "kimi-linear":   "KDA conv and delta-rule state",
    "kimi-k3":       "KDA conv and delta-rule state",
    "bailingmoe3":   "KDA conv and delta-rule state",
    "minimax-01":    "lightning-attention state (head_dim^2 per head), with no ssm keys in its header",
    "falcon-h1":     "an attention cache and a recurrent state in every layer",
    "qwen4exp":      "the sparse-attention indexer cache and PLE convolution rows",
    "deepseek4":     "its compressed attention cache (llama_kv_cache_dsv4)",
    "minimax-m3":    "its sparse-attention indexer cache (llama_kv_cache_msa)",
    "graniteswitch": "a router attention layer the loader adds beyond block_count",
}

// defaultInterval4 are the architectures whose loader defaults
// full_attention_interval to 4 when the header leaves it out
// (src/models/{qwen35,qwen35moe,qwen3next,qwen4exp}.cpp, load_arch_hparams,
// at b29c606).
var defaultInterval4 = map[string]bool{"qwen35": true, "qwen35moe": true, "qwen3next": true, "qwen4exp": true}

// maxLayers bounds block_count, so a damaged header is an error rather than a
// huge allocation: the deepest model on straylight (2026-09-30) has 65.
const maxLayers = 4096

// ShapeOf reads the layer structure llama.cpp builds from a model's headers
// (every shard; the first holds the metadata). The last nextn_predict_layers
// blocks are multi-token-prediction heads, which the main context gives no
// cache. A trunk layer is recurrent if {arch}.attention.recurrent_layers says
// so; failing that, if it is not every full_attention_interval-th layer (4
// when the key is absent from qwen35, qwen35moe, qwen3next or qwen4exp);
// failing that, for a hybrid whose
// head_count_kv is a per-layer array (jamba, granite-hybrid, nemotron-h), if
// it has no KV heads and, where feed_forward_length is per layer, no
// feed-forward. Recurrent state per layer is the Mamba-family size llama.cpp
// allocates (llama_hparams::n_embd_r and n_embd_s): a convolution state of
// (d_conv-1)(d_inner + 2*n_group*d_state) numbers and an SSM state of
// d_state*d_inner numbers. A sliding-window layer is one the header's
// sliding_window_pattern marks; without that key every attention layer is
// taken to be full, which can only overestimate.
//
// ActiveBytes is what one decoding step reads: the trunk's shared tensors,
// one row of token_embd (all of it when the output head is tied to it), and
// the used experts' share of the trunk's expert tensors.
func ShapeOf(hs ...*Header) (Shape, error) {
    if len(hs) == 0 || slices.Contains(hs, nil) {
        return Shape{}, fmt.Errorf("gguf: ShapeOf needs every header of the model")
    }
    h := hs[0]
    arch, _ := h.KV["general.architecture"].(string)
    if arch == "" {
        return Shape{}, fmt.Errorf("gguf: no general.architecture")
    }
    if why, ok := unmodelled[arch]; ok {
        return Shape{}, fmt.Errorf("gguf: cannot estimate architecture %s: the memory model leaves out %s", arch, why)
    }
    key := func(k string) string { return arch + "." + k }
    s := Shape{Arch: arch}
    s.Context, _ = h.Int(key("context_length"))
    if s.Context < 0 {
        return Shape{}, fmt.Errorf("gguf: %s = %d", key("context_length"), s.Context)
    }
    blocks, ok := h.Int(key("block_count"))
    if !ok {
        return Shape{}, fmt.Errorf("gguf: no %s", key("block_count"))
    }
    if blocks < 1 || blocks > maxLayers {
        return Shape{}, fmt.Errorf("gguf: %s = %d, want 1 to %d", key("block_count"), blocks, maxLayers)
    }
    nextn, _ := h.Int(key("nextn_predict_layers"))
    if nextn < 0 || nextn > blocks {
        return Shape{}, fmt.Errorf("gguf: %s = %d with %d blocks", key("nextn_predict_layers"), nextn, blocks)
    }
    trunk := int(blocks - nextn)

    kvHeads, ok := h.Ints(key("attention.head_count_kv"), int(blocks))
    if !ok {
        kvHeads, _ = h.Ints(key("attention.head_count"), int(blocks)) // no GQA
    }
    if slices.ContainsFunc(kvHeads, func(n int64) bool { return n < 0 }) {
        return Shape{}, fmt.Errorf("gguf: negative %s", key("attention.head_count_kv"))
    }
    convK, hasSSM := h.Int(key("ssm.conv_kernel"))
    _, hasAttn := h.KV[key("attention.head_count")]
    _, perLayerKV := h.KV[key("attention.head_count_kv")].([]int64)
    recurrent := make([]bool, trunk)
    every, hasEvery := h.Int(key("full_attention_interval"))
    if !hasEvery && defaultInterval4[arch] {
        every, hasEvery = 4, true // llama.cpp's default for these architectures
    }
    switch layers, hasMap := h.Ints(key("attention.recurrent_layers"), int(blocks)); {
    case hasMap:
        for i := 0; i < trunk && i < len(layers); i++ {
            recurrent[i] = layers[i] != 0
        }
    case hasEvery:
        if every < 1 {
            return Shape{}, fmt.Errorf("gguf: %s = %d", key("full_attention_interval"), every)
        }
        for i := range recurrent {
            recurrent[i] = int64(i+1)%every != 0
        }
    case hasSSM && perLayerKV:
        ff, perLayerFF := h.KV[key("feed_forward_length")].([]int64)
        for i := 0; i < trunk && i < len(kvHeads); i++ {
            recurrent[i] = kvHeads[i] == 0 && (!perLayerFF || i < len(ff) && ff[i] == 0)
        }
    case hasSSM && hasAttn:
        return Shape{}, fmt.Errorf("gguf: %s has SSM and attention keys but no layer map", arch)
    case hasSSM:
        for i := range recurrent {
            recurrent[i] = true // a pure state-space model
        }
    }
    sliding := make([]bool, trunk)
    if f, ok := swaFlags(h, key("attention.sliding_window_pattern"), trunk); ok {
        if w, _ := h.Int(key("attention.sliding_window")); w > 0 {
            sliding, s.Window = f, w
        } else if w < 0 || slices.Contains(f, true) {
            return Shape{}, fmt.Errorf("gguf: sliding layers but %s = %d", key("attention.sliding_window"), w)
        }
    }

    kLen, okK := h.Int(key("attention.key_length"))
    vLen, okV := h.Int(key("attention.value_length"))
    if !okK || !okV { // llama.cpp's default: n_embd / n_head
        embd, _ := h.Int(key("embedding_length"))
        if heads, _ := h.Int(key("attention.head_count")); heads > 0 {
            kLen, vLen = embd/heads, embd/heads
        }
    }
    kSWA, vSWA := kLen, vLen
    if v, ok := h.Int(key("attention.key_length_swa")); ok {
        kSWA = v
    }
    if v, ok := h.Int(key("attention.value_length_swa")); ok {
        vSWA = v
    }
    for i := 0; i < trunk; i++ {
        switch {
        case recurrent[i]:
            s.RecurLayers++
        case i >= len(kvHeads):
            return Shape{}, fmt.Errorf("gguf: head_count_kv has %d entries for %d layers", len(kvHeads), trunk)
        case kvHeads[i] > 0 && sliding[i]:
            s.Attn = append(s.Attn, AttnLayer{Heads: kvHeads[i], KeyLen: kSWA, ValueLen: vSWA, Sliding: true})
        case kvHeads[i] > 0:
            s.Attn = append(s.Attn, AttnLayer{Heads: kvHeads[i], KeyLen: kLen, ValueLen: vLen})
        }
    }
    for _, l := range s.Attn {
        if l.KeyLen < 1 || l.ValueLen < 1 {
            return Shape{}, fmt.Errorf("gguf: %s has attention layers with head width %d/%d", arch, l.KeyLen, l.ValueLen)
        }
    }
    var z sizer
    if s.RecurLayers > 0 {
        inner, _ := h.Int(key("ssm.inner_size"))
        state, _ := h.Int(key("ssm.state_size"))
        groups, _ := h.Int(key("ssm.group_count"))
        if inner < 1 || state < 1 || convK < 1 || groups < 0 {
            return Shape{}, fmt.Errorf("gguf: %s has recurrent layers but ssm sizes %d/%d/%d/%d", arch, convK, inner, state, groups)
        }
        s.StatePerLayer = z.add(z.mul(convK-1, z.add(inner, z.mul(2, groups, state))), z.mul(state, inner))
    }

    var shared, experts, embdAll, embdRow int64
    tied := true // the output head reads all of token_embd unless output.weight exists
    for _, sh := range hs {
        for _, t := range sh.Tensors {
            n := int64(t.Bytes)
            s.WeightBytes = z.add(s.WeightBytes, n)
            switch blk, ok := blockIndex(t.Name); {
            case ok && blk >= trunk:
                // a multi-token-prediction block: resident, never read by the trunk
            case t.Name == "token_embd.weight":
                embdAll, embdRow = n, n
                if len(t.Dims) == 2 && t.Dims[1] > 0 && t.Dims[1] <= math.MaxInt64 {
                    embdRow = n / int64(t.Dims[1]) // one token's row
                }
            case strings.Contains(t.Name, "_exps."):
                experts = z.add(experts, n)
            default:
                shared = z.add(shared, n)
                if t.Name == "output.weight" {
                    tied = false
                }
            }
        }
    }
    if tied {
        embdRow = embdAll
    }
    s.ActiveBytes = z.add(shared, embdRow, experts)
    if n, ok := h.Int(key("expert_count")); ok && n > 0 {
        used, _ := h.Int(key("expert_used_count"))
        if used < 1 || used > n {
            return Shape{}, fmt.Errorf("gguf: %d of %d experts used", used, n)
        }
        s.ActiveBytes = z.add(shared, embdRow, z.mul(experts, used)/n)
    }
    if z.bad {
        return Shape{}, errImpossible
    }
    return s, nil
}

Estimate applies the settings to the shape, as derived above. cacheBytes holds each cache type’s bytes per number as a fraction (34/32 for q8_0), pad256 is pad256\mathrm{pad}_{256}, rsRollback lists the architectures that keep draft rows, and orDefault supplies f16 for an unset cache type.

// Estimate is the memory a loaded model holds, sized as llama.cpp b29c606
// sizes it. Weights: all of them, since the next token may route to any
// expert. KV: the attention layers only. The context is padded to a multiple
// of 256, n; a unified cache is one stream of n cells, otherwise each of
// Parallel streams holds pad256(n/Parallel). A sliding-window layer holds,
// per stream, pad256(min(stream cells, Window*Parallel + UBatch)) when unified
// and pad256(min(stream cells, Window + UBatch)) when not, or the stream's
// cells under SWAFull. State: each recurrent layer keeps Parallel rows of f32
// state, Parallel*(1+DraftRS) for an architecture that rolls drafted tokens
// back. CacheRAM: the host prompt cache, charged at its limit.
//
// Not counted, by design: compute buffers; context checkpoints (up to 32 per
// slot, llama-server's n_ctx_checkpoints); the KV cache of a draft model's
// own context (an MTP, EAGLE3, DFlash or DSpark draft); and llama-server's
// fitting, which may shrink a context the preset leaves unset to fit free
// device memory, so that the estimate is then high.
func Estimate(s Shape, set Settings) (Footprint, error) {
    ctx, par, unified := set.Context, set.Parallel, set.Unified
    if ctx == 0 {
        ctx = s.Context
    }
    if par <= 0 {
        par, unified = 4, true // llama-server's auto (tools/server/server.cpp)
    }
    if ctx < 1 || set.CacheRAM < 0 || set.DraftRS < 0 {
        return Footprint{}, fmt.Errorf("context %d, cache-ram %d, draft rows %d", ctx, set.CacheRAM, set.DraftRS)
    }
    k, okK := cacheBytes[orDefault(set.CacheK, "f16")]
    v, okV := cacheBytes[orDefault(set.CacheV, "f16")]
    if !okK || !okV {
        return Footprint{}, fmt.Errorf("unknown cache type %q/%q", set.CacheK, set.CacheV)
    }
    var z sizer
    cells, streams := pad256(ctx), int64(1)
    if !unified {
        cells, streams = pad256(pad256(ctx)/par), par
        if cells == 0 {
            return Footprint{}, fmt.Errorf("context %d is too small for %d slots", ctx, par)
        }
    }
    swaCells := cells
    if !set.SWAFull {
        window := s.Window
        if unified {
            window = z.mul(window, par)
        }
        swaCells = pad256(min(cells, z.add(window, orDefault64(set.UBatch, defaultUBatch))))
    }
    f := Footprint{Weights: s.WeightBytes, Active: s.ActiveBytes, CacheRAM: set.CacheRAM}
    for _, l := range s.Attn {
        c := cells
        if l.Sliding {
            c = swaCells
        }
        f.KV = z.add(f.KV, z.mul(c, streams, l.Heads, l.KeyLen, k[0])/k[1],
            z.mul(c, streams, l.Heads, l.ValueLen, v[0])/v[1])
    }
    rs := set.DraftRS
    if !rsRollback[s.Arch] {
        rs = 0
    }
    f.State = z.mul(par, z.add(1, rs), s.RecurLayers, s.StatePerLayer, 4)
    f.Total = z.add(f.Weights, f.KV, f.State, f.CacheRAM)
    if z.bad {
        return Footprint{}, errImpossible
    }
    return f, nil
}

EstimateModel, outside the listing, joins the two for a catalog entry. It reads every shard of a split model (Shards names them from the first), applies the section’s settings with llama.cpp’s defaults (cache-ram 8,192 MiB, spec-draft-n-max 3), adds the sizes of a local mmproj and model-draft file to the weights, and returns an error for anything it cannot size: an hf-repo or mmproj-url download, cache-ram = -1 (no limit), or a refused architecture.

The pool

Pool owns one record per catalog model and, for a loaded model, one child. Everything that changes the records happens under one mutex. A state change closes and replaces a channel, changed; a request that has to wait takes the channel under the lock, releases the lock, and waits on the channel or on its context (waitLocked). Nothing polls, and a request whose client hangs up leaves at once. Lifecycle events (wait, spawn, loading, ready, evict, unload, exit, fail) are queued under the lock by emitLocked and delivered by unlock after the lock is released, so an OnEvent callback that calls back into the pool cannot deadlock it. Events raised on one goroutine arrive in order; two raised within microseconds on different goroutines, a request’s and a supervisor’s, may arrive in either order.

Acquire is the whole request path, and its switch reads as the cases it handles. Two need a reason. Without autoload it refuses a model being stopped (ErrStopping, 503) as well as one not running (llama.cpp’s 400 “model is not loaded”), so that a request without autoload never reloads a model on its way out. And a request that joins the queue records the epoch, which an Unload advances, so that every request waiting at that moment is told ErrUnloaded rather than left for a load nobody asked for. fitsAloneLocked refuses a model that could never fit the budget, or whose size is unknown, before it registers. The deferred leaveQueueLocked takes the request out of the queue however it leaves, unless an Unload has already done so, and runs the scheduler, since the slot the request was holding, or the retry it was blocking (reportingFailure), may now go to someone else. A lease’s Release decrements the in-flight count and runs the scheduler too: a model that just became idle may be the victim a queued request is waiting for.

// Acquire returns a lease on a loaded model, loading it first if it is not
// running and opts.Autoload allows. A request that has to wait (the model is
// loading, or no slot is free until another model is evicted or finishes its
// requests) waits here, until ctx is done.
func (p *Pool) Acquire(ctx context.Context, name string, opts AcquireOptions) (Lease, error) {
    p.mu.Lock()
    inst, ok := p.lookupLocked(name)
    if !ok {
        p.mu.Unlock()
        return nil, fmt.Errorf("%w: %q", ErrUnknownModel, name)
    }
    name = inst.model.Name
    queued := false
    target, epoch := 0, 0 // the load attempt this request waits for, and in which epoch
    defer func() {
        if queued && epoch == inst.epoch { // an Unload has already dropped it otherwise
            p.leaveQueueLocked(inst, target)
        }
        p.unlock()
    }()
    for {
        switch {
        case p.closed:
            return nil, ErrClosed
        case queued && epoch != inst.epoch:
            return nil, fmt.Errorf("%w: %q", ErrUnloaded, name)
        case inst.status == Loaded && !inst.stopping:
            inst.inflight++
            if opts.Touch {
                p.clock++
                inst.lastUsed = p.clock
            }
            u := &url.URL{Scheme: "http", Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(inst.port))}
            return &lease{p: p, inst: inst, target: u}, nil
        case queued && target <= inst.failedAttempt:
            return nil, fmt.Errorf("model %q failed to load: %s", name, inst.err)
        case !queued && inst.status == Unloaded && !opts.Autoload:
            return nil, fmt.Errorf("%w: %q", ErrNotLoaded, name)
        case !queued && inst.stopping && !opts.Autoload:
            return nil, fmt.Errorf("%w: %q", ErrStopping, name) // never a reload without autoload
        case !queued:
            if err := p.fitsAloneLocked(inst); err != nil {
                return nil, err
            }
            // Waiting on the attempt now loading, or on the next one.
            target = inst.attempts + 1
            if inst.status == Loading && !inst.stopping {
                target = inst.attempts
            }
            p.joinQueueLocked(inst, target)
            epoch = inst.epoch
            p.emitLocked(name, "wait", "")
            queued = true
            p.scheduleLocked()
            continue
        }
        if err := p.waitLocked(ctx); err != nil {
            return nil, err
        }
    }
}

scheduleLocked walks the queue in arrival order, skipping models that already have a child and models whose waiters are still being told of a failure. Besides counting every model that is not unloaded against both limits, it counts separately what will remain once the stopping ones have exited, and a held-back model spawns when a victim’s supervisor sees the process exit and runs the scheduler again. If every running model is busy, nothing can be evicted, and the queue waits for a Release. A model that becomes ready runs the scheduler too: if every request that wanted it has left, it is now the victim a queue may need.

// scheduleLocked gives free capacity to the queue, as llama.cpp's scheduler
// does: a model that fits loads at once, and the first one that does not
// fit holds back every model behind it, so a large model is not starved by
// small ones. For each model that does not fit, idle models are asked to
// exit, least recently used first, until it will once they have. Models
// count against models-max and the budget until their process has exited.
// A model with requests in flight, one still loading, and one a queued
// request wants are never victims.
func (p *Pool) scheduleLocked() {
    if p.closed {
        return
    }
    size := func(inst *instance) int64 {
        if inst.footprint == nil {
            return 0
        }
        return inst.footprint.Total
    }
    fits := func(n int, held, need int64) bool {
        return (p.cfg.ModelsMax <= 0 || n+1 <= p.cfg.ModelsMax) &&
            (p.cfg.MemoryBudget <= 0 || held+need <= p.cfg.MemoryBudget)
    }
    // running: every child not yet exited. after: the same, once the
    // children already asked to stop have exited.
    running, held, after, heldAfter := 0, int64(0), 0, int64(0)
    for _, inst := range p.models {
        if inst.status != Unloaded {
            running, held = running+1, held+size(inst)
            if !inst.stopping {
                after, heldAfter = after+1, heldAfter+size(inst)
            }
        }
    }
    blocked := false
    for _, name := range append([]string(nil), p.queue...) {
        inst := p.models[name]
        needsChild := inst.status == Unloaded || inst.stopping // no child, or one on its way out
        if !needsChild || inst.reportingFailure() {
            continue
        }
        need := size(inst)
        if inst.status == Unloaded && !blocked && fits(running, held, need) {
            if p.spawnLocked(inst) {
                running, held = running+1, held+need
                after, heldAfter = after+1, heldAfter+need
            }
            continue
        }
        blocked = true // first come, first served
        for !fits(after, heldAfter, need) {
            victim := p.victimLocked()
            if victim == nil {
                return // every running model is busy: wait for a Release
            }
            p.stopLocked(victim, "evict")
            after, heldAfter = after-1, heldAfter-size(victim)
        }
        after, heldAfter = after+1, heldAfter+need // its slot, once the victims have exited
    }
}

func (p *Pool) victimLocked() *instance {
    var victim *instance
    for _, inst := range p.models {
        if inst.status != Loaded || inst.stopping || inst.inflight > 0 || inst.waiting > 0 {
            continue
        }
        if victim == nil || inst.lastUsed < victim.lastUsed {
            victim = inst
        }
    }
    return victim
}

stopLocked marks a model stopping, closes its stop channel for the supervisor, and emits evict or unload. Unload moves the model to a new epoch and drops its waiting requests from the queue, so that nothing loads it for them, calls stopLocked, and waits on the child’s gone channel, which the supervisor closes when that child has exited; a reload that a later request starts does not keep it waiting. Drain refuses every waiting and every new request with ErrClosed and leaves loaded models serving the requests in flight. Close stops every model and waits for every supervisor.

spawnLocked starts a child. It takes a free port from the kernel (freePort, as llama.cpp’s common_http_get_free_port does; exercise (e) is about the race this leaves), builds the arguments as llama.cpp’s update_args does (--host 127.0.0.1, --port, --alias with the model’s name, then the preset’s options), prefixes each line of the child’s output with the model’s name (newLineWriter), and sets childAttr, which on Linux is Pdeathsig: SIGKILL and elsewhere nothing. A failure to start goes through failLocked, which marks the attempt failed and tells its waiters.

func (p *Pool) spawnLocked(inst *instance) bool {
    name := inst.model.Name
    inst.status, inst.stopping, inst.failed, inst.exitCode, inst.err = Loading, false, false, 0, ""
    inst.stop = make(chan struct{})
    inst.attempts++
    p.clock++
    inst.lastUsed = p.clock // a load counts as use, as in llama.cpp's server_models::load
    port, err := freePort()
    if err != nil {
        p.failLocked(inst, -1, err.Error())
        return false
    }
    inst.port = port
    inst.args = append([]string{p.cfg.Bin, "--host", "127.0.0.1", "--port", strconv.Itoa(port),
        "--alias", name}, inst.model.Args...)
    cmd := exec.Command(p.cfg.Bin, inst.args[1:]...)
    cmd.Env = append(os.Environ(), p.cfg.Env...)
    cmd.Stdout = newLineWriter(p.cfg.Log, "["+name+"] ")
    cmd.Stderr = cmd.Stdout
    cmd.SysProcAttr = childAttr() // the child dies with the router (Linux)
    if err := cmd.Start(); err != nil {
        p.failLocked(inst, -1, err.Error())
        return false
    }
    p.emitLocked(name, "spawn", strconv.Itoa(port))
    p.broadcastLocked()
    exited := make(chan struct{})
    go func() { cmd.Wait(); close(exited) }()
    inst.gone = make(chan struct{})
    p.wg.Add(1)
    go p.supervise(inst, cmd, exited, inst.stop, inst.gone)
    return true
}

supervise polls every HealthInterval. The first 503 emits loading; after the child is ready, HealthFailures failed checks in a row kill it as hung; and a child that has not answered 200 within LoadTimeout is killed and its load failed. When the process has exited, the outcome is one of three: stopped on request (unloaded, not failed), never ready (a failed load, its waiters told), or died while loaded (unloaded and marked failed with its exit code, so /v1/models shows it; the next request reloads it). Either way the slot is free, and the scheduler runs.

// supervise owns one child from spawn to exit: it polls /health until the
// child is ready (503 while the model loads, 200 after), then keeps polling to
// catch a child that hangs, and it stops the child when asked: SIGTERM, then
// SIGKILL after the model's stop-timeout.
func (p *Pool) supervise(inst *instance, cmd *exec.Cmd, exited, stop, gone chan struct{}) {
    defer p.wg.Done()
    health := &http.Client{Timeout: p.cfg.HealthTimeout}
    url := fmt.Sprintf("http://127.0.0.1:%d/health", inst.port)
    tick := time.NewTicker(p.cfg.HealthInterval)
    defer tick.Stop()
    deadline := time.NewTimer(p.cfg.LoadTimeout)
    defer deadline.Stop()
    ready, answering, failures := false, false, 0
    why := "" // why the child is going away, if the router ended it
    for why == "" {
        select {
        case <-exited:
            why = "exited"
        case <-stop:
            why = "stopped"
        case <-deadline.C:
            if !ready {
                why = "no 200 from /health within the load timeout"
            }
        case <-tick.C:
            code := probe(health, url)
            switch {
            case code == http.StatusOK && !ready:
                ready = true
                p.mu.Lock()
                inst.status = Loaded
                p.emitLocked(inst.model.Name, "ready", "")
                p.scheduleLocked() // if nobody waits for it any more, it may be the victim a queue needs
                p.broadcastLocked()
                p.unlock()
            case code == http.StatusOK:
                failures = 0
            case ready:
                if failures++; failures >= p.cfg.HealthFailures {
                    why = "health check failed"
                }
            case code == http.StatusServiceUnavailable && !answering:
                answering = true // listening, and loading the model
                p.mu.Lock()
                p.emitLocked(inst.model.Name, "loading", "")
                p.unlock()
            }
        }
    }
    if why != "exited" {
        terminate(cmd, exited, inst.model.StopTimeout)
    }
    <-exited
    p.mu.Lock()
    defer p.unlock()
    code := cmd.ProcessState.ExitCode()
    inst.port = 0
    switch {
    case why == "stopped":
        inst.status, inst.failed, inst.exitCode, inst.err = Unloaded, false, 0, ""
    case !ready:
        p.failLocked(inst, code, fmt.Sprintf("%s (exit code %d)", why, code))
    default:
        inst.status, inst.failed, inst.exitCode, inst.err = Unloaded, true, code, why
        p.emitLocked(inst.model.Name, "exit", fmt.Sprintf("%s (exit code %d)", why, code))
    }
    inst.stopping = false
    close(gone)
    p.scheduleLocked() // a slot is free
    p.broadcastLocked()
}

One model's lifecycle in aec-router, and the queue of requests waiting for slots Four states left to right. Unloaded: no process. A request for the model, with autoload on and a slot free, spawns a child: Loading, the child spawned and /health answering 503. A 200 from /health makes it Loaded, taking requests. Evicted, as an idle, least recently used model no queued request wants, or unloaded on request, it goes to Stopping: SIGTERM, then SIGKILL after the stop-timeout. A model unloaded while it is still loading goes to Stopping too. When the process has exited it is Unloaded again. Two failure edges, in the accent colour, also return to Unloaded: from Loading, when the child exits or the load times out, the load has failed and every waiting request is told; from Loaded, when the child crashes or /health keeps failing, the model is marked failed and the next request reloads it. Below, the queue: requests for one model share one entry; model b has three waiting requests and does not fit yet, so it holds back every entry behind it; model c has one waiting request behind b. Unloaded no process Loading child spawned, /health 503 Loaded /health 200, taking requests Stopping SIGTERM, then SIGKILL after stop-timeout request, autoload, slot free /health 200 unloaded evicted: idle, least recently used, unwanted; or unloaded exited or load timeout: failed, waiters told crashed, or /health failing: next request reloads exited Queue b: 3 requests waiting c: 1 request waiting does not fit yet: holds back the rest behind b

The handler

Handler is the HTTP side, llama-server’s router API. /health is the router’s own. GET /v1/models lists the catalog (listModels) in llama.cpp’s shape, id, aliases, tags and a status object with value and the child’s args, plus failed and exit_code after a failure, as llama.cpp reports them; aec-router adds a memory object with the footprint. POST /models/load and /models/unload manage models (manage). GET /props without ?model= is the router’s own properties, as llama.cpp’s get_router_props answers (lines 1921–1946); with ?model=, like every other GET, it is routed to the child, and so is GET /metrics?model=. Every other request is a POST routed by its body’s model.

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    switch {
    case r.URL.Path == "/health" || r.URL.Path == "/v1/health":
        writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
    case r.Method == http.MethodGet && (r.URL.Path == "/v1/models" || r.URL.Path == "/models"):
        h.listModels(w)
    case r.Method == http.MethodPost && (r.URL.Path == "/models/load" || r.URL.Path == "/models/unload"):
        h.manage(w, r)
    case r.Method == http.MethodGet && r.URL.Query().Get("model") == "" && r.URL.Path == "/props":
        writeJSON(w, http.StatusOK, h.Props)
    case r.Method == http.MethodGet && r.URL.Query().Get("model") == "" &&
        r.URL.Path == "/metrics" && h.Metrics != nil:
        h.Metrics.ServeHTTP(w, r)
    case r.Method == http.MethodGet:
        h.route(w, r, r.URL.Query().Get("model"), nil, false)
    default:
        // Read the whole body: the model is inside it, and net/http only
        // notices a client that hangs up once the body has been read to EOF.
        body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, MaxBody))
        if err != nil {
            writeError(w, http.StatusRequestEntityTooLarge, "request body too large")
            return
        }
        var peek struct {
            Model string `json:"model"`
        }
        if err := json.Unmarshal(body, &peek); err != nil {
            writeError(w, http.StatusBadRequest, "request body is not a JSON object")
            return
        }
        h.route(w, r, peek.Model, body, true)
    }
}

func (h *Handler) route(w http.ResponseWriter, r *http.Request, model string, body []byte, post bool) {
    if model == "" {
        writeError(w, http.StatusBadRequest, "model name is missing from the request")
        return
    }
    lease, err := h.Backend.Acquire(r.Context(), model,
        AcquireOptions{Autoload: h.autoload(r), Touch: post})
    if err != nil {
        h.fail(w, r, err)
        return
    }
    defer lease.Release()
    fwd := h.Forward
    if fwd == nil {
        fwd = ReverseProxy{}
    }
    fwd.Forward(w, r, h.canonical(model), lease.Target(), body)
}

The handler reads the whole body before it routes, for two reasons. The model’s name is inside the body, so there is nothing to route by until it has been read. And Go’s net/http notices a client that hangs up only after the handler has read the request body to EOF; a router that streamed the body through unread would not see a client go away, which is chapter 23’s subject. autoload reads ?autoload=true|1|false|0 and falls back to the router’s setting, as llama.cpp’s is_autoload does (line 1868). fail maps the pool’s errors to statuses: an unknown model and a model not loaded with autoload off are 400, as in llama.cpp’s router_validate_model (lines 1849–1866); so is a model that can never fit the budget or whose size is unknown under one, since retrying cannot help. A router shutting down, a model unloaded while the request waited, and a model being stopped when the request has no autoload are 503 with Retry-After: 5 (RetryAfter): the same request can succeed later. A failed load is 500. writeError writes llama.cpp’s error shape, {"error": {"code", "message", "type"}}. orEmpty lists an absent alias or tag set as [], as llama.cpp lists an empty set. canonical turns a requested alias back into the model’s catalog name before the forwarder is called, so chapter 23’s metrics label each model with one name.

aec-router departs from llama.cpp at /models/load and /models/unload. llama.cpp’s load answers 404 for an unknown model and 400 “model is already running” for a running one, and returns once the child is spawned (lines 1993–2009). When no slot can be freed, its load fails with “model limit reached, try again later” (lines 1140–1142), where aec-router queues. Its unload answers 400 “model is not running” for a model that is not, and returns once it has asked the child to stop (lines 2087–2103), force-killing a child that is still loading (lines 1250–1256). aec-router’s load returns when the model answers /health with 200. Its unload returns when the child has exited, which can take up to the model’s stop-timeout, since it sends SIGTERM and then SIGKILL, even to a child still loading. Both are idempotent: loading a loaded model, or unloading an unloaded one, succeeds. A client that wants a model ready can then use one call.

A run

go/cmd/aec-router/testdata/fake.ini is a catalog of three fake models, and cmd/aec-fake-llama is the tests’ fake llama-server as a program. The fake takes llama-server’s --host, --port and --alias, ignores its other options, serves /health, /v1/models, /props and /v1/chat/completions with a canned reply, and reads a few options of its own, here --fake-reply (chapter 51 adds --replies, a script of completions, and --embed-dim, which serves /v1/embeddings). Build both, start the router with models-max 2 and a time limit of 20 seconds, and send four requests:

cd go && go build -o /tmp/aec-router ./cmd/aec-router && go build -o /tmp/aec-fake-llama ./cmd/aec-fake-llama && cd ..
timeout 20 /tmp/aec-router -bin /tmp/aec-fake-llama -models-preset go/cmd/aec-router/testdata/fake.ini -models-max 2 -listen 127.0.0.1:11499 > /tmp/aec-router.log 2>&1 &
curl -s http://127.0.0.1:11499/v1/chat/completions -d '{"model":"small","messages":[{"role":"user","content":"hi"}]}'
curl -s http://127.0.0.1:11499/v1/chat/completions -d '{"model":"medium","messages":[]}'
curl -s http://127.0.0.1:11499/v1/chat/completions -d '{"model":"small","messages":[]}'
curl -s http://127.0.0.1:11499/v1/chat/completions -d '{"model":"large","messages":[]}'
curl -s http://127.0.0.1:11499/v1/models

On talos on 2026-10-01, the four answers were each a fake’s reply as the router’s forwarder delivers it: chapter 23’s proxy, which asks the child for a stream and assembles it into one object, so the fields come in the order of its Completion type. The first:

{"id":"chatcmpl-fake","object":"chat.completion","created":1790844623,"model":"small","choices":[{"index":0,"message":{"role":"assistant","content":"a small answer"},"finish_reason":"stop"}],"usage":{"completion_tokens":3,"prompt_tokens":5,"total_tokens":8}}

and the router’s log, once timeout had sent SIGTERM after 20 seconds, was:

2026/10/01 01:50:22 small: size unknown: open /nonexistent/small.gguf: no such file or directory
2026/10/01 01:50:22 medium: size unknown: open /nonexistent/medium.gguf: no such file or directory
2026/10/01 01:50:22 large: size unknown: open /nonexistent/large.gguf: no such file or directory
2026/10/01 01:50:22 aec-router: serving 3 models on 127.0.0.1:11499
2026/10/01 01:50:22 small wait 
2026/10/01 01:50:22 small spawn 35833
[small] fakellama: small listening on 127.0.0.1:35833
2026/10/01 01:50:23 small ready 
2026/10/01 01:50:23 medium wait 
2026/10/01 01:50:23 medium spawn 33881
[medium] fakellama: medium listening on 127.0.0.1:33881
2026/10/01 01:50:24 medium ready 
2026/10/01 01:50:24 large wait 
2026/10/01 01:50:24 medium evict 
2026/10/01 01:50:24 large spawn 38241
[large] fakellama: large listening on 127.0.0.1:38241
2026/10/01 01:50:25 large ready 
2026/10/01 01:50:42 small unload 
2026/10/01 01:50:42 large unload 
aec-router: stopped

The fake catalog names files that do not exist, so the three footprints are unknown, which is harmless without a budget. Each request for a model that was not running queued (wait), spawned a child on a port the kernel chose, and was answered once /health turned 200, a second later by the default poll interval. When large arrived, two models were running and models-max was 2, so one had to go. Both were idle and neither was wanted by a queued request; small had been loaded first, but the third request had used it after medium was loaded, so medium was the least recently used and was evicted. large spawned as soon as medium’s process had exited, in the same second. On SIGTERM the router drained the pool, so that any request still waiting for a model would be refused at once, stopped accepting, let requests in flight finish for up to 30 seconds, and then stopped the two running children, with time for each to exit or be killed at its stop-timeout. /v1/models, read between the last request and the shutdown:

{"data":[{"id":"small","aliases":[],"tags":[],"object":"model","owned_by":"aec-router","created":1790844622,"status":{"value":"loaded","args":["/tmp/aec-fake-llama","--host","127.0.0.1","--port","35833","--alias","small","--ctx-size","4096","--model","/nonexistent/small.gguf","--fake-reply","a small answer"]}},{"id":"medium","aliases":[],"tags":[],"object":"model","owned_by":"aec-router","created":1790844622,"status":{"value":"unloaded","args":["/tmp/aec-fake-llama","--host","127.0.0.1","--port","33881","--alias","medium","--ctx-size","4096","--model","/nonexistent/medium.gguf","--fake-reply","a medium answer"]}},{"id":"large","aliases":[],"tags":[],"object":"model","owned_by":"aec-router","created":1790844622,"status":{"value":"loaded","args":["/tmp/aec-fake-llama","--host","127.0.0.1","--port","38241","--alias","large","--ctx-size","4096","--model","/nonexistent/large.gguf","--fake-reply","a large answer"]}}],"object":"list"}

medium is unloaded, not failed: an eviction is not a failure, so there is no failed or exit_code. Its args are those of its last child, port included, which is what to read when a model that should have loaded did not. The [*] section’s ctx-size reached every child, and each section’s fake-reply reached its own.

Exercises

(a) Compute ornith’s KV bytes per position at q8_0 and its cache at ctx-size 262,144 with straylight’s settings for it. Then explain why raising parallel from 4 to 8 leaves the cache unchanged but doubles the recurrent state, and find settings under which changing parallel does change the cache.

Answer

A position is 10×2×(256+256)×1.0625=10,88010 \times 2 \times (256 + 256) \times 1.0625 = 10{,}880 bytes, and the cache is 262,144×10,880=2,852,126,720262{,}144 \times 10{,}880 = 2{,}852{,}126{,}720 bytes, 2.66 GiB. Under kv-unified, the cache is one stream of pad256(262,144)=262,144\mathrm{pad}_{256}(262{,}144) = 262{,}144 cells whatever PP is: the slots share the cells, so more slots means less context each, not more cache. The state is allocated per slot, 65,863,680 bytes each, so it goes from 4×65,863,680=263,454,7204 \times 65{,}863{,}680 = 263{,}454{,}720 to 526,909,440526{,}909{,}440 bytes.

Without kv-unified the streams are PP of pad256(⌊n/P⌋)\mathrm{pad}_{256}(\lfloor n/P \rfloor) cells, and the second rounding is where PP shows. At 262,144 it does not: 4×65,536=8×32,768=262,1444 \times 65{,}536 = 8 \times 32{,}768 = 262{,}144. At ctx-size 100,000 and P=3P = 3, n=100,096n = 100{,}096, and per-slot streams hold 3×pad256(33,365)=3×33,536=100,6083 \times \mathrm{pad}_{256}(33{,}365) = 3 \times 33{,}536 = 100{,}608 cells, 512 more than the unified cache’s 100,096. TestEstimateModelReadsServerOptions pins this case.

(b) On 2026-09-29 at 22:09 PDT, straylight’s /v1/models showed three models sleeping (ornith-1.5-35b-a3b, ornith-1.5-9b-uncensored and trinity-mini) under max_instances 3. By the b29c606 code, what happens when a request names a fourth model?

Answer

A sleeping model counts as running: is_running() is true for LOADED, LOADING and SLEEPING (server-models.h, lines 94–96). So has_capacity is false, and the request joins the queue (join). tick computes the free slots as models_max - n_running + n_stopping - n_claimed =3−3+0−0=0= 3 - 3 + 0 - 0 = 0, fewer than the one entry needing a slot, and calls pick_victim, whose candidates are models with no request in flight that are ready or asleep (is_ready_or_sleep), not stopping and not queued for. All three sleeping models qualify, and the one with the oldest last_used is asked to stop. When its process has exited, the queued request’s model claims the slot (try_claim) and loads. A request that names a sleeping model is different: ensure_model_ready returns at once for a sleeping model (lines 1439–1440) and the request is proxied, which wakes the child and reloads its weights. Either way a request that names a model moves gigabytes, which is why the fleet rule treats a wake as a load and re-checks /v1/models for loaded before any request that names a model.

(c) Why does aec-router count use with a counter, and only on a load or a POST? Construct the interleaving in which wall-clock LRU that counts a monitoring GET every 10 s keeps an unused model resident. Then show that not counting the GET is not enough while the monitor’s requests may autoload.

Answer

Take Mmax=2M_{\max} = 2, models xx and yy loaded, and a dashboard that reads /metrics?model=x every 10 s. At t=0t = 0 an agent sends a POST to yy; nothing sends one to xx for hours. At t=30t = 30 s a request for zz arrives. If a GET counted, xx’s last use would be at most 10 s old and yy’s 30 s old, so yy, the model in use, is evicted, and the agent’s next turn reloads it, evicting xx or zz. Each scrape renews xx, so the order never changes: xx stays resident on monitoring traffic alone.

Counting only loads and POSTs makes xx the victim, but only once. With autoload on, the next scrape, 10 s later, names the evicted xx, loads it, and that load counts as use; with Mmax=2M_{\max} = 2 it evicts the least recently used of yy and zz, a model in real use, and so on at every scrape. The monitor has to send ?autoload=false: its GET then reads a running xx without renewing it and gets 400 “model is not loaded” for an evicted one. That is the fleet rule exercise (b) ends on, seen from the router’s side.

A counter rather than a clock gives a strict total order: two uses within one millisecond of ggml_time_ms() tie. (That clock is monotonic on Linux, so it cannot be stepped backwards; a wall-clock LRU could be, by NTP, and would then rank a later use as older.) The counter also makes the tests deterministic.

(d) straylight’s trinity-mini header (afmoe) has attention.sliding_window 2,048 but no pattern key. llama.cpp’s loader defaults the period in code (src/models/afmoe.cpp, lines 17–19, at b29c606):

        uint32_t swa_period = 4;
        ml.get_key_or_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, swa_period, false);
        hparams.set_swa_pattern(swa_period);

Add an architecture default to ShapeOf, as defaultInterval4 does for the interval, and recompute trinity’s KV at straylight’s settings (ctx-size 262,144, q8_0, parallel 2, per-slot streams). Its 32 layers each have 4 KV heads of width 128.

Answer

With period 4, layer ii slides when imod4<3i \bmod 4 < 3: 24 sliding layers and 8 full ones. Each of the 2 streams has 131,072 cells, and a sliding layer holds pad256(min(131,072,2,048+512))=2,560\mathrm{pad}_{256}(\min(131{,}072, 2{,}048 + 512)) = 2{,}560 per stream, 5,120 in all. With 4×(128+128)=4×2564 \times (128 + 128) = 4 \times 256 numbers per position per layer:

8×262,144×4×256×1.0625+24×5,120×4×256×1.0625=2,281,701,376+133,693,440=2,415,394,816 8 \times 262{,}144 \times 4 \times 256 \times 1.0625 + 24 \times 5{,}120 \times 4 \times 256 \times 1.0625 = 2{,}281{,}701{,}376 + 133{,}693{,}440 = 2{,}415{,}394{,}816

bytes, 2.25 GiB, against 32×262,144×4×256×1.0625=9,126,805,50432 \times 262{,}144 \times 4 \times 256 \times 1.0625 = 9{,}126{,}805{,}504 (8.50 GiB) with every layer full, the figure in the -footprints run. The total falls from 25.33 to 19.08 GiB. A sketch of the change: a map defaultSWAPeriod = map[string]int64{"afmoe": 4}, and in ShapeOf, when swaFlags finds no key and the architecture has a default, build the flags as for an integer period. The test is a header with the window and no pattern, expecting 24 sliding layers. Overestimating was safe, so the change is a matter of budget efficiency, not of safety.

(e) freePort asks the kernel for a free port, closes it and gives the number to the child. What happens if another process binds the port between freePort and the child’s bind, and why does the design survive it? llama-server’s --host binds a UNIX socket when the address ends in .sock (the server README). What would the pool, the health probe and the forwarder have to change to use one?

Answer

The child’s bind fails and it exits with an error before it ever answers /health. The supervisor sees the process exit before readiness, so failLocked fails the attempt: the requests waiting for it get “failed to load” (500), the model shows failed with the exit code, and the next request retries with a fresh port. The window is short and the cost is one failed attempt, which is why llama.cpp’s common_http_get_free_port accepts the same race.

With a socket there is no race: the router creates a private directory (mode 0700) and names a path in it per child, --host /run/aec-router/NAME.sock, which no other user can take. The pool keeps a path where it keeps a port, and removes the file after the child exits. The probe and the forwarder need an http.Transport whose DialContext dials unix at the model’s path, ignoring the address; the target URL keeps a placeholder host such as http://NAME. The children then also stop listening on TCP at all, which closes them to every other local user.

(f) Start aec-router with the fake catalog, load two models, kill the router with SIGKILL, and list the processes that remain. Repeat with childAttr returning nil. Explain the result, Pdeathsig’s thread caveat, and llama.cpp’s alternative.

Answer

On talos (2026-09-30), after small and medium were loaded and the router was killed with kill -9, pgrep -x aec-fake-llama found nothing: the kernel had sent each child SIGKILL when its parent died. Built with childAttr returning nil, the same steps left both fakes running and still listening on their ports (ss -ltnp showed them), each now a child of init, until they were killed by PID.

The parent-death signal is sent when the parent thread terminates, not the process (PR_SET_PDEATHSIG). In Go, the thread that forks a child is whichever OS thread the calling goroutine ran on; the runtime keeps its threads alive unless a goroutine exits while locked to one with runtime.LockOSThread, which the router never does. A program that did so could see its children killed while it lives. The signal is also cleared if the child executes a set-user-ID binary or one with file capabilities. llama.cpp’s children read stdin until EOF and exit when it comes; the kernel closes the pipe when the router dies however it dies, the method needs no Linux feature and has no thread caveat, but it needs the child’s code to watch stdin, which only a llama-server started in router child mode does.

Lab

The Go labs follow the pattern of chapter 1’s Python labs, under go/labs/chNN/. go/labs/ch22/lab.go declares Pool, the interface the tests need (the handler’s router.Backend, plus Load, Start and Close), and asserts at compile time that both the reference *router.Pool and your *mine.Pool satisfy it, so a starter whose API drifts from the reference does not build. New returns the reference’s constructor or yours according to AEC_IMPL, through labkit.Select[NewPool], called with an explicit type argument. Your starter is go/labs/ch22/mine/pool.go, its methods stubbed. The acceptance tests are in go/labs/ch22/lab_test.go, and rig_test.go holds the rig they use. Run the reference first, then yours:

make lab CH=22 IMPL=ref
make lab CH=22 IMPL=mine

make lab runs go test -count=1 ./labs/ch22 from go/ with AEC_IMPL set. Against the reference the lab takes about 1.7 s on talos; with -race -count=20 it passed in 30.1 s on straylight (2026-09-30).

The tests drive your pool through the real router.Handler over HTTP. The children are the test binary itself: TestMain calls fakellama.RunIfChild() first, and the rig gives the pool its own executable as Bin with AEC_FAKE_LLAMA=1 in the environment, so each spawned child runs the fake instead of the tests, the pattern of os/exec’s own tests. The fake is controlled over HTTP: POST /fake/ready ends a slow load, /fake/crash exits with status 3, /fake/hang stops answering /health, /fake/release lets held completions go, and GET /fake/wait?held=1 blocks until a counter reaches a value. A completion with "fake_hold": true in its body is held before its first byte, and a child started with --fake-term-wait (preset fake-term-wait = true) takes its SIGTERM but exits only at the next /fake/release, a server slow to shut down. The rig’s OnEvent calls Models() on every event, so a pool that delivers events with its lock held deadlocks. The rig records the pool’s events through Config.OnEvent and waits on them. It also reads the children’s output through Config.Log: a fake child that loses the free-port race names the port it was given and its model, and the rig takes that spawn out of the counts, whenever the line arrives. No test sleeps; the one constant, patience, is only the deadline after which a wait fails.

The tests pin, one each:

  • TestRoutesByModelField: POST by the body’s model, GET by ?model=, /props without it is the router’s own, and a model spawns once.
  • TestRejectsBadRequests: a missing model, an unknown one and a body that is not a JSON object are 400, as is a GET without ?model=.
  • TestAutoloadOff: an unloaded model is 400 “not loaded”, ?autoload=true overrides, and /models/load loads.
  • TestEvictsLeastRecentlyUsed: with models-max 2, the least recently used model goes, and an evicted model is not a failed one.
  • TestGetRequestsDoNotCountAsUse: a GET does not renew a model.
  • TestLoadCountsAsUse: a model just loaded by /models/load is not the first victim.
  • TestBusyModelIsNotEvicted: a model with a request in flight stays, and the waiting request is served once it is idle.
  • TestSlowLoadHoldsTheRequest: a request waits through /health 503, and the status reads loading.
  • TestConcurrentRequestsShareOneLoad: five requests, one spawn.
  • TestCancelledWaiterDoesNotPinItsModel: a request that leaves while its model loads no longer protects it.
  • TestFailedLoadIsReportedAndRetried: a failed load is 500 “failed to load” for its waiters, shows failed and the exit code, and the next request retries.
  • TestCrashedChildIsReloadedOnDemand: a crash emits exit with the code, and the next request spawns again.
  • TestHungChildIsKilled: a child whose /health stops answering is killed and replaced.
  • TestUnloadAndClose: /models/unload stops a child, Close leaves no child answering, and requests after it are 503 with Retry-After.
  • TestLoadOnStartup: Start loads exactly the models marked load-on-startup.
  • TestMemoryBudget: footprints in /v1/models, two models that fit together, a third that needs both evicted, and one larger than the budget refused at once, 400 naming the budget, with nothing evicted.
  • TestAliasesRouteTagsDoNot: a request by alias is served by the model and unloads by alias; a tag is “not found”.
  • TestUnloadFailsWaitersWithoutReloading: unloading a model a request waits for returns, the request gets 503 with Retry-After, and the model is not loaded again.
  • TestColdLoadsRunSideBySide: with free slots, a second model loads while the first is still loading.
  • TestStoppingModelStillCounts: a model evicted but not yet exited holds its slot, however often the scheduler runs.
  • TestNoEvictionBeyondNeed: a model already stopping counts as freed, so nothing more is evicted.
  • TestSizeUnknownIsRefusedUnderABudget: under a budget, a model of unknown size is 400 and never loads.
  • TestLoadingModelIsNotAVictim and TestWantedModelIsNotAVictim: a model still loading, and one just loaded for waiting requests, are not evicted; the first becomes a victim once it is ready and unwanted.
  • TestQueueIsFirstComeFirstServed and TestNoJumpingAheadOfAnEviction: a model that fits waits behind an earlier one that does not, even while an eviction is making room for that one, and is scheduled as soon as that one leaves the queue.
  • TestNoJumpingAheadOfARestart: a request for a model still exiting holds its place, and a later model that would fit waits until it has restarted.
  • TestEvictsForEveryQueuedModel: when two queued models each need room, both victims are asked to stop at once.
  • TestLoadTimeoutFailsTheLoad: a child that never answers 200 is killed at the load timeout, and its waiters are told.
  • TestAutoloadOffNeverReloadsAStoppingModel: without autoload, a request for a model being evicted is 503 with Retry-After, not a reload.
  • TestLostPortRaceIsRetriedOnce, TestNoJumpingAheadOfARestartAfterALostRace and TestEveryAssertionHoldsAfterALostRace: a child told to bind a port the test holds exits with status 98. The rig retries that one failure, as a client would, and takes the lost attempt’s spawn and one wait per re-sent request out of the counts. Every other test’s assertions then hold after a lost race.

Your pool must emit the events router.Event documents, wait, spawn, loading, ready, evict, unload, exit and fail, with the child’s port as a spawn’s detail, because the tests wait on them, and must deliver them without holding its lock. It must also write each child’s output to Config.Log, as the field says, at any time; the rig reads a lost port race from it. TestMemoryBudget builds its own small GGUF files; its preset sets cache-ram = 0, since otherwise llama-server’s default of 8 GiB would be charged to each 10 KiB model.

With a real llama-server, by hand. None of the automated tests use a real binary. On a machine with llama-server and a small GGUF of your choice, and with no other llama-server holding the GPU, write a preset with two sections for the same file, each with n-gpu-layers = 0, and run:

aec-router -bin $(command -v llama-server) -models-preset yours.ini -models-max 1

Send a request for the first model, then for the second, and watch the second evict the first in the log, with each child’s log lines prefixed by its name. Never do this on straylight, dixie or titan beside their running services.

On the fleet, read-only. Copy aec-router to straylight and run aec-router -models-preset <the preset path from systemctl cat llama-server> -footprints. It reads GGUF headers and starts nothing. Compare its list with straylight’s GET /v1/models, read by a short urllib script of your own built with ProxyHandler({}), and check which models a budget could admit. Do not send any request that names a model.

Further reading

results matching ""

    No results matching ""