Repository navigation
Serve each page through starlette and uvicorn - #774
Conversation
One process per page, as before: `LeafHTTPServer` now opens the listening socket itself and hands uvicorn a duplicate, so the port is a fact before anything serves and a taken address still raises out of the constructor. `Handler` keeps the page's own boundary — route scoping, the key and its cookie, the layer gate, the `Leaf-*` headers, `_select_page` multiplexing and the preview snapshot mode — and becomes an ordinary per-request object that `page_app` builds and runs on a worker thread. Gone with the standard library: the `handle` BrokenPipe suppression, `log_message`, the `ThreadingHTTPServer` subclasses and their `SHUT_RD` close, `DualStackHTTPServer`, `server_at`, the `protocol_version` choice, and the news stream's `select()` peer-gone loop, which `StreamingResponse` now owns. The 50 ms `LOOK_S` re-stat is unchanged; only its transport moved, and the loop reads `server.stopping` as it did. The event door now declares its body bound instead of discovering it through a failed allocation, so a `Content-Length` past 10 MiB is refused in those words. starlette, uvicorn and anyio move from transitive `mcp` dependencies to stated ones, floored at the lowest versions this interpreter resolves; the server, website and MCP suites were run against exactly those. sse-starlette is deliberately not among them: its `EventSourceResponse` writes `data:` frames leaf already writes, its documented `ping=0` spins rather than disabling the keepalive `ALIVE_S` already provides, and it patches `uvicorn.Server.handle_exit` process-wide on import. State: complete. `uv run pytest tests` is green (1133 passed), pre-commit is green, and `leaf server start`/`stop` timings are within noise of the base, bar ~20 ms of extra import in the detached child. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts: # TODO.md
leaf-agent
left a comment
There was a problem hiding this comment.
The transport swap itself reads well, and my selection is green — tests/test_interact_server.py -k "server or news or stream or close or bind or wildcard or idle or preconnect or refus" (101 passed) and tests/test_website_server.py (72 passed). Three things below survive that: two change behaviour a reader can reach, and one is a header the rewrite dropped in passing.
A handled signal never reaches the news stream, so a stop with a tab open hangs. shutdown() sets stopping and should_exit together, but a signal goes to uvicorn's own handle_exit, which sets only should_exit. _readings loops on self.server.stopping, so it keeps yielding, and uvicorn's graceful shutdown waits on open connections with timeout_graceful_shutdown unset — an unbounded wait. Reproduced against this head on a real page: with one /api/news reader connected the server was still alive 15s after SIGTERM; with no reader it exited at once. That is worker/server.py's container stop, where every reader holds a stream, and leaf serve in the foreground on Ctrl-C.
Related, and why the new comment in worker/server.py does not hold: uvicorn re-raises the captured signal after its graceful shutdown, with the original handler already restored (capture_signals, in uvicorn's server.py), so SIGTERM then terminates the process by its default disposition and the finally never runs. In the reproduction the process reported -15, and neither server_close() nor agent_host.close() ran — the removed signal.signal(SIGTERM, lambda *_: sys.exit(0)) was what carried them. Setting stopping from handle_exit ends the hang but not this; if the App Server stop is owed, the adapter needs to make it before uvicorn re-raises.
The declared 10 MiB bound reads Content-Length, which a chunked body does not carry. _read_posted refuses on the declared length and then calls read_body(), which buffers the whole stream regardless. A Transfer-Encoding: chunked POST to /api/event therefore passes the bound untouched: 40 MiB sent to a server on this head was buffered whole and answered 200. On an ordinary page server the key gate stands in front of that read, but worker/server.py's WebsitePageHandler.authorized() returns True — "the outer Worker has already selected this browser's isolated container" — so on the website there is no gate, and this bound is what stands between a visitor and the container's memory. Before this change the same request read zero bytes and was refused as invalid JSON. The suggestions keep the declared-length refusal, which the door needs to answer a length with no body behind it, and put the same bound on the read.
Cache-Control: no-store is gone from the news stream. _news sent it beside the content type; the StreamingResponse now carries media_type plus whatever end_headers appended, which is X-Content-Type-Options and the Leaf-* set. Nothing in the suite asserts it, so it went quietly.
Three findings from review, each reproduced first. A signal reaches uvicorn alone, and its `handle_exit` sets `should_exit` without telling the news stream to end, so a page with one reader survived SIGTERM past 30 seconds; `stopping` is now set in a wrapper around it, and the same page exits in 0.5 s. The 10 MiB event bound read `Content-Length`, which a chunked body does not carry, so 12 MiB sent in chunks was buffered whole and then refused as invalid JSON. The bound now belongs to the read, which stops taking chunks once they pass it. The door answers and closes while the sender is still writing, so the new case treats a broken pipe as the refusal arriving early. The news stream lost its `Cache-Control: no-store` in the rewrite; `_news` now asserts the header every test that opens a stream goes through. Everyday suite 1,136 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
leaf-agent
left a comment
There was a problem hiding this comment.
Three things on this head. The first is new, and it is the one I would hold the merge on: the swap turns a full pipe from a leaked thread into a page that stops answering.
A full stderr pipe now stops the page. start_server spawns the detached serve with stderr=subprocess.PIPE and deliberately never drains it — the comment there rests the safety of that on "the handler logs nothing (log_message)", and log_message is the override this PR deletes. uvicorn's uvicorn.error logger writes into that pipe instead: log_config=None configures nothing, so logging's last-resort handler prints every warning to stderr, and "Invalid HTTP request received." is one 31-byte line per unparsable request line. The write now happens on the single serving loop rather than in a per-request thread, so the page dies with it rather than one thread.
Paired against origin/main, same page directory, same undrained pipe, 3,000 malformed request lines then one GET /api/state: the base took 64,759 bytes into the pipe and still answered HTTP/1.0 200 OK; 512cc106 filled the pipe after 2,112 requests (2,112 × 31 = 65,472 bytes) and never answered again, with the process still alive. It needs the parent to still hold the pipe, which is the watcher's revive path — start_server(page_dir, revive=True) in session.py — and scripts/preview.py, not a leaf server start that returns and lets the writes fail.
Either fix works and the choice is design rather than mechanics: drain the child's stderr into a discard thread, which makes start_server's premise true; or give uvicorn.error a NullHandler and propagate = False in LeafHTTPServer, which makes the uvicorn.Config comment's "a server with a logging voice of its own" true instead. I can push whichever you pick.
An unauthenticated WebSocket upgrade reaches page_app and answers 500 with a traceback naming http.py. websockets is a stated dependency and uvicorn.Config leaves ws at "auto", so uvicorn hands the handshake to the app as a websocket scope — past _select_page, the key gate, and the rest of what this file calls the page's own boundary. raise ValueError(f"leaf serves HTTP, not {scope['type']}") is what the peer gets: HTTP/1.1 500 Internal Server Error and the traceback, which is the shape test_a_reader_who_closes_the_tab_is_not_a_server_error existed to keep out of a log and which this PR removes. It is also the cheapest writer into the pipe above, at ~600 bytes a request. ws="none", suggested inline, makes the scope unreachable and hands the request back to the ordinary HTTP path where the key gate answers it.
The container's stop still skips what the adapter says it owes. Reproduced again on this head: SIGTERM to a LeafHTTPServer process exits -15 in 0.16 s with the finally never entered, because capture_signals restores the original handler and re-raises the captured signal before run() returns. The description now reads as though all three review findings were fixed, and the new comment in worker/server.py — "the close below is what this adapter still owes its App Server when the container is taken away" — asserts the opposite of what happens. Make the stop run that close, or drop the claim and say the container teardown owns it; as written the finally is dead on the only path that reaches it.
The three fixes in 512cc106 themselves check out: the wrapper does reach uvicorn's handle_exit, the bound does belong to the read and refuses a chunked body while the sender is still writing, and no-store is back and asserted for every stream _news opens.
Reproductions and selection run
Selection, green on this head: tests/test_interact_server.py -k "news or stream or door or refusal or bound or stop or close or idle or preconnect or serve" (101 passed), tests/test_website_server.py (72 passed), and test_every_event_door_refusal_is_final_and_read_refusals_name_the_attempt five times alone under -n0, green each time.
The pipe reproduction spawns LeafHTTPServer over the page directory the page_dir fixture builds, in a child with stdout=PIPE, stderr=PIPE and nothing draining either — start_server's own arrangement — then sends NOT-A-REQUEST\r\n\r\n on a fresh connection 3,000 times and finishes with one GET /api/state?t=…. On origin/main the same probe against server_at writes 64,759 bytes of socketserver tracebacks into the pipe (end_headers reads self.path on a request line that never parsed, which is a base-branch bug of its own) and keeps answering, because each of those writes blocks a request thread rather than the loop.
The stop reproduction is a child that runs serve_forever inside try/finally, where the finally writes a marker file; SIGTERM 1 s in gives exit -15 and no marker.
The upgrade reproduction is a raw Upgrade: websocket handshake on the page port. With ws="none" set on the config the same request is logged as an unsupported upgrade and served as ordinary HTTP, so the page_app guard becomes unreachable — worth noting the two warning lines uvicorn emits there also land on stderr, which the first finding's fix needs to cover.
A detached serve's stderr is a pipe its parent stops reading once the URL is in hand, and the override that kept the old handler quiet went with `http.server`. uvicorn's own "Invalid HTTP request received." took its place at 31 bytes a refusal, and on the serving loop the write that fills the pipe stops the page answering: measured, 2,112 malformed request lines and the page never answered again. Its loggers now hold a NullHandler and do not propagate, which is what the comment beside the config already claimed. `test_a_refused_request_line_writes_nothing_into_the_pipe_nobody_drains` sends 2,500 of them and then reads state; it times out against the talking server. `ws="none"` keeps an upgrade handshake on the ordinary HTTP path, where the key gate answers it with a sentence. Left on, it arrived as a scope past the gate and the route scoping, and the peer got a 500 with a traceback naming `http.py`. The comment in `worker/server.py` said the close was what the adapter owed its App Server on SIGTERM. uvicorn re-raises the captured signal with the original handler restored, so the process dies where it stood and the `finally` never runs; the comment now says the close is for the ordinary return and that a container taken away takes the socket and the child with it. Everyday suite 1,138 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
leaf-agent
left a comment
There was a problem hiding this comment.
The three fixes on this head check out. The loggers are silenced before anything can construct a uvicorn.Server, and "uvicorn" alone already covers uvicorn.asgi by ancestry; ws="none" makes _should_upgrade_to_ws return False so the handshake falls through to ordinary HTTP — I got 403 with open the link leaf printed; it carries the key as the body; and the worker/server.py comment now matches capture_signals, which restores the original handler and re-raises before run() returns. Selection green: tests/test_interact_server.py and tests/test_website_server.py, 175 passed.
One thing holds the verdict, and it is in the two new tests rather than the server. Both end their read on a timeout instead of on the response the server states, which tests/CLAUDE.md rules out under A wait consumes a fact the system states — "It does not infer completion from elapsed time" — and A wait states its end as well as its fact. The consequences differ:
test_a_refused_request_line_writes_nothing_into_the_pipe_nobody_drainsfinishes withfetch, which passes no timeout to urllib, so that read blocks with no end. On exactly the regression the test exists to catch, the wedged loop still has the kernel accepting from the listen backlog — 2,500 is well underSOMAXCONN, so the send loop never raises either — and nothing answers, so the test does not fail, it hangs;cmd_stopin thefinallywould hang too, since it waits on the server's lease. Measured on this head with theNullHandlerblock removed fromLeafHTTPServer.__init__and nothing else changed: no pytest output at all, killed at 240s. So the "it times out against the talking server" in the thread isci's 20-minute cap, not the test: the worker's remaining share of the suite goes with it, and the job concludescancelledrather than naming an assertion — the shaperunning-tendalready warns reads as a replaced run.test_an_upgrade_is_answered_by_the_key_gate_like_any_other_requestreads until the peer closes, which is uvicorn'stimeout_keep_alive: 5.02s, the slowest case in the file and 5s added to every everyday gate. The complete response is in hand in 13ms.
Both suggestions below are measured — 1.53s and 0.02s for the two cases, with the same assertions passing. The upgrade one leaves the heard = b"" seed above it redundant; worth deleting with it.
`test_a_refused_request_line_writes_nothing_into_the_pipe_nobody_drains` finished with a read that had no end of its own. On the regression it exists to catch, the kernel keeps accepting from the backlog while nothing answers, so the test hung rather than failed: measured, no pytest output at 240 s with the silencing removed. The read now carries a timeout, and the same control fails in 8.6 s naming what it waited for. `test_an_upgrade_is_answered_by_the_key_gate_like_any_other_request` read until the peer closed, which is uvicorn's 5 s keep-alive, with the whole response already in hand. It now reads the response the server states: both cases together take 1.4 s. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A rejected candidate now earns one line and the number that decided it, so asking again costs a glance rather than a survey. The digest store leaves TODO for that table: it buys disk and nothing else, 38 KB a save against 3.28 MB. Five conditional items become one line each under what would trigger them, the items that stay lose their narrative and keep what constrains the work, and the header states the rule so the lists stay this way. Two measurements land with it. The chrome libraries are answered while the question stays open: 12 commits since the rename across the ~500 lines of dialog and popover glue one of them would own, against 88 across the margin, the keyboard and the trays — worth reaching for where the platform has no primitive, not as a retrofit. And #774 left `Handler` wearing `BaseHTTPRequestHandler`'s shape over a starlette response, which is now item #25, because a compatibility layer inside a finished cutover is the one thing this repository does not keep. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`TODO.md`'s item 25. #774 moved the transport to starlette and uvicorn, but the per-request object kept `BaseHTTPRequestHandler`'s shape: a route left its answer on `self.response` after assembling a `_headers` list through `send_header` and `end_headers`, and a `close_connection` flag decided whether the answer ended the connection. That is a compatibility layer inside a finished cutover, so it goes rather than getting renamed. Behaviour at the HTTP boundary is unchanged, deliberately: same status codes, same header sets on the same paths, same refusals, same `Connection: close` on a declared body no route drained. ### Reading the diff `skills/leaf/scripts/leaf/http.py` carries the change; `worker/server.py` and `skills/leaf/scripts/leaf/mcp_page.py` are the two transports that subclass it, and `hosting.py` is the seam to uvicorn. **Routes return responses.** `_get`, `_post`, `_select_page` and the `_serve_*` helpers each return a `starlette` response, or `None` where they have nothing to answer with. `self.response` is gone. **One place for the shared headers.** `_delivery_headers()` returns the `Leaf-*` delivery identity, the key cookie, `nosniff`, and `Connection: close`, and `respond()` applies it once to whatever the route returned. The website adapter extends it (`{"Leaf-Session": "active", **super()._delivery_headers()}`) instead of overriding `end_headers`. The key gate was already the single gate in `_answer` and stayed there. The layer gate stays on the POST path, where it needs the view revision the request names; `response_layer` and `set_cookie` are both decided inside routes, so ASGI middleware would still leave the routes writing to `request.state` and would make the website's extra header a second middleware wrapping an app that does not otherwise exist. **Construction.** `Handler` becomes `PageEndpoint`, bound to its page by an ordinary constructor rather than by a `type()` subclass, so `handler_for` becomes `page_endpoint` and hands back a `partial`. `LeafHTTPServer` takes that endpoint and now owns the two facts that were living on the handler class: `server_id`, the incarnation a tab watches, and `viewed_at`, the news stream's reader-recency throttle. **Fallout.** `self.command` becomes `self.method`; the path and query arrive already apart, removing the fourteen `urlsplit(self.path)` calls that split them again per route; `layer` is derived from `layer_identity` rather than stored beside it, which drops an assignment each multiplexed transport had to remember; and the website adapter's `bootstrap` binding, which nothing read, is deleted. ### Checks Green locally: `ruff`, the everyday suite (1138), and a complete `uv run pytest tests --run-nightly` (2703). No TypeScript changed, so neither the worker nor the browser-framework gate is in scope. > _This was written by Claude Code on behalf of max-sixty_ Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
The nightly leg of `ci` on `main` went red on [run 35295861023](https://github.com/max-sixty/leaf/actions/runs/35295861023): `test_tab_extends_the_comment_with_individual_emoji_buttons` opened the command reference expecting its `z` row to read `Take back: shorten on “The store is capped…`, and read a register of 81 commands with no such row. The case now opens the reference from the moment the page says the press is live, which is the fact the row states. That row is dead until the page has taken in a log reading that accounts the reader's own send. `history.undo`'s `when` clause asks `!unaccountedGesture() && Boolean(undoable())` ([`keyboard/page.js:1178`](https://github.com/max-sixty/leaf/blob/8d8bec8005c970234abd5f33415c25463a09aa01/skills/leaf/assets/runtime/keyboard/page.js#L1178)), and `undoable()` reads the server projection `runtime.view.undo` and answers null while a state is still being applied ([`projection/commands.js:19`](https://github.com/max-sixty/leaf/blob/8d8bec8005c970234abd5f33415c25463a09aa01/skills/leaf/assets/runtime/projection/commands.js#L19)). The case pressed `?` straight off `painted()` — the forward paint the reaction makes in the turn it sends, a turn before that reading arrives — and the register is built at the press, so the sentence it asserts could not be in it. `render_harness.undo` already carries this exact hazard for the `z` press itself, and waits on the line offering the chip: the line and the dispatcher ask one predicate, so the chip standing on the line is the page saying the press will be taken. This case waits on the same fact one step earlier, before opening the reference that names it. Not caused by `8d8bec80`, the commit this run reports on. The ordering was never stated; #774 (`145da07d`, serving each page through starlette and uvicorn) moved the timing into the window it left open. CI says the same on its own: the nightly leg of `145da07d`'s [run 35289151800](https://github.com/max-sixty/leaf/actions/runs/35289151800) failed this case with this message, and the last green `main` nightly before it is `f292b4d2` ([run 35282456731](https://github.com/max-sixty/leaf/actions/runs/35282456731)). `dc694cd8` and `80c26f0f` sit between them and were replaced before their nightly ran, so CI has no reading on either; the local repeats below cover that gap. <details><summary>Measurements</summary> All on this runner, `-n0 --run-nightly`, one node id. At the old press point the press was dead in 6 of 6 runs, and the new wait returned 3–117 ms later — so the case was green only when the reading happened to land inside the poll of the `to_be_hidden()` above it. Reopening the reference 1.5 s after a failing read showed 82 commands, so the row was merely late rather than absent. Where the window opened, by repeat runs of the case alone: | commit | result | per run | | --- | --- | --- | | `43d92073` (#767) | 4 passed | 3.8 s | | `80c26f0f` (#773) | 4 passed | 3.8 s | | `145da07d` (#774) | 3 failed, 1 passed | 4.8 s | | `8d8bec80` (#776) | 1 failed | 4.8 s | | `e382d828` (`main`) | 2 failed, 1 passed | 4.8 s | </details> Checked: the case 6/6 green with the change, `tests/test_render_reactions.py` under `--run-nightly` (50 passed), and `pre-commit run --files tests/test_render_reactions.py`. The everyday suite ran 1130 passed / 5 failed here, and all five are this sandbox rather than the change — three `test_interact_session.py` cases that need a writable `/tmp` for their private unix socket, `test_staged_writes_honor_umask`, and `test_live_shell_artifact.py::test_a_browser_executes_the_published_capture_with_live_api_routes[True]` on its node bundle step. The `test` job of the run above is the Linux control and was green on this commit; this change touches only a nightly-only file. Co-authored-by: leaf-agent <[email protected]>
Every page is now served by starlette over uvicorn, still one process per page. This is the transport alone: no shared daemon, no database, no change to event admission or projection. starlette, uvicorn and anyio are declared in
pyproject.toml, butmcpalready brought them, so an install fetches nothing new.The point is not the line count, which comes to −28 across the change and −75 of that in tests. It is that uvicorn now owns connection lifetime, and the workarounds Leaf carried for
http.servergo with it: the BrokenPipe suppression inhandle, the news stream'sselect()peer-gone loop,ThreadingHTTPServerwith its open-connection set and theSHUT_RDclose that fixed dropped Chromium preconnects in #630, plusDualStackHTTPServer,server_at, and three tests that reached intohttp.serverinternals.LeafHTTPServeropens the listening socket itself and hands uvicorn adup(), so the port is a fact before anything serves on it and a taken address still raises out of the constructor rather than exiting the process.Handlerbecomes an ordinary per-request object thatpage_app, an ASGI callable inhttp.py, builds and runs throughrun_in_threadpool; the route bodies stayed synchronous. Route scoping, the key and cookie gate, theLeaf-*headers and layer gate,/p/<capability>multiplexing, the website manifest lookup, preview snapshot mode, the 50 msLOOK_Sre-stat,TemporaryPageServer,cmd_serve, the detached handshake and session lifetime all keep their meaning.Two things were tried and left out. The
_get/_postdispatch chains stay hand-written, because_select_pagerewrites the path after the ASGI scope is fixed — both the MCP capability prefix and the website's longest-prefix manifest lookup do this — so a starlette router keyed onscope["path"]cannot express either, and the branch bodies are page semantics a route table would not delete. sse-starlette was adopted and backed out: its documentedping=0does not disable the keepalive but spinsawait sleep(0)in a send loop, and it patchesuvicorn.Server.handle_exitprocess-wide at import.StreamingResponsegives the disconnect cancellation the stream needs, since uvicorn reports ASGI spec 2.3.One behaviour change: the event door declares a 10 MiB body bound instead of discovering it through a failed allocation, so an oversized
Content-Lengthis refused as exceeding the limit rather than as invalid. Under ASGI the old refusal would have hung waiting for bytes. Its test now also assertsConnection: close.Review found five things, each reproduced before it was fixed. A signal reaches uvicorn alone, and its
handle_exitsetsshould_exitwithout telling the news stream to end, so a page with one reader survived SIGTERM past 30 seconds;stoppingis now set in a wrapper around it, and the same page exits in 0.5 s. The 10 MiB event bound readContent-Length, which a chunked body does not carry, so 12 MiB sent in chunks was buffered whole and then refused as invalid JSON; the bound now belongs to the read, and the door's refusal arrives while the sender is still writing. The news stream lost itsCache-Control: no-store, which is back, with_newsasserting it for every test that opens a stream.Then two more. A detached serve's stderr is a pipe its parent stops reading once the URL is in hand, and the override that kept the old handler quiet went with
http.server; uvicorn's own "Invalid HTTP request received." took its place at 31 bytes a refusal, and on the serving loop the write that fills the pipe stops the page answering — measured, 2,112 malformed request lines and the page never answered again. Its loggers now hold aNullHandlerand do not propagate, which is what the comment beside the config already claimed, and a new test sends 2,500 such lines before reading state.ws="none"keeps an upgrade handshake on the ordinary HTTP path, where the key gate answers it with a sentence; left on, it arrived as a scope past the gate and the peer got a 500 with a traceback.The comment in
worker/server.pyclaimed the close was what the adapter owed its App Server on SIGTERM. uvicorn re-raises the captured signal with the original handler restored, so the process dies where it stood and thatfinallynever runs; the comment now says the close is for the ordinary return.TODO.mdloses the row this implements.Checks: the everyday suite passes (1,138) on the merge with main, as do
test_website_server.pyandtest_interact_server.py(173) and the MCP and startup selections; pre-commit is green. Against the declared floors —starlette==0.48.0,uvicorn==0.31.1,anyio==4.10.0— the server, website and MCP suites pass (188). Server start goes from 324 ms to 346 ms over 7 paired runs, from a 20 ms import.🤖 Generated with Claude Code