Repository navigation
Bessemer v1.0.0rc8
Pre-release
Pre-release
Changed
- On Linux and macOS with the default
event_loop="auto", a worker whose
application has synchronous work serves its connections on two I/O threads
beside Bessemer's loop, as a worker withloopsabove 1 or asyncio's loop
does, instead of on the loop's own thread. Synchronous work is adef
route handler, a request-scopeddef, generator or class dependency at any
depth (mounted apps and WebSocket routes included) or adefexception
handler. The loop's thread takes the GIL for every callback, so while a
handler thread held the GIL nothing was accepted, read or written: one
defhandler inside a 0.9 s C call delayed native/healthzby up to
700 ms, long enough for a liveness probe to restart a healthy worker. It
now waits under 3 ms. These applications pay for it in CPU per request.
With the worker on one core, an async route of such an application used
about 20% more at one connection and 30% more at 64 (89,000 to 70,000
requests a second), and a sync route 20 to 40% more at one connection and
no more at 64.event_loop="bessemer"named explicitly keeps the
single-thread layout and its figures. All-async applications,
loopsabove 1, asyncio's loop,io_backend="io_uring"and free-threaded
builds with the GIL disabled are unchanged. Each worker writes the layout
it chose to standard error when it starts, for example
Bessemer worker pid=4242 event_loop=bessemer loops=1 connections=io-threads (sync handler GET /report).
An all-async application that holds the GIL in threads the worker cannot
see at start (asyncio.to_thread, an executor, a C extension) still
delays native routes on the single-thread layout;event_loop="asyncio"
avoids it. - A worker refuses to start when a
BESSEMER_*environment variable is a
near miss of a real setting (BESSEMER_MAX_CONECTIONS), or is any unknown
BESSEMER_TLS_*name, and names the setting it resembles. Such a variable
was ignored with at most a warning, so a limit or TLS option an operator
believed was set was not. OtherBESSEMER_*names still belong to the
application. APIKeyQueryanswers400when its parameter is repeated, as the header
schemes do, with or withoutauto_error. Cookies keep the first value.- Static mounts and
FileResponseshare one descriptor for each file being
sent, read by position, and a worker holds at mostmax_connections
distinct files open for bodies; a body for a further file gets the existing
503"Static file capacity is full". The per-mount slots are gone: eleven
slow downloads could take all of a mount's slots and leave every other
client of that mount with503,304s included, and three HTTP/2
connections that never opened their windows held 300 descriptors.304,
404,416andHEADtake nothing. Resolving, opening and the first
read of a static file are one trip to the blocking pool, which cut the
server's CPU per small static response to between a third and a quarter.
A file replaced while it is being sent finishes as the file its headers
describe. - A
FileResponsewhose path has become something other than a regular
file is answered500at once: the open no longer waits for a FIFO's
writer, which froze the worker. The file is still opened when the handler
returns the response, so one removed by ayielddependency's cleanup is
sent as before, and it is now read off the event loop. - Response bodies and stream frames of 16 KiB or more are compressed on the
blocking pool (it was more than 64 KiB, which a file's 64 KiB chunks never
were), a stream that has compressed 64 KiB inline sends its later frames
there too, and at most one compression per CPU runs at a time; the rest
wait without holding a pool thread. Eight compressed downloads of a 48 MB
file held native/healthzat a median of 50 to 150 ms; it is now about
1 ms.
Small bodies such as typical JSON are compressed inline as before. - A
304or206for a resource that compression applies to carries
Vary: Accept-Encoding, and a304answering the weakETaggiven with
a compressed200carries that tag, as RFC 9110 requires, so a cache can
match the revalidation to the representation it holds. - A multipart upload to a route that spools to disk is refused with
413
before any of it is read when itsContent-Lengthalready exceeds
max_upload_size, and a client that sentExpect: 100-continueis not
invited to send it. It was read and written to disk up to the limit first. - An HTTP/1.1 request answered before its body was read (a
413for its
declared length, a401) has the rest of that body read and discarded
before the connection closes: until the client closes, sends nothing for
half a second, or five seconds have passed. Closing on unread input resets
the connection, and a client still sending then lost the answer; on
Windows a response it had already received was discarded. Nothing read is
kept and the request's admission slot has been returned by then. - An incoming W3C trace context (
traceparent,tracestate) is honoured
only from a peer insidetrusted_proxies, or from any peer with the new
OpenTelemetry(trust_inbound_context=True). Any client could choose the
trace id and force its spans to be exported whateversample_ratiowas:
with a ratio of 0, twenty unauthenticated requests were all exported with
the client's trace id,401s included, and a flood displaced real spans
from the queue. Other clients now start a new trace sampled by
sample_ratio. A service called directly by other services, with no
proxy intrusted_proxies, must settrust_inbound_context=Trueto go
on joining its callers' traces. - A full local rate-limit table no longer refuses clients. A client that
cannot be given its own record shares one with its network (IPv4 /24 then
/16, IPv6 /48 then /32, then a single record for everyone left), so the
limit still applies, more strictly, and nobody is answered503"Rate
limiter is at capacity" because the table is full: one routed IPv6 /48, or
one request a window from each of 10,000 addresses, was enough to refuse
every other client on every limited path. Records in use are never
evicted, a client that moves from a shared record to its own keeps the
history it had, and memory stays bounded.Retry-Afterfrom a shared
record can be up to nine eighths of a window. - The router adds
Allowonly to its own405. A control's401,403
or429for a path whose method did not match carried the path's
methods, which told an unauthenticated client which paths and methods
exist. - The limit of 1,024 route templates counts each path once, whatever its
methods, and applies only when metrics, the access log or tracing uses
them. An application with 520 paths that each tookGETandPOSTand
no telemetry failed to start. access_log=Truecosts about a tenth of what it did. Each record is
encoded straight into a buffer and the writer takes whatever is queued
in batches of whole records of at most 4,096 bytes, woken only when it is
idle. On a trivial route the server's CPU per request with the log on
fell from 26 to 30 µs to 10 to 12 µs, against about 9 µs without it, and
futexandwritecalls for 40,000 requests from about 65,000 and
40,000 to 83 and 3,100. The output is byte for byte what it was; a record
can be written up to about a millisecond later.- A worker runs at most
max_connectionsWebSocket sessions, however they
arrive; a handshake beyond that is answered503"Too many WebSocket
sessions". Each HTTP/2 connection could carry 100 sessions, so the bound
was 100 timesmax_connections: with--max-connections 4, three
connections ran 300 handlers. HTTP/1.1 sessions, one a connection, cannot
reach the bound on their own, and one HTTP/2 connection still carries at
most 100. - An HTTP/2 extended CONNECT to anything but a WebSocket route is refused
with400"Not a WebSocket route" before any handler runs. It ran the
route'sGEThandler, discarded the body and answered200without
ending the stream, which a client reads as an accepted handshake, and the
WebSocket origin allowlist was never consulted. Authentication and rate
limiting still answer first. - With
tls_client_caset, TLS sessions are never resumed: no session
cache and no tickets, so every connection makes a full handshake and has
its client certificate checked against the current time and CRLs. A
resumed session restored the certificate chain without verifying it
again, so an expired client certificate went on working for as long as
its sessions kept being resumed. Servers without client authentication
resume sessions as before. JWTAuth.entrawith several tenants uses a signing key only for the issuer
that key publishes. Microsoft's sharedcommonkey set holds keys for
every tenant beside keys for one issuer only, each naming its issuer, and
Microsoft requires an API reading that set to check it: a key'sissuer,
with the token'stidin place of{tenantid}, must equal the token's
iss. Any key in the set was accepted for any listed tenant. A token whose
tiddisagrees with itsiss, or that a one-issuer key signed for another
issuer, is now answered401. Keys without the member (v1.0 key sets,
static keys, other providers) and single-tenant configurations behave as
before.require_scope(...)runs on the event loop instead of the handler pool
and does not count as synchronous work, so an all-async application that
uses it keeps the single-thread connection layout. A scope-checked route
cost 124 to 215 µs a request in a probe on a busy host and now costs 37 to
41 µs, the same as the check writtenasync def. Calling the returned
dependency directly still returns the principal.- The verified-token cache hashes a bearer token before it takes its lock,
and a route takingPrincipalis handed the verified claims without a
copy of the claims tree for each request. - Typed request models with more than 16 fields find a body key's field
through an index built once per model, so keys out of order or unknown no
longer cost a scan of every field: parsing a 1 MiB body for a 256-field
model took 382 million instructions with its keys reversed and 686 million
with unknown keys, and now takes 79 and 62 million. Narrower models are
unchanged. - Generic requests, those with dependencies, Request injection or HTTP
middleware, do less work per call. The sync pool borrows fields from its
work tuple and calls the usual keyword bindings by vectorcall, and the
worker no longer wraps ordinary sync results or flattened async handlers in
an extra coroutine, which saves two coroutine allocations for a generic
dependency request and one for a generic sync Request handler. At 64
connections, with the worker on one core, genericDependsran 5.3%, 4.4%,
5.7% and 16.6% faster on 3.13, standard 3.14, 3.14t with the GIL and 3.14t
without it, using 8.1%, 9.1%, 11.0% and 18.0% less CPU per reply (paired
medians against the previous build). A GIL-disabledRequestroute was
7.9% faster with 9.5% less CPU. Other workloads were mixed: 3.13 inline
CPU (0.971x), 3.13 byte responses (0.962x) and GIL-disabled JSON (0.987x)
were slightly slower in paired medians, and GIL-disabled 3.14t still
reached only 0.880x of standard 3.14 on genericDepends. The host was
shared and unpinned. - Adaptive admission charges the event loop's CPU from the instant a request
joins the queue instead of from before it queued, and takes the queue
timestamp once instead of reading the clock twice per handoff. A request
that waits in the queue no longer has its wait counted as loop work. The
measured effect was mixed and is not attributed: in one 395-sample run
standard 3.13 JSON and 256 KiB bytes responses were 5.4% and 14.3% slower
with 9.8% and 14.3% more CPU per reply, GIL-disabled CPU workers were 14.3%
faster, and after the second clock read was removed the paired medians were
+3.7% (JSON) and +2.8% (bytes) with ranges that crossed parity. The shared
host does not establish that the change caused any of them. - Synchronous routes that take no bindings are called through the pool's
fixed-argument path, so they no longer build an unused argument vector,
clone references or create a boundContext.run.Request.urland
base_urlof a native request read only theHostheader and leave the
rest of the headers unconverted, and typedfloatfields skip repeated
generic type dispatch while keeping their depth, finiteness, byte-budget
and signed-zero behaviour. In a 72-sample comparisonRequestthroughput
was 6.5% higher with 6.8% less CPU per reply and 256-model responses used
3.2% less CPU; CPU-bound sync and typed echo ranges crossed parity. In the
main 395-sample matrix four configurations were slower than the previous
build in every round, including typed echo on 3.13, 3.14 and GIL-disabled
3.14t, and a later study did not reproduce the typed-echo loss. - The native sync pool signals a thread only when one is waiting, the invoker
reuses interned names for its dispatch methods, and the typed model parser
matches an expected plain field name and its colon together, leaving
escaped keys, reordered fields and whitespace before the colon to the
general parser. At 64 connections sync CPU throughput was 1.029x and CPU per
reply 0.988x of the previous build, both ranges crossing parity. Typed echo
varied between runs (0.957x to 0.960x in one matrix, 1.010x to 1.037x in the
recheck), so no typed-echo gain is claimed. - Typed JSON bodies decode matching ordered fields straight into the model
without rebuilding the accepted prefix, short JSON numbers are accumulated
while they are scanned, bound body arguments are moved to the call instead
of copied, a complete single-frame body skips an extra allocation and
poll, and free-threaded model responses write bounded runs of exact
scalars under the container's critical section, rolling back if the
expected shape fails. The free-threaded path needs CPython 3.14 or later
for borrowed ASCII. On GIL-disabled 3.14t a 256-model response was 1.261x as
fast with 0.806x the CPU per reply (all six pairs improved), raising its
throughput relative to standard 3.14 from 0.759x to 0.968x. Typed echo
improved 5.3% on 3.13 and 6.8% on GIL-disabled 3.14t, but all four echo
ranges crossed parity and standard 3.14 and GIL-enabled 3.14t medians were
below the previous build, so repeatable typed-echo throughput is not
established. - On standard CPython 3.14, model responses are encoded in one walk over
compatible ordered dictionaries that matches the expected key identities as
it writes, rewinding to the general path when the order differs. HTTP/1 now
writes a reply larger than 8 KiB as headers plus body without copying the
body into the connection buffer. At 64 connections a 256-model response ran
18,110 requests a second, 1.120x the previous build (range 0.931 to 1.272x)
with 0.901x the CPU per reply and 0.860x the p99 latency; at 16 connections
it was 1.109x and the direct encoder used 0.892x the CPU. Small JSON was
0.961x, and the model route's CPU and high-concurrency throughput
qualification remains open. These measurements come from a shared host and
do not establish the formal M0 performance gate.
Fixed
request.form()and form models no longer decode a multipart text field
with the codec its part names. A part declaringcharset=punycodewas
decoded by a quadratic pure-Python codec: 80 KB took 1.2 s and six
concurrent 150 KB posts 26 s each, on the sync pool and past the request
timeout. Text fields are now always read as UTF-8, and part headers are
read with exactly the grammar of the native parser behindForm()and
File(), in one linear pass, so the two cannot be made to see different
requests: text inside a quoted value cannot rename a part or turn a field
into a file. A part the native parser refuses (noname, a disposition
other thanform-data, a repeated parameter, a trailing;, a malformed
filename*) is refused with the same400where it was skipped or
accepted.UploadFile.content_typefromrequest.form()is the part's
Content-Typeas sent, orNone, rather than its lower-cased type
defaulting totext/plain; anameonContent-Typeno longer supplies
a filename;filename*must declare UTF-8 and wins overfilename; and
RFC 2231 continuations are not joined. A generated test holds the two
parsers to the same answer for thousands of part headers.- A WebSocket session now ends when its client disconnects while the handler
is behind on receiving. The reader stopped reading the socket once 64
messages were waiting, so a handler that never receives, such as a push
endpoint, was never told that a client which had sent 64 frames was gone:
the handler, its socket and its connection slot were held until the worker
restarted. The reader now keeps watching the socket through its existing
16 KiB buffer while it waits, and a failed send ends the session too.
Messages already buffered are still delivered in order to a handler that
keeps receiving; one that does not sees the disconnect and is cancelled
within about ten seconds. - Requests waiting for their bodies without an admission slot are bounded on
HTTP/2. A client could park 100 streams a connection by sending headers
and no body: 391 KiB over 300 connections held about 210 MiB until the
request timeout, whatevermax_in_flightwas. Each HTTP/2 connection now
has 8 places of its own for streams waiting for a body and beyond them
draws on a worker-wide pool ofmax_connections; a stream that can get
neither is answered503withRetry-After, and only that stream. One
client's parked streams cannot take another connection's places, so they
cannot make other clients' uploads fail. HTTP/1.1 requests, one to a
connection, take no place and are never refused, and a request whose body
arrives with its head never waits. The same 300 connections now hold
about 95 MiB. - Adding
TrustedHostMiddleware,CORSMiddlewareorGZipMiddlewareto an
app that is already mounted raisesValueErrorinstead of being accepted
and then not enforced, andbuild()repeats the check over every mounted
app, so a server-wide option set on a sub-app aftermount()is refused
rather than dropped. Set these on the outermost app. - Bessemer's event loop polls for I/O at least every 200 µs while callbacks
keep its ready queue busy. With one loop per worker it polled only about
every 61st iteration, so one handler doing work in slices separated by
await asyncio.sleep(0)delayed new connections, native health checks and
asyncio readers by about 61 slices: 57 ms behind 1 ms slices and nearly a
second behind 20 ms ones. They now wait one to three slices. Instructions
per request are unchanged within 0.3%. - Queued sync handlers using dependencies, Request injection or HTTP middleware
no longer start after their request has timed out or its client has left.
Both sync invocation paths check the closed reply channel before starting. - Informational CI throughput summaries drain outstanding load, retain warmup
and measured errors, and withhold comparisons for errored, client-limited or
unavailable measurements. Successful throughput is recorded separately. run_cpurecovers when a process-pool child dies. A killed child broke
the pool for good and every later job failed withBrokenProcessPool. The
broken pool is discarded and a new one of the same size is built for the
next job; only the jobs that were in it fail. The discarded pool is shut
down outside the executor's lock, where a job submitted while its failures
were being delivered could otherwise deadlock the worker.- A server-sent event whose data holds a carriage return is sent as separate
data:lines, as a line feed already was, instead of aborting the stream.
event,idandretrystill refuse line breaks. - An in-process
TestClientinside a supervised worker's child no longer
has its listening socket closed underneath it. Whether the native server
owns the listener was read from an environment variable every child of a
worker inherits; the worker's entry point now says so explicitly. - An urlencoded body with more than 1,000 fields is refused before it is
decoded. A 1 MiB body ofa&pairs allocated half a million pairs on the
I/O thread, about 40 ms and 40 to 50 MiB, before its400. - A multipart
filename*that decodes to a control character is refused
with400by the native and Python parsers. The RFC 5987 form could carry
a NUL, CR or LF that a quotedfilenamecannot.
UploadFile.filenameis client-supplied and is never a path. - The file parts of a spooled upload share their request's one descriptor.
Each part held its own, so one 71 kB request with 1,000 one-byte files
held 1,000 descriptors for as long as its handler ran, and with a limit of
512 open files failed with500. A request now holds one however many
parts it has. Reads, seeks, per-part positions andclose()are
unchanged. - Refused uploads no longer force a full garbage collection about once a
second. The collection that reclaims spool space from unreferenced uploads
counts only what it freed, and backs off from one second up to 64 when it
frees nothing. - Bessemer's event loop keeps its ready queue, timers and registered readers
visible to the garbage collector at all times. A collection that ran while
an I/O thread held the loop's lock for an instant could take everything
reachable only through the loop for garbage: scheduled callbacks were
finalised, a pending task hadGeneratorExitthrown into it and a watched
socket was closed. - The loop drops a reader or writer still registered for a descriptor that
was closed, instead of re-arming it for the descriptor number's next
owner. A pendingsock_recvcould read another connection's data and a
pendingsock_sendallwrite to it; those operations now fail withEBADF
once their socket has been closed, or are never run. - A descriptor left readable when
run_foreverstopped is seen when the
loop runs again. With one loop per worker it was missed until some other
event arrived, so a reader could wait two seconds and a transfer stall
around shutdown. - A reader or writer whose handle was cancelled directly is unregistered
when its event arrives rather than polled for again and again, which spun
the loop at up to a full core. A burst ofcall_soon_threadsafecalls
writes one wake-up rather than one each (51 writes instead of 9,005 for
50 bursts of 200), and a timer due within 10 ms no longer costs two
timerfd_settimecalls on every wake-up. - With
io_backend="io_uring", a connection dropped off its ring's thread
is left for the ring to close instead of having its descriptor closed
under a receive still armed on it, completions held back by a full
completion queue are collected before the ring sleeps, and a submission
queue that stays full fails the ring instead of spinning the worker. tests/security/fuzz_transport.py --wheelruns against the current wheel
again: its provenance check failed onpy.typed, and its cookie property
still expected the400for duplicate cookies that 1.0.0rc4 replaced. The
sanitizer workflow also builds and runs the unsafe crates on free-threaded
CPython 3.14t, so theirPy_GIL_DISABLEDpaths are compiled and exercised
under AddressSanitizer; ThreadSanitizer on that interpreter is reported
but does not gate, because CPython itself is not instrumented.- The native JSON encoders refuse a string holding a lone surrogate before
converting it, and leave it to the general path. The conversion consults
Python's codec error registry, where an application may have replaced the
stricthandler with Python code; run in the middle of an encode on
CPython 3.13, that code could free what the encoder was reading and crash
the worker. ASCII strings are now encoded in place on CPython 3.12 and
3.13, about a fifth fewer instructions per string. - A response
dictthat changes size while it is converted (by such a
handler, or by another thread on free-threaded Python) is answered500.
It panicked inside the dict iterator, which stopped the worker's event
loop: every later request on that worker went unanswered until the
supervisor replaced it. - On CPython 3.13 the native model builder sets
__dict__through the
descriptor for a class with inline values, or for an object of another
type returned by a model's__new__. Installing the dict directly left
such an instance inconsistent and could crash. Pydantic models, which
never have inline values there, keep the direct path. - The free-threaded response encoder checks that a string-keyed
dictcan
fit in the remaining response allowance before it copies it. - A connection whose response could not be sent, or ran out of time being
sent, is dropped at once. The server first tried to close it gracefully,
which over TLS waited on the same stalled peer again, and the deadline's
own wake-up counted as progress and restarted the clock: a client that
stopped reading held its connection for 10 to 12 seconds against a 4
second timeout, where a plaintext client held it for 4. Both now take 4. - The Redis rate limiter remembers a client the store has told to wait and
answers it429itself until the wait ends. It asked the store for every
request, so one already limited client sending about 1,100 requests a
second through a 5 ms store took every pooled connection and turned other
clients' requests into503"Rate limiter is unavailable". Each worker
remembers at most 4,096 such clients. A Redis error written to standard
error has its control characters escaped.