23. Proxies and cancellation
Why this layer exists
An agent abandons requests as a matter of course. A user interrupts a turn, a tool call hits its deadline, a parent cancels a subagent, a harness gives up and retries. Each abandoned request is a generation nobody will read, and while it runs it holds a slot of the model server and spends decode steps that the requests still wanted could have had. The router of chapter 22 decides which model serves a request; this chapter makes sure that when the client goes away, the generation stops.
The fleet has already paid for not doing this. tether’s design note (docs/SPEC.md, tether b267e2f, 2026-09-23) records the incident on dixie, running llama.cpp 0.4.1: on 2026-09-22 from about 23:00 to 23:42, “about 80 orphaned requests held all 8 slots, the deriver stalled (231 queued), and only systemctl restart llama-server cleared it.” Honcho’s deriver, dialectic and summaries and Hermes’s auxiliary calls are all non-streaming, and under saturation their timeouts and retries left an orphan backlog. The note also records the measurement made at 00:10 on 2026-09-23: “a stream:true chat request is cancelled within seconds when its client disconnects; a stream:false request that is queued when its client disconnects later takes a slot and generates to its full max_tokens for nobody.” tether is the fleet’s fix: a small Go proxy in front of dixie’s llama-server that sends every non-streaming chat completion upstream as a stream, assembles the result, and ties the upstream request to the client’s connection. Its unit on dixie, read on 2026-09-30, runs tether -listen 0.0.0.0:11435 -upstream http://127.0.0.1:11434 from a store path built at b267e2f. aec-router builds the same fix into its forwarder, so that every model it serves gets it.
A fix of this kind has to be measurable. A router that cannot say how many requests were abandoned, and how far each had got, cannot show that abandoned requests stop, or how often agents abandon them, which is what the router’s metrics are for.
Mechanism
Where cancellation is lost
A hang-up starts as a closed TCP connection between the client and the router, and it has to become an aborted generation inside the child. Three hops each have to pass it on.
The router must notice. Go’s net/http server cancels a handler’s r.Context() when it sees the client’s connection close, but it can only see that by reading from the connection while the handler runs, and it starts that background read only once the handler has read the request body to EOF. The server code says so (net/http/server.go, Go 1.27.1, lines 2120–2127): “When the request has a body, we start the background read only after the entire body has been consumed.” The reason is that before EOF the next bytes on the connection are body bytes the handler is entitled to; a background read would steal them. A server that has not consumed the body cannot tell a closed connection from body bytes not yet read, so it does not look. The rule is easy to get wrong in a proxy, which naturally hands the body on without reading it, so it is worth measuring. A scratch test runs a client, a front server that forwards to an upstream server with the front’s r.Context(), and an upstream that waits on its own r.Context(). Each side either reads its request body to EOF or does not, and the client cancels once the upstream has the request. On talos with Go 1.27.1 on 2026-09-30, go test -count=1 -v printed:
=== RUN TestFF
ctx_test.go:51: front reads=false up reads=false: upstream did NOT see the abort within 3s
ctx_test.go:37: front Do returned after 5.002s: Post "http://127.0.0.1:43855": context deadline exceeded
--- PASS: TestFF (5.00s)
=== RUN TestFT
ctx_test.go:51: front reads=false up reads=true: upstream did NOT see the abort within 3s
ctx_test.go:37: front Do returned after 5.001s: Post "http://127.0.0.1:41153": context deadline exceeded
--- PASS: TestFT (5.00s)
=== RUN TestTF
ctx_test.go:37: front Do returned after 0s: Post "http://127.0.0.1:40807": context canceled
ctx_test.go:51: front reads=true up reads=false: upstream did NOT see the abort within 3s
--- PASS: TestTF (5.00s)
=== RUN TestTT
ctx_test.go:37: front Do returned after 0s: Post "http://127.0.0.1:41537": context canceled
ctx_test.go:49: front reads=true up reads=true: upstream saw the abort
--- PASS: TestTT (0.00s)
PASS
ok ctxcheck 15.012s
The front’s outbound request carries a 5-second deadline of its own, so the first two cases show the front’s context never being cancelled: its Do ran until that deadline. In the third the front did notice and cancelled its upstream request at once, but the upstream had not read its body, so it did not notice its own connection closing. Only when both servers read their bodies did the hang-up cross both hops. This is why chapter 22’s Handler.ServeHTTP reads the whole body before it routes, and why fakellama reads its body before it does anything else. tether’s source carries a comment claiming the opposite, that net/http does not cancel r.Context() while the handler is blocked in an outbound Do, and works around it with CloseNotifier. The workaround rides on the same background read (handleReadErrorLocked, which cancels the context, also fires the close notification), and tether’s chat path reads the body with io.ReadAll first, so on Go 1.27.1 its context is cancelled anyway. This chapter relies on the measurement, not on the comment.
The upstream request must carry that context. http.NewRequestWithContext(r.Context(), …) ties the outbound request to the client’s. When the context is cancelled, the transport abandons the request and closes its connection to the child, whether the request is still waiting for response headers or is in the middle of the body. A proxy that builds its upstream request with context.Background(), or copies the body with a context of its own, keeps the generation running after its client has gone.
The child must notice the closed socket. What llama-server does depends on the mode, as of llama.cpp b29c606 (2026-09-14). Its HTTP layer, cpp-httplib, gives each request an is_connection_closed function: a zero-timeout select on the socket and, if it is readable, a one-byte MSG_PEEK read, which returns 0 at the client’s FIN (vendor/cpp-httplib/httplib.cpp, Server::process_request, lines 9735–9739, and is_socket_alive, lines 1795–1804). llama-server passes it to its handlers as req.should_stop. A streaming request checks it before sending each chunk (tools/server/server-context.cpp, handle_completions_impl, lines 4430–4434). The non-streaming path also passes it, into wait_for_all (line 4352). Yet tether’s measurement on the same release found queued non-streaming requests running to max_tokens. Exercise (e) reads the source for the reason. The fix does not depend on the answer: llama-server demonstrably cancels a streamed generation whose client has gone, so the proxy sends every chat completion upstream as a stream. A client that asked for one JSON object still gets one; the proxy assembles it. That is conversion. Its scope is chat completions, at /v1/chat/completions and at /chat/completions, which llama-server serves with the same handler. llama-server’s other generation routes, /completion, /completions, /v1/completions, /v1/responses, /responses, /v1/messages and /infill (tools/server/server.cpp, lines 253–264), pass through unconverted, so a non-streaming request to one of them keeps the queued-orphan behaviour. The agent stack of the later parts speaks chat completions (chapter 24), which is why the conversion stops there.
Conversion
A non-streaming chat completion is one chat.completion object. The same request with "stream": true is a sequence of chat.completion.chunk objects whose delta fields carry the pieces. The proxy sets two fields on the way up, stream: true and stream_options.include_usage: true, changes nothing else, and rebuilds the object from the chunks by tether’s rules. Each rule follows from how the chunks divide the object.
Content. Write the message’s text as a string , and the content deltas of one choice, in arrival order, as . The server cuts into these pieces, so , where juxtaposition is concatenation. Concatenation is associative, so how the server grouped tokens into chunks does not matter, and appending each delta to a buffer as it arrives rebuilds exactly. An empty delta is the identity and changes nothing. reasoning_content, where llama.cpp puts a thinking model’s reasoning, is a second string cut the same way, and it is concatenated into its own buffer under its own name: merged into content it would hand the reasoning to a client that asked for the answer.
Tool calls. A message with tool calls arrives as fragments, each tagged with the index of its call, . The first fragment of call carries its id, type and function.name, and every fragment adds a piece of function.arguments. Fragments of different calls may interleave; the lab’s test sends call 1’s first fragment before call 0’s. So the merge is keyed by index, not by arrival position, and not by id, which only the first fragment carries. For a fixed , the argument pieces arrive in order over one TCP stream, so the argument rule is the content rule applied per index. The calls are emitted in index order, which is the order of the non-streaming response’s array. A message with tool calls and no text has content null, not "", as the OpenAI API returns it; a client that tests for content is None to recognise a tool-only turn depends on that.
finish_reason appears on one chunk near the end, and a chunk without one sends null. The assembler takes the last non-null value, so a null cannot erase it. usage is not in any chunk unless the request asks for it: include_usage makes the server send one more chunk, after the finish chunk, with "choices": [] and the token counts, and llama-server attaches timings, its per-request timing object, to whichever chunk is last (tools/server/server-task.cpp, lines 487–517). That chunk is why the proxy sets include_usage; without it the assembled object, and the router’s token counters, would have no usage. timings is passed through. logprobs arrive per chunk as arrays under logprobs.content, and their concatenation in order is the response’s array, by the content argument again. id, model, created and system_fingerprint are the same on every chunk and are taken from the first.
What the assembler does not rebuild it does not invent. It knows the fields above and drops any other, such as the __verbose debugging object llama-server adds to the first chunk when asked. Field order in the JSON object differs from the server’s own, which JSON does not give a meaning. The proxy also does nothing else on the client’s behalf, by tether’s rules: it does not change any other field (a 20-digit seed passes through as the digits sent, because the body is handled as raw JSON values, never decoded into float64), it does not retry, and it has no timeouts of its own. The client’s deadlines stay the client’s, and the proxy only adds cancellation.
Errors keep their place. An upstream that answers with an error status before the stream starts, such as llama-server’s 400 for a malformed request, is passed through with its status and body unchanged. An error inside a stream that began with 200, either an SSE error event or a data object with an error field, becomes a 500 whose body is {"error": …} with the upstream’s error object, as the same failure would have been had it come before the stream. A stream that is not valid at all, such as a chunk that is not JSON, or a stream that ends without a single chunk, is 502 Bad Gateway with a message saying the model’s stream could not be assembled, and so is a child that refuses the connection. Here aec-router differs from tether, which answers 500: the fault is the upstream’s, and 502 says so. A child that answers a converted request with 200 and something other than an event stream, a plain chat.completion for instance, has its answer passed through unchanged: there is nothing to assemble, and dropping it would lose the answer.
Pass-through
Every other request passes through, streaming chat completions included. A streamed body is a text/event-stream, and the format’s unit is the event: lines of field: value, ended by a blank line (WHATWG HTML, §9.2.5–9.2.6). A line that starts with a colon is a comment, which llama-server uses as a keep-alive ping (:\n\n after sse_ping_interval, 30 seconds by default, of silence; common/common.h line 624). An event is complete at its blank line and not before, so the proxy reads the child’s stream an event at a time, writes each event’s raw bytes, comments included, and flushes at that boundary. The client’s parser sees what the child sent, byte for byte, when the child sent it. A proxy that buffers instead delays every token until a buffer fills, and the first token until the buffer or the response ends; that delay is chapter 24’s time to first token, added by a component that has no reason to add it. The format allows a lone CR as a line ending, which llama-server never sends, and the reader here does not split on it. The format also discards a final block not followed by a blank line; this reader hands it over, so that a pass-through copies every byte.
Two transport settings follow. Compression is disabled on the upstream transport: Go’s transport otherwise asks for gzip on its own and decompresses the answer transparently, and a gzipped stream arrives in blocks of the compressor’s choosing, which the proxy could flush per event only by re-framing it. That setting stops only the transport’s own request, not a client’s: the OpenAI SDKs send Accept-Encoding: gzip, and the proxy forwards the client’s headers. A converted request therefore goes upstream with Accept-Encoding: identity, because the proxy itself has to parse the answer. A pass-through request keeps the client’s header, and whatever encoding the child chooses reaches the client as sent. llama-server compresses neither at b29c606: its vendored cpp-httplib is built without CPPHTTPLIB_ZLIB_SUPPORT (vendor/cpp-httplib/CMakeLists.txt), and would not compress text/event-stream in any case (httplib.cpp, line 2862). On the loopback between router and child, compression would save nothing. And hop-by-hop fields are dropped in both directions. RFC 9110 §7.6.1 says an intermediary MUST remove Connection and every field it names as an option, and SHOULD remove Proxy-Connection, Keep-Alive, TE, Transfer-Encoding and Upgrade, which describe one connection, not the message; the proxy removes all of them, and also Trailer and the proxy authentication pair, which RFC 2616’s list of hop-by-hop fields included. Host and Content-Length are dropped too, because net/http sets them for the next hop.
Everything else is copied, Retry-After included. A child that answers 503 (llama-server while loading, for instance) reaches the client with its status, body and Retry-After unchanged, and the router’s own 503s from chapter 22 carry Retry-After: 5. The retry decision belongs to chapter 24’s client, which reads both the same way. The router’s Retry-After stays a fixed 5 seconds: nothing measured here gives a reason to vary it by cause.
Metrics
The router’s metrics are served at GET /metrics (without ?model=, which chapter 22 routes to a child) in the Prometheus text exposition format, version 0.0.4, content type text/plain; version=0.0.4 (prometheus/docs exposition_formats.md at c42ff58). Each metric family is a # HELP name text line, a # TYPE name counter|gauge|histogram line, and one sample line per series: the name, an optional label set {a="x",b="y"}, a space and the value. Help text escapes \ and newline; label values escape \, " and newline. A value is a float in Go’s ParseFloat syntax, or NaN, +Inf or -Inf. A series is a name plus a set of label values, and every distinct set is a separate series that Prometheus stores and indexes.
Three types are used. A counter only goes up (it resets to zero when the process restarts), and what is read from it is its rate. A gauge goes up and down and is read as is. A histogram counts observations into buckets with fixed upper bounds and exposes, for a histogram named x, one x_bucket{le="u"} counter per bound , which counts every observation and so is cumulative, a mandatory x_bucket{le="+Inf"} equal to the total, and x_sum and x_count (prometheus/docs metric_types.md at 4933d05).
The router’s series:
| Metric | Type | Labels | What it counts |
|---|---|---|---|
aec_router_requests_total |
counter | model, kind, code |
requests forwarded, by outcome |
aec_router_request_duration_seconds |
histogram | model, kind |
from forwarding to the last byte |
aec_router_first_byte_seconds |
histogram | model |
from forwarding to the first byte of the child’s body |
aec_router_tokens_total |
counter | model, type |
prompt and completion tokens the child reports in usage |
aec_router_requests_in_flight |
gauge | model |
requests being forwarded now |
aec_router_cancelled_total |
counter | model, stage |
requests whose client hung up |
aec_router_model_events_total |
counter | model, event |
pool lifecycle events: spawn, ready, evict, unload, exit, fail |
kind is converted, stream or passthrough. code is the HTTP status the client was sent, the child’s or the proxy’s own 400, 500 or 502, or 499 when the client hung up before the whole answer had been written: nginx’s “client closed request”, used here because nobody received a complete answer, whatever the child had begun to send. An answer written in full, a stream up to its [DONE] (or the child’s end of stream) or a whole non-streamed body, counts with its status even if the client closes its connection before the handler returns. stage is waiting when the hang-up came before the child’s first body byte and streaming after it. Chapter 49’s daemon serves its own families (chapter 28’s aec_route_*, aec_provider_requests_total and aec_breaker_open, and the aecd_* families) and does not re-serve these; a scraper of a stack that runs the router reads this /metrics too, and the names are fixed so its rules keep working.
The label sets must stay bounded. Every series costs memory in the registry and in Prometheus, and a label whose value comes from a request lets a client create series at will: one typo per request, or one hostile client, grows them without limit. Every model label here is a catalog name, because the handler refuses an unknown model before it calls the forwarder, and it passes the forwarder the model’s catalog name even when the request named an alias, so each model has one set of series that joins with aec_router_model_events_total and with its child’s own metrics. The number of series is bounded by the catalog’s size times the other labels’ few values. tether solves the same problem another way: its canonicalModel maps any name not in the router’s model list to other.
The counters miss two things. A client that hangs up while its request is still in the router’s own queue, waiting in Acquire for a model to load, never reaches the forwarder: Handler.fail sees the cancelled context and writes nothing, so neither requests_total nor cancelled_total records it (exercise (d)). And a streaming request passes through unchanged, so its tokens are counted only if its client asked for include_usage; the proxy does not add it, because the extra chunk would change what the client receives. Converted requests always carry usage.
Quantiles from buckets. A histogram exists to answer “how slow is the slowest tenth”, which its buckets can answer only approximately. Let the upper bounds be , with , let be the cumulative count of bucket , with , and let be the total. The -quantile of sorted observations is the observation at rank , where . The cumulative counts are non-decreasing in , so there is a first bucket with , and for it . The observations of bucket lie in , and the histogram says nothing about where. Assume they are spread uniformly over that interval. Then the observations of rank advance evenly from to : rank sits at for . Setting the rank equal to gives , and the estimate
This is the linear interpolation histogram_quantile performs for classic histograms (prometheus/prometheus docs/querying/functions.md at 76dce27: “it assumes a uniform distribution of observations within the bucket (also called linear interpolation)”). The same page fixes the two edges: the lowest bucket’s lower limit is taken as 0 when its upper bound is positive, as does here, and a quantile that falls in the +Inf bucket is reported as the highest finite bound, since an interval with no upper end has no interpolation.
How wrong can be? Since , the fraction lies in , so . The true quantile lies there too: the counts are integers, so gives , and gives , so the observation of rank is one of bucket ’s. Two points of an interval of width differ by less than that width:
The error approaches the bound when bucket ’s observations are bunched at one end. The walkthrough’s run below has an example. Its two converted requests to small took a few milliseconds and, abandoned by curl -m 1, just over a second; their sum is 1.0021 seconds. The second lies in . For , , the first bucket with is with and , and seconds, about 1.2 seconds above the true value and within the bound of 1.5.
The error is a fraction of the bucket’s width, so the bounds decide the precision at each scale. A request to a local model takes from tens of milliseconds (a cached prefix and a short answer) to minutes (a long answer, or a queue). Thirteen equal buckets over 0 to 600 seconds would each be about 46 seconds wide, and every interactive request would fall into the first. What has to stay bounded is the error relative to the value. For a bucket , both and lie in with , so each exceeds and neither exceeds , and the larger divided by the smaller is less than
the ratio of the bucket’s bounds. The estimate is within a factor of the truth. With bounds that grow by a constant ratio that factor is the same at every scale, and spanning from to takes buckets. The lowest bucket has no such ratio; there the absolute bound, its upper bound, is the useful one. The router’s bounds are 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300 and 600 seconds: ratios of 2, 2.5 or 3 between neighbours, whose product is . At throughout, spanning that range would take buckets; these thirteen bounds cover it with ratios of 2 to 3, so from 50 milliseconds to 10 minutes an estimate is within a factor of 3 of the true quantile, and within a factor of 2 or 2.5 outside the bucket from 10 to 30 seconds. Below 50 milliseconds it is off by less than 50 milliseconds, and above 10 minutes it reports 600 seconds. Each (model, kind) pair costs 16 series: 13 buckets, +Inf, _sum and _count.
Little’s law, , derived in chapter 19’s “Queueing and backpressure” with no assumption about how arrivals or service times are distributed, ties three of these series together. It is exact over a window that starts and ends with nothing in flight; otherwise the requests in flight at the window’s edges make the two sides differ by their times, an error that shrinks relative to both as the window grows. On the router, is the rate of aec_router_requests_total summed over its labels, is aec_router_request_duration_seconds_sum divided by _count over the same window, and is the time-average of aec_router_requests_in_flight, itself estimated from the gauge’s values at each scrape. The three are recorded independently, so a window in which the identity fails by more than the edge requests and the sampling can explain points at a series that is recorded wrong. The same identity applies inside a child, with llama.cpp’s own gauges: the router’s gauge drops when a client leaves, but a generation that runs on keeps a child’s slot busy, so a child whose busy and queued requests exceed the router’s in-flight count for its model is running orphans.
First byte. aec_router_first_byte_seconds runs from the moment the forwarder sends the request to the child until the first byte of the child’s response body. It therefore includes the child’s queue wait for a slot and its prompt processing, and it excludes the router’s own wait for the model to load, which happens before the forwarder is called. For a stream, llama-server sends nothing, headers included, until its first result is ready (handle_completions_impl, lines 4384–4413), so this is the router’s view of time to first token. For a converted request it is the first streamed byte too, but the client sees nothing until the stream has been assembled: its time to first token is the request’s whole duration. The histogram measures the child, not what a converting client experiences.
Walkthrough
go/internal/proxy holds the forwarder, go/internal/obs the metrics registry. Forward is the router’s Forwarder (chapter 22): the handler calls it with the request, the model’s name, the child’s address and the body it has already read.
// Forward sends the request to the child and copies the answer back. A
// non-streaming chat completion is converted; anything else passes through,
// a server-sent event at a time. The upstream request carries the client's
// context, so a client that hangs up cancels it, and the child's server sees
// its connection close.
func (p *Proxy) Forward(w http.ResponseWriter, r *http.Request, model string, target *url.URL, body []byte) {
start := time.Now()
kind := "passthrough"
if converts(r) {
kind = "converted"
if wantsStream(body) {
kind = "stream"
}
}
p.m.InFlight.Add(1, model)
defer p.m.InFlight.Add(-1, model)
var code int
var delivered bool // was the whole answer written: a stream's [DONE], or a complete body?
started := false // has the child's body begun?
out, err := body, error(nil)
if kind == "converted" {
out, err = forceStream(body)
}
if err != nil {
code, delivered = http.StatusBadRequest, jsonError(w, http.StatusBadRequest, err.Error())
} else {
code, delivered = p.forward(w, r, model, kind, target, out, func() {
started = true
p.m.FirstByte.Observe(time.Since(start).Seconds(), model)
})
}
if !delivered && r.Context().Err() != nil {
stage := "waiting"
if started {
stage = "streaming"
}
p.m.Cancelled.Inc(model, stage)
code = 499 // nginx's "client closed request": nobody received the whole answer
}
p.m.Requests.Inc(model, kind, strconv.Itoa(code))
p.m.Duration.Observe(time.Since(start).Seconds(), model, kind)
}
kind is decided from the method, the path and the body’s stream field. started is set by firstByte, a reader wrapped around the child’s body that calls its function on the first byte read through it, which is also where the first-byte histogram is observed. forward reports the status it sent and whether it wrote the whole answer, delivered. The cancellation check comes after it returns: if the answer was not delivered and the client’s context is cancelled, the request is a cancellation at the stage it reached, and its code is 499. A client that reads a stream through [DONE] and closes its connection while the proxy still waits for the child’s end of stream has its answer, and counts as 200. InFlight is incremented on entry and decremented by a defer, so a panic cannot leave it high. A chat completion to be converted whose body, or whose stream_options, is not a JSON object is refused with 400 and a message naming which, counted like any other answer, before anything is sent upstream.
// forceStream sets "stream": true and stream_options.include_usage, so the
// final chunk carries the token counts. Every other field keeps its value:
// it is carried as raw JSON, so numbers are never re-parsed as float64.
func forceStream(body []byte) ([]byte, error) {
var req map[string]json.RawMessage
if err := json.Unmarshal(body, &req); err != nil {
return nil, errors.New("request body is not a JSON object")
}
opts := map[string]json.RawMessage{}
if raw, ok := req["stream_options"]; ok && present(raw) {
if err := json.Unmarshal(raw, &opts); err != nil {
return nil, errors.New("stream_options is not a JSON object")
}
}
opts["include_usage"] = json.RawMessage("true")
req["stream"] = json.RawMessage("true")
req["stream_options"], _ = json.Marshal(opts)
return json.Marshal(req)
}
The body is decoded into map[string]json.RawMessage, so each field’s value stays the bytes the client sent, and only stream and stream_options are replaced. An existing stream_options object keeps its other keys. The test that pins this sends "seed":12345678901234567890, which float64 cannot hold, and checks it arrives unchanged. Re-encoding sorts the keys; field order in a JSON object carries no meaning.
forward (not listed) builds the upstream request with r.Context(), the client’s path and query, the filtered headers and the body, and for a converted request sets Accept: text/event-stream and Accept-Encoding: identity. On a transport error it answers 502, unless the client has gone, in which case it writes nothing. Then it picks one of three ways to answer: a converted request that got 200 with an event stream is assembled; any text/event-stream answer is streamed; anything else, an error status or a body that is not a stream, is copied with its status and headers. A copied body counts as delivered when the copy reached the child’s end of body without an error. copyHeaders drops the hop-by-hop fields and those named in Connection.
// stream copies the child's events to the client as they arrive, flushing
// after each, and counts the tokens of any usage chunk on the way. It
// reports whether the client was sent the whole stream: up to [DONE], or to
// the child's end of stream.
func (p *Proxy) stream(w http.ResponseWriter, model string, up io.Reader) bool {
flush := func() {}
if f, ok := w.(http.Flusher); ok {
flush = f.Flush
}
done := false
err := ReadEvents(up, func(ev Event) error {
if _, err := w.Write(ev.Raw); err != nil {
return err // the client has gone
}
flush()
p.countUsage(model, ev.Data)
done = done || ev.Data == "[DONE]"
return nil
})
return done || err == nil
}
stream writes each event’s raw bytes and flushes. A failed write means the client has gone; returning its error stops the read, and Forward’s context check counts the cancellation. The stream counts as delivered once [DONE] has been written, or, for a stream without one, once the child’s stream ended and every event was written. countUsage looks at an event only if its data mentions "usage", and adds the counts of a usage chunk to the token counter. A count that is not a finite, non-negative integer is the child’s error and is left out: Counter.Add panics on a negative delta, since a counter only goes up, and nothing a child sends may panic the router.
// ReadEvents reads a text/event-stream and calls emit once per event, at the
// blank line that ends it, and once for trailing lines at EOF. Lines end in
// LF or CRLF (the format also allows a lone CR, which llama-server never
// sends); a line starting with ':' is a comment; "field: value" drops one
// space after the colon; several data lines join with newlines. Every block
// of lines is emitted, comments included, so that a pass-through can copy
// the stream exactly. An error from emit stops the read and is returned, as
// is ErrEventTooLong once an event passes MaxEvent bytes.
func ReadEvents(r io.Reader, emit func(Event) error) error {
br := bufio.NewReaderSize(r, 64<<10)
var ev Event
var data []string
var line []byte
for {
part, err := br.ReadSlice('\n')
line = append(line, part...)
if len(ev.Raw)+len(line) > MaxEvent {
return ErrEventTooLong
}
if err == bufio.ErrBufferFull {
continue // the line goes on past the buffer
}
if len(line) > 0 {
ev.Raw = append(ev.Raw, line...)
text := strings.TrimRight(string(line), "\r\n")
line = line[:0]
switch {
case text == "":
ev.Data = strings.Join(data, "\n")
if err := emit(ev); err != nil {
return err
}
ev, data = Event{}, nil
case text[0] == ':':
// a comment: kept in Raw, no field
default:
field, value, _ := strings.Cut(text, ":")
value = strings.TrimPrefix(value, " ")
switch field {
case "event":
ev.Name = value
case "data":
data = append(data, value)
}
}
}
if err == io.EOF {
if len(ev.Raw) > 0 {
ev.Data = strings.Join(data, "\n")
return emit(ev)
}
return nil
}
if err != nil {
return err
}
}
}
ReadEvents accumulates lines until a blank one and then emits the event: its event field, its data lines joined with newlines, and its raw bytes. Comment lines and unknown fields stay in Raw and add nothing else, and a block of comments alone is emitted with empty data. One space after the colon is dropped, as the format specifies, so data:x and data: x carry the same value. The 64 KiB buffer is a read size, not a line limit: a longer line is read in pieces and joined. What is limited is the event. Once one passes MaxEvent, 16 MiB, the read stops with ErrEventTooLong, so a child that never ends a line, or never ends an event, cannot grow the router’s memory without bound; a pass-through stream then ends without [DONE], and a conversion is a 502.
// convert assembles the child's stream into one chat.completion. An error
// the child sends inside the stream becomes a 500 with its body, as the
// same error before the stream began would have been; a stream that cannot
// be assembled, or has no chunk at all, is the child's fault: 502. It
// reports the status and whether the whole answer was written.
func (p *Proxy) convert(w http.ResponseWriter, r *http.Request, model string, up io.Reader) (int, bool) {
c, err := Assemble(up)
if r.Context().Err() != nil {
return http.StatusBadGateway, false // the client left before its answer existed
}
var se *StreamError
switch {
case errors.As(err, &se):
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, err := w.Write(se.Body)
return http.StatusInternalServerError, err == nil
case err != nil:
return http.StatusBadGateway, jsonError(w, http.StatusBadGateway, "cannot assemble the model's stream: "+err.Error())
}
if c.Usage != nil {
p.countUsage(model, `{"usage":`+string(c.Usage)+`}`)
}
b, err := json.Marshal(c)
if err != nil {
return http.StatusInternalServerError, jsonError(w, http.StatusInternalServerError, err.Error())
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(b)
return http.StatusOK, err == nil
}
convert turns the assembler’s three outcomes into statuses: an error the child sent inside the stream is 500 with that error’s body, any other failure is 502, and success is 200 with the assembled object. The usage it counts is the assembled object’s, the same counts the stream carried.
// Assemble reads a chat.completion.chunk stream and builds the one
// chat.completion it amounts to: per choice index, content and
// reasoning_content concatenated separately; tool calls merged by their
// index, the first fragment carrying id, type and name and every fragment
// adding to the arguments; finish_reason from the last chunk that has one;
// usage, timings and logprobs carried over. An error inside the stream is
// returned as *StreamError, and a stream without a chunk as ErrEmptyStream.
func Assemble(r io.Reader) (*Completion, error) {
out := &Completion{Object: "chat.completion", Choices: []Choice{}}
accs := map[int]*choiceAcc{}
chunks := 0
err := ReadEvents(r, func(ev Event) error {
if ev.Name == "error" {
return &StreamError{Body: errorBody([]byte(ev.Data))}
}
if ev.Data == "" || ev.Data == "[DONE]" {
return nil
}
var c chunk
if err := json.Unmarshal([]byte(ev.Data), &c); err != nil {
return fmt.Errorf("stream chunk is not JSON: %w", err)
}
if present(c.Error) {
return &StreamError{Body: errorBody(c.Error)}
}
chunks++
if out.ID == "" && c.ID != "" {
out.ID, out.Created, out.Model, out.SystemFingerprint = c.ID, c.Created, c.Model, c.SystemFingerprint
}
if present(c.Usage) {
out.Usage = c.Usage
}
if present(c.Timings) {
out.Timings = c.Timings
}
for _, ch := range c.Choices {
a := accs[ch.Index]
if a == nil {
a = &choiceAcc{calls: map[int]*ToolCall{}, args: map[int]*strings.Builder{}}
accs[ch.Index] = a
}
if ch.Delta.Role != "" {
a.role = ch.Delta.Role
}
a.content.WriteString(ch.Delta.Content)
a.reasoning.WriteString(ch.Delta.ReasoningContent)
if ch.FinishReason != nil && *ch.FinishReason != "" {
a.finish = *ch.FinishReason
}
if ch.Logprobs != nil {
a.logprobs = append(a.logprobs, ch.Logprobs.Content...)
}
for _, tc := range ch.Delta.ToolCalls {
call := a.calls[tc.Index]
if call == nil {
call = &ToolCall{Type: "function"}
a.calls[tc.Index], a.args[tc.Index] = call, &strings.Builder{}
}
if tc.ID != "" {
call.ID = tc.ID
}
if tc.Type != "" {
call.Type = tc.Type
}
if tc.Function.Name != "" {
call.Function.Name = tc.Function.Name
}
a.args[tc.Index].WriteString(tc.Function.Arguments)
}
}
return nil
})
if err != nil {
return nil, err
}
if chunks == 0 {
return nil, ErrEmptyStream
}
for _, i := range sortedKeys(accs) {
a := accs[i]
msg := Message{Role: a.role, ReasoningContent: a.reasoning.String()}
if msg.Role == "" {
msg.Role = "assistant"
}
for _, k := range sortedKeys(a.calls) {
a.calls[k].Function.Arguments = a.args[k].String()
msg.ToolCalls = append(msg.ToolCalls, *a.calls[k])
}
if text := a.content.String(); text != "" || len(msg.ToolCalls) == 0 {
msg.Content = &text
}
c := Choice{Index: i, Message: msg, FinishReason: a.finish}
if a.logprobs != nil {
c.Logprobs, _ = json.Marshal(map[string]any{"content": a.logprobs})
}
out.Choices = append(out.Choices, c)
}
return out, nil
}
The accumulators are per choice index, because a request with n > 1 interleaves the chunks of several choices. Within a choice, calls and args are maps keyed by the tool call’s index, and a call’s Type defaults to function so that a server that omits it in the first fragment still produces a valid call. present treats a JSON null as absent, which is how a null usage or error on a chunk is ignored. content is set to a string when there is text or when there are no tool calls, and left nil only for a message of tool calls alone. errorBody turns either error shape into {"error": {...}}: an upstream error object is kept as it is, and anything else becomes its message.
// Observe records one value: it lands in the first bucket whose upper bound
// is at least v. The exposition makes the counts cumulative.
func (h *Histogram) Observe(v float64, values ...string) {
h.r.mu.Lock()
defer h.r.mu.Unlock()
s := h.f.get(values)
i := sort.SearchFloat64s(h.f.buckets, v) // first bound >= v
if i < len(h.f.buckets) {
s.counts[i]++
} else {
s.inf++
}
s.sum += v
s.count++
}
sort.SearchFloat64s returns the first bound , which is the inclusive upper bound le means. Each observation increments one non-cumulative count; the cumulative sums are formed only when the registry is written.
// WriteTo writes every family: # HELP and # TYPE lines, then one line per
// series. A histogram is written as cumulative _bucket series, one per upper
// bound (le) ending with +Inf, then _sum and _count.
func (r *Registry) WriteTo(w io.Writer) (int64, error) {
r.mu.Lock()
defer r.mu.Unlock()
var b strings.Builder
for _, f := range r.families {
fmt.Fprintf(&b, "# HELP %s %s\n# TYPE %s %s\n", f.name, helpEscaper.Replace(f.help), f.name, f.kind)
keys := make([]string, 0, len(f.series))
for k := range f.series {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
s := f.series[k]
if f.kind != histogram {
fmt.Fprintf(&b, "%s%s %s\n", f.name, labelSet(f.labels, s.values), formatValue(s.value))
continue
}
var cum uint64
for i, bound := range f.buckets {
cum += s.counts[i]
fmt.Fprintf(&b, "%s_bucket%s %d\n", f.name, labelSet(f.labels, s.values, "le", formatValue(bound)), cum)
}
fmt.Fprintf(&b, "%s_bucket%s %d\n", f.name, labelSet(f.labels, s.values, "le", "+Inf"), cum+s.inf)
fmt.Fprintf(&b, "%s_sum%s %s\n", f.name, labelSet(f.labels, s.values), formatValue(s.sum))
fmt.Fprintf(&b, "%s_count%s %d\n", f.name, labelSet(f.labels, s.values), s.count)
}
}
n, err := io.WriteString(w, b.String())
return int64(n), err
}
Families come out in registration order and series sorted by their label values, so two scrapes of an unchanged registry are identical. A histogram’s buckets are written in increasing le, as the format requires, and the +Inf bucket is the running sum plus the observations above the last bound, which equals _count. The registry’s recorders defer their unlock, so a misuse panic (a negative counter increment, a wrong number of label values) cannot leave the registry locked; registering a duplicate name, an invalid name or the reserved label le panics at startup, where the mistake is in the code.
cmd/aec-router creates the registry and the metrics, passes metrics.OnEvent into the pool’s OnEvent callback beside its log line, and gives the handler Forward: proxy.New(metrics) and Metrics: reg. OnEvent counts every pool event except wait and loading: wait is one per request that found its model unloaded, a request’s event rather than the model’s, and loading marks the child’s first 503 during a load that spawn and ready already bracket.
A run
The walkthrough uses chapter 22’s fake catalog and fake llama-server. It starts the router for 12 seconds and sends three requests: a non-streaming one, which the proxy converts; a streaming one with include_usage, which passes through; and a non-streaming one with the fake’s fake_hold, which makes the child hold it before its first byte as a busy llama-server holds a queued request, abandoned by curl -m 1 after a second. Then it asks the small child, on its port from the router’s log, whether it saw an abort, and reads /metrics:
cd go && go build -o /tmp/aec-router ./cmd/aec-router && go build -o /tmp/aec-fake-llama ./cmd/aec-fake-llama && cd ..
timeout 12 /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:11498 > /tmp/aec-router.log 2>&1 &
curl -s --retry-connrefused --retry 20 --retry-delay 1 http://127.0.0.1:11498/v1/chat/completions -d '{"model":"small","messages":[]}'
curl -s -N http://127.0.0.1:11498/v1/chat/completions -d '{"model":"medium","stream":true,"stream_options":{"include_usage":true},"messages":[]}'
curl -s -m 1 http://127.0.0.1:11498/v1/chat/completions -d '{"model":"small","fake_hold":true,"messages":[]}'; echo "curl exit $?"
port=$(grep -o 'small listening on 127.0.0.1:[0-9]*' /tmp/aec-router.log | cut -d: -f2)
curl -s "http://127.0.0.1:$port/fake/wait?aborted=1"
curl -s http://127.0.0.1:11498/metrics
On talos on 2026-09-30 at 23:05, the converted request’s answer was the assembled object, in the field order of Completion:
{"id":"chatcmpl-fake","object":"chat.completion","created":1790834738,"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}}
The fake sends no system_fingerprint, so the object has none. The streaming request came back as the child sent it, event by event:
data: {"choices":[{"delta":{"content":"","role":"assistant"},"finish_reason":null,"index":0}],"created":1790834739,"id":"chatcmpl-fake","model":"medium","object":"chat.completion.chunk"}
data: {"choices":[{"delta":{"content":"a"},"finish_reason":null,"index":0}],"created":1790834739,"id":"chatcmpl-fake","model":"medium","object":"chat.completion.chunk"}
data: {"choices":[{"delta":{"content":" medium"},"finish_reason":null,"index":0}],"created":1790834739,"id":"chatcmpl-fake","model":"medium","object":"chat.completion.chunk"}
data: {"choices":[{"delta":{"content":" answer"},"finish_reason":null,"index":0}],"created":1790834739,"id":"chatcmpl-fake","model":"medium","object":"chat.completion.chunk"}
data: {"choices":[{"delta":{},"finish_reason":"stop","index":0}],"created":1790834739,"id":"chatcmpl-fake","model":"medium","object":"chat.completion.chunk"}
data: {"choices":[],"created":1790834739,"id":"chatcmpl-fake","model":"medium","object":"chat.completion.chunk","usage":{"completion_tokens":3,"prompt_tokens":5,"total_tokens":8}}
data: [DONE]
These are the chunks the converted request was assembled from, too: the empty first delta, three content deltas whose concatenation is “a medium answer”, the finish chunk, and the usage chunk with "choices":[]. The third request printed curl exit 28, curl’s timeout, and the child’s counters then read:
{"aborted":1,"completed":1,"held":1,"requests":2}
The small child had two requests: the first completed, and the held one was aborted. The child saw the hang-up because each hop passed it on: curl closed its connection, the router’s net/http cancelled r.Context() because the handler had read the body, the proxy’s upstream request was cancelled and its connection closed, and the fake, which had also read its body, saw its own context cancelled. /metrics then held these families, excerpted verbatim, without the histograms:
# HELP aec_router_requests_total Requests forwarded to a model, by outcome.
# TYPE aec_router_requests_total counter
aec_router_requests_total{model="medium",kind="stream",code="200"} 1
aec_router_requests_total{model="small",kind="converted",code="200"} 1
aec_router_requests_total{model="small",kind="converted",code="499"} 1
# HELP aec_router_tokens_total Tokens the models report in usage, by type.
# TYPE aec_router_tokens_total counter
aec_router_tokens_total{model="medium",type="completion"} 3
aec_router_tokens_total{model="medium",type="prompt"} 5
aec_router_tokens_total{model="small",type="completion"} 3
aec_router_tokens_total{model="small",type="prompt"} 5
# HELP aec_router_requests_in_flight Requests being forwarded now.
# TYPE aec_router_requests_in_flight gauge
aec_router_requests_in_flight{model="medium"} 0
aec_router_requests_in_flight{model="small"} 0
# HELP aec_router_cancelled_total Requests abandoned by their client, by how far they had got.
# TYPE aec_router_cancelled_total counter
aec_router_cancelled_total{model="small",stage="waiting"} 1
# HELP aec_router_model_events_total Model lifecycle events: spawn, ready, evict, unload, exit, fail.
# TYPE aec_router_model_events_total counter
aec_router_model_events_total{model="medium",event="ready"} 1
aec_router_model_events_total{model="medium",event="spawn"} 1
aec_router_model_events_total{model="small",event="ready"} 1
aec_router_model_events_total{model="small",event="spawn"} 1
The abandoned request is the line aec_router_requests_total{model="small",kind="converted",code="499"} 1: a converted request to small whose client left before any answer, and aec_router_cancelled_total{model="small",stage="waiting"} 1 says it left before the child’s first byte, which is where the fake held it. Only one of small’s two requests counted tokens, the one that completed. The streaming request’s tokens are there because its client asked for usage. The model events count each model’s spawn and ready; the router’s wait events, one per request that found its model unloaded, are in its log but not in the counter. One histogram, the request duration of small’s converted requests:
# HELP aec_router_request_duration_seconds Time from forwarding a request to its last byte.
# TYPE aec_router_request_duration_seconds histogram
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="0.05"} 1
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="0.1"} 1
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="0.25"} 1
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="0.5"} 1
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="1"} 1
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="2.5"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="5"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="10"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="30"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="60"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="120"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="300"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="600"} 2
aec_router_request_duration_seconds_bucket{model="small",kind="converted",le="+Inf"} 2
aec_router_request_duration_seconds_sum{model="small",kind="converted"} 1.0021378490000001
aec_router_request_duration_seconds_count{model="small",kind="converted"} 2
The counts are cumulative: the fast request is in every bucket from 0.05 up, the abandoned one from 2.5 up, and +Inf equals _count. The sum prints as 1.0021378490000001 because Go writes the shortest decimal that parses back to the same float64, and the float64 this sum landed on is not the one nearest 1.002137849, so seventeen significant digits are needed. The router’s log, which timeout ended with SIGTERM after 12 seconds:
2026/09/30 23:05:37 small: size unknown: open /nonexistent/small.gguf: no such file or directory
2026/09/30 23:05:37 medium: size unknown: open /nonexistent/medium.gguf: no such file or directory
2026/09/30 23:05:37 large: size unknown: open /nonexistent/large.gguf: no such file or directory
2026/09/30 23:05:37 aec-router: serving 3 models on 127.0.0.1:11498
2026/09/30 23:05:37 small wait
2026/09/30 23:05:37 small spawn 38441
[small] fakellama: small listening on 127.0.0.1:38441
2026/09/30 23:05:38 small ready
2026/09/30 23:05:38 medium wait
2026/09/30 23:05:38 medium spawn 45517
[medium] fakellama: medium listening on 127.0.0.1:45517
2026/09/30 23:05:39 medium ready
2026/09/30 23:05:49 small unload
2026/09/30 23:05:49 medium unload
aec-router: stopped
The abandoned request left nothing in the log: it found small loaded, was forwarded, and was cancelled inside the forwarder.
Exercises
(a) Reproduce the four-case matrix with two httptest servers and a client, as the Mechanism describes, and explain each case from net/http’s background read. Then add a fifth case in which the front reads only half of a body larger than one read, and predict its outcome before running it.
Answer
The front is an httptest.Server whose handler optionally runs io.ReadAll(r.Body), then sends an upstream request built with http.NewRequestWithContext(r.Context(), …); the upstream optionally reads its body, signals that it has the request, and waits on r.Context().Done() with a deadline. The client cancels when the upstream signals.
Neither reads: the front never arms its background read, so it never sees the client go; its outbound request runs to its own deadline, and the upstream is never cancelled. Only the upstream reads: the same at the front, so the upstream’s connection is never closed and it has nothing to see. Only the front reads: the front’s context is cancelled, its transport closes the upstream connection, but the upstream has not reached body EOF and so is not watching. Both read: the cancellation crosses both hops at once.
The fifth case behaves like “the front does not read”: bodyRemains() is still true after a partial read, so the read that would arm the background read (the one that hits EOF) never happens, and the client’s hang-up is not seen. On talos with Go 1.27.1, a front that read 512 KiB of a 1 MiB body before forwarding never saw the client go: its upstream request ran to its 5-second deadline, and the upstream saw no abort. A server that wants to see the hang-up must consume the body to the end, which is why the router reads it whole, bounded by MaxBody.
(b) A histogram has bounds 0.5, 1, 2.5 and 5 seconds, with cumulative counts 40, 70, 95 and 100 (and +Inf 100). Estimate the median and the 95th percentile by linear interpolation, and give each estimate’s error bound.
Answer
The total is 100. The median’s rank is ; the first bucket with is , with and , so seconds, with error below the bucket’s width, 0.5 seconds.
The 95th percentile’s rank is 95; the first bucket with is , with and , so seconds, the bucket’s upper bound, with error below 1.5 seconds. When the rank equals a bucket’s cumulative count, the estimate is that bucket’s bound.
(c) Suppose the forwarder took the model label from the request body before the handler’s catalog check. What goes wrong, and for whom?
Answer
Every distinct model string a client sends, a typo or a deliberately random name per request, creates new series in four families at once (requests, duration, first byte, in-flight), and a histogram costs 16 series per label set. The registry’s memory grows without bound in the router, and Prometheus stores and indexes every series it scrapes, so the cost lands on the monitoring system too, for as long as its retention. One client can therefore degrade both. The handler’s catalog check bounds the label to the catalog’s names; a router that had to accept arbitrary names would map unknown ones to a single value, as tether’s canonicalModel maps them to other.
(d) aec_router_cancelled_total{stage="waiting"} counts a request abandoned before the child’s first byte. Name the places such a request can be at that moment, and say which of them the router can tell apart, and how.
Answer
Three places: in the router’s own pool queue, waiting in Acquire for its model to load or for a slot; in the child’s queue, deferred because every slot is busy; and in prompt processing in a slot, before the first token. The router can tell the first from the other two, but not through this counter: a hang-up inside Acquire never reaches the forwarder (Handler.fail sees the cancelled context and writes nothing), so it is not counted at all, and the pool’s wait event in the log is its only trace. Counting it would take a counter in the handler’s failure path. The second and third are indistinguishable from outside the child: both are before the first body byte. The child’s own metrics separate them in aggregate, llamacpp:requests_deferred against llamacpp:requests_processing (exercise (f)), but not per request.
(e) At b29c606 the non-streaming path passes should_stop into wait_for_all, and should_stop is cpp-httplib’s is_connection_closed. Find why tether nonetheless measured queued non-streaming requests running to max_tokens. Read is_connection_closed in the cpp-httplib that llama.cpp vendors at b29c606, then follow wait_for_all into tools/server/server-queue.cpp and find when should_stop is actually called for a task still waiting in the queue. Assert nothing you did not read.
Answer
Read on 2026-09-30 at llama.cpp b29c606. is_connection_closed works: Server::process_request sets it to !detail::is_socket_alive(sock) (vendor/cpp-httplib/httplib.cpp, lines 9735–9739, cpp-httplib 0.56.0), which returns “alive” when a zero-timeout select finds the socket unreadable and otherwise peeks one byte, so a FIN reads as closed (lines 1795–1804). The detection is not where the time goes.
The polling is. wait_for_all (server-queue.cpp, lines 580–600) loops on next(should_stop), and next (lines 548–577) calls should_stop() only when recv_with_timeout returns no result. recv_with_timeout (lines 450–473) waits on condition_results for HTTP_POLLING_SECONDS, 1 second (server-context.cpp line 39), and returns null only if that wait times out; any wake-up restarts a full second’s wait. server_response::send (lines 480–493) calls notify_all on that one condition variable for a result of any task some handler is waiting for. So while results for other requests arrive at least once a second, as they do on a busy server, where every streamed token is a result, a waiting handler’s should_stop is never called, and its queued task is not cancelled. When the task reaches a slot, the two modes part. A streaming task sends partial results; its chunk callback checks should_stop before each chunk (server-context.cpp, lines 4430–4434), so it stops after its first token. A non-streaming task sends no partial results (they are sent only when params.stream is set, line 1876); its handler keeps waiting on the same notifications and keeps not polling, and the task generates to the end.
This reading explains the measurement; it was not reproduced against dixie, and the fleet’s traffic on 2026-09-22 was not observed here. tether’s measurement remains the operative fact, and the reading also says what conversion buys: a converted request queued behind busy slots still costs its prompt processing and one token after its client has gone, not max_tokens.
(f) Read-only, on dixie: with a urllib script of your own, GET /v1/models from dixie’s router and, only if it shows honcho-embed with status.value loaded, immediately GET /metrics?model=honcho-embed&autoload=false. Re-check /v1/models immediately before the second request, never send it otherwise, and never name another model. Find llamacpp:requests_processing and llamacpp:requests_deferred and say what each counts. Why is the colon legal in a metric name, and why does Prometheus advise against it?
Answer
If the child was started without --metrics, the answer is llama-server’s error “This server does not support metrics endpoint. Start it with --metrics” (server-context.cpp, lines 4669–4670), and the families below cannot be read live. Their definitions at b29c606 are in tools/server/server-task.cpp (lines 1578–1585): requests_processing is the number of busy slots, and requests_deferred the number of tasks waiting for a slot, both gauges, written with the prefix llamacpp: (lines 1596–1598).
The colon is legal because the format’s metric names follow the expression language’s identifier, [a-zA-Z_:][a-zA-Z0-9_:]*. Prometheus’s data model reserves it by convention: “Colons (‘:’) are reserved for user-defined recording rules. They SHOULD NOT be used by exporters or direct instrumentation” (prometheus/docs data_model.md at 8bdb919). llama.cpp ignores the convention; a recording rule over these series must therefore avoid producing names that collide with them.
Lab
The lab mechanics are chapter 22’s. go/labs/ch23/lab.go declares Impl, a constructor for a router.Forwarder that records into a proxy.Metrics and the stream assembler, and checks at compile time that the reference and go/labs/ch23/mine have the same API. Write mine/proxy.go, New, Forward and Assemble, and run
make lab CH=23 IMPL=mine
make lab CH=23 runs the same tests against the reference. Provided: proxy.ReadEvents (the SSE reader, which keeps each event’s raw bytes), the proxy.Completion types and StreamError, the obs registry, and proxy.NewMetrics, whose help strings say what each series counts.
The tests pin:
- Pass-through, byte-identical and flushed per event: the upstream holds back the rest of its stream until the client has read the first two events, so a proxy that buffers deadlocks the test until its deadline. A usage chunk on the way is counted, and the first byte is observed once, though the body arrives in two reads. Usage counts that are negative or fractional are left out, and the stream and the conversion that carry them are still answered in full.
- The upstream request: the client’s path and query; for a conversion, at either chat path,
stream: true,Accept: text/event-streamandAccept-Encoding: identity; for a pass-through, the client’s ownAccept-Encoding. - Cancellation reaching the upstream, in four cases: converted and streaming, each abandoned before any token and mid-stream. Every upstream reads its body to EOF, the precondition for noticing. The test waits until the upstream reports its own context cancelled, and checks the 499 and the
stage. Its converse: a stream read through[DONE]by a client that then closes, while the child still holds its connection open, counts as 200 and no cancellation. The stage is pinned wherever the client can know it. A converted request abandoned mid-stream races with the proxy reading the first event, since its client sees nothing until assembly ends, so only the cancellation is pinned there. - Conversion to the exact object, with reasoning, interleaved tool-call fragments emitted in index order,
finish_reason,usageandtimings, and the request’s other fields untouched: a 20-digitseedarrives as sent. - The edges of assembly: null content for tool calls alone;
""for an empty answer; nousagewithout a usage chunk, and a later null that does not erase one; the lastfinish_reason; logprobs merged in order; both shapes of an error inside the stream; a truncated chunk; keep-alive comments and empty events, which are not chunks; two choices whose chunks interleave; a stream with no chunk at all. - Upstream errors: an error status before the stream passes through unchanged; an error inside the stream is 500 with its message; an unparseable stream, a stream with no chunk and an unreachable child are 502; a converted request answered 200 with something other than a stream gets that answer unchanged; a
stream_optionsthat is not an object is the proxy’s own 400, counted; a child’s 503 keeps itsRetry-After; a 204 with no body records no first byte. - End to end: the router’s handler and pool in front of a fake child, with the proxy as forwarder. Its first request names the model by an alias, and the series carry the catalog name. A request the child holds, as a busy llama-server holds a queued one, is abandoned, and the child reports the abort through
/fake/wait?aborted=1; then/metricsmust parse line by line as the exposition format, and must count the model’sreadyevent but not itswait. That test is the chapter’s claim, executed.
The reference passes in under 0.1 seconds on talos (0.03 to 0.09 seconds over the runs made for this chapter, on 2026-09-30, with talos under other load). A mutation pass on straylight (2026-10-01), one deliberate fault at a time in the proxy, the assembler, the SSE reader, the registry and the handler’s model label, made 83 faults that compile; these tests and the packages’ own caught all 83. Among the caught: an upstream request built with context.Background(), swapped or constant stage labels, a missing 499, a delivered stream counted as 499, no flush per event, tool calls in arrival order, a ping parsed as a chunk, a content that is never null, a 500 where 502 belongs, and a first byte recorded for an answer with an empty body. One fault, writing an answer to a client already gone, was caught in the final pass and missed in an earlier one: whether a write to a closed connection fails depends on timing, and the context check it removes is what makes the count independent of it.
An optional measurement: drive the walkthrough’s router on your machine with N concurrent streaming requests from a Go program of your own, read /metrics before and after, and check Little’s law, , over a window that starts and ends with nothing in flight. Say which machine produced the numbers.
Further reading
- WHATWG, HTML Living Standard, §9.2 “Server-sent events”: the event stream’s grammar (§9.2.5) and how a client interprets it line by line (§9.2.6).
- Prometheus,
docs/instrumenting/exposition_formats.mdat c42ff58 (the text format, version 0.0.4);docs/concepts/metric_types.mdat 4933d05 (counters, gauges, histograms);docs/concepts/data_model.mdat 8bdb919 (names and labels); and prometheus/prometheusdocs/querying/functions.mdat 76dce27 (histogram_quantileand its interpolation). - John D. C. Little, “A Proof for the Queuing Formula: L = λW”, Operations Research 9(3), 383–387 (1961).
- R. Fielding, M. Nottingham and J. Reschke (editors), “HTTP Semantics”, RFC 9110 (2022). §7.6.1 “Connection”: hop-by-hop fields and what an intermediary must remove.
- Jeffrey Dean and Luiz André Barroso, “The Tail at Scale”, Communications of the ACM 56(2), 74–80 (2013). Why latency is measured as a distribution, and what its tail costs a system that fans out.
- llama.cpp at b29c606:
tools/server/server-context.cpp,tools/server/server-queue.cppand the vendoredvendor/cpp-httplib/httplib.cpp, for how llama-server notices a client that has gone. - tether,
docs/SPEC.mdat b267e2f (2026-09-23), the reader’s own stream-converting proxy: the incident of 2026-09-22, the measurement behind it, and the assembly rules this chapter follows. It is in the reader’s private repository and has no public link.