Repository navigation
Releases
5.8.3
A fix for multi-threaded serving on event loops other than uvloop.
Fixed
STARIO_THREADS>1worker threads run the same loop class as the loop
runningserve(), whatever it is. Before, only uvloop was mirrored: any
other loop (loopyloop, rloop, auvloop.Loopsubclass) left the extra
threads on a stdlibSelectorEventLoop, so one thread ran the chosen loop
and the rest silently did not. A loop class that can't be built without
arguments now fails startup with aStarioErrornaming it.
5.8.2
A second security and performance review of the whole tree. Timings are
benchmarks/server/inproc.py and inproc_paths.py on one pinned CPU, best
of four interleaved rounds against 5.8.1 (plain builds, no profile).
Security
- HTTP/1: llhttp 9.2.1 → 9.4.3. An empty
Transfer-Encoding:was read
as absent, so the bytes after such a request were parsed as a second
request (request smuggling behind a front end that frames it
differently). The vendored files are upstream'srelease/v9.4.3,
unmodified. - HTTP/1: no second status after a request's own response. A handler
that answered a chunked upload before reading it left the connection
open; a malformed chunk after that wrote a400behind the200, which
a client or pooling front end reads as the answer to its next request.
The connection now closes without writing. - HTTP/2: small bodies waiting for dispatch are bounded per connection.
Bodies up to 256 KiB are read before their handler starts, with the
windows open: 200 stalled streams held 50 MiB on one connection, on any
path. Past 1 MiB of such bytes a stream dispatches at its next DATA
frame. - nghttp2 1.68.1 is the minimum (CVE-2026-27135: an assertion failure
when frames arrive afternghttp2_session_terminate_session(), which
the reset budget calls). Wheels already bundle 1.70 / 1.71. - Response writer: a declared
Content-Lengthof 16 digits or more
overflowed a stack buffer (a fortified build aborts the process). - Response writer: a list body is counted and sent from one iteration
(a list that changed between the two put bytes pastContent-Lengthon
the wire); an HTTP/1.0 close-delimited stream closes even if the handler
removesconnection: close. - Relay:
publish()of a subject with thousands of dots (a path
parameter inroom.{id}) cost O(length × dots) and cached the result:
0.45 s and 400 MB for one 40 KB subject. Lookup keys now come from the
registeredprefix.*lengths. - Multipart:
filename*is decoded as UTF-8 or Latin-1 only. The
client could name any Python codec:punycodedecodes in quadratic
time,idnaraised pastread_formas a 500. - Datastar:
data.on(target=, case=),on_intersect(threshold=),
scroll_into_view(...)and theDatastarAttributesprefix are checked
as attribute-name parts (a value from data could add an attribute);
numeric and boolean action options must be numbers and booleans, and
at.intl()quotes nested strings. - Markup caches (
classes(), attribute names) keep only short
entries: 1024 megabyte-long class lists pinned 2 GB for good. - Codecs: zstd decoding reads every concatenated frame and Brotli
rejects bytes after the stream; stream encoders and decoders run in a
critical section on free-threaded builds (two threads finishing one
encoder returned it to the pool twice). ParsedCookiescopies bytes-like lines tobytes(abytearrayline
was read past its start);RequestHeaders.__init__run twice resets its
hot indexes;data_receivedaccepts a memoryview instead of dropping
it; NaN timeouts are rejected; the TTY tracer escapes Unicode bidi
controls; an idle HTTP/2 connection gives back an outbound buffer over
64 KiB.- Build:
-fvisibility=hidden,-fstack-clash-protectionand
-fcf-protection=fullwhere the compiler has them,-DNDEBUGwhatever
CFLAGSsays; bundled native libraries are built hardened and stripped;
CI actions are pinned to commit SHAs with a read-only token.
Performance
| case | 5.8.1 | now | |
|---|---|---|---|
| plaintext | 2.39 µs | 2.02 | -15% |
| json | 4.16 | 3.77 | -9% |
GET /user/{id} |
5.04 | 4.58 | -9% |
| browser header set | 3.34 | 2.93 | -12% |
response headers + set_cookie |
19.25 | 7.26 | -62% |
| multipart form | 55.85 | 31.78 | -43% |
| urlencoded form | 9.81 | 8.41 | -14% |
| in-memory asset | 11.32 | 7.98 | -29% |
| 405 / 308 | 3.64 / 2.87 | 3.16 / 2.44 | -13% / -15% |
| pipelined ×4 | 2.66 | 2.38 | -11% |
| 50-row HTML page | 43.51 | 42.81 | -2% |
HTTP/2, SSE and compressed-page cases are within ±3% (noise).
- Hidden symbol visibility: calls between the Cython modules' helpers,
llhttp and the compression glue skip the PLT. respond()with headers set sends head and body in one write.set_cookiewrites theSimpleCookieline without building one.Assetsanswers a held file with ETags andLast-Modifiedbuilt at
load, through the same header and body functions as every other file.- Multipart part headers and form
Content-Typevalues are memoized. - A 405 under middleware builds its handler once per allowed-method set.
- Markup: clean text is found eight bytes at a time and copied once;
non-ASCII text is encoded straight into the render buffer;render()
of ASCII output skips the UTF-8 decode (render-21%,render_bytes
-13% on a prebuilt page). Text where every string needs escaping
renders 5-8% slower.
Changed
- x86-64 builds no longer pass
-msse4.2(it applied to the whole
protocol module: SIGILL on a CPU or VM without SSE 4.2). llhttp's header
scan loses about 45 ns on a 600-byte request, under 1% end to end. filename*with a charset other than UTF-8 or Latin-1 is read as UTF-8.ParsedCookiesraisesTypeErrorfor a line that is not text or bytes.escape.validate_attribute_keyno longer hascache_info().
5.8.1
Results of a security and performance review of the whole tree. Timings are
benchmarks/server/inproc.py on one pinned CPU, best of three interleaved
rounds against 5.8.0.
Security
- HTTP/2: server-side resets are rate limited (MadeYouReset,
CVE-2025-8671). nghttp2's reset limit counts only RST_STREAM frames the
client sends. A DATA frame pastcontent-length, or malformed trailers,
made the server reset a stream whose handler had already started, without
bound. Streams that close while their handler runs now draw from one
budget (100 burst, 33/s), whoever reset them; an empty budget ends the
connection with GOAWAY(ENHANCE_YOUR_CALM). - HTTP/2: an HPACK reference flood no longer stalls the loop. One index
byte can name a 4 KiB table entry, and nghttp2 validated every field of a
block the server had already given up on: a 100 KB read blocked the loop
for 289 ms. A block is now cut off (RST_STREAM) once its ignored fields
decode to twicemax_header_bytes, and at once when a field is rejected.
Such blocks spend the same reset budget, so spreading the flood over
streams ends the connection. A request just over the limit still gets
its 431. - HTTP/1: a final response before
100 Continuecloses the connection.
A handler that answered 401/403 without reading the body left the
connection open; a front end that then skipped the body had its next
request read as that body (request smuggling).Expect: 100-continuein
an HTTP/1.0 request is now ignored (RFC 9110 10.1.1). - Request body: a failed allocation fails the read. It was reported as
success, and body bytes were copied through a missing or short buffer
(a crash under a memory limit, with a client-chosenContent-Length). - Cookies: a quoted value never spans
;. Two planted cookies
(a="x...z=y") could swallow the cookies between them into one
value an app might echo.parse_cookie_headersnow runs the same scan
asc.req.cookies. Files(untrusted=True)serves scripts (under every JavaScript media
type name), stylesheets, wasm, HTML, SVG and XML as
application/octet-stream. A browser ignores
content-dispositionand the sandbox CSP when a page loads an upload as
a script, service worker, or stylesheet.Files: an 8.3-alias-shaped name (x~1) lists its directory only
when it exists (a made-up one cost alistdirof the whole directory per
request); files open withO_NONBLOCK, so a FIFO cannot hang an executor
thread; withfollow_symlinks, a link that resolves to a dotfile is
hidden on every platform.read_formcounts urlencoded pairs before decoding them. A 10 MB
a&a&a...body used 570 MB and 0.7 s before its 413.- Datastar:
string_literalanddata.signalsnever write an escaped
backslash before a closing quote, which Datastar's statement splitter
reads as an escaped quote; a value ending in\broke the expression. - Response writer: lengths of
bytes/bytearraysubclasses come
from their storage, not__len__/__bytes__;write_headers()
accepts only digits inContent-Length, refuses conflicting values, and
sends one canonical field;
proxy-connectionis dropped from HTTP/2 responses. Route.href()rejects.and..parameter values.- Builds pass
-fstack-protectorand-D_FORTIFY_SOURCE=2and link with
full RELRO and a non-executable stack on Linux, whatever the
interpreter's own flags.
Performance
| case | 5.8.0 | now |
|---|---|---|
| plaintext | 2.28 µs | 2.37 |
| json | 5.52 | 4.26 |
GET /user/{id} |
6.26 | 5.07 |
| JSON POST | 11.57 | 9.72 |
| 50-row HTML page | 47.31 | 44.33 |
| traced json | 16.76 | 12.76 |
SSE patch_signals |
7.18 | 2.99 |
SSE patch_elements, zstd |
3.10 | 2.13 |
| HTTP/2 plaintext | 5.87 | 5.31 |
| HTTP/2 json | 10.00 | 8.40 |
Plaintext is within run-to-run noise (-7% to +7% across runs).
- JSON encodes with one shared
json.JSONEncoderon builds with the
GIL.json.dumpswith options built a new encoder on every call (which
free-threaded builds keep doing, so threads share no encoder). - Tracing: pending spans sit in a deque under one lock, and
JsonTracerformats a span's fixed fields directly. - HTTP/2: DATA frames up to 4 KiB are copied behind their header into
the outbound buffer: a small response is onewrite. c.req.body()returns a complete body without a second coroutine.- Profile-guided builds.
STARIO_PGO=1(GCC) compiles instrumented,
runsscripts/pgo_train.py, and compiles again with the profile; Linux
wheels are built this way (STARIO_PGO=require: the wheel build fails
rather than ship without a profile). On top of the table above it takes 12-16% off
small requests in-process, 6% off the HTML page, and 13% (geometric mean)
off the 28 cases of the newbenchmarks/server/inproc_paths.py. A
profile trained without those 28 cases still made them 9% faster and none
slower. SeeCYTHON.md. benchmarks/server/inproc_paths.pymeasures the request paths
inproc.pydoes not take (query, cookies, routing misses, uploads,
forms, streamed responses, assets, HTTP/2 uploads).- Datastar SSE:
patch_signals/patch_elementsskip per-call
closures, ABCisinstancechecks, and the line split for one-line
payloads. - Markup: the tag-call argument scan and the render walk compare
borrowed type pointers (no refcount writes),styles()runs its plain
case in C (1.19 → 0.54 µs), and escaping counts growth with a table sum.
Changed
- A cookie value such as
x="a;b"now reads as"a(browsers send it that
way only when something planted it). Stario's ownset_cookiewrites
;as an octal escape and round-trips as before. - An empty path segment or host label no longer matches a
{param}:
/users//postsagainst/users/{id}/postsis 404, notid == "". c.req.cookies.get()returns the default for a name that is too long or
not Latin-1 instead of raising.max_header_bytesis capped at 2^30 (was 2^31-1).Files(untrusted=True)no longer sendstext/css, JavaScript, wasm,
HTML, SVG or XML media types: those files download as
application/octet-stream. Serve files you trust with a plainFiles.- A response sent before the request body was read, to a request with
Expect: 100-continue, now carriesconnection: close. Clients that
sendExpect(curl on large uploads, some SDKs) reconnect after an
early 401/403/413; a handler that reads the body first is unaffected. write_headers()raises for aContent-Lengththat is not plain digits
(" 50","+50","5_0"were accepted) and for two different values.parse_cookie_headersuses Stario's own scan, not
http.cookies.SimpleCookie; a line that is not Latin-1 is skipped.
5.8.0
Performance
-
Building and rendering
h.*trees scales acrossSTARIO_THREADSon
free-threaded Python. Each element holds a reference to itsTag, and
render increfed the tag's strings, so every thread wrote the refcounts of
the sameh.Td/h.Trobjects, and an HTML page served fewer requests
on 2 threads than on 1. On a free-threaded build aTagand its empty
element are now immortal (Py_INCREF / Py_DECREF only read them), and so
are its strings (interned), theclasses()/ attribute-name /data()
caches and their entries,@bakedstatic text, and the result of a
@bakedfunction without parameters. Render no longer takes references
on the tree it walks. Measured on 3.14t against 5.7.0:- Building and rendering a 50-row table on per-thread data, on 2 CPUs:
1.9-2.2x the throughput of one thread (was 0.3-0.45x); with
classes()and attributes, 2.0x (was 0.6x). - A 50-row page with classes and attributes on 4 CPUs: 3.8x at 4 threads
(was 0.36x). - Over HTTP, that page does 16.5k requests/s on 2 threads against 8.7k
on 1 (was 5.7k on 2, 8.1k on 1).
Builds with the GIL behave as before. Their single-thread timings are
unchanged within noise, and render is about 7% faster on a small tree. - Building and rendering a 50-row table on per-thread data, on 2 CPUs:
-
styles()checks for:;{}\with string literals instead of a
module-level regex (which free-threaded CPython increfs on every load).
About 7% faster with the GIL.
Changed
- On a free-threaded build a
Tagand a@bakedtemplate are never
freed. Create them once, at import (Widget = Tag("my-widget")), not per
request. Cache entries stay bounded by the caches' caps. A Python
subclass ofTagstays mortal (it works, but does not scale as well), and
a 32-bit build makes nothing immortal. - An
Element,SafeStringorAttrskept in a module-level variable and
put in every page is still increfed on each use, from every thread. For
static fragments that every request repeats, use a@bakedfunction
without parameters orclasses(): seedocs/free-threading.md.
5.7.0
Added
- Windows support (x86-64, Python 3.12-3.14 and 3.14t). PyPI gets
win_amd64wheels with nghttp2, Brotli 1.2.1, zstd, and zlib linked
statically. A source build needs MSVC plus
scripts/build-native-deps.ps1, which builds those libraries with vcpkg
pinned to one commit and prints thePKG_CONFIG/PKG_CONFIG_PATH
values forsetup.py;PKG_CONFIGnow names the pkg-config binary on
every platform. On Windows:- The server runs one event loop on the stdlib proactor loop: there is no
SO_REUSEPORT, soSTARIO_THREADSstays at 1. Unix sockets and uvloop
are unavailable (theuvloopextra installs nothing there). - Ctrl+Break (
SIGBREAK) starts a graceful shutdown like Ctrl+C, since
Windows never deliversSIGTERMto a console process. reuse_addris ignored:SO_REUSEADDRthere lets a second socket bind
the same port instead of rebinding pastTIME_WAIT.- Winsock takes a whole send into kernel memory while the send buffer has
room, however large: a big one-shotrespond()to a client that is not
reading is held by the kernel rather than aborted afterwrite_timeout.
Streamed bodies (w.write+await w.drain(),Files) stay bounded.
Filesopens files without delete sharing, so replacing a file while it
is streamed fails until the response ends. Filesopens files in binary mode, treats directory junctions as
symlinks, and answers 404 for names Win32 would not open as written:
reserved characters (<>:"|?*, controls), a drive or NTFS stream
colon (C:x,a.txt::$DATA), a trailing dot or space (app.py.would
openapp.py), and device names (CON,NUL.txt,COM1). With
include_hidden=Falsethe resolved path is checked again, so an 8.3
short name (GIT~1) cannot reach a dot directory.
- The server runs one event loop on the stdlib proactor loop: there is no
Security
Fileschecks that the file it opened is the one path resolution vetted:
the OS's own path for the open file (Linux/proc/self/fd, macOS
F_GETPATH, WindowsGetFinalPathNameByHandleW) must equal the vetted
path, so a link swapped into any component between the checks and the
open (by a local user who can write the served tree) is a 404. Where the
OS cannot say, the device and inode stand in. On a mismatch it resolves
once more, so a deploy that replaces files still serves the new file.- With
include_hidden=False,Filesrefuses a path segment that names a
file only through an NTFS/FAT 8.3 alias (GIT~1for.git) on Linux and
macOS too, where an ntfs-3g, vfat, or SMB mount (or WSL's/mnt/c)
answers to short names thatrealpath()never expands. A segment shaped
like an alias must appear verbatim in its directory listing. - On Windows, any name-surrogate reparse point (junction, WSL or container
link), not only a symlink or junction, counts as a link for
follow_symlinks=False.
Fixed
Filesanswers 404, not 500, for a path segment longer than 255
characters, a path longer than 4096, or a name the filesystem rejects as
too long (ENAMETOOLONG, or a name Windows cannot represent).- A
FilesorAssetsstream cancelled mid-read (a client reset) closes
its file only after the worker thread's read returns. On Windows the
close used to block the event loop on the CRT's descriptor lock, and the
lseek+readfallback could read from a reused descriptor. - The request body byte counter is
Py_ssize_t, like the limits it is
compared with; as anintit wrapped after 2 GiB of discarded HTTP/2
DATA.
5.6.1
Fixed
Tag,VoidTag,Tag.__init__andTag.__call__have signatures for
inspect.signatureagain.Tagbecame a Cython type in 5.5.0, and its
slot methods lost their signatures, so doc tools showedTagwithout
arguments.- The
prefixed()docstring names its import path again
(from stario.markup.attributes import prefixed); 5.6.0 dropped it.
5.6.0
Changed
Elementis a sealed Cython type. A tag call (h.Div(...)) returns an
immutableElementwith read-only fields (tag,name,attrs,
children) instead of atuplesubclass. Python code cannot create one
(Element(...),Element.__new__andobject.__new__raise
TypeError), subclass it, pickle it, or treat it as a sequence:el[0],
len(el), iteration and unpacking raise. Elements compare by identity, so
tests should comparerender()output.h.Div()with no arguments
returns the tag's cached emptyElement, not aSafeString.SafeStringandAttrsare final Cython types instead of frozen
dataclasses. Setting a field raisesAttributeError(was
FrozenInstanceError), anddataclasses.replaceno longer applies. Both
take astronly: astrsubclass such asmarkupsafe.Markupis copied
to a plainstr, andSafeString(5)raisesTypeErrorat once.Attrs
must be empty or start with whitespace:Attrs('id="x"')rendered
<divid="x">.- A bad child (
True, a tuple, an uncalledTag, any other object) raises
StarioErrorat the tag call that receives it, not later at render. The
context names the receiving tag (parent). Items inside a list are still
checked at render. In@baked, a static enum member child is now refused,
as it already was outside@baked. - Void elements (
h.Br,h.Img,h.Input, ...) areVoidTaginstances,
so a type checker rejects children (h.Br("x")). The runtime check stays. - Raw-text elements (
h.Script,h.Style) refuse element children,
because the browser reads their content as text. Numbers join the text
around them for the early-end check. render()raisesStarioErrorfor a lone surrogate (U+D800 to U+DFFF).
Before,render()returned it and the UTF-8 encode inw.htmlfailed.
Added
- The
Elementread API:el.tag,el.name,el.attrs,el.children,
el["href"],el.get("href"),"href" in el, and
el.with_attrs({...}), which returns a copy with attributes set or
removed (None/False). A value reads back decoded, as a browser reads
it.with_attrscopies every attribute it does not change byte for byte. render_bytes(*nodes): the markup ofrender, UTF-8 encoded in the same
pass.w.htmland the Datastar SSE patch helpers use it.stario.markupexportsElement,VoidTagandrender_bytes.benchmarks/html/compare_versions.pyandpage_versions.pytime two
stario builds side by side and refuse builds that render different
markup.compare.pychecks that every library renders the same page.
Fixed
- A
Noneor an emptySafeStringbetween two text pieces ofh.Script
orh.Stylesplit the early-end check, so
h.Script("</scr", None, "ipt><img src=x onerror=...>")ended the script
and sent the rest as HTML. Children that put nothing on the wire no longer
split the check, inside lists and@bakedbuilders too. - Raw-text children in a list that contains itself crashed the process
(unbounded C recursion). Past 1000 levels they raiseStarioError. - A custom raw-text tag with an upper-case name
(Tag("STYLE", raw_text=True)) never matched</stylein its check. - A tag call read the keys and values of an attribute mapping through
borrowed pointers while the attribute-name validator ran Python code.
Another thread that changed the dict then could make the call write freed
memory into the page, or crash;data()andaria()had the same flaw.
Mappings are now walked with strong references, and a mapping that
changes during the call raisesRuntimeError. Under free threading,
render reads lists the same way, and the attribute caches read with
PyDict_GetItemRefand never replace an entry.
Performance
classes(),data(),aria()andprefixed()run in Cython, and
classes()also caches calls withNoneorFalsetokens. A tag call
writes its attributes into one string and keeps its own argument tuple as
the children. Render writes UTF-8 straight into one buffer. On the
50-row page ofbenchmarks/html/compare.py(Python 3.14), a tree built
per request takes 44 µs, down from 101 µs (Jinja2: 118 µs), and the
@bakedversion takes 22 µs, down from 39 µs. A 100-row page builds and
renders to bytes in 133 µs, down from 223 µs (on 3.14t: 146 µs, down from
252 µs).
5.5.0
Fixed
-
An HTTP/2 exchange whose response was cut off by the client is returned
to the pool again. Two cases skipped it: a handler answering a stream the
client had already reset (the 500 for aClientDisconnectedraised from
a body read, or a handler catching its cancel and still responding), and
any response in flight when the connection was lost, which is every SSE
stream whose browser tab closes on HTTP/2. The exchange was still freed by
the cyclic garbage collector, but held its buffers until then and cost a
fresh allocation on the next request. Writes for a stream that no longer
exists are now dropped. -
A lingering close (the FIN after a 413 while the client is still
uploading) no longer waits forever on a peer that stops reading: the
socket is closed after the linger window, and aborted one window later
ifclose()is still waiting for the peer to take the buffered response. -
One connection raising inside the timeout sweep no longer leaves the
other connections unchecked or stops the sweep until the next connection
opens. -
stario_cython.xxh64.updaterefuses a non-contiguous memoryview instead
of hashing the underlying buffer as if it were contiguous. -
A plain tuple in child position is no longer rendered as markup. Elements
built byh.*are now anElement(atuplesubclass) and the renderer
and@bakeddispatch on that type, so a four-column database row passed
as one child raisesStarioErrorinstead of writing its text to the
page unescaped.h.Li(*row)keeps escaping each cell. -
h.Scriptandh.Styleare raw-text elements:strchildren are sent
as they are, because the browser never decodes entities inside them, so
h.Script("if (a < b) go()")now works. Text that would end the element
early (</script,<!--in a script,</style) raisesStarioError;
the check runs once over the joined children, soh.Script("</scr", "ipt>")fails likeh.Script("</script>")does. A@bakedparameter
insideh.Scriptorh.Styleis spliced verbatim too, with the same
joined check on every call.Tag(name, raw_text=True)marks a custom
raw-text tag. -
The compiled attribute-name cache and the
classes()fragment cache
stop filling at their cap instead of being cleared in place, and the
name cache reads with a strong reference, so a build on one thread can
no longer free an entry another thread is reading under free threading. -
data.on("myEvent", …)emitsdata-on:my-event__case.camel, and
data.class_("myClass", …)emitsdata-class:my-class__case.camel
(__case.pascalfor PascalCase), so the browser's lowercasing of the
attribute name no longer changes the event or class name.data.attr
anddata.styleraise for a key with uppercase letters (HTML lowercases
it; usedata.attrs/data.styles), as dodata.bind(prop=…)and
data.bind(event=…)for modifier values with uppercase letters. -
An HTTP/2 request body that grows past the read limit while the handler
is reading it is answered once, by the handler'sRequestBodyErrorpath
(413 with a text body, as on HTTP/1). The protocol no longer sends its
own empty 413 first, which left the request span marked as a failure. -
HTTP/2 writes queued behind a slow reader are compacted only once half
of the buffer has been sent. Before, every DATA frame sent moved the
whole unsent backlog, so a handler that did notdrain()paid for the
backlog size on each frame. -
A span that fails with an exception whose message is empty (
KeyError(),
asyncio.CancelledError()) is exported with statuserror, and the
error text is the exception type name. Before, the JSON, SQLite, and
test tracers exported it asokwith no error. -
JsonTracerandSqliteTracerkeep spans that end while the tracer
exits: the writer thread drains them before it stops. Before, a span that
ended between the stop request and the join was dropped and logged as
ended "while stopped". -
TTYTracerexit no longer waits forever on a terminal write that is
stuck. The final render and the stdout/stderr drain give up after one
second, like the render thread join. -
set_cookie(expires="Wed, 21 Oct 2015 07:28:00 GMT")works. Thestr
form rejected a comma, which every HTTP-date contains.;is still
rejected. -
A
Rangeheader with several ranges (bytes=0-1,3-4) is answered 200
with the full body, as RFC 9110 14.2 allows. Before it was 416. -
Filesno longer raisesKeyErrorwhen two event-loop threads
(STARIO_THREADSabove 1) evict the same changed file from the cache.
Changed
-
HTTP/2 writes one buffer per send pass: every HEADERS and DATA frame
nghttp2 produced for all streams, in order, goes to the transport in one
writelines. Before, each DATA frame was its own transport call behind a
flush of the frames before it, so a response with a body cost two writes
(two TLS records) and a 64 KiB body cost five. Nothing is written from
inside an nghttp2 callback any more.benchmarks/server/inproc.pygained
h2_*cases that also print writes per request. -
Text and attribute escaping for strings with characters above U+00FF
(CJK, emoji) runs in one C pass like Latin-1 text: a 60-character CJK
string with&,<,>escapes in 0.14 µs instead of 0.42 µs; clean
strings still return the same object. -
STARIO_MALLOC_TUNE=0leaves glibc's malloc thresholds alone. The
64 MiB mmap and trim thresholds Stario sets on first use are now
documented inCYTHON.md, including that the trim threshold applies per
malloc arena (per allocating thread). -
One clock per event loop.
Connections(one per loop) now owns the
timeout tick: a singleloop.call_laterhandle, scheduled only while a
connection with timeouts exists, readsloop.time()once and walks the
live connections in C. TheServerno longer runs aDatecoroutine per
loop, and an idle loop makes no timer wakeups. TheDateheader comes
from a per-second cache on the same object: one coarse wall-clock read
per response, reformatted in C only when the second changed, so a busy
loop can no longer serve a staleDate. The lingering-close wait and
the HTTP/2 GOAWAY grace are deadlines on that tick instead of timers,
so the protocol holds noTimerHandle. With timeouts off
(timeout_cleanup="off", the test client) a lingering close closes
at once. -
HttpProtocol(loop, app, tracer, compression, connections, ...)no
longer takes adate_boxlist;Connections(date=...)or
Connections.pin_date()fixes theDateline for tests, and
Connections.date_linereads it.Connections(server_driven=...)is
gone: a registry always ticks itself. -
SSE.patch_elementsdocuments thatbytesandstrare trusted HTML
sent as they are (likew.html); build user text withh.*. -
at.get/post/put/patch/delete/queryshare one
FetchOptionstyped dictionary (**options: Unpack[FetchOptions])
instead of six copies of the option list. Calls are unchanged. -
Building an element is cheaper:
Tag.__call__tests child types before
theMappingcheck, inlines thestrattribute path, and builds its
repronly for errors;classes()checksstrtokens first and caches
the fragment for repeated all-strargument tuples;styles()scans
names and values with one regex each.escape_attribute_valueis no
longer cached. Output is byte-identical. The 50-row page in
benchmarks/server/inproc.pygoes from 219 µs to 173 µs per request. -
An SSE payload with no line breaks (rendered markup, compact JSON) is
written without being copied through the line splitter, and signal
patches with no dotted key skip the path check. -
A full span queue in
JsonTracer/SqliteTracerwrites at most one
message per second to stderr. The message carries the number of spans
dropped since the previous one;stats().dropped_spansstill counts
every drop. -
A span keeps at most 1000 events. Later events are dropped and counted,
and the span ends with the attributespan.dropped_eventswhen the
count is above zero. -
A recorded span costs less: on the in-process benchmark a traced
plaintext request went from about 27 µs to about 9 µs on one machine.
Span ids come from a per-thread uuid7 state with pooledos.urandom
bytes instead of a process-wide lock and one syscall per id, so ids are
monotonic within one thread only. The span lock is taken directly
instead of through a generator, and the JSON serializer formats ids
withoutstr(). -
Internal:
RecordingSpan.mutexis always a context manager (a no-op one
by default) instead ofNone.RecordingSpan.duration_nsand the
unusedstario._terminal.style_text/styledare removed. -
Assets.load()reads each file once. It holds the bytes while they fit
max_bytesand only fingerprints the files after that. Before, every
file undermax_file_sizewas read into memory before the budget
applied, and every file was hashed from disk a second time. A file
pinned byhref()beforeload()is still verified against the disk. -
read_formopens a file spool only when a file part has a filename or
carries bytes. A file input left empty (filename="") counts toward
max_fieldslike an empty field, not towardmax_files, so a form with
many optional file inputs still posts. Before, each empty part allocated
and closed a spool and never counted, so an unlimited number of them was
accepted. -
Building and rendering markup runs in C.
Tag.__call__, the render
walk,escape_text, andescape_attribute_valuelive in
stario_cython.markup;stario.markup.tag,.render, and.escape
re-export them. Elements, the@bakedplan,SafeString,Attrs, and
every error message are unchanged, and the output is byte-identical.
On the in-process benchmark the 50-row page goes from 219 µs to 57 µs
per request; one...
5.4.0
Changed
RequestPolicy.max_body_bytes(STARIO_REQUESTS_MAX_BODY_BYTES) is now
the default limit for one read, not a cap for the server. A handler
passesmax_size=tobody()orstream()to accept more or less. An
upload route readsawait c.req.body(max_size=6_000_000), and every
other route keeps the default.- The server no longer answers 413 before the handler runs when
Content-Lengthis above the default. The read raises 413 instead. It
checks the declared length first, so it allocates nothing and sends no
100 Continue. Only a length above 2^31-1 bytes still gets a 413 before
the handler. - A body that the handler does not read drains up to the default, then the
HTTP/1 connection closes. A small declared body (256 KiB or less) still
drains and keeps the connection. - An HTTP/1 close while the client still sends a body is a lingering close
(RFC 9112 9.6): the server sends FIN after the response, then reads and
drops input for up to 2 seconds. Before, the close sent RST, and a
browser in the middle of an upload could lose the 413 and show a reset. StaticFilesandAssetsregister only the GET route; it answers HEAD.- A GET route also answers HEAD (RFC 9110 9.3.2). The handler runs with
c.req.method == "HEAD", and the server drops the body. Before, HEAD on
a GET route was 405, and each route needed a HEAD twin. An explicit HEAD
route still wins. TheAllowheader of a 405 now listsHEADnext to
GET. read_signals()reads thedatastarquery parameter for HEAD, as for
GET.- A HEAD response ends at its headers (RFC 9112 6.3). The connection then
serves the next request, and laterwrite()/end()calls are no-ops.
For HEAD,c.disconnectresolves andc.disconnectedis true once the
response is sent, soc.alive()stops an SSE handler. Before, an SSE
handler kept running under HEAD and held a keep-alive connection.
Added
stream(max_size=)limits the total bytes of a streamed body.read_signals(req, max_size=)passes the limit tobody(), for signals
that carry aFileSignal.stario.forms:read_form(req)returns aFormwith the text fields and
the uploaded files of an HTML form. GET and HEAD read the query string.
Other methods read anapplication/x-www-form-urlencodedor
multipart/form-databody. Multipart bodies stream: each file is an
UploadFilein aSpooledTemporaryFilethat moves to disk past
spool_size. Writes to disk andawait upload.read()run in a thread,
so the event loop keeps serving. A cancelled request waits for that
thread before it closes the spool.Form.get/getlist/items/
as_dictmatchreq.query.max_size,max_fields,max_field_size,max_files, and
max_file_sizelimit the body (413). A malformed body is 400, and another
Content-Typeis 415.RequestBodyErroraccepts 415.- The test client quotes multipart names and filenames as browsers do
("as%22), not with backslashes.read_formdecodes%22,%0D, and
%0Ain names and filenames back to", CR, and LF. same_origin(trusted_origins=[...])lets a listed origin post cross-site
(a payment return), andsame_origin(exempt=["/hooks"])skips the check
under a path prefix. The prefix matches the path as sent, so
/hooks%2Fx(one segment for the router) is not exempt. The docstring
now namessame_origin()as the CSRF protection for current browsers:
CSRF tokens would only add browsers from before about 2023.stario.cookies.SignedCookie: a cookie with a JSON payload that the
client can read but not change.set(w, data)signs it with HMAC-SHA256,
andget(req)returns aSignedValue(data,issued_at,expires_at,
age) only when the signature is valid and the expiry, which the server
checks, has not passed. The first ofkeyssigns and every key verifies,
for rotation. Each key is 32 bytes or more. The signing key is derived
from the key and the cookie name, so a value cannot move to another
cookie. A value past about 3.9 KB raises an error instead of being
dropped by the browser. The defaults areHttpOnly,Secure, and
SameSite=Lax.set_cookie,delete_cookie, andSignedCookieraiseStarioErrorfor a
__Host-name withoutsecure=True,path="/", and no domain, and for a
__Secure-name withoutsecure=True. Browsers drop such a cookie
without an error.
5.3.4
Changed
- The wheels ship without debug info. The extensions compile with
-g0,
and on Linux they link with-s. The cp314 manylinux aarch64 wheel goes
from 5.1 MB to 2.0 MB, and thestario_cythonmodules go from 14.3 MB
to 2.3 MB on disk. The source and the code that runs do not change. STARIO_DEBUG_BUILD=1builds the extensions with debug info and symbols,
forgdborperf. A source build without it also leaves them out.