0281. HTTP server v2: one poll loop, keep-alive, streaming and SSE
- Status: Accepted (maintainer, 2026-11-22; recommended defaults for all open questions; frozen-file edits listed here approved)
- Date: 2026-11-22
- Plan: R6; M-HTTP follow-on; supersedes the deferral in 0165
- Review: Design Critic #13; Planner #5
Context
v1 (ADR-0165) serves one connection at a time,
Connection: close, with a 30 s total deadline per
connection (ADR-0163). One slow client (slow-loris headers, a
stalled reader) blocks every other client for up to 30 s, each
request pays a TCP handshake, and nothing can stream: agent UIs
cannot push model tokens to a browser. http.wire
rejects Transfer-Encoding (501). Threads are a poor
fit: par workers reject non-Fs
capabilities (ADR-0103), arenas are per thread (ADR-0102), and the
runner is single-threaded (ADR-0107). The outbound side already
has a pull-based http.transport
(start/poll/cancel,
ADR-0247) and a chunk-safe SSE parser (ADR-0108). TLS stays at a
reverse proxy (Caddy) on the box, per PLAN-http; WebSockets are
later.
Decision
- Concurrency: one thread, one
poll(2)loop, non-blocking sockets. No worker pool, no process per connection in v2. A slow client never blocks others; a slow handler still does, and handlers must bound their work (as today). Aparhandler pool is a later ADR, only if Measurement S2 shows handler CPU dominates. Multi-core = run N processes later (SO_REUSEPORT), not threads. - One new native set on
cli(as ADR-0165 foresaw):Net.wait(listener, reads: vec<Conn>, writes: vec<Conn>, ms) -> result<Waited, CliError>withWaited { now_ms, events }andNetEvent = Accepted(Conn) | Data(Conn, bytes) | Writable(Conn) | Closed(Conn) | Term;Conn.write_some(bytes) -> result<i64, CliError>(bytes taken, non-blocking) andConn.key() -> i64. Events are ordered listener first, then by key, so both backends agree. C:poll(2)plus a SIGTERM/SIGINT self-pipe (Term). Interpreter:set_nonblockingscan with 1 ms backoff (std only, no crate, nounsafe). Wait-accepted conns have no total deadline; the server's timers replace it.CliError.Iokeeps its fixed message set. - Pure core, thin driver
(
http.server).step(Server, Waited) -> Stepped { server, out: vec<Out> }withOut = Write(key, bytes) | Close(key) | Dispatch(id, Request)holds per-connection parser state, timers and buffers as plain values (map set-reuse, ADR-0053). It is unit-testable with fake events; the driver only callsNet.wait/write_some. - Two APIs, no closures needed. Plain:
serve(listener, handler, cfg)keepsHandler.handle(Request) -> Responseunchanged. Pull (for agent apps, mirrors ADR-0247):poll(server, ms) -> Polled { server, events }, thenrespond(server, id, Response),open(server, id, status, headers),send(server, id, bytes) -> Sent,finish(server, id). The app's loop polls its modelTransportand the server side by side; no callback crosses C. Once ADR-0275 closures land,serve_fn(listener, cfg, { req -> ... })and middleware become plugin sugar over the same core. - Keep-alive and limits (
Config, defaults):max_conns256 (at the cap, stop polling the listener; the kernel backlog pushes back),head_ms10 000 for a complete request head,idle_ms5 000 between requests,write_stall_ms30 000,max_requests1 000 per connection,out_cap1 MiB buffered per connection, pluswire.Limits(8 KiB line, 16 KiB / 100 headers, 1 MiB body). One request in flight per connection; pipelined bytes wait in the input buffer under the same caps.Connection: closeand HTTP/1.0 are honoured. - Streaming. Chunked request bodies are decoded
under the body cap (501 goes away).
openresponses use chunked framing on HTTP/1.1 and close-delimited on 1.0. Fixed responses keepContent-Length. - Backpressure.
sendreturnsSent.Queued | Sent.Full;Writable(id)fires below half ofout_cap. A stream aboveout_capforwrite_stall_msis closed, so one stalled SSE reader cannot grow memory. - SSE (
http.sse):event(name: option<str>, id: option<str>, data: str) -> bytessplits data on LF intodata:lines and rejects CR/LF in name/id;comment(str);start(headers)setstext/event-stream,Cache-Control: no-cache. The server sends a:heartbeat every 15 s on idle streams.Last-Event-IDreaches the app as a header. Encoder output must parse back unchanged under ADR-0108's rules (CR/LF/CRLF, joined data lines). - Graceful shutdown. On
Term: stop polling the listener, close idle connections, sendConnection: closeon in-flight responses, emitTermto pull apps (to end streams), and exit afterdrain_ms(10 000). - Arenas. Each
step/pollcall is one transition (ADR-0107 shape): request parsing and handler scratch die with it; onlyServerstate carries over.
Prior art
- Go
net/http: goroutine per conn;ReadHeaderTimeout,IdleTimeout,Shutdown— https://pkg.go.dev/net/http#Server - nginx event model (one loop per worker, epoll/kqueue) — https://nginx.org/en/docs/events.html, https://aosabook.org/en/v2/nginx.html
- Node.js event loop and
server.headersTimeout/keepAliveTimeout— https://nodejs.org/api/http.html#serverheaderstimeout - Python asyncio / uvicorn (
timeout-keep-alive,limit-concurrency) — https://www.uvicorn.org/settings/ - hyper on tokio
(
http1::Builder::header_read_timeout) — https://docs.rs/hyper/latest/hyper/server/conn/http1/struct.Builder.html; Zigstd.http.Server(caller-driven, one connection at a time) — https://ziglang.org/documentation/master/std/#std.http.Server; SSE: https://html.spec.whatwg.org/multipage/server-sent-events.html
Alternatives considered
- Thread pool, one arena per worker
(ADR-0100/0102) — conflicts with ADR-0103 capture rules
(
Connis notFs), needs shared mutable server state, and breaks backend determinism. - Process per connection (fork) — 1–2 ms and MBs per connection, no shared SSE state; fan-out would need IPC.
- epoll/kqueue now — two code paths;
poll(2)is fine at 256 fds. Can sit behindNet.wait. - Callbacks from a C loop into handlers — interpreter parity and arena ownership get hard; the pull API gives the same power with values.
- libuv / h2o embed — external dependency and a second I/O model.
Consequences
UX: one slow browser or stalled tab no longer freezes the app;
tokens stream live. DX: same Handler, keep-alive by
default, a documented knob set mirroring Go's. AX: one loop, one
native, pure step testable with fake events; the pull
API reuses the ADR-0247 shape agents already know. Harder: the
per-connection state machine is new code (~600 lines Tenon); slow
handlers still block (documented). LANGUAGE.md: 0 lines;
plugins/http/DOCS.md (1 500 budget, near full) moves
transport detail to a linked section. No new compile-time
diagnostics. Frozen files (slice 4 only, needs the maintainer's
OK): plugins/cli/platform.toml,
plugins/cli/native/trt_net.h,
plugins/cli/DOCS.md,
crates/tenon/src/interp_net.rs,
crates/tenon/src/interp.rs (native dispatch).
Coordinate with Forge P7/P8, which also serve HTTP.
Measurement plan
Baseline v1 before any code, in new bench/http/
(opt-in, not the gate). Load client: a stdlib-only Python asyncio
client (bench/http/load.py);
oha/wrk used when on PATH. C backend for
timing; the interpreter only for byte-identical responses. Record
req/s, p50/p99 latency, peak RSS, open fds; 5 runs, median.
| ID | Scenario | v2 acceptance |
|---|---|---|
| S1 | 1 / 16 / 256 keep-alive clients, 200 B GET | 1 client within 10% of v1; 16 ≥ 3× v1; 256 no errors, RSS ≤ 64 MiB, fds ≤ 272 |
| S2 | 1 slow-loris (1 byte/s head) + 16 fast clients | fast p99 ≤ no-loris p99 + 5 ms (v1: ~30 s) |
| S3 | 1 reader that stops reading a 10 MiB stream + 16 fast | same as S2; RSS growth ≤ out_cap |
| S4 | SSE fan-out: 100 clients, 10 events/s × 200 B, 60 s | all events in order; p99 event latency ≤ 50 ms; RSS flat (≤ 10% after warm-up) |
| S5 | static files 4 KiB and 1 MiB via http.files |
≥ Python ThreadingHTTPServer req/s |
| S6 | SIGTERM with 50 in-flight requests | all complete; exit ≤ drain_ms |
Implementation slices
- bench/http baseline of v1 — S1–S6 runner,
RESULTS.md. Files:
bench/http/. Frozen: no. Agent: Claude Sonnet. - Wire: chunked codec, keep-alive framing,
http.sseencoder — test blocks (ADR-0269). Files:plugins/http/{wire,sse}.tn, DOCS.md. Frozen: no. Agent: Claude Sonnet. - Pure
http.servercore (step,Config, timers, backpressure, pull API) with fakeWaitedevents. Files:plugins/http/server.tn. Frozen: no. Agent: Claude Opus. Net.wait/write_some/keynatives in both backends +Termself-pipe. Files:plugins/cli/platform.toml,plugins/cli/native/trt_net.h,plugins/cli/DOCS.md,crates/tenon/src/interp_net.rs,crates/tenon/src/interp.rs. Frozen: yes. Agent: Claude Opus (or OpenCode build-deep).- Driver
serve, examples (examples/tools/http-demo/SSE token stream), v2 bench run vs thresholds, retire v1serveloop. Files:plugins/http/{serve,server}.tn,examples/,bench/http/RESULTS.md. Frozen: no. Agent: Claude Sonnet.
Open questions (resolved)
Resolved by maintainer on 2026-11-22: every question takes its stated default.
- Approve slice 4's frozen-file touches before M14 ends? Default: yes, after slices 1–3 land.
- Default
max_conns: 256 or 1 024? Default: 256 (fits defaultulimit -n). - Keep v1
serveas an alias of v2 or remove it? Default: alias for one release, then remove. - Handler worker pool: decide now or only if S2/S5 show need? Default: only after measurement.
- WebSockets: a separate later ADR on the same loop? Default: yes, after R4 web toolkit ships.