Skip to content

Releases

5.8.3

Choose a tag to compare

@github-actions github-actions released this 11 Nov 19:04
b1f4e9b

A fix for multi-threaded serving on event loops other than uvloop.

Fixed

  • STARIO_THREADS>1 worker threads run the same loop class as the loop
    running serve(), whatever it is.
    Before, only uvloop was mirrored: any
    other loop (loopyloop, rloop, a uvloop.Loop subclass) left the extra
    threads on a stdlib SelectorEventLoop, 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 a StarioError naming it.

5.8.2

Choose a tag to compare

@github-actions github-actions released this 11 Nov 13:01
aa4ebb4

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's release/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 a 400 behind the 200, 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 after nghttp2_session_terminate_session(), which
    the reset budget calls). Wheels already bundle 1.70 / 1.71.
  • Response writer: a declared Content-Length of 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 past Content-Length on
    the wire); an HTTP/1.0 close-delimited stream closes even if the handler
    removes connection: close.
  • Relay: publish() of a subject with thousands of dots (a path
    parameter in room.{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
    registered prefix.* lengths.
  • Multipart: filename* is decoded as UTF-8 or Latin-1 only. The
    client could name any Python codec: punycode decodes in quadratic
    time, idna raised past read_form as a 500.
  • Datastar: data.on(target=, case=), on_intersect(threshold=),
    scroll_into_view(...) and the DatastarAttributes prefix 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).
  • ParsedCookies copies bytes-like lines to bytes (a bytearray line
    was read past its start); RequestHeaders.__init__ run twice resets its
    hot indexes; data_received accepts 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-protection and
    -fcf-protection=full where the compiler has them, -DNDEBUG whatever
    CFLAGS says; 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_cookie writes the SimpleCookie line without building one.
  • Assets answers a held file with ETags and Last-Modified built at
    load, through the same header and body functions as every other file.
  • Multipart part headers and form Content-Type values 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.
  • ParsedCookies raises TypeError for a line that is not text or bytes.
  • escape.validate_attribute_key no longer has cache_info().

5.8.1

Choose a tag to compare

@github-actions github-actions released this 10 Nov 13:45
a2423f3

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 past content-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 twice max_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 Continue closes 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-continue in
    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-chosen Content-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_headers now runs the same scan
    as c.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-disposition and 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 a listdir of the whole directory per
    request); files open with O_NONBLOCK, so a FIFO cannot hang an executor
    thread; with follow_symlinks, a link that resolves to a dotfile is
    hidden on every platform.
  • read_form counts urlencoded pairs before decoding them. A 10 MB
    a&a&a... body used 570 MB and 0.7 s before its 413.
  • Datastar: string_literal and data.signals never 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 / bytearray subclasses come
    from their storage, not __len__ / __bytes__; write_headers()
    accepts only digits in Content-Length, refuses conflicting values, and
    sends one canonical field;
    proxy-connection is dropped from HTTP/2 responses.
  • Route.href() rejects . and .. parameter values.
  • Builds pass -fstack-protector and -D_FORTIFY_SOURCE=2 and 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.JSONEncoder on builds with the
    GIL. json.dumps with 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
    JsonTracer formats 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 one write.
  • c.req.body() returns a complete body without a second coroutine.
  • Profile-guided builds. STARIO_PGO=1 (GCC) compiles instrumented,
    runs scripts/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 new benchmarks/server/inproc_paths.py. A
    profile trained without those 28 cases still made them 9% faster and none
    slower. See CYTHON.md.
  • benchmarks/server/inproc_paths.py measures the request paths
    inproc.py does not take (query, cookies, routing misses, uploads,
    forms, streamed responses, assets, HTTP/2 uploads).
  • Datastar SSE: patch_signals / patch_elements skip per-call
    closures, ABC isinstance checks, 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 own set_cookie writes
    ; as an octal escape and round-trips as before.
  • An empty path segment or host label no longer matches a {param}:
    /users//posts against /users/{id}/posts is 404, not id == "".
  • c.req.cookies.get() returns the default for a name that is too long or
    not Latin-1 instead of raising.
  • max_header_bytes is capped at 2^30 (was 2^31-1).
  • Files(untrusted=True) no longer sends text/css, JavaScript, wasm,
    HTML, SVG or XML media types: those files download as
    application/octet-stream. Serve files you trust with a plain Files.
  • A response sent before the request body was read, to a request with
    Expect: 100-continue, now carries connection: close. Clients that
    send Expect (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 a Content-Length that is not plain digits
    (" 50", "+50", "5_0" were accepted) and for two different values.
  • parse_cookie_headers uses Stario's own scan, not
    http.cookies.SimpleCookie; a line that is not Latin-1 is skipped.

5.8.0

Choose a tag to compare

@github-actions github-actions released this 09 Nov 18:47
03d54a9

Performance

  • Building and rendering h.* trees scales across STARIO_THREADS on
    free-threaded Python. Each element holds a reference to its Tag, and
    render increfed the tag's strings, so every thread wrote the refcounts of
    the same h.Td / h.Tr objects, and an HTML page served fewer requests
    on 2 threads than on 1. On a free-threaded build a Tag and its empty
    element are now immortal (Py_INCREF / Py_DECREF only read them), and so
    are its strings (interned), the classes() / attribute-name / data()
    caches and their entries, @baked static text, and the result of a
    @baked function 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.

  • 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 Tag and a @baked template 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 of Tag stays mortal (it works, but does not scale as well), and
    a 32-bit build makes nothing immortal.
  • An Element, SafeString or Attrs kept 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 @baked function
    without parameters or classes(): see docs/free-threading.md.

5.7.0

Choose a tag to compare

@github-actions github-actions released this 08 Nov 18:37
483c004

Added

  • Windows support (x86-64, Python 3.12-3.14 and 3.14t). PyPI gets
    win_amd64 wheels 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 the PKG_CONFIG / PKG_CONFIG_PATH
    values for setup.py; PKG_CONFIG now 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, so STARIO_THREADS stays at 1. Unix sockets and uvloop
      are unavailable (the uvloop extra installs nothing there).
    • Ctrl+Break (SIGBREAK) starts a graceful shutdown like Ctrl+C, since
      Windows never delivers SIGTERM to a console process.
    • reuse_addr is ignored: SO_REUSEADDR there lets a second socket bind
      the same port instead of rebinding past TIME_WAIT.
    • Winsock takes a whole send into kernel memory while the send buffer has
      room, however large: a big one-shot respond() to a client that is not
      reading is held by the kernel rather than aborted after write_timeout.
      Streamed bodies (w.write + await w.drain(), Files) stay bounded.
      Files opens files without delete sharing, so replacing a file while it
      is streamed fails until the response ends.
    • Files opens 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
      open app.py), and device names (CON, NUL.txt, COM1). With
      include_hidden=False the resolved path is checked again, so an 8.3
      short name (GIT~1) cannot reach a dot directory.

Security

  • Files checks 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, Windows GetFinalPathNameByHandleW) 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, Files refuses a path segment that names a
    file only through an NTFS/FAT 8.3 alias (GIT~1 for .git) on Linux and
    macOS too, where an ntfs-3g, vfat, or SMB mount (or WSL's /mnt/c)
    answers to short names that realpath() 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

  • Files answers 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 Files or Assets stream 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 + read fallback could read from a reused descriptor.
  • The request body byte counter is Py_ssize_t, like the limits it is
    compared with; as an int it wrapped after 2 GiB of discarded HTTP/2
    DATA.

5.6.1

Choose a tag to compare

@github-actions github-actions released this 07 Nov 20:58
8917357

Fixed

  • Tag, VoidTag, Tag.__init__ and Tag.__call__ have signatures for
    inspect.signature again. Tag became a Cython type in 5.5.0, and its
    slot methods lost their signatures, so doc tools showed Tag without
    arguments.
  • The prefixed() docstring names its import path again
    (from stario.markup.attributes import prefixed); 5.6.0 dropped it.

5.6.0

Choose a tag to compare

@github-actions github-actions released this 07 Nov 20:23
73e86be

Changed

  • Element is a sealed Cython type. A tag call (h.Div(...)) returns an
    immutable Element with read-only fields (tag, name, attrs,
    children) instead of a tuple subclass. Python code cannot create one
    (Element(...), Element.__new__ and object.__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 compare render() output. h.Div() with no arguments
    returns the tag's cached empty Element, not a SafeString.
  • SafeString and Attrs are final Cython types instead of frozen
    dataclasses. Setting a field raises AttributeError (was
    FrozenInstanceError), and dataclasses.replace no longer applies. Both
    take a str only: a str subclass such as markupsafe.Markup is copied
    to a plain str, and SafeString(5) raises TypeError at once. Attrs
    must be empty or start with whitespace: Attrs('id="x"') rendered
    <divid="x">.
  • A bad child (True, a tuple, an uncalled Tag, any other object) raises
    StarioError at 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, ...) are VoidTag instances,
    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() raises StarioError for a lone surrogate (U+D800 to U+DFFF).
    Before, render() returned it and the UTF-8 encode in w.html failed.

Added

  • The Element read 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_attrs copies every attribute it does not change byte for byte.
  • render_bytes(*nodes): the markup of render, UTF-8 encoded in the same
    pass. w.html and the Datastar SSE patch helpers use it.
  • stario.markup exports Element, VoidTag and render_bytes.
  • benchmarks/html/compare_versions.py and page_versions.py time two
    stario builds side by side and refuse builds that render different
    markup. compare.py checks that every library renders the same page.

Fixed

  • A None or an empty SafeString between two text pieces of h.Script
    or h.Style split 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 @baked builders too.
  • Raw-text children in a list that contains itself crashed the process
    (unbounded C recursion). Past 1000 levels they raise StarioError.
  • A custom raw-text tag with an upper-case name
    (Tag("STYLE", raw_text=True)) never matched </style in 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() and aria() had the same flaw.
    Mappings are now walked with strong references, and a mapping that
    changes during the call raises RuntimeError. Under free threading,
    render reads lists the same way, and the attribute caches read with
    PyDict_GetItemRef and never replace an entry.

Performance

  • classes(), data(), aria() and prefixed() run in Cython, and
    classes() also caches calls with None or False tokens. 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 of benchmarks/html/compare.py (Python 3.14), a tree built
    per request takes 44 µs, down from 101 µs (Jinja2: 118 µs), and the
    @baked version 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

Choose a tag to compare

@Bobowski Bobowski released this 06 Nov 18:01
f5e22f0

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 a ClientDisconnected raised 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
    if close() 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.update refuses 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 by h.* are now an Element (a tuple subclass) and the renderer
    and @baked dispatch on that type, so a four-column database row passed
    as one child raises StarioError instead of writing its text to the
    page unescaped. h.Li(*row) keeps escaping each cell.

  • h.Script and h.Style are raw-text elements: str children 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) raises StarioError;
    the check runs once over the joined children, so h.Script("</scr", "ipt>") fails like h.Script("</script>") does. A @baked parameter
    inside h.Script or h.Style is 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", …) emits data-on:my-event__case.camel, and
    data.class_("myClass", …) emits data-class:my-class__case.camel
    (__case.pascal for PascalCase), so the browser's lowercasing of the
    attribute name no longer changes the event or class name. data.attr
    and data.style raise for a key with uppercase letters (HTML lowercases
    it; use data.attrs / data.styles), as do data.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's RequestBodyError path
    (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 not drain() 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 status error, and the
    error text is the exception type name. Before, the JSON, SQLite, and
    test tracers exported it as ok with no error.

  • JsonTracer and SqliteTracer keep 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".

  • TTYTracer exit 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. The str
    form rejected a comma, which every HTTP-date contains. ; is still
    rejected.

  • A Range header 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.

  • Files no longer raises KeyError when two event-loop threads
    (STARIO_THREADS above 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.py gained
    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=0 leaves glibc's malloc thresholds alone. The
    64 MiB mmap and trim thresholds Stario sets on first use are now
    documented in CYTHON.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 single loop.call_later handle, scheduled only while a
    connection with timeouts exists, reads loop.time() once and walks the
    live connections in C. The Server no longer runs a Date coroutine per
    loop, and an idle loop makes no timer wakeups. The Date header 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 stale Date. The lingering-close wait and
    the HTTP/2 GOAWAY grace are deadlines on that tick instead of timers,
    so the protocol holds no TimerHandle. With timeouts off
    (timeout_cleanup="off", the test client) a lingering close closes
    at once.

  • HttpProtocol(loop, app, tracer, compression, connections, ...) no
    longer takes a date_box list; Connections(date=...) or
    Connections.pin_date() fixes the Date line for tests, and
    Connections.date_line reads it. Connections(server_driven=...) is
    gone: a registry always ticks itself.

  • SSE.patch_elements documents that bytes and str are trusted HTML
    sent as they are (like w.html); build user text with h.*.

  • at.get / post / put / patch / delete / query share one
    FetchOptions typed 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
    the Mapping check, inlines the str attribute path, and builds its
    repr only for errors; classes() checks str tokens first and caches
    the fragment for repeated all-str argument tuples; styles() scans
    names and values with one regex each. escape_attribute_value is no
    longer cached. Output is byte-identical. The 50-row page in
    benchmarks/server/inproc.py goes 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 / SqliteTracer writes at most one
    message per second to stderr. The message carries the number of spans
    dropped since the previous one; stats().dropped_spans still counts
    every drop.

  • A span keeps at most 1000 events. Later events are dropped and counted,
    and the span ends with the attribute span.dropped_events when 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 pooled os.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
    without str().

  • Internal: RecordingSpan.mutex is always a context manager (a no-op one
    by default) instead of None. RecordingSpan.duration_ns and the
    unused stario._terminal.style_text / styled are removed.

  • Assets.load() reads each file once. It holds the bytes while they fit
    max_bytes and only fingerprints the files after that. Before, every
    file under max_file_size was read into memory before the budget
    applied, and every file was hashed from disk a second time. A file
    pinned by href() before load() is still verified against the disk.

  • read_form opens a file spool only when a file part has a filename or
    carries bytes. A file input left empty (filename="") counts toward
    max_fields like an empty field, not toward max_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, and escape_attribute_value live in
    stario_cython.markup; stario.markup.tag, .render, and .escape
    re-export them. Elements, the @baked plan, 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...

Read more

5.4.0

Choose a tag to compare

@Bobowski Bobowski released this 06 Nov 12:22
b575937

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
    passes max_size= to body() or stream() to accept more or less. An
    upload route reads await 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-Length is 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.
  • StaticFiles and Assets register 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. The Allow header of a 405 now lists HEAD next to
    GET.
  • read_signals() reads the datastar query 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 later write() / end() calls are no-ops.
    For HEAD, c.disconnect resolves and c.disconnected is true once the
    response is sent, so c.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 to body(), for signals
    that carry a FileSignal.
  • stario.forms: read_form(req) returns a Form with the text fields and
    the uploaded files of an HTML form. GET and HEAD read the query string.
    Other methods read an application/x-www-form-urlencoded or
    multipart/form-data body. Multipart bodies stream: each file is an
    UploadFile in a SpooledTemporaryFile that moves to disk past
    spool_size. Writes to disk and await 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_dict match req.query. max_size, max_fields, max_field_size, max_files, and
    max_file_size limit the body (413). A malformed body is 400, and another
    Content-Type is 415.
  • RequestBodyError accepts 415.
  • The test client quotes multipart names and filenames as browsers do
    (" as %22), not with backslashes. read_form decodes %22, %0D, and
    %0A in names and filenames back to ", CR, and LF.
  • same_origin(trusted_origins=[...]) lets a listed origin post cross-site
    (a payment return), and same_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 names same_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,
    and get(req) returns a SignedValue (data, issued_at, expires_at,
    age) only when the signature is valid and the expiry, which the server
    checks, has not passed. The first of keys signs 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 are HttpOnly, Secure, and
    SameSite=Lax.
  • set_cookie, delete_cookie, and SignedCookie raise StarioError for a
    __Host- name without secure=True, path="/", and no domain, and for a
    __Secure- name without secure=True. Browsers drop such a cookie
    without an error.

5.3.4

Choose a tag to compare

@Bobowski Bobowski released this 04 Nov 14:01
02790e3

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 the stario_cython modules go from 14.3 MB
    to 2.3 MB on disk. The source and the code that runs do not change.
  • STARIO_DEBUG_BUILD=1 builds the extensions with debug info and symbols,
    for gdb or perf. A source build without it also leaves them out.