Changelog¶
All notable changes to this project are documented here. The format follows Keep a Changelog and the project uses Semantic Versioning.
[Unreleased]¶
[0.9.2] — 2026-10-20¶
Patch release: security fixes (rustls-webpki and the webpki root stores, constant-time Stripe signatures, mail header
injection and SMTP smuggling, subprocess arguments, openpyxl styles), native asyncio.create_subprocess_exec, loguru,
passlib, pgpy, qrcode, reportlab, openpyxl and stripe-python, SQLModel tables and relationships, dependencies and routers
written in the shapes real applications use, --python-side auto that no longer stops on a refusal outside the routes,
endpoint decorators refused instead of ignored, and --backend removed.
Security¶
asyncio.create_subprocess_exec: NUL bytes and illegal environment names raise as asyncio (or end the value, as uvloop does);kill()never signals a pid tokio has already reaped. docs: Security § Outgoing mail, subprocesses and documents (with the SMTP TLS risks kept as in aiosmtplib).email.mime(compat32) messages: a header value with line breaks raises CPython's HeaderParseError / HeaderWriteError when written instead of being sent with an injected header; the SMTP payload normalises lone\ras aiosmtplib does (SMTP smuggling).- openpyxl: styles indexed by hash (one style per row was quadratic under the book's lock); a numeric sheet-title suffix past 64 bits no longer wraps to a duplicate title.
rustls-webpki0.103.16 (RUSTSEC-2026-0382),webpki-rootsandwebpki-root-certs1.0.10 (RUSTSEC-2026-0381, RUSTSEC-2026-0383: distrusted emSign roots) in the shipped lock file;tools/cargo_audit.shis green again.- Stripe webhook signatures compared in constant time (as
hmac.compare_digest); a plain comparison let a client time its guesses of the signature of a forged event.
Added¶
- Background jobs started by a lifespan translate (such a lifespan was refused, so
--python-side autoleft the whole application to Python):fcntl.flockwithLOCK_SH/LOCK_EX/LOCK_NB/LOCK_UNandBlockingIOError;sqlalchemy.exc.InterfaceErrorandDBAPIError.connection_invalidated(supported.md);request.scope.get()of the keys only a middleware sets (session,user,auth: absent without one, on both sides). -
asyncio.create_subprocess_execnatively (dynrt/subproc.rs):PIPE/DEVNULL/STDOUT,cwd=,env=,Process.communicate(),wait(),returncode,pid,kill(),terminate(),send_signal(), cancellation bywait_for, and theOSErrorof a failed spawn with asyncio's or uvloop's message;ProcessLookupError,NotADirectoryError(also frompathlibcalls on a path whose parent is a file). Fixturefixtures/subprocapp. docs: Python reference § asyncio. -
--python-side autono longer stops on a refusal outside the routes (py2axum/fallback.py, docs: Hybrid mode § What auto leaves to Python): module code of a library translated from source moves the routes using the library; a lifespan or@app.on_eventhandler that does not translate runs in the Python process alone, with each translated route reading what it sets in the process (app.state, a module global, a class attribute); a middleware, an exception handler, module code of the project or an app option leaves the whole application to Python (the binary relays every request). Refused as before: syntax errors, and the whole application with WebSocket routes. Error code P2A0316.py2axum check --python-side autoreports the same (route reasons, notes). - Tests that
py2axum checkand generation agree: with--python-side auto(route, lifespan, whole application) the routescheckreports python-side are exactly those the generated binary relays, and native + python-side covers every route;--python-side lifespanalone is accepted by both. --translate-libsreads a licence written as free text (License: BSD,BSD-like) from the distribution's licence file, compared word for word with the canonical MIT, BSD-2/3/4-Clause, ISC, 0BSD, Zlib, HPND, Unlicense and Apache-2.0 texts (py2axum/licenses.py); a modified licence, an unknown one or an extra grant is refused with the text found, and--allow-license <distribution>admits a distribution whose licence was not recognised. Zlib and HPND are admitted by default, and by decision of the project BSD-4-Clause (xlrd), MPL-2.0 (tqdm) and the passlib 1.7 distribution (BSD-3-Clause plus code derived from Beer-ware/UnixCrypt/jBCrypt); LGPL stays refused. Vague classifiers (Other/Proprietary,DFSG approved) defer to the file.- Standard-library names the libraries translated from their source (
--translate-libs) reach (fixtures/stdmapapp):errno.E*(the numbers glibc and macOS share),sys.byteorder/maxunicode/warnoptions,collections.abc.Mapping/ MutableMapping/Sequence/MutableSequence/Set/MutableSetasisinstancetargets, theWarningclasses,warnings.warnof a category the default filters ignore (andsimplefilter/filterwarnings("ignore"),catch_warnings()),bisectandinsort(lo,hi,key, the messages of each Python), chained comparisons ofsys.version_infofolded at translation,str.join(chain(...)),importlib.import_module("literal")of an installed module. A warning CPython would print (stderr, module path) or raise,dir(),inspect.*,xml.*,array.*are refused with what to do instead (py2axum/libmap.pySTDLIB_HINTS,tests/test_rejects_stdmap.py). - Class protocols of libraries translated from source (
--translate-libs):metaclass=ABCMetaon a plain class (asABC),__str__/__repr__/__bool__of an exception class (str(), f-strings,%s, tracebacks and logs use__str__), chainedsys.version_infocomparisons ((3, 8) <= sys.version_info < (3, 10)) folded in class bodies and modules; copy/pickle methods (__getstate__...) kept when no translated code reachescopy/pickle(was: any module importing them). aiosmtpd, apscheduler, loguru, validators now reach their next refusal. fixtures/protoapp/klass.py. - Decorators on methods of plain classes (the path
--translate-libstakes for libraries): a property's setter (@name.setter, run byobj.name = vandobj.name += v; a property without one raises CPython'sAttributeError: property 'x' of 'C' object has no setter, a class attribute can still be shadowed by the instance),functools.cached_property(stored in the instance, which then shadows it),contextlib.contextmanager(on methods and functions:_GeneratorContextManager, CPython'sRuntimeErrormessages), and any function decorator (@functools.wrapswrappers, decorator factories) read as the function it returns and bound to the instance.typing.final/override/no_type_checkare markers. A redefinition in a class body keeps the last def. Refused with a message: a property deleter, a decorator that is a class (descriptor protocol),@classmethodor@staticmethodbeside a function decorator. fixtures/langapp/decoprops.py. -
Silently wrong values made exact, or refused at generation (found 17/10/2026 behind a production gap):
frozensetis its own type (it was aset:type(),repr,isinstance, mutators,set | frozensettakes the left operand's type, hashable as a dict key or set member, pickled as FROZENSET,frozenset[T]fields give a frozenset);str()of the ValidationError of aTypeAdaptercarries pydantic-core's validator name (1 validation error for list[int], a type whose name is not reproduced raises instead); a model field given a non-dict fails asmodel_typeunlessfrom_attributesis on (it saidmodel_attributes_type);bytes.decode(errors=)takesignore,replaceandbackslashreplacefor utf-8 and ascii,str.encode(errors=)alsobackslashreplace,xmlcharrefreplace,surrogateescape/surrogatepass(a literal handler outside these is refused at generation); on a parameter annotatedRequest, an attribute the runtime does not provide (session,user,auth,close,stream, the Mapping over the scope:request[...],in,keys(),sorted(request),request.x = ...) is refused at generation, with file and line (P2A0204).set ^ setis implemented. -
@abstractmethodon a class without ABCMeta madeC()raise TypeError (CPython instantiates it). A class with a class keyword or decorator that was not otherwise recognised was compiled as an exception class (keywords and decorators ignored); it is now refused with its reason. -
Starlette's Request objects reproduced for
request._body(Starlette's body cache): one per BaseHTTPMiddleware (request._body = datathere is what the inner app reads, withrequest._receive), the route's, ExceptionMiddleware's on a 404/405 and ServerErrorMiddleware'sRequest(scope)(itsbody()raises "Receive channel has not been made available");form()leaves no cache ("Stream consumed"). fixtures/bodyapp, fixtures/bodycrash. - A library's router left to Python (
app.include_router(<library router>)) no longer has to be the app's last registration when what follows is a function given the app that adds routes at startup (setup(app)->app.add_route(...)): those routes come after the library's in Starlette's order, so the binary relays them. gzip.compress(data, compresslevel=, mtime=): zlib's stream (the system zlib, like CPython), the header each Python writes (3.12: its own unlessmtime=0; 3.13: zlib's XFL, OS 255; 3.14:mtime=0by default).pydantic_core.PydanticSerializationErroras a class (except,isinstance).- Alias generators written as project functions of several statements (
if,for, assignments with*rest,not/and/or/in, generator expressions over the name) are evaluated at translation time; anything else stays refused with file:line. model_configbuilt from another model's:ConfigDict(**Base.model_config, ...)(or {}included),{**Base.model_config, ...}, andalias_generator=Other.model_config["alias_generator"]; a key given twice toConfigDict()is refused like Python's TypeError.hide_input_in_errors=True:str()of the model'sValidationErrorleaves outinput_value/input_type, as pydantic does (errors()and 422 bodies keep the input).- pydantic-settings
env_ignore_empty=True: an empty environment variable is as if unset (the field keeps its default). model_configallow_inf_nan=False(every float of the model, in its containers too, rejects inf/nan withfinite_number) andvalidate_default=False(the default); the other values are refused.- pydantic-settings: a validation error shows as input only what was read (environment, then init keywords), not the defaults.
- Pydantic's strict and constrained annotation aliases are native:
StrictStr/StrictInt/StrictFloat/StrictBool/StrictBytes,PositiveInt/NegativeInt/NonNegativeInt/NonPositiveIntand the*Floatones, and the call formsconstr(...),conint(...),confloat(...),condecimal(...),conlist(T, ...),conset(T, ...);pathlib.Pathfields (path_typeerror, strict mode, JSON dump asstr). - Dependency forms of public applications translated natively: a
yieldunderwith/async with/if/nestedtryblocks (several only in exclusiveifbranches), a class dependency inheriting__init__from a plain base (its signature read in the base's module),Depends(Cls.classmethod)andDepends(Cls.staticmethod)(found along the bases;Sub.make()of a base's classmethod getsSub), dependency factories with*rolesand factories returning another factory's call,Depends(lambda: ...). fixtures/depapp. - Refused at their line instead: a
yieldin a loop or two on one path, a base other thanABC/object/one plain class,__new__on a class dependency, an instance method read on its class. - A dependency that is a library's object, or a global built by calling one (
get_current_user = fastapi_users.current_user(), an instance of a subclass of a library class), is refused with the library named: FastAPI reads the signature of what the library makes (fastapi-users builds it at run time with makefun). - Dependencies and
Annotatedaliases bound in the application factory (Auth = Annotated[Claims, Depends(claims_from_request)]insidecreate_app()), read by the endpoints defined there, in their parameters or independencies=[...]: compiled with the factory's locals. Refused when bound twice or after the endpoint (Python's NameError). - Pydantic's DSN types are native:
PostgresDsn,MongoDsn(multi-host types, one host here:hosts(), nohost/port),CockroachDsn,AmqpDsn,KafkaDsn,MySQLDsn,MariaDBDsn. - Experimental
--path DIR(repeatable, generation andcheck): extra import roots for the sibling packages of a monorepo the application installs from its own checkout (oasst_shared,lfx,titiler.core). - httpx: the rest of its exception hierarchy (
ReadError,RemoteProtocolError,ProtocolError,WriteTimeout,PoolTimeout,ProxyError,StreamError...) usable inexcept/isinstance; the client raisesRemoteProtocolErrorandReadErroras httpx does, every error carrying.request; timeouts' messages are now empty, as httpx's. - A lifespan the app factory defines (
create_app()->async def lifespan(app)underif not settings.TESTING:): native, with the factory's locals, used only when theifs aroundFastAPI(lifespan=...)hold at startup; with--python-side auto, left to Python alone when it does not translate (it sent the whole application to Python: "the lifespan is not a function of the project"), andcheckjudges the routes without it, as the generation does. Astateattribute the lifespan only initialises, read with that value asgetattr's default, no longer moves its readers (or the application) to Python. - loguru 0.7 native (dynrt/loguru.rs): the default handler on stderr (format, call site, colours as loguru decides them on a terminal or a CI,
LOGURU_LEVEL/LOGURU_COLORIZE/LOGURU_AUTOINIT), the level methods andlog(),add(sys.stderr | sys.stdout, level=, format=, colorize=)with a literal format compiled at translation,remove(); fixturefixtures/loguruapp, compared with the logs. Refused at translation:exception(),opt,bind,contextualize,catch, file and callable sinks,serialize,enqueue,filter. - A project class wrapping engine and
async_sessionmaker(one instance per pool) called outside a dependency (get_worker_session()->WRAPPER()): a session of its own, its engine'sconnect_argsoptions set in each of its transactions (set_config(..., true)). fixtures/dynapp/makerwrap.py. - passlib 1.7.4:
CryptContext(schemes=["bcrypt"], deprecated="auto")native (hash,verify,verify_and_update,needs_update,identify,dummy_verify), over bcrypt 4.3 or 5.0 as passlib loads it (with 5.0 every hash raises, as in Python);passlib.excerrors. bcrypt 4.3 joins the tested range (itshashpwhashes the first 72 bytes). pathlib.Path.cwd()andos.getcwd(): the process's current directory, as CPython (FileNotFoundError when it was removed); fixturefixtures/pdfmergeapp.- pgpy 0.6.0's
PGPKey.from_blob()natively (dynrt/pgpy.rs, pgpycore.rs; fixturefixtures/pgpyapp): the armor as pgpy's regex finds it, base64 and CRC-24 (its warning), every packet and subpacket type with the bytes pgpy reads of it, v4 keys of every algorithm with their fingerprint, signatures, user ids and attributes in pgpy's order, text that is not ASCII parsed as binary, every exception pgpy lets out with its message, the warnings on stderr as CPython prints them.PGPKey'sis_public,is_primary,fingerprint(a str:keyid,shortid, pgpy's==),userids,userattributes,subkeys;PGPUID'sname,comment,email,userid,is_uid,is_ua,is_primary. Any other pgpy call is refused at transpile time. Supported versions: pgpy 0.6.0 with pyasn1 0.6.4. Differences: supported.md § pgpy (bzip2 blocks, warning addresses,OrderedDict). - qrcode 8.2 natively with Pillow's default image (dynrt/qr.rs):
QRCode(...),add_data,make,make_image()in black on white,qrcode.make,image.save(io.BytesIO(), format="PNG"); the encoder is a port of qrcode's (data modes, version fit, mask choice, exceptions) and the PNG is Pillow 12.3's byte for byte (row filters of ZipEncode.c, zlib-ng's deflate through zlib-rs, IDAT chunks).image_factory=is refused. Fixturefixtures/qrapp. - The synchronous redis client (
redis.Redis,redis.from_url,Redis.from_url) is translated on the same runtime asredis.asyncio, withConnectionPool.from_url+Redis(connection_pool=)for both, pipelines (pipeline(transaction=),execute()), hash, list, set and sorted-set commands, andwith/async withon a client. - reportlab 4.4.5 natively (dynrt/rl/, bound in dynrt/rlbind.rs; docs: Generated documents § PDF):
SimpleDocTemplateinto anio.BytesIOwith page callbacks and their canvas,Paragraphand its markup,ParagraphStyle,getSampleStyleSheet(),Spacer,PageBreak,HRFlowable,Table/TableStyle, the shapes ofreportlab.graphics, colours, units, page sizes; the PDF byte for byte but its instants. The paragraph markup follows thehtml.parserof the project's Python patch release (probed on the transpiler's);rl_accelorrl_renderPMin the lock refuses the calls that build documents. Fixturefixtures/docapp(pdfs.py). include_routerunder a module-levelifread from the settings or the environment (if settings.FASTAPI_ENV == "development":,if os.getenv(...),elsebranches, nestedifs): each test is evaluated once at startup and the routes of a branch that is off are not matched (404, no 307 to them); other tests stay refused.app.routesstill lists them (documented).- A project function given the app that registers routers (
def add_routers(app): app.include_router(...), called once with the app, in the factory or at module level) is native: its routers are registered where it is called, prefixes from its parameters as the call passes them (or their literal defaults) or from module globals (read at startup). for r in ROUTERS: app.include_router(r)over a literal tuple (or a list never changed) of the module is unrolled.APIRouter(default_response_class=...)(JSONResponse, ORJSONResponse, HTMLResponse, PlainTextResponse): the route's own router, else the nearest router including it, as FastAPI fixes it on the route.- A project function without parameters that only builds a router from routers (
def build(): r = APIRouter(...); r.include_router(...); return r) is a router:app.include_router(build())is native (each call makes the same router). - Routers in the project's modules outside the translated directory (src/ layout,
--rootabove it) are found through the app's imports, factory imports included. - An import guard on the project's own code (
try: from app.api import x / except ImportError: x = None) is decided as CPython decides it when the module is absent:if x is not None: app.include_router(x.router)never runs andif FLAG:keeps one branch. secrets.randbelow,secrets.randbits(up to 63 bits),secrets.token_bytesandsecrets.DEFAULT_ENTROPY;secrets.token_*take a bool or None as CPython does and raise itsTypeErrorfor anything else (it was a py2axum message).secrets.choice/random.choicefollowRandom.choice:len(seq)thenseq[i](a set, a generator or a dict now raise or index as in CPython instead of picking among their elements).- More shapes of the session dependency are native (they sent the routes to Python as "session or engine", P2A0505, on the real-application bench):
s = maker()annotated or inside thetrywithfinally: [await] s.close()(async too),raise excof the caught exception, a maker read into a local from a cached factory (factory = get_session_factory()), a maker returned by a project function (SessionLocal = make_sessionmaker(engine)), and the maker a module instance of a project class keeps (db_manager.session_maker()), set once in__init__or by a method the lifespan calls before itsyield; set any other way, it is refused at its line. - SQLModel's
AsyncSession(sqlmodel.ext.asyncio.session) is the session type like SQLAlchemy's, and a maker created inside the dependency (maker = sessionmaker(engine, class_=AsyncSession, ...)thenasync with maker() as s:) is read like a module one. - A SQLModel table whose base without a table is in another module of the project (
class User(UserBase, table=True),UserBaseimported): its inherited fields are columns, when every name they read means the same in both modules (else the table stays refused). An Enum-annotated field is SQLModel'sEnum(...)column.session.exec()oftext(...),update(...),delete(...)orinsert(...)returns the Result, as SQLModel does. - SQLModel columns of type
EmailStr(VARCHAR, likestr) anddatetimewhen the project locks SQLModel < 0.0.45 (a naive TIMESTAMP, as SQLModel maps it there; from 0.0.45 itsUTCDateTimestays refused). The SQLModel version is read from uv.lock or an==pin in requirements*.txt / pyproject.toml. session.exec(stmt)where the statement is refined before (stmt = select(Hero), thenstmt = stmt.where(...)under anif): read as theselect()it started from (it was refused:.exec()not implemented).- SQLModel
Relationship(back_populates=, cascade_delete=, passive_deletes=, sa_relationship_kwargs=)on a table class (FastAPI's relationships tutorial): rewritten as SQLModel's metaclass builds it,relationship("Target", ...)withcascade="all, delete-orphan"forcascade_delete=True, and left out of the table's Pydantic fields (the whole class was refused).link_model=stays refused. - SQLModel
Field(sa_column=Column(...)): the Column as SQLModel takes it (its type, nullability and defaults; the Field's column options ignored, its default kept as the instance's), and the SQLAlchemy namessqlmodelre-exports as they are (from sqlmodel import Column, DateTime, JSON, func) read as SQLAlchemy's, also bycreate_all. - A SQLModel table class used by the routes of another module (
from app.models import Song, thenresponse_model=list[Song], aSongbody orSong.model_validate(...)): those routes see it as SQLModel does, as in its own module (it was refused: "not a Pydantic model or an enum"). str.format_map(mapping): each field read throughmapping[key](adefaultdictfills and keeps its default), a positional field refused with CPython's ValueError.sys.moduleswith a literal key for a module the project's Python cannot import (PEP 594, 3.13+: animghdrstub put there before importing a library), andtypes.ModuleType(name, doc=None); any other use ofsys.modulesis refused (P2A0105).tempfile.TemporaryDirectory(suffix, prefix, dir, ignore_cleanup_errors, delete=)natively:with ... as path,.name,cleanup(), removal with its content at the block's end or when the object goes (dynrt/pathio.rs; docs: Generated documents § Temporary files).traceback.format_exc(): the handled exception's chain, project frames only (as the logs). Before Python 3.13 a chain is followed only from a true exception (one whose__bool__is false shows alone, in tracebacks and logs too); from 3.13 always, as TracebackException testsis not Nonethere.- WebSocket routes can be left to Python (
--python-side '/ws/{room}', or moved by--python-side auto, for instance when they read what a lifespan left to Python sets), and a whole application relayed may have WebSocket routes: the binary relays their connections toPY2AXUM_PYTHON_URL, handshake first (the client gets the Python application's 101 with its subprotocol and headers, or its rejection), then messages and close frames unchanged. fixtures/wsrelayapp. - stripe-python 14.0–14.4 translated natively (dynrt/stripe.rs): every resource classmethod of the release
(
stripe.Customer.create(...),stripe.checkout.Session.create(...),stripe.Invoice.list(...).auto_paging_iter()), the request options, the module configuration (stripe.api_key = ...at module level or in a function),stripe.Webhook.construct_eventandWebhookSignature.verify_header. Requests (form encoding, headers, retries), objects (a dict subclass with attribute access, list objects) and errors (stripe.error.*, messages and attributes) as stripe-python's; tables generated from the release (tools/gen_stripe.py). The*_asyncmethods,StripeClientand the instance methods of an object stay refused. Conformance fixturefixtures/stripeappagainst a fake Stripe API (tests/stripe_stub.py). The binary readsSTRIPE_LOGas stripe-python does. Differences: docs/supported.md § stripe. - openpyxl 3.1 translated natively (dynrt/xlsx.rs, docs: Generated documents):
Workbook(), worksheets, cells,Font/PatternFill/Border/Side/Alignment, a merged range, column widths,save()into aBytesIO, the bytes openpyxl writes without lxml. With lxml in the project's lock, the routes building a workbook are refused (or left to Python by--python-side auto), not the whole application. tempfile.NamedTemporaryFile(mode, suffix, prefix, dir, delete)(w/w+ modes) andtempfile.gettempdir()translated natively;f.nameof an open file. Leavingwithon a file now closes it the wayclose()does.
Changed¶
- orjson accepted from 3.12.0 (was 3.13.0): 3.12.0 answers the 738 orjson conformance cases byte for byte like 3.13.0;
the CI
versionsjob's lower end now installs it. - Breaking:
--backend(generation andpy2axum check) and the keybackendof the JSON ofcheck, deprecated since 0.4 and 0.8 (they had no effect: one backend): passing--backendis now an error,error: --backend was removed in 1.0 (it has had no effect since 0.4: there is one backend): drop it(exit status 2), the key is no longer emitted nor incheck-schema.json.--reportis hidden from--helpand the reference (an internal tool, still prints its deprecation warning). Decided 2026-10-19 for 1.0. - pydantic-settings accepted up to 2.16 (range
>=2.11.0,<2.17, tested at 2.16.0: marketing's 293 conformance cases and the settings cases of the reference apps). - A class of the project (an Enum) as a key of a declarative base's
type_annotation_map: refused at each column annotated with it (it refused every mapped class of the base, hence the whole application).
Fixed¶
-
The binary coerces the legacy C locale at startup as CPython does (PEP 538): with LC_ALL unset and a C LC_CTYPE,
LC_CTYPE=C.UTF-8is set in its environment, read byos.environand inherited by the processes ofasyncio.create_subprocess_exec(their messages were in the C locale;PYTHONCOERCECLOCALE=0/warnhonoured). -
The router's 404 and 405 and FastAPI's body errors are Starlette's HTTPException: a handler registered for
fastapi.HTTPExceptionno longer handles them (it did, dropping the 405'sallowheader). - A generated crate could fail to compile (E0061) although the generation succeeded: the stub of a generator
function that does not translate (raising if ever called, never reached by a route) lacked the yielder parameter
its callers pass (seen with
--translate-libs autoon et_xmlfile), and a generator method called through its method wrapper (obj.gen()resolved at run time,@classmethodgenerators) was called without it. A test now generates such a crate and runscargo checkon it (tests/test_generated_compiles.py); conformance cases for generators iterating generators, generator methods and a generator handed to an@asynccontextmanager(fixtures/libsrcapp/gens.py). --translate-libsreads from source the names the library map does not cover of a library it covers in part (jinja2.Template,aiosmtplib.SMTP,requests.utils,pywebpush.WebPusher; refused before as "not in the py2axum library map", whatever the library's licence or code). The map's names stay native, in the library's own code too: its exceptions derive from the map's classes. A binary that would use both a map's object and the library's source refuses the routes reaching the source (P2A0705;--python-side autoleaves them to Python).h11andcertifiare no longer kept from translation (the map has none of their names). docs: Libraries translated from source § Libraries the map covers in part.- A project module adopted because the package imports it (outside the package dir) no longer contributes its own
FastAPI()app: its middlewares were added to the served app. - An exception escaping a route under two or more BaseHTTPMiddleware layers (
add_middlewareof a subclass,@app.middleware("http")) is logged as uvicorn logs it with Starlette 1.3+: the inner layer's anyioExceptionGroupfirst, then "The above exception was the direct cause of the following exception:" and the exception (Starlette'screate_collapsing_task_groupandcall_nextre-raise itfromits cause or context). The binary printed the exception alone. py2axum checkand the generation crashed (StopIteration, AttributeError) on a function given the application whose result is kept or that is called in a nested function, and on a router prefix read at startup that does not translate next to a project middleware class: they are refused with their file:line.- A route decorator's path given as
path="/x"is read (IndexError before; a decorator with no path is refused); arequirements*.txtis decoded as pip does (BOM:pip freezeunder PowerShell writes UTF-16; acodingline; else UTF-8, an undecodable file refused with its name); modules are decoded by their PEP 263 coding line; a module global declared by its annotation only (X: int) then rebound withglobalis refused with its file:line (all crashedpy2axum check). - compat32 e-mail headers (
MIMEText,MIMEMultipart...): a non-ASCII value is cut into encoded words whereemail.headercuts it (to the 78-column line when sent, one word inas_string()), Q or base64 chosen once for the whole value; a continuation line sent over SMTP no longer carried a stray CR.formataddrencodes a non-ASCII name as a single word;make_msgidstamps hundredths of a second and 64 random bits, as CPython. - A decorator on an endpoint besides its route decorator (
@app.get(...)over@require_admin,@lru_cache, a library decorator, or a decorator above the route decorator) was silently ignored: the binary served the bare function, skipping what the decorator does in FastAPI (authentication, cache, rate limit, transaction...). It is now refused at the decorator's line (P2A0318);--python-side autoleaves such a route to Python. - Two route decorators on one function (
@app.getover@app.post) served only one route; refused (P2A0318). @app.api_route,@app.head,@app.options,@app.traceand@app.route(and the same on routers) left the function unregistered: the binary answered 404/405 where FastAPI served the route. Refused (P2A0318).FileResponse(headers=...): the endpoint's ownContent-Disposition(orETag,Last-Modified...) replaces the one Starlette makes (setdefault) instead of going out as a second header beside it; headers in Starlette's order.- A generic model specialized in another module than the one that declares it (
Response[Role]withResponseandRoleimported from different modules,Page[List[Item]]) is translated instead of refused with "must mean the same in ...": the arguments are bound under names of the generic's module. gzip.compress(mtime=)outside 0..2**32-1 (negative, beyond 32 bits, nan, inf) writes an mtime of 0 on Python 3.15 and still raisesstruct.errorbefore it.--translate-libs: a library whose guarded imports (try: import x / except ImportError:) form a cycle (structlog'sfrom structlog import twisted, reportlab) madecheckand generation crash with a RecursionError. A module whose imports are being decided is importable, as CPython finds it insys.modulespartially initialised.pathlib.Pathfields: Python 3.13 alone names the classpathlib._local.Pathin thepath_typeerror message, as pydantic prints it; the other versions keeppathlib.Path.- qrcode's PNG on Linux: Pillow's manylinux wheels compress with zlib 1.3.1, not zlib-ng (their macOS wheels): the binary built for Linux now compresses with classic zlib (libz-sys, static), so its IDAT bytes are Pillow's there too (they differed on Linux, measured on x86_64; macOS was already identical).
redis.asyncio:hgetall()returned a flat list instead of redis-py's dict, and an error reply's message carried the Rust client's wording instead of redis-py's (WRONGTYPE Operation against a key holding the wrong kind of value).include_router(prefix="/v1", router=r)(the router as a keyword) was skipped without an error: its routes were never served (404). It is read like the positional form.- Routes are tried in registration order: an
include_routertakes its place among its owner's routes, instead of the order the modules were walked in (a router included first could be shadowed by an overlapping route of another module, androuter.include_router(nested)placed before@router.get("/{id}")lost to it). - A failed flush (
commit(),flush(), a savepoint'scommit()) rolls the transaction or savepoint back at once and leaves the session raising SQLAlchemy's PendingRollbackError on every statement, flush and commit until the matchingrollback()(the savepoint's for a failed savepoint commit, after which the outer transaction is usable), as SQLAlchemy 2.x; before, the next statement met PostgreSQL's aborted transaction.async with session.begin_nested()ends that state at its exit. - A statement abandoned mid-flight (
asyncio.wait_for(session.execute(...), timeout)expired) invalidates the transaction as asyncpg/psycopg under SQLAlchemy: PendingRollbackError ("Can't reconnect until invalid transaction is rolled back") untilrollback(); the pool's connection comes back clean. session.in_transaction(),session.in_nested_transaction()andsp.is_activenatively.async with session.begin_nested() [as sp]:andasync with session.begin():(withon a synchronous Session) natively, as SQLAlchemy's SessionTransaction: RELEASE / COMMIT at a normal exit, ROLLBACK TO / ROLLBACK when the body raises, an IntegrityError of the exit's flush rolled back with the outer transaction still usable, nothing when the block was already ended;begin()on a begun session raises InvalidRequestError. Both were a TypeError at run time (a 500 on every decision insert of an application using them).with/async withon the value of a SQLAlchemy session, connection or result method (execute(),scalar(),commit()...) is refused at generation with its file:line (a TypeError in Python, a 500 before).with io.StringIO()(a TypeError before) andwith io.BytesIO()close the buffer at the block's end; a closed buffer's methods raise CPython's ValueError.--translate-libswith--python-side auto: a library mixed from the map and from its source (P2A0705) next to a middleware class of the project madecheckand generation crash with an AttributeError while the stack's errors were collected (a real application with--translate-libs auto).str.format()/format_map()of a string ending in a lone{: CPython'sSingle '{' encountered in format string, notexpected '}' before end of string.except stripe.error.Xwith stripe 14.0.0 locked (wherestripe.errordoes not exist): translated instead of refused, raising the bareAttributeErrorof stripe's module__getattr__(itsKeyError('error')context, the suggestiontracebackprints on Python 3.12) only when an exception is tested against the clause, as CPython does;stripe.error.Xas a value raises it when evaluated.
Tests¶
- Python 3.15 timestamp functions py2axum does not translate (
time.localtime,time.gmtime,date.fromtimestamp) are pinned as refused (P2A0201,file:line) by a reject test. - Conformance compares PDF and OOXML documents byte for byte, masking only their instants and the PDF's
/ID(tests/docmask.py); fixturefixtures/docapp.
[0.9.1] — 2026-10-18¶
Patch release: an ammonia security update, fixes for differences seen in production (request bodies validated from
JSON bytes, SMTP over TLS with validate_certs=False, has()/any() after a join, datetimes and strftime), and
pytz, python-dateutil and cachetools translated natively.
Security¶
ammonia4.2.4 in the shipped lock file and as the runtime's minimum (was 4.2.3): RUSTSEC-2026-0373, CSSurl()matched case-sensitively when sanitizing (nh3.clean).
Added¶
- pytz 2026.5 native (
dynrt/pytzrt.rs, pytz's own zones dumped by tools/gen_pytz.py):timezone(),utc,FixedOffset(), the zone lists,localize/normalize/fromutc/utcoffset/dst/tznamewith pytz's instances (isholds), croniter over pytz zones (itslocalizebranch). fixtures/libapp/pytzx.py: every zone over its transitions. - python-dateutil 2.9:
dateutil.parser.parse()with its options,ParserError,isoparse()/isoparser(dynrt/duparse.rs), anddateutil.tz(dynrt/dutz.rs):tzutc,tzoffset,tzlocal,gettz(system zone files as dateutil reads them, dateutil's tarball,tzstr),tzstr,enfold,datetime_exists,datetime_ambiguous,resolve_imaginary. fixtures/libapp/duparsex.py, dutzx.py (3,000 generated strings for the parser). The python-dateutil range is checked when its parser or tz is imported; the binary readsTZ(gettz()). - cachetools 7.2 (
dynrt/ctools.rs):Cache,FIFOCache,LRUCache,TTLCache,@cached,@cachedmethod,cachetools.func.lru_cache/fifo_cache/ttl_cache,keys.hashkey/methodkey. fixtures/libapp/ctoolsx.py. - Error codes P2A0210 (cachetools decorator not supported) and P2A0119 (strftime directive not supported).
Fixed¶
Model.model_validate_json(await request.body())always failed: the bytes went throughstr()("b'{...}'"), so the JSON was refused at its first character (a route swallowing the error silently dropped every request).model_validate_jsonandTypeAdapter.validate_jsonnow take str or bytes parsed by jiter (json_invalidandjson_typevalidation errors, as pydantic) and validate in pydantic's JSON mode: its own type errors (Input should be a valid array,Input should be an object,valid duration), a JSON string as an exact input for date, datetime, time, timedelta, UUID, bytes and Decimal in a smart union, Decimal from a JSON float as pydantic writes it (1.0->Decimal('1')). Strict fields, complex, Iterable, deque/Counter/OrderedDict/Sequence, unions discriminated by a function and models with wrap validators are refused in JSON mode when reached (never a wrong value). fixtures/dynapp/reqbody.py.await request.json()decodes the body asjson.loads(bytes)does (UTF-8 BOM, UTF-16/32,UnicodeDecodeError): invalid UTF-8 was replaced by U+FFFD.await request.form()andrequest.stream()are refused at generation (file:line): they raised AttributeError at run time.aiosmtplib.send(validate_certs=False)now accepts a certificate issued for another host name, as aiosmtplib does (it checks neither the chain nor the name); the binary skipped the chain only, so a relay dialled by an internal name (e.g.internal-mailserveragainst a certificate formail.example.fr) failed with "certificate not valid for name".validate_certs=Truestill refuses. Covered by/small/mail-tls(integapp) againsttests/smtp_sink.py --tls.Model.rel.has()/.any()in a statement that joins the relationship's target (select(A).join(A.b).where(A.b.has(...))): the EXISTS kept its target in its FROM list like SQLAlchemy'scorrelate_except(target); since 0.7.0 it auto-correlated it away and raised InvalidRequestError (500, Python 200).correlate_except()onselect(),exists()andscalar_subquery(), andcorrelate()onexists(), are native.- Datetimes: two values under the same tzinfo subtract and compare by their wall times (CPython), and between zones
a value whose offset depends on its fold equals nothing (PEP 495);
astimezone()of the same tzinfo returns the value;dt.tzname()anddt.dst();%Zwrites the zone's abbreviation (it wrote a ZoneInfo's key);datetime(..., fold=); 3.14'sfold must be either 0 or 1, not N;timezone/ZoneInfovalues are hashable,isholds between tzinfos;isinstance(x, timezone),isinstance(x, tzinfo). - A keyword argument a function does not take names the closest parameter on Python 3.13+ (
Did you mean 'dt'?). UnicodeDecodeError(encoding, object, start, end, reason)'sstr();<class 'decimal.DivisionImpossible'>and the other library exception classes'reprwith their module; a library named tuple'srepr(CacheInfo(hits=0, ...)).- A decorator named
lru_cacheorcachefrom another library than functools (cachetools.func) was compiled as functools' own. strftime("%Y")of a year below 1000 on Linux before Python 3.14 writes it unpadded (1), as glibc does through CPython; macOS and 3.14+ pad it (0001). Likewise%G,%Cand%F;%ckeeps glibc's unpadded year on every version.strftimecopied the directives it did not know into the output (%c,%e,%u,%V,%:z...): every directive whose output is the same on glibc and macOS is rendered as CPython does, and%Pas each C library does; flags (%-d), widths,%E/%O,%s(the local time zone) and unknown letters are refused at generation for a literal format (P2A0119) and raise ValueError for a computed one.dateutil.parser.parse()of a field beyond a C int raises 3.13'sPython int too large to convert to C int(datetime.replacethrough Argument Clinic since 3.13.0; it was written for 3.14 only).
[0.9.0] — 2026-10-16¶
The runtime becomes a library crate of its own, compiled once and shared by every generated crate (link-time
optimisation thin by default: a generated crate builds in under 3.1 GiB on Linux), and the binary allocates with
mimalloc. The documentation corpora reach FastAPI 96.9 %, Pydantic 96.6 %, SQLAlchemy ORM 99.2 % and Core 100 %
with no silent difference. Pure-Python libraries can be translated from their source (--translate-libs, off by
default), and itsdangerous' URLSafeSerializer, mimetypes, email.message.EmailMessage and dnspython's resolver
are translated natively.
Added¶
--translate-libs none|auto|DIST,...(generation,check,watch), with--venvand--allow-license: pure-Python libraries of the project's environment translated from their source, only the functions the routes reach (see Libraries translated from source). The project and the library map keep precedence; a distribution is refused with a code of the new 07xx family when its licence is not admitted (P2A0701), when it is not pure Python (P2A0702), or when it is not installed as the project locks it (P2A0703).checklists the translated libraries (functions translated and refused, lines, estimated gen.rs and rustc peak; newlibrarieskey of its JSON output). Off by default. With it, a closed list of pure-Python modules of the standard library is translated from the project's Python'sLib/(colorsys,gettext,html.entities,keyword, never a module with a C accelerator such asbisect; P2A0704 when py2axum runs on another minor); a library's module statements run at import, itstry: import x / except ImportError:is decided by the environment, and the lazy imports of a package's__getattr__are followed.- Protocol methods of plain classes and dataclasses:
__iter__/__next__(aforloop and a comprehension call__next__between their bodies),next(),__len__,__bool__,__contains__,__getitem__/__setitem__/__delitem__, the arithmetic and bitwise operators with their reflected and in-place forms andNotImplemented,__neg__/__pos__/__invert__/__abs__, with CPython's errors. Pickle and copy methods (__getstate__,__reduce__,__deepcopy__...) are ignored when nothing imports copy or pickle. - Bases
Generic[T],Protocol[T]and subscripted project bases; method defaults read in the class body; statements afterreturn/raise/break/continueno longer translated;mod.X = v/mod.X += vrebind a module variable (they were refused). threading.local(),operator.index(),sys.maxsize,str.isascii(),object()as a sentinel,bytearray,memoryviewandcomplexasisinstancemembers,s.__contains__(and__getitem__,__len__) of a builtin container read as a value (keyword.iskeyword),@typing.overloadsignatures dropped, module flags made of a version or platform test (PY3 = sys.version_info[0] == 3) folded,isinstance(x, string_types)with a module variable holding types,__slots__as one string,if TYPE_CHECKING:in a class body.FastAPI(telemetry={...})with its literal switches (the binary emits no OpenTelemetry data: documented).- Pydantic
create_model("M", ...)at module level, compiled as the class it creates (fields,__base__, validators and computed fields of__namespace__/__validators__). -
SQLModel (FastAPI's SQL databases tutorials): classes rewritten at translation into SQLAlchemy mapped classes and Pydantic models (same DDL as SQLModel),
Session(engine)dependencies,session.exec(select(...)),model_validate,sqlmodel_update,SQLModel.metadata.create_all(engine);Base.metadata.create_all(engine)with a synchronous engine. fixtures/sqlmodelapp. -
Pydantic:
datetime/datebounds (Field(gt=datetime(...)),annotated_types),AwareDatetime,NaiveDatetime;model_post_init(self, context);PrivateAttr(default_factory=...)computed (datetime.now);@with_config(...)on a stdlib dataclass; a method of a builtin type as a value (MyAfterValidator(str.lower),key=str.lower). -
FastAPI: subclasses of
HTTPBearer/HTTPBasic/OAuth2PasswordBeareroverridingmake_not_authenticated_error/make_authenticate_headers;SecurityScopesandSecurity(dep, scopes=[...])(scopes of the chain, cache per set of scopes);AfterValidatoron path, query, header and cookie parameters;yield fromover a file, a literal or a builtin's result; iterating an open file. -
Model.__table__as a Core table when the code uses it as one (t.join(...),t.c.col,select(t),select_from(t)): rows of values, columns by their column name. A value both used as a Core table and iterated for introspection (or given to other code), and the table of an inheriting class, are refused at translation. - Core
Table.join(right, onclause=None, isouter=, full=)andouterjoin(), chained; a Join given toselect_from()supersedes the FROM entries of its tables, as in SQLAlchemy. with_polymorphic(Base, [Sub, ...], aliased=True, flat=...): an alias of the base with its subclass tables LEFT OUTER JOINed under their own aliases, two of them joined to each other,poly.Sub.colin the criteria, the subclass columns loaded with the objects. SQLAlchemy ORM corpus 93.8 % → 95.4 % (0 differences).Model.model_construct(...)(pydantic 2.12 to 2.14: aliases, validation aliases, defaults,_fields_set, extras, private attributes) andmodel_extra. A value of another type than its field is refused when the instance is dumped (pydantic dumps it with a serializer warning), a required field left out at run time.- A router of a library included last in the app (
app.include_router(lib.router)) stays on the Python side with--python-side mount(orauto), like a finalapp.mount(): refused withfile:lineunder the new code P2A0315 when something registers routes after it (also through a function given the app), when it is conditional, or when its prefix is not literal. It used to stop the generation of the whole application. - FastAPI parameter markers kept in module variables (
RadiusQuery = Query(50.0, ge=5)given as a default or inAnnotated) were evaluated as values (a library call, refused); they now stand for the call they hold. A marker withoutalias=shared by parameters of different names is refused (FastAPI gives it the first one's name). - A function held as a plain class attribute through
staticmethod(f)(read through the class or an instance, never bound). - Hybrid attributes with a custom comparator (
@x.comparator,@x.inplace.comparator) and hybrid value objects:sqlalchemy.ext.hybrid.Comparatoris translated from Python source of py2axum's own (py2axum/shims/, its frames left out of tracebacks like a library's); its subclasses, plain classes or@dataclass(eq=False), are compared in Python and in SQL throughoperate(), coerced to SQL by__clause_element__()(also on analiased()class). A hybrid setter runs for a keyword of the default constructor. - Rich comparisons of project classes (
__ne__,__lt__,__le__,__gt__,__ge__, reflected ones, the result as returned),sorted()/min()/max()of such instances,__hash__ = object.__hash__,@dataclass(eq=False), a dataclass deriving from a plain class,operator.eq& co. as values (<built-in function eq>). relationship(primaryjoin=fk == col)(a foreign key equal to the column it references) andpost_update=Trueon a many-to-one relationship: two tables referencing each other are flushed (INSERT, then UPDATE of the key; UPDATE to NULL before the DELETEs).select(tuple_(...))raises SQLAlchemy's CompileError.- fixtures/ormapp (116 cases). SQLAlchemy ORM corpus 95.4 % → 99.2 % (257/259, 0 differences; all SQLAlchemy
85.2 % → 87.4 %); the last ORM refusal is the documentation's own defect (
ext/associationproxy.rst:592). The corpus leaves out a definition block Python fails to run (a fragment such asclass X(Base): # ...), which made the Python reference of the later blocks of its page fail. - itsdangerous
URLSafeSerializer(the serializer without timestamp):dumps(obj, salt),loads(s, salt), same tokens byte for byte, key rotation, the library's exceptions; itsdangerous joins the tested version ranges (2.2). mimetypes.guess_type,guess_file_type(Python 3.13+),guess_extension,guess_all_extensions(strict=): the project's Python built-in tables, then the host'smime.typesfiles,data:URLs, suffix and encoding maps, the order ofguess_all_extensions.- SQL of reporting queries: window functions (
func.f(...).over(partition_by=, order_by=), frames refused), CTEs (select(...).cte(name), anonymous, chained, read in a subquery: all in the WITH clause of the outermost statement), LATERAL subqueries (.lateral(), correlated to their statement's FROM list),correlate(*entities)andcorrelate(None),union_all()/union()/intersect()/except_()(and_all, functions or methods) made a subquery, a CTE or executed,case(*whens)from a list built at run time (no WHEN: built, then refused by PostgreSQL as with SQLAlchemy; a list of whens: SQLAlchemy'sArgumentError),icontains/istartswith/iendswith,cast(x, Numeric),literal_column(text),postgresql.array([...])withany_()/all_(),bindparam(key, type_=ARRAY(String())),Result.fetchone(),mapped_column(..., type_=T),aliased(Model, subquery or cte())(a union of such selects too),aliased(Model, flat=True)on a plain table,scalar_subquery().correlate(t). SQLAlchemy corpus: Core 88.7 % → 100 %, all of SQLAlchemy 87.4 % → 92.6 % (0 differences);text(...).columns(...)is refused at translation (it failed at run time). - Dependencies built by a factory (
Depends(make_dep(Query([], alias="id"), int))): the function it returns, its defaults and annotations holding the factory's arguments (constants, builtin types, FastAPI markers of constants); tracebacks name it as CPython does (make_dep.<locals>.inner). typing.NamedTupleclasses: built like a dataclass, a tuple everywhere else (indexing, unpacking, equality and hash with tuples, concatenation,isinstance(x, tuple), JSON as an array),_asdict(),_replace(),_make(),_fields,_field_defaults, read-only fields with CPython's messages per version.string.Formatter().parse(s)consumed whole (list(...),tuple(...)): CPython's parser, items and errors;itertools.chain(*its)/chain.from_iterable(its)consumed whole (list(),tuple(),set(),sorted());float.is_integer()/int.is_integer();from builtins import list(the builtins called by that name);Ellipsis.- Dataclasses (stdlib and
pydantic.dataclasses) as FastAPI request and response types and as model fields: validated like pydantic dataclasses (dataclass_type), into instances of the class. pydantic.Json/Json[T], parsed with jiter (the crate pydantic-core uses: same error messages and positions), then validated asT. New runtime dependency:jiter0.16 (no Python feature).__get_pydantic_core_schema__(a field type's classmethod, an Annotated metadata's) andGetPydanticSchema, read at translation as the equivalent annotation (scalar schemas and constraints, after/before/wrap/plain validator functions,chain_schema, plain serializers,schema['max_length'] = 10,if/assertknown at translation): the documentation's CompressedString, RestrictCharacters, SmallString, CustomType examples.- Custom route classes:
APIRouter(route_class=R)andapp.router.route_class = R,R.get_route_handler()wrapping the route's own handler (request validation errors caught, the Response object's headers changed), and a projectRequestsubclass whosebody()the route parses (FastAPI's GzipRequest).repr()of a Response and of its headers as Starlette writes them,request.headers.getlist(). - Pydantic
Iterable[T]fields (pydantic-core's ValidatorIterator): any iterable accepted, items validated when reached (next, loops,list, JSON dumps, responses), with pydantic's errors and titles. email.message.EmailMessageunder the modern policies (email.policy.default,SMTP,SMTPUTF8,HTTP): unstructured and address headers set and read back (msg[name] = value, a list of addresses,None),get,get_all,keys/values/items,del,in,len,set_content(str, subtype=, charset=, cte=)(the text handler's choice of 7bit, 8bit, quoted-printable or base64),as_bytes(),as_string(),str()andbytes(): a port ofemail._header_value_parser(address lists, encoded words, folding), byte for byte on every CPython release from 3.12.12 to 3.15.0 (the folder changed in 3.12.13, 3.13.12 to 3.13.14, 3.14.3 to 3.14.6 and 3.15: each change follows the project's Python, probed on the transpiler's own when it is the same minor). Headers with a structured value of their own (Date, Message-ID, Content-*, MIME-Version, In-Reply-To, References) and the other methods (add_attachment,get_content,iter_parts...) are refused.- dnspython 2.8's stub resolver:
dns.resolver.Resolver(filename=, configure=)read from/etc/resolv.confas dnspython reads it, its settings (nameservers,nameserver_ports,port,timeout,lifetime,search,use_search_by_default,retry_servfail,rotate,ndots,use_edns()),resolve()and the module'sresolve()on the default resolver: the same queries over UDP (TCP when truncated ortcp=True), retries, backoff, timeouts and nameserver eviction, CNAME chains, answers of MX, TXT, A, AAAA, CNAME and NS records (to_text(),str(),repr(), their attributes),dns.name.from_text, and the exceptions with their messages (NXDOMAIN,NoAnswer,NoNameservers,LifetimeTimeout,NoMetaqueries,dns.nameerrors...). dnspython joins the tested version ranges (2.8). tests/dns_stub.py serves the conformance.
Changed¶
- The runtime is a library crate of its own (
dynrt/, next to the generated crate, its path dependency) instead of a module copied intosrc/dynrt/, and the release profile uses thin LTO instead of fat (CARGO_PROFILE_RELEASE_LTO=fatrestores it). Throughput within the noise (−3.0 to +7.9 %), up to 3 % more server CPU per request, compilation peak of a large project 6.94 → 4.48 GiB; the runtime compiles once for every crate that shares a target directory (the Docker image precompiles it). The generated crate is a Cargo workspace; aCargo.lockgenerated by an earlier version is replaced. The generated project stays outside the public contract. - The generated binary allocates with mimalloc instead of the C library's
malloc(a default Cargo feature of the generated crate;cargo build --release --no-default-featureskeeps the system's): 7 to 17 % less server CPU per request, up to 22 % more throughput, at the price of 16 to 28 MiB more RSS. Building needs a C compiler (already needed for zlib). - Fewer instructions per request (callgrind, the dynapp fixture): a 20-row ORM list −6.8 %, a single row −4.9 %,
a
selectinload−7.2 %, a 404 −5.1 %. Table and column names are quoted at translation, a row's object is built once, the response model reads loaded attributes without a future per field, dict keys are hashed once.
Fixed¶
float(str)follows CPython's grammar: underscores between digits ("1_000"), Unicode decimal digits; it used to refuse the first and accept Rust-only forms.- Iterating a plain class instance or a dataclass without
__iter__raises CPython'sTypeError(it iterated nothing). - An ORM object whose autoincrement primary key was set to None was inserted with NULL (SQLAlchemy leaves the key out and lets the sequence give it).
- A missing parameter's default other than None is validated, as FastAPI does (
Query(0, ge=1)is a 422 when the parameter is missing); it was returned as is. model_post_initwas never called (now refused only withmodel_construct).- A stdlib dataclass inside a model takes that model's
str_*anduse_enum_valuesconfig, as in pydantic (it was validated without it); understrict=orextra=it is refused. -
A
typing.NamedTupleas a Pydantic type was validated like a model (other errors): refused. -
A method named like a library function (
stmt.compile(), named likere.compile) passed the translation's check that some runtime value implements it, then failed at run time (AttributeError): refused at its line now (P2A0203). No route of the ATOM applications changes. str()of a SQL statement or expression (also in an f-string orformat()) returned the PostgreSQL text the binary runs, never SQLAlchemy's (its default compiler::param_1, line breaks beforeFROM...): it now raises TypeError;str()of a column (table.col) is unchanged.tuple * int(andint * tuple) raised TypeError: the repeated tuple, as in CPython.int(x),round(x),math.floor/ceil/trunc(x)of a float beyond 64 bits returned 2⁶³−1 (a saturating conversion) instead of failing: OverflowError, like the other integers py2axum does not represent;int(inf)raised ValueError instead of CPython's OverflowError,round(nan)/round(inf)returned 0 / 2⁶³−1.from pkg import namewherepkg/name.pyexists andpkg/__init__.pybindsname(from .name import name,from .name import *) resolved to the submodule; it is now the object the package binds, as CPython reads the package's attribute first (python-slugify, tenacity, email-validator do it).- A class held as a class attribute (
class G: NT = _NT) called through the class held as a value (alias = G; alias.NT()) raised AttributeError at run time. A method read on its class (Cls.method, through a value too) now gives a function (taking the receiver first, none for a@staticmethod), or the method bound to the class for a@classmethod, instead of raising AttributeError; anasync defread that way is refused at translation (P2A0101,file:line) when the class is named, at run time through a class held as a value (fixtures/resolveapp). - An integer expression of literals beyond 64 bits (
10**100,1 << 70, also through a comprehension variable over a literal tuple:[10**x for x in (3, 100)], seen in humanize) raised OverflowError at run time, at startup for a module constant; it is now refused at translation withfile:line(P2A0101). - A function or lambda held as a plain class attribute was read unbound through an instance (CPython binds it to
the instance): it is now refused,
staticmethod(f)is the supported form. from module import *ignored the names the module imports itself (HTTPExceptionimported there from FastAPI was an unknown name), and bound names that__all__leaves out or that start with_.-
isinstance(x, Parent)was false for an instance of a Pydantic model that subclasses another model of the project (andParent.model_validate(child)raised a validation error). -
An exception raised while FastAPI's default handler encodes a 422 or an HTTPException's detail (
infin the input) carries the handled exception as its__context__(the traceback of the 500 differed). - A StopIteration escaping an endpoint or a dependency is
RuntimeError: coroutine raised StopIteration(PEP 479), with the StopIteration as its cause, as in CPython (the traceback of the 500 differed). urllib.parse.urlparse/urlsplit: a URL's trailing spaces were stripped (CPython strips only the leading ones),;paramswere split for every scheme (CPython: only those ofuses_params), and the netloc checks were missing (unbalanced or invalid brackets, an IPv4 address in brackets, NFKC delimiters raiseValueError).FileResponseguessed its type with the same lenient split.- Attribute reads that a runtime value provides (httpx
Response.reason_phrase,insert().excluded,__wrapped__,OAuth2PasswordRequestForm.grant_type/client_id/...) or that a raw ASGI middleware sets throughscope["state"](request.state.<key>) were refused at generation as certain AttributeErrors, unless another module of the project had a__getattr__. - With Starlette before 1.3, an exception raised while a
StreamingResponse(or a generator endpoint) streams is logged as Python logs it: re-raised out of anyio'sExceptionGroup, which becomes its__context__. - A
StreamingResponsechunk that is neitherstrnorbytes(anint, afloat) was sent as itsstr(); it now fails as in Starlette (AttributeError: 'int' object has no attribute 'encode', logged, the connection dropped). - A task that failed without being awaited, or an async generator, stored in the request's state
(
request.state.t = asyncio.create_task(...)) kept the whole request alive until the process exited (a few KiB per request), and asyncio's « Task exception was never retrieved » / the generator'sfinallynever came. Both are now freed with the request, as in CPython; the log line carries the task's repr (future: <Task finished name=... coro=<f() done, defined at file:line> exception=...>).
[0.8.0] — 2026-10-15¶
The public contract is frozen ahead of 1.0 (versioning and deprecation policy, tests that pin the command lines,
the binary's options and variables, the error codes and the JSON of check), after a second security review of
the runtime. The behaviour follows the project's Python from 3.12 to 3.15. Popular libraries are translated
natively (orjson, PyYAML, croniter, Unidecode, ecs-logging, aio-pika) and the binary applies the project's alembic
migrations itself (<binary> migrate). Upgrading is recommended: several fixes below close denials of service
that, depending on the application, need no authentication.
Added¶
- Versioning and deprecation: the public
contract semver covers from 1.0 (command lines, the binary's options and environment variables, the supported
subset, the JSON of
check, the error codes) and how a deprecation works. The JSON output ofcheckis published as a JSON Schema (reference/check-schema.json); tests freeze the contract. - orjson 3.13:
loads(the decoder's messages and positions, its depth and memory limits) anddumpswith everyOPT_*,default=and the types orjson serializes natively; FastAPI'sORJSONResponse(returned,response_class=,default_response_class=). - Unidecode 1.4:
unidecode,unidecode_expect_ascii,unidecode_expect_nonascii,errors=,UnidecodeError(tables generated from Unidecode bytools/gen_unidecode.py). - ecs-logging 2.3:
StdlibFormatter, called or fromdictConfig. - PyYAML 6.0 native (
import yaml):safe_load/load(Loader=yaml.SafeLoader)of a str, bytes or file object andsafe_dump/dump/safe_dump_all/dump_allwith all their options, ported from PyYAML's pure-Python loader and dumper: same values, same text byte for byte, same exceptions (str(),problem,context, marks and snippets). The other loaders, libyaml's classes and the extension API are refused at translation; the differences (integers beyond 64 bits, recursion depth,yaml.dumpof!!python/objectvalues) are documented. - aio-pika 10: exchanges of every type (
declare_exchange,get_exchange,bind/unbind),queue.consume/cancel,queue.iterator(),message.process(),ack/nack/reject,purge,delete,set_qos, the broker's channel errors as aiormq's classes; a published message gets aiormq's defaults (delivery mode 1, priority 0, amessage_id). - croniter 6.2 native (
dynrt/croniter.rs, a port of croniter.py):croniter(...)and itsget_next/get_prev/get_current/set_current/next()/all_next()/all_prev(),is_valid,match,match_range,expand,croniter_range, its exceptions; 5, 6 and 7 fields,L,W,#, names, aliases,Hhashing, time zones and DST transitions (timezone,ZoneInfo).R(random) fields are refused (see the known differences). datetime(the class) as a value:ret_type=datetime,type(x) is datetime, called later.datetime.replace(fold=);replace()keeps the fold of the datetime, as CPython does.asyncio.Future(loop.create_future()),asyncio.Event,asyncio.wait_forof a future or task held in a variable.- A plain class's
__new__(a factory returning something else, a singleton throughsuper().__new__(cls)/object.__new__(cls)), andcls.Xread or assigned on a class held as a value. <binary> migrate: the project's alembic migrations applied by the binary, rendered at translation time by alembic's offline mode (docs/advanced/migrations.md); revisions that read the database are refused with file:line. New error codeP2A0510(an alembic option or layoutmigratecannot reproduce); the binary's subcommands (migrate [upgrade [head|<revision>]],migrate current,migrate --sql) join the frozen public contract.str.isprintable().
Changed¶
unicodedata.normalize/combiningandstr.isalpha()... follow the Unicode version of the project's Python (15.0 to 17.0), even when the translating Python is newer.re.erroris namedPatternErrorfrom Python 3.13 (type(e).__name__, tracebacks);re.PatternErroris refused for a 3.12 project.socket.create_connection(timeout=)reads its timeout like CPython'ssettimeout:Decimal/Fractionfrom 3.15, each version's messages (down to the patch release for an out-of-range delay, probed like the other backported fixes, so a distribution's Python is matched),ValueError/OverflowErrorfor NaN and huge values (they made the request panic).- A synchronous generator consumed synchronously (
list(),for,next(), a comprehension) is refused at translation (P2A0118); it answered 500.StreamingResponse(gen())is unchanged.
Deprecated¶
--backendnow prints a deprecation warning (it has no effect since 0.4); it is removed in 1.0, with the keybackendof the JSON ofcheck.--report: an internal coverage report, outside the stable interface; usepy2axum check --format jsonor--format markdown. It prints a deprecation warning.
Fixed¶
check --helplistsmountamong the values of--python-side(it was accepted, not shown).check: the first reason of a route refused for several reasons, the order of its blockers and of the whole-application errors no longer change from run to run (hash order of the call graph): closest to the route first, then source order.StreamingResponse(content)started iterating its content as soon as the response object was built: the generator could read state before the endpoint finished or before aDepends(scope="function")dependency ran its exit code (seen as an intermittent conformance difference). It now starts when the body is sent, as Starlette does.asyncio.sleep(delay, result)returnsresult;asyncio.sleep/wait_forread their delay like asyncio (TypeErrorfor astr, or aDecimaloutside uvloop; a timeout <= 0 raisesTimeoutErrorwithout running the awaitable, which used to run once).- SQLAlchemy: objects INSERTed then rolled back are transient again, with their attributes and loaded relationships; pending objects a failed flush did not reach are transient too.
email.utils.formataddrraisesUnicodeEncodeErrorfor a non-ASCII address, as CPython.- Memory: a finished task stored in the request's state no longer keeps the request alive; anonymous subqueries
are numbered per statement (
anon_1...), so a query is the same SQL at every request. repr()of a string escapes non-printable characters as CPython does ('\xa0','\u200b','\U000e0001'); only ASCII control characters were escaped.str()of a Pydantic model is its fields separated by spaces (BaseModel.__str__), not its repr.exc.__cause__/exc.__context__of an exception without a chain isNone(was anAttributeError).- A dict keeps the first object of a key set again under an equal key (
{1: "a", True: "b"}is{1: "b"}). int(b"42").repr(int)/str(int)of a builtin type is<class 'int'>;type(zoneinfo.ZoneInfo(...)).__name__isZoneInfo.
Security¶
rustls0.23.46 in the shipped lock file (was 0.23.45): RUSTSEC-2026-0346 to RUSTSEC-2026-0349.- Second review of the runtime, see Security:
str.zfill/ljust/rjust/center, format specs and%-formatting with a width or precision from the request raiseMemoryError/ValueErrorlike CPython (a negative width panicked, a huge one aborted);range()near the 64-bit edge no longer loops for ever, and a range too large to hold isMemoryError;Fraction(text)appliesint()'s 4300-digit limit; a JSON integer past 4300 digits is a 400.- Raw ASGI apps and middlewares:
sendwaits for a client that does not read (it buffered the whole response); a stream the application leaves unfinished closes the connection instead of holding it. WebSocketsendwaits likewise (the outgoing queue was unbounded). - A raw ASGI middleware next to WebSocket routes is refused at translation unless it hands non-HTTP scopes straight on (the binary does not run raw middlewares for WebSocket connections: an auth or rate-limit check written for websockets would have been skipped).
- uvicorn's proxy headers: the last
X-Forwarded-Protois used,*trusts everyone only alone, networks with host bits set are literals (as uvicorn);regexp_match(flags=)binds its flags.
[0.7.1] — 2026-10-14¶
Security release. Upgrading is strongly recommended.
Security¶
- Denial of service fixed (all earlier versions): a request reaching a
Decimalfield with constraints, orDecimalarithmetic in the application, could make a generated binary spend minutes of CPU and then exhaust its memory until the process was killed, without authentication.Decimalnow follows CPython's default context and its limits. Upgrading is strongly recommended. - MCP (
mcpSDK, stateless server): aGETevent stream now ends when the client leaves. Before, each disconnect kept a pooled database connection open in a transaction until the pool was exhausted (all earlier versions serving MCP natively).
[0.7.0] — 2026-10-14¶
Pydantic documentation corpus at 90.8 % and SQLAlchemy ORM documentation corpus at 93.8 % (both past the 1.0 threshold, none differing), logging identical to Python's, Python 3.15, and memory leaks found by a long soak.
Added¶
- Pydantic:
validation_alias(AliasPath,AliasChoices),serialization_alias,alias_generator(evaluated at translation),validate_by_alias/validate_by_name/serialize_by_alias;Field(exclude=, exclude_if=, frozen=, multiple_of=, union_mode=, strict=, discriminator=); strict mode (config and field); discriminated unions (by aLiteralfield or byDiscriminator(fn)withTag);AfterValidator/BeforeValidator/PlainValidator/WrapValidator,@field_validator(mode="plain"|"wrap"),@field_serializer,@model_serializer,PlainSerializer/WrapSerializer; specialised generic models,RootModel,SecretStr,UUID1..UUID8,Fraction,complex,deque,Counter,OrderedDict,Sequence, fixed tuples,default_factorytaking the validated data,PydanticCustomError. Pydantic documentation corpus 52.1 → 90.8 % (216/238); the messages of pydantic 2.12 and 2.13 are reproduced by the locked version. - SQLAlchemy ORM inheritance: single table (
polymorphic_on/polymorphic_identity), joined table (one table per class, flushed table by table),of_type(),with_polymorphic(),selectin_polymorphic(),polymorphic_load="selectin"|"inline". - SQLAlchemy ORM: deferred columns (
load_only,defer,undefer,undefer_group,defaultload,deferred(group=), raise-loading),composite(),@hybrid_property/@hybrid_method(with.expressionand.setter), write-only collections (WriteOnlyMapped),eager_defaults=True,Session(engine)/AsyncSession(engine)in an endpoint,session.expire(obj[, names]),__init__on a mapped class,filter_by()on hybrids and composites,and_()/with_parent()/add_columns()/aliased(name=), and CoreTable()objects used as values (t.c,alias(),bindparam(), executemany,insert().values([...]), FULL OUTER JOIN).dataclasses.astuple()/asdict(),typing.cast(). - Logging identical to Python's: the
logginghierarchy (levels, propagation, handlers,Formatterwith%,{and$styles, filters,LoggerAdapter,basicConfig,dictConfig, python-json-logger 4.0), uvicorn's startup, shutdown and access lines and its command-line options, and tracebacks with the project's frames, source lines and carets (raise ... from,__context__). The mcp SDK's own log lines are reproduced. Module and factory statements that configure logging are translated. See Logging. - SQLAlchemy ORM:
relationship(secondary=<Table>)(many-to-many: joins, lazy andselectinloading,any(), association rows written at flush and deleted with their owner;back_populates/backref, cascades andorder_by=on it are refused),session.expunge()/expunge_all()(DetachedInstanceError),expire_all(),obj in session, relationship criteria (Child.parent == obj,Parent.children.contains(obj),join(Target, Model.rel), aliases),execution_options(populate_existing=, autoflush=, yield_per=); bulkexecute(insert(Model), [dicts])(and withreturning(Model)), bulkupdate(Model)by primary key,insert().values([dicts])as SQLAlchemy builds it; results are exhausted and closed like SQLAlchemy's (ResourceClosedError).Model.__mapper__and Core use ofModel.__table__are refused at translation. - SQLAlchemy documentation corpus: the doctests of the 2.1.4 documentation replayed as routes against the binary; ORM scope 93.8 % identical (243/276, the 1.0 threshold is 90 %), Core 88.7 %, none differing (coverage).
- Python 3.15 is supported (3.12 to 3.15; Python versions
reviews every change of 3.14 and 3.15). The binary follows the project's Python:
--python X.Y, else its.python-version, else the Python running py2axum whenrequires-pythonallows it (it used to take the lowest Pythonrequires-pythonallowed).sys.version_infois folded against it at translation, and a branch it rules out is never translated (version-gated imports work). - Python 3.14 and 3.15 constructs: comprehension unpacking (
[*x for x in xs],{**m for m in ms}),lazy importof libraries,case +1:,with var.set(x):,Path.copy()/move(),uuid.uuid7(),re.prefixmatch(),\z,Counter ^ Counter,bytes.replace(count=),format()separators in the fractional part, json's exception notes,add_note()/__notes__; and the messages that changed between 3.12 and 3.15 (ZeroDivisionError, unpacking,dict(seq), context managers,strptime('%d'), base32, unpaddedurlsafe_b64decode,fromtimestamp,os.urandom). Template strings and lazy imports of project modules are refused.
Security¶
nh3.clean()runs onammonia4.2.3 (was 4.2.1): RUSTSEC-2021-0157 (url()escaping in CSS style attributes) and RUSTSEC-2021-0158 (SVG animation tags), both XSS in the sanitizer.
Fixed¶
- Memory: a nested function that calls itself no longer keeps its closure alive (113 KiB per request with 100 KB
captured); ORM objects left by a failed flush, a rollback or a delete are released with their session; a
streamed response with a
yielddependency cut by the client released its connection only at shutdown (each cut kept a connection idle in transaction: 200 cuts blocked every route using the database); an abandoned raw ASGI app is completed. - Sentry: an exception already captured for a request is not sent a second time by the
loggingintegration (uvicorn logs it after the response), and a record'sextraleaves out sentry-sdk's common record attributes. session.close()did nothing: objects are now detached and the transaction rolled back, like SQLAlchemy; a session dropped with an open transaction rolls it back at once. Reserved table and column names ("user","order") are quoted.base64.b64decode(and python-jose's padding) follows the padding rules CPython rewrote in its 3.13.13 and 3.14.4 security releases (data after the padding is decoded, excess=skipped), by the project's patch release. Tracebacks in the logs print the exception's notes, and theValueErroran enum's_missing_chains as__context__('x' is not a valid E, "During handling of the above exception...").socket.getaddrinfo,socket.create_connectionandasyncio.open_connectioncheck the host like CPython'sidnacodec before any lookup (a label of 64 characters or an empty one:UnicodeEncodeError,UnicodeErroron 3.12); the binary passed it to the C library.UnicodeErrorexists as the base of the encode/decode errors.- Behaviours that changed inside a Python minor follow the project's patch release:
strptime('%e')is a bad directive before 3.13.6. The patch is the one--python X.Y.Zor.python-versionnames, else the Python running py2axum when it runs the project's minor (PY2AXUM_PYTHON_VERSIONoverrides it at start). - Differences with Python on every version:
"a".count()or[1].count()without an argument aborted the request,str.replace(count=)was ignored,bytes.replacewas missing,base64.b32decode(map01=)was ignored and the base64 functions dropped unknown keyword arguments,f"{n:_}"grouped with commas, the builtinformat()was not translated,FileResponseguessed the media type from a table of 20 extensions (now CPython's table of the project's Python and the host'smime.types, asmimetypesreads them), and the types named by operator and context-manager errors (Counter,_thread.lock). The text of a type expression (repr(int | str)) is refused instead of<GenericAlias>. - Async sessions: reading an attribute that needs IO (expired or deferred column, unloaded relationship) raises
what the locked SQLAlchemy raises:
MissingGreenletup to 2.0, aStatementErrorwrapping it since 2.1 (except MissingGreenletis now translated, and does not catch it).e.origis readable on SQLAlchemy errors (the psycopg exception of a database error, the cause of a missing bind parameter or an unknown enum value). The primary key of an object expired as a whole (commit,expire_all()) was read from memory; it now needs IO like the other columns. - The declarative base's
type_annotation_mapwas ignored:Mapped[datetime]became aDateTimewithout time zone where the map said otherwise. It is applied, andMapped[Decimal]/Mapped[time]map toNumeric/Time.
[0.6.0] — 2026-10-09¶
FastAPI documentation corpus at 90.6 %, raw ASGI middlewares three times cheaper, error codes and py2axum
watch, a builder Docker image, and the constructs the remaining routes of real applications needed.
Performance¶
- Raw ASGI middlewares: the cost per layer drops from ~2.7 µs to ~0.85 µs. The binary advances the middleware's
future itself instead of spawning a task per layer (code left after the response, or a client gone, still
finishes in its own task, never aborted), the ASGI channels are a queue plus a waker, and a known-length body is
forwarded without a oneshot. On the reference app with 11 layers,
POST /describegoes from ~24k to ~40k req/s.
Added¶
- Error codes: every refusal has a stable code (
P2A0201: library call not supported, ...) and the command line prints it with thefile:line, why the construct is refused, what to do and a link to its entry in the new error code reference.py2axum check --explain CODEprints the same in a terminal. py2axum check: a suggestion per refused route (the alternative py2axum knows, the--python-sideflag that leaves it to Python), a summary of what would make the most routes native,--format text|json|markdown(--jsonstays a synonym).py2axum watch: regenerate, rebuild (debug profile, only the generated crate) and restart the binary on each change of the project, with debounce; a failed cycle keeps the previous binary running.-
Guide: Migrating an existing application, from
checkto a reversible switch in production. -
Coverage of the FastAPI documentation corpus: 79.6 % → 90.6 % of the exercised examples identical, none differing (coverage). Newly native:
yielddependencies withtry/exceptaround theyield(the request's exception is raised there, as FastAPI does; one swallowed isFastAPIError),Depends(scope="function"), an instance with__call__as a dependency,app.dependency_overrides[f] = gat module level, generator endpoints (JSON Lines,EventSourceResponsewithServerSentEvent,StreamingResponse),response_model_include=/_exclude=/_exclude_unset=/_exclude_none=, aResponseclass as the return annotation,FastAPI(default_response_class=),FastAPI(root_path=), unannotated parameters (Any),fastapi.exception_handlersdefaults called from an application's handler,TrustedHostMiddleware,HTTPSRedirectMiddleware,model_configval_json_bytes/ser_json_bytes, pwdlib's Argon2PasswordHash.recommended(),anyio.sleep. -
SQLAlchemy's JSON index and its typed accessors, on
JSONandJSONBcolumns:col["k"]/col[0]withas_string(),as_integer(),as_float(),as_boolean(),as_numeric(precision, scale),as_json()(CAST(col ->> 'k' AS VARCHAR), as SQLAlchemy's PostgreSQL compiler renders it);sqlalchemy.true()andfalse(). A JSON path index,col[("a", "b")], is refused at translation. -
Constructs of real applications: Pydantic
serialization_alias=/validation_alias=(distinct input and output names;AliasChoices/AliasPathrefused), closures with cells as CPython builds them (late binding, comprehensions included) andnonlocal,TypedDictcalled as adict(refused as aresponse_model),Model.__table__(columns and their real SQLAlchemy types, computed at translation),StaleDataErrorwhen a flushedUPDATEmatches no row,html.unescapewith CPython's HTML5 tables, icalendar 7.0 (Calendar/Event/Alarm,add,add_component,to_ical, byte-identical output),os.remove/os.unlink; the runtime'sOSErrors carryerrno,strerror,filenameand the subclass of their errno. - SQLAlchemy:
with engine.connect()/engine.begin()on a synchronouscreate_engine,executemanythroughexecute(text(...), [dicts]),||for a string+on SQL expressions;execute/scalars/scalar(stmt, params)outsidetext(), which failed at run time, is refused at translation withfile:line. - asyncpg 0.32 in the supported range.
- Docker:
ghcr.io/larrymotalavigne/py2axum, a builder image (Python 3.14, py2axum, a pinned Rust toolchain and the runtime's crates precompiled with the release profile), multi-arch, with SBOM and provenance; a multi-stage example whose final image holds the binary alone (Docker image). - SQLAlchemy documentation corpus: the doctests of the 2.1.4 documentation replayed as routes against the binary (480 examples, none differing; the starting point of the 0.7 work).
Fixed¶
- A value stored in a
JSONcolumn (notJSONB, which PostgreSQL normalizes) was written as compact JSON,{"a":1}, where SQLAlchemy writesjson.dumps' text,{"a": 1};->>on an object or a list returned the other text. - A request-scoped
yielddependency of a streamed response closed before the stream instead of after it (without a session dependency). - An
HTTPExceptionwith a no-body status (204, 304) lost itsheaders=. - Generator endpoints under FastAPI < 0.141 follow that version: JSON Lines and Server-Sent Events responses
ignore
status_code=(200), and the items of a route declared on anAPIRouterare neither validated nor filtered by theirAsyncIterable[T]type (include_routerdrops it), as FastAPI does. x in yon a value that is no container raises Python 3.14's message ("is not a container or iterable") when the project runs on 3.14.
[0.5.1] — 2026-10-09¶
Fixed¶
- itsdangerous
loads(..., return_timestamp=True)answered 500. The keyword was accepted at transpile time and refused only at run time, so magic-link and 2FA logins built on it failed in production.URLSafeTimedSerializer.loadsnow takess, max_age, return_timestamp, saltpositionally or by keyword and returns(payload, datetime)with an aware UTC datetime, like itsdangerous 2.2;BadSignature.payload,BadTimeSignature.date_signedandSignatureExpired.date_signedare set as the library sets them. Any other argument is refused at transpile time withfile:line. isinstance(x, int | float)(andX | None,Optional[X],Union[X, Y]) raised "cannot be a parameterized generic" in the binary: a 2FA login of a production app answered 500. A union is now tested member by member, as CPython 3.10+ does.- Arguments the runtime dropped or ignored are now implemented or refused at transpile time (an audit of the library map after the bug above):
str.encode(encoding, errors)always produced UTF-8; it now implements utf-8, utf-8-sig, latin-1 and ascii witherrors=strict, ignore or replace (UnicodeEncodeErroras CPython).str(b, encoding)decodes likebytes.decodeinstead of lossy UTF-8.str.find/rfind/index/rindex/count/startswith/endswith(sub, start, end)andlist/tuple.index(x, start, stop)ignored their bounds;set.update(*others)read only the first;Match.groups/groupdict(default=)ignored the keyword.- Starlette responses given positional arguments read
FileResponse'sfilenameandcontent_disposition_typeat wrong indexes and dropped a positionalbackground;background=,stat_result=andmethod=are refused. MIMEApplication(data, Name=...),MIMEMultipart(..., **params)dropped their Content-Type parameters;policy=,boundary=,_subparts=,_encoder=and arguments ofas_string()/as_bytes()are refused.Path.read_text/write_text(encoding=, errors=, newline=)were ignored (andread_textdecoded lossily).- csv:
DictReader(restval=, restkey=)were ignored; a positional dialect is refused. - redis:
scan_iter("pattern:*")ignored a positional pattern and scanned every key;_type=andset(px=timedelta)were dropped. model_validate_json(strict=...)ignored its keywords; class methods such asModel.model_validate(...)now go through the transpile-time keyword check.- HTTP client responses (
resp.text(encoding=),resp.json(loads=)...), SQLcol.like(pattern, escape)given positionally, a second positional ofdequemethods andPattern.search(s, pos)raise instead of ignoring the argument.
[0.5.0] — 2026-10-09¶
Security¶
- Denial of service fixed (all earlier versions): a small request carrying a deeply nested JSON body could
overflow the stack of a generated binary and abort the process, without authentication. The decoder is now
iterative (400 past 10 000 levels, as CPython), the runtime threads get a larger stack (
PY2AXUM_STACK_SIZE), and recursive walks raiseRecursionErrorinstead of overflowing, so the worst outcome is a 500, never an abort. Upgrading is strongly recommended. - Security review of the runtime before 1.0: threat model, guarantees and differences with uvicorn/Starlette in
the new docs/security.md. Hardening of SQL identifiers given as strings, request input
handling (nesting, sizes, multipart limits, cookies),
Path.resolve(), response headers, bcrypt off the event loop, the--python-siderelay and the multiprocess Prometheus files. Upgrading is recommended. - New settings:
PY2AXUM_MAX_BODY(optional 413 on large bodies, off by default) andPY2AXUM_STACK_SIZE. - CI audits the runtime's
Cargo.lockwithcargo audit(tools/cargo_audit.sh).
Added¶
- Documentation site (MkDocs Material, https://larrymotalavigne.github.io/py2axum/), organised like FastAPI's:
getting started, tutorial, advanced, reference, release notes. Its examples (
docs_src/) are tested against the binary in CI. - pydantic 2.14 / pydantic-core 2.50 supported (range
pydantic>=2.12.0,<2.15,pydantic-core>=2.41.1,<2.51). The binary reproduces the minor the project locks: error URLs…/2.14/v/…; UUID messages of the uuid crate 1.23.4 (0-based positions,invalid length: found N, the requested form);EmailStrrefusing CR/LF;Decimalmax_digits/decimal_placescounted withoutDecimal.normalize()'s 28-digit rounding; an Enum_missing_that raises something other than aValueErrorpropagates. Projects on 2.12/2.13 keep their messages. See docs/supported.md, "Pydantic behaviours that follow the project's minor version". - The project's library version is also read from an
==pin inrequirements*.txt/pyproject.toml(onlyuv.lockwas read), or chosen inside the project's specifier when the installed one is outside it. - CI: the
versionsmatrix runs pydantic 2.12 (min), 2.13 (python -m py2axum.versions pydantic2.13) and 2.14 (max).
Fixed¶
x is Enum.MEMBERbetween Enum members was alwaysFalse, and a header parameterx: list[str] = Header()answered 422 instead of collecting every occurrence: two silent wrong answers found by the documentation's examples.model_config'sstr_strip_whitespace/str_to_lower/str_to_upperwere ignored onEmailStrfields.- An Enum
_missing_raising aValueErrorgave avalue_errorinstead of pydantic'senumerror; returning a value that is neitherNonenor a member gave theenumerror instead of Enum'sTypeError. Decimaldigit bounds compared only the normalized value: a value whose written form fits passes, as in pydantic.- Refused instead of mistranslated: a
default_factorytaking the validated data (lambda data: ..., called without arguments before), length constraints onIterable[T].
[0.4.0] — 2026-10-08¶
Breaking¶
- The typed backend is removed (
--backend typed,codegen.py,body.py,runtime/rt.rs). It emitted statically-typed Rust for simple CRUD handlers only and covered none of the real applications measured; every application already went through the general backend.--backend typednow exits with an error ("removed in 0.4: use the default backend");--backend autoand--backend dynare accepted until 1.0 and change nothing.py2axum checkand--reportno longer try it first;check --jsonkeeps"backend": "dyn".
Added¶
- Large list responses streamed at constant memory (what only the typed backend did): an endpoint with
response_model=list[Schema]returning(await session.execute(stmt)).scalars().all()(orsession.scalars, or through a local) reads the rows with a cursor and sends the JSON array in 64 KiB blocks — 57 MB served with 13–16 MiB of RSS instead of 1.6 GiB, first byte after 16 ms instead of 2.9 s, identical bytes. Only when nothing observable changes (the session wrote nothing, one mapped class without loader options, a schema of plain columns...);PY2AXUM_STREAM_CHUNK,PY2AXUM_STREAM_MIN_ROWSand--no-streamkeep their meaning. See docs/supported.md, "Large list responses". app.state(set in the lifespan, read throughrequest.app.state).- Raw ASGI middleware: a project class with
__init__(self, app, ...)andasync def __call__(self, scope, receive, send), registered withapp.add_middleware(...)orFastAPI(middleware=[Middleware(...)]), runs natively in Starlette's stack around the router (shared scope, uvicorn'sreceive,sendchunked without acontent-length, rewritten scope as a new request, wrappedreceive/send, short-circuit answers, exceptions raised through the stack).starlette_context'sRawContextMiddlewarewithRequestIdPluginandCorrelationIdPlugin,FastAPI(strict_content_type=)andtraceback.format_exception(...)/format_exception_only(exc)are translated too. An application without raw middleware gets no extra layer; each one costs about 2.5 µs per request. See docs/supported.md. create_engine(connect_args=...)/create_async_engine(connect_args=...)applied to every pooled connection: libpqoptions(-c name=value,-cname=value,--name=value, split like libpq,\escapes) and asyncpg'sserver_settings. ATimeZonesetting overrides the time zone discovered from the server, so timestamps decode in the session's zone as psycopg does (they kept the server's zone before). Any other literal libpq option is refused at transpile time.- PyJWT 2.15 (
import jwt) translated natively, like python-jose:jwt.encode(algorithm=,headers=,sort_headers=;exp/iat/nbfdatetimes encoded from a copy),jwt.decode/decode_complete(everyoptions=key,audience=,issuer=,subject=,leeway=as a number or a timedelta),get_unverified_header, with HS256/HS384/HS512 andnone: identical tokens, the same checks in the same order, thejwt.exceptionshierarchy and messages. An asymmetric algorithm written as a literal,json_encoder=,detached_payload=,verify=andPyJWK/PyJWKClientare refused at transpile time.
Changed¶
- Assigning another module's attribute (
config.LIMIT = 2) is refused at transpile time withfile:line; the binary used to fail at startup. json.loads(bytes)with invalid UTF-8 raises CPython's exactUnicodeDecodeErrormessage.JSONBcolumns:contains(@>),contained_by(<@),has_key(?),has_any(?|) andhas_all(?&) are compiled to PostgreSQL's operators, their argument typed as SQLAlchemy types it. They raised aTypeErrorat run time (a 500 where Python answered).- A path left to Python (
--python-side) answers FastAPI's 404 whenPY2AXUM_PYTHON_URLis unset, as documented; it used to fall through to a translated route whose pattern also matched (/books/export.zipreached/books/{book_id}and answered 422). - An exact pin equal to the lowest version a feature needs is accepted:
starlette==1.7.0was refused for WebSocket routes ("need starlette>=1.7.0"). tests/conformance.py --scenario path/to/scenario.py(andtests/difftest.py) load a scenario file from anywhere, so an application can keep its scenario in its own repository.- New example,
examples/bookshelf: users, JWT Bearer authentication (PyJWT), CRUD, relationships, 422s, a WebSocket and one route left to Python; its conformance scenario (75 steps) andcompare.shrun in CI.examples/docker: a reference multi-stage Dockerfile, the Python sidecar and a Compose file for the hybrid mode.bench/bench.py --target bookshelfmeasures it against FastAPI. - Documentation: a getting-started guide (
docs/getting-started.md), the conformance guide rewritten for users, the README,docs/supported.mdanddocs/how-it-works.mdreviewed for first-time readers. - Translated natively:
validate_assignment=Truewith field and model validators (before, type, after withinfo.data, modelafter, as pydantic-core; refused with a modelbeforevalidator),Field(min_items=, max_items=),File(default=[]), a SQL column name other than the attribute (Column("metadata", JSON)), theundefer()loader option (top level,session.get(options=),selectinload(...).options(undefer(...))),exists().where(...)with SQLAlchemy's auto-correlation,regexp_match,delete().returning(columns),...as a sentinel value,collections.Counter,asyncio.open_connection(asyncio's or uvloop's messages, after the project's lock),socket.create_connection,cryptographyRSA key generation and serialization (DKIM), andzipfile.ZipFile(io.BytesIO(), "w")with CPython's bytes. - A pydantic
ValidationErrorraised by an assignment carries the model'stitle(andstr(e)names it). - A crate generated from an application with
GZipMiddlewarefailedcargo build --locked: the shippedCargo.lockdid not listtower-httpamong the root crate's dependencies. It is now always declared. - Fixed: a list of
UploadFileholding an empty string was treated as absent; FastAPI reports it (422).str.splitlines()split on\nand\r\nonly (CPython's line boundaries now:\r,\v,\f,\x1c-\x1e,\x85, U+2028/2029); iterating anio.BytesIO(aStreamingResponseover one) raised.
[0.3.1] — 2026-10-08¶
- An Enum member given to a scalar field is validated as pydantic-core does: an ORM enum column read into
status: stranswered 500 (string_type) where Python returned the member's value (found in production). Astr/intsubclass member is its value forstr,int,float,boolandLiteral(anintone isstr(value)in astr); a plain member isstr(value)in astr, its value unchecked in an unconstrainedint. - Graceful shutdown in every generated binary (it only existed with a lifespan or
sentry_sdk; otherwise SIGTERM killed in-flight requests): as uvicorn 0.54, new connections refused, idle keep-alive connections closed, in-flight requests finished withconnection: close, WebSocket sessions closed with 1012 on both sides, a second signal forces the exit, and the process ends by the signal it received (status 143, uvicorn re-raises it; it was 0). The pool is closed before the exit. - Memory leaked at every call (dyn backend), found by the endurance test: an MCP
tools/call(its arguments' validator),column.op("...")(value)(the operator) andjson.dumps(separators=...)(the separators). Each is now built once per distinct value; a test forbidsBox::leakoutside those caches. bench/bench.py --target dynapp --compare: a performance guard comparing a generated binary with a reference.- Differential testing (
tests/difftest.py, extradifftest):replayreplays traffic recorded on the Python app (py2axum.record, an optional ASGI recorder writing anonymised JSONL) against both servers from the same database snapshot, with ddmin minimisation;gengenerates valid and invalid requests from the OpenAPI schema (schemathesis 4 + hypothesis, fixed seed) plus a corpus of edge cases per operation. - asyncpg (0.31) as the database driver, read from
DATABASE_URL;on_conflict_do_nothing/update(constraint=). BaseHTTPMiddlewarewithout its own__init__;deferred()columns; Jinja2env.filters[name] = f;p: Model = Depends()(one query parameter per field);text(...).bindparams();super()in a model's classmethod;aiosmtplib.send(sender=, recipients=);desc("label")and labels in GROUP BY / ORDER BY;update(...).returning(Model)refreshes the session's objects;session.refresh()keeps loaded relationships;StreamingResponseover a synchronous iterable.
Fixed¶
- A route reading a module global filled by a function that does not translate (a registry filled in place by
module-level statements: a loop,
REG[k] = lambda: f()) was reported native and the error lost: it is now blocked (--python-side automoves it). Module-level item and attribute assignments run at startup; an assignment to an unmapped library's attribute (stripe.api_key = ...) stays on the Python side. - Request bodies decoded as CPython's
json.loadsdoes (BOM, UTF-16/32, NaN, exact positions and messages, too deep nesting); anullbody is absent; FastAPI'sstrict_content_type; Starlette's form limits and multipart error message follow the locked Starlette version (1.4, 1.7); Starlette's redirect slashes. - Pydantic: bool from float/Decimal/bytes, int from str,
int_parsing_sizeandbool_typebeyond 64 bits, timestamps parsed as speedate does, empty URL;exclude_noneon extras;response_modelserialised throughdump_json(NaN and infinities becomenull). - Dates: years 1–9999 (
OverflowError),timedelta.days,date()/datetime()checks and messages of CPython 3.12/3.14;format()of-0.0,nan,inf; Python whitespace U+001C–U+001F;str.is*()from the translating Python's Unicode data; paths containing NUL. - SQL: an integer out of the column's range raises
DataErroras psycopg does, the exact psycopg class per SQLSTATE,tuple_(...).in_(...)without a cast; JSON columns keep float round-trips. request.url.pathwithout tabs and newlines; AMQP names validated as pamqp does (no panic); a status code outside 100–599 drops the connection as uvicorn does.
[0.3.0] — 2026-10-08¶
py2axum check <package>: every route marked native, python-side or refused with the reason atfile:line, the blockers ranked by routes touched, without generating a crate;--json, and an exit status for CI (1 when generation would fail,--fail-under PCTon the share of native routes).-
Supported version ranges (FastAPI 0.137–0.142, Starlette 1.0–1.7 (1.7 for WebSocket routes), Pydantic 2.12–2.13, pydantic-settings 2.11–2.15, SQLAlchemy 2.0.44–2.1, psycopg 3.2.12–3.3, httpx 0.28, aiohttp 3.13–3.14, mcp 2.2, Python 3.12–3.14), tested at both ends in CI. A project locking or pinning a version outside them (
uv.lock,requirements*.txt,pyproject.toml) is refused withfile:line;--allow-untested-versionsoverrides. -
await conn.run_sync(Base.metadata.create_all)(dyn backend), e.g. in the lifespan: the DDL is compiled at translation time by SQLAlchemy from the mapped classes rebuilt statically (no project code runs), then replayed with SQLAlchemy's checkfirst (enum types, tables, indexes, comments, foreign keys of cycles).async with engine.begin() as conncommits on exit.--python-side lifespanis no longer needed for it. - WebSocket routes (dyn backend):
@app.websocket/@router.websocketwith dependencies and path/query/header parameters, Starlette'sWebSocket(accept, receive/send in every form, close,iter_*, denial responses, states), uvicorn's handshake outcomes (403, 500, 1006), exception handlers called with the WebSocket;async forover async iterators. The typed backend refuses@router.websocket(it was skipped silently). -
x: Annotated[T, Query()/Header()] = defaultis optional (it was required);request.url.pathis percent-decoded, as Starlette builds it fromscope["path"]. -
sentry_sdkreports to Sentry (it was a no-op): a native client on the Rust SDK sends the same events as the Python SDK (scopes per request, FastAPI/Starlette and logging integrations, transactions, scrubbing,before_send), each taggedpy2axum.sourcewith the route'sfile.py:line. Options the binary cannot reproduce (transport=,before_breadcrumb=, profiling...) are refused. An app factory'sinit_sentry()runs at startup.tests/sentry_check.pycompares what a fake Sentry server receives. -
dateutil.relativedelta(relative fields),xmltodict.parse(default options, namespaces) withExpatError, Pydantic private attributes (PrivateAttr,_name),session.connection()and itsclose()(readiness probes),__getattr__/__setattr__on plain classes (object.__setattr__), enum members with list/tuple values (strmixin:("A",)is"A"), a module-level endpoint shadowed by a later function of the same name. -
Applications served next to Starlette:
response_class=wraps the returned value (HTML, plain text, redirect, file);uuid.UUIDvalidated as pydantic-core does andUuidcolumns read and written asuuid.UUID;HTTPBasic;Jinja2Templates(directory=)andTemplateResponse;importlib.metadata.version("literal")resolved at compile time frompyproject.tomlanduv.lock. An app wrapped in a project ASGI class (app = Middleware(api)) is refused (it was served without the wrapper). app.mount(...)registered last can stay on the Python side (--python-side mount, orauto).- Synchronous SQLAlchemy (already in 0.2.0, not listed there):
sessionmaker, a synchronous generator dependency, real lazy loads (also while aresponse_modelreads the object), the legacysession.queryAPI. Now also: self-referential relationships (remote_side=), bound parameters shared by an expression reused inGROUP BY, ORM@propertys read by a response model,awaiton a synchronousSession(CPython'sTypeError). model_json_schema()computed at translation time;sqlalchemy.inspect(x, raiseerr=False);unicodedata.normalize/combining;json.dumps(sort_keys=, indent=);bytes.decodeand bytes methods;BaseModel.dict();request.base_url;join(subquery, on);zip(strict=);date/datetime.replaceand their methods read as values; f-string format specs through__format__; class attributes read on a plain or Pydantic class;Annotated[T, Header()] = default; python-side routes under a prefix read from the settings.collections.dequeanddefaultdict(deque); single inheritance of plain classes,abc.ABCand@abstractmethod;nh3(clean,clean_text,is_html) on theammoniacrate;socket.getaddrinfo,ipaddress.ip_address/ip_network;email.mime.base.MIMEBaseandemail.encoders.encode_base64;Fernet.generate_key();string.Template(substitute,safe_substitute).break/continueleaving atry/finallyor awith: thefinally(or__exit__) runs first, as in CPython.
Fixed¶
- Length constraints of
list/set/tuple/dictfields and keyword arguments of builtins were ignored silently: applied as pydantic-core does, refused otherwise. A validator's error carries the raw input. email.encoders.encode_base64()of a message without payload raises CPython'sTypeError(it encoded nothing).- An app factory's
init_sentry()is refused only for the functions it reaches (functions queued by other code were blamed on it).
Changed¶
sentry_sdkis no longer a no-op (see above): a project whoseinit_sentry()passestransport=(a Python transport class) is refused at translation time; it used to be skipped silently.
[0.2.0] — 2026-10-07¶
FastAPI(lifespan=...)is translated: the code beforeyieldruns before the server listens, the rest after a graceful shutdown on SIGTERM/SIGINT (PY2AXUM_SHUTDOWN_TIMEOUT). Async generators run in lockstep with their consumer (anext,asend,athrow,aclose),@asynccontextmanager,contextlib.suppress,contextvars.ContextVar,Task.cancel().- Raw ASGI routes:
app.add_route(path, obj)with an object whose class definesasync __call__(scope, receive, send);Request(scope, receive), response objects called as ASGI apps. - MCP servers (
mcp2.2):MCPServer,@server.tool(async, structureddict[str, Any]output),ToolError, streamable HTTP without state and with JSON responses, the JSON-RPC envelope validated like the SDK. Tool argument schemas are computed at compile time (pydantic 2.13 JSON schema,py2axum/jsonschema.py). -
str(ValidationError)in pydantic-core's format where the model is known. -
Replacing
aiohttp.ClientSession._request/httpx.AsyncClient.requestwith a wrapper (timing outgoing calls): the clients call it; other assignments to library attributes are refused. -
A project function given the app in the factory (
configure(app)) runs while the middleware stack is built:app.add_middlewareof projectBaseHTTPMiddlewaresubclasses,app.add_route(it was skipped). Routing objects as values:request.app,app.router.routes,route.matches(scope),Match,request.scope.timeit.default_timer. -
--python-side auto: every route that does not translate (and rawadd_routeroutes with a literal path) is left to the Python application, each printed with the error that blocked it. -
Module-level
try/if/for/while/withstatements run at startup (they were skipped), their bindings becoming module variables; import fallbacks (try: import x except ImportError: ...). -
sys.settrace/threading.settrace_all_threads: the project's functions report call/return/exception events to the trace function (function call metrics);traceback.extract_tb. Module-level functions are single objects; nested functions may name themselves. - prometheus_client:
start_http_server, OpenMetrics output, exemplars, name escapings, restricted registries. - httpx / aiohttp responses keep their
Content-Encodingheader (the body is decoded by the runtime, not reqwest). - prometheus_client multiprocess mode: the per-process files (shared with Python workers) and
MultiProcessCollector,mark_process_dead. -
prometheus_client 0.26:
Counter,Gauge,Summary,Histogram,Info,Enum, labels,time(),count_exceptions(),track_inprogress(),CollectorRegistry,REGISTRY,generate_latest(text format byte for byte). -
Typed backend: request bodies above 2 MB are read like Starlette does (axum answered 413).
[0.1.0] — 2026-10-07, first public release¶
- Ahead-of-time compilation of FastAPI + SQLAlchemy 2.0 (async, PostgreSQL) + Pydantic v2 applications to Rust (axum, tokio, sqlx): the dyn backend (general) and the typed backend (simple CRUD).
- Runtime reproducing CPython, Pydantic v2, SQLAlchemy and Starlette semantics, plus a closed list of standard and third-party libraries (docs/supported.md).
--report: per-route coverage report with the first blocking construct (file:line).--python-side: paths andlifespanleft to the Python application, relayed by the binary whenPY2AXUM_PYTHON_URLis set.- Differential conformance harness (
tests/conformance.py) and reference applications. pip install-able package with apy2axumcommand; example application with a multi-stage Dockerfile.- aio-pika 10: connect, channels, durable queues, publishing with confirms,
queue.get(). json.loadsaccepts bytes (UTF-8/16/32 detection, like CPython).importlib.import_moduleof a literal project module (module objects),callable().collections.defaultdict(builtin type factories),string.Formatter().vformat/format;str.formatgains!r/!sand CPython's error messages.- tenacity 9 (
@retryand its strategies).g/e/G/E/X/o/bpresentations and#informat()and%;ConnectionErrorand its subclasses;logginglevel constants andLogger.log.