Skip to content

Free-threaded CPython 3.14.7+/3.15: memo.__name__/__doc__ assignments in memoized_instancemethod stop the world, making multi-threaded statement execution far slower #13667

Closed as not planned

Description

@ashugupt

Describe the bug

On free-threaded CPython 3.14.7+ and 3.15.0, assigning __name__ or __doc__ to a function object stops the world: every running thread is paused for each assignment (python/cpython#159136, introduced by the data-race fixes python/cpython#154826 / #154851). util.langhelpers does this on a hot path. memoized_instancemethod, HasMemoized.memoized_instancemethod and MemoizedSlots.__getattr__ build a new memo closure on the first call and assign memo.__name__ / memo.__doc__ (and oneshot.__doc__ in MemoizedSlots).

MemoizedHasCacheKey._generate_cache_key is one of these memoized methods. It runs once per new statement object, from ClauseElement._compile_w_cache on every execute. As a result, executing statements from several threads is several times to tens of times slower on 3.14.7+/3.15.0t than on 3.14.6t or on GIL builds. Removing those assignments brings the timings back to 3.14.6t levels.

Optional link from https://docs.sqlalchemy.org which documents the behavior that is expected

No response

SQLAlchemy Version in Use

2.1.4 (the same assignments exist in 2.0.51 and on main)

DBAPI (i.e. the database driver)

None needed for the reproducer (originally observed with asyncpg)

Database Vendor and Major Version

None needed for the reproducer (originally observed with PostgreSQL 16)

Python Version

CPython 3.14.8 and 3.15.0 free-threaded (3.14t/3.15t); 3.14.6t is unaffected

Operating system

Linux

To Reproduce

import sys
import threading
import time

import sqlalchemy
from sqlalchemy import Column, Integer, MetaData, String, Table, bindparam, select

metadata = MetaData()
t = Table("t", metadata, Column("id", Integer, primary_key=True), Column("name", String))

ITERATIONS = 2_000  # per thread


def work():
    for _ in range(ITERATIONS):
        stmt = select(t.c.id).where(t.c.name == bindparam("name"))
        # Connection.execute() -> ClauseElement._compile_w_cache() calls this
        # once per new statement object; it is a @memoized_instancemethod.
        stmt._generate_cache_key()


def run(nthreads):
    threads = [threading.Thread(target=work) for _ in range(nthreads)]
    start = time.perf_counter()
    for th in threads:
        th.start()
    for th in threads:
        th.join()
    return time.perf_counter() - start


print(sys.version, "| SQLAlchemy", sqlalchemy.__version__)
print("GIL enabled:", getattr(sys, "_is_gil_enabled", lambda: True)())
print(" | ".join(f"{n} threads: {min(run(n) for _ in range(3)):.3f}s" for n in (1, 2, 4, 8)))

Error

No error. This is a performance regression. Wall time is best of 3, each thread does 2,000 iterations, SQLAlchemy 2.1.4:

| Python build                                   | 1 thread | 2 threads | 4 threads | 8 threads |
|------------------------------------------------|----------|-----------|-----------|-----------|
| 3.14.6 free-threaded                           | 0.062s   | 0.096s    | 0.198s    | 0.332s    |
| 3.14.8 free-threaded                           | 0.066s   | 0.383s    | 2.859s    | 9.229s    |
| 3.15.0 free-threaded                           | 0.063s   | 0.316s    | 1.802s    | 4.758s    |
| 3.14.8 (GIL)                                   | 0.048s   | 0.106s    | 0.229s    | 0.499s    |
| 3.15.0 (GIL)                                   | 0.048s   | 0.105s    | 0.253s    | 0.546s    |
| 3.14.8 free-threaded, memo setters removed (*) | 0.062s   | 0.098s    | 0.199s    | 0.322s    |
| 3.15.0 free-threaded, memo setters removed (*) | 0.067s   | 0.102s    | 0.194s    | 0.324s    |

(*) The 7 lines `memo.__name__ = ...`, `memo.__doc__ = ...` and `oneshot.__doc__ = ...` in lib/sqlalchemy/util/langhelpers.py replaced with `pass`.

sys.version strings:
3.14.6 free-threading build (main, Aug  4 2026, 18:28:08) [Clang 22.1.3 ]
3.14.8 free-threading build (main, Oct  9 2026, 15:23:34) [Clang 22.1.3 ]
3.15.0 free-threading build (main, Oct  9 2026, 15:24:59) [Clang 22.1.3 ]
3.14.8 (main, Oct  9 2026, 15:20:54) [Clang 22.1.3 ]
3.15.0 (main, Oct  9 2026, 15:24:40) [Clang 22.1.3 ]

Additional context

Environment: Linux x86_64 (Intel Xeon Gold 6248), Docker container pinned to 16 CPUs. Interpreters are uv-managed python-build-standalone builds (uv 0.13.0). Free-threaded runs used PYTHON_GIL=0, and sys._is_gil_enabled() was False.

In an end-to-end check, 16 threads each ran their own event loop with an AsyncEngine (asyncpg, PostgreSQL 16), executing 1,200 short transactions per thread. This took 2.9s on 3.14.6t and 26-28s on 3.15.0t. With the setters removed it took 3.0s on 3.15.0t. Disabling the Cython extensions or garbage collection made no difference. A profile showed the threads waiting in CPython's stop-the-world, reached from memoized_instancemethod.<locals>.oneshot.

Suggested fix, validated above: stop assigning __name__ / __doc__ to the per-call memo / oneshot closures. They are stored in the instance __dict__, and as far as I can tell nothing reads those attributes. If the name or doc should be kept for introspection, a small callable object holding the result avoids mutating a function object at runtime. The CPython side is reported as python/cpython#159136, but releases already shipped (3.14.7, 3.14.8, 3.15.0) will keep this behaviour.

Activity

  1. zzzeek commented on Oct 10, 2026

    @zzzeek
    Member

    But if cpython fixes on their end, then we can ignore this. Depends on what they do. This kind of thing is difficult to test for.

    Propose we wait to see what they'll do because free threaded is IMO still an experimental novelty at this point

  2. CaselIT commented on Oct 10, 2026

    @CaselIT
    Member

    Agree with mike here. This seems like an upstream issue that python should fix

  3. added
    external library/application issues
    on Oct 11, 2026
  4. 0xamlab commented on Oct 12, 2026

    @0xamlab
  5. locked as too heated and limited conversation to collaborators on Oct 12, 2026
  6. zzzeek commented on Oct 19, 2026

    @zzzeek
    Member

    cpython is fixing this in all versions:

    python/cpython#159269 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    external library/application issues

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions