You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
encode() is not thread-safe: get_encode_cache() publishes the table before filling it (IndexError on free-threaded Python) #27
get_encode_cache() stores the new lookup table in encode_cachebefore filling it:
cache: list[str] = []
encode_cache[exclude] =cache# visible to other threads now, still emptyforiinrange(128):
...
cache.append(...)
A second thread calling encode() with the same exclude at that moment gets the half-built list from the cache, and encode() raises IndexError: list index out of range at cache[code]. The cache is per process and filled lazily, so this only happens the first time each exclude is used, with several threads starting at once. Under the GIL a thread switch in the middle of the loop makes it rare. On a free-threaded build (3.13t/3.14t) it happens almost every time. We hit it through markdown-it-py (normalizeLink calls mdurl.encode), with documents parsed in a thread pool.
Reproduce (mdurl 0.1.2, also matches current main; CPython 3.14.3 free-threading build, Windows 11):
Output, in three separate runs: attempt 0: 2 thread(s) failed, e.g. IndexError('list index out of range') (2–4 threads each time).
Suggested fix: build the list first and store it only when it is complete:
cache: list[str] = []
foriinrange(128):
...
forchinexclude:
cache[ord(ch)] =chencode_cache[exclude] =cache# publish only when completereturncache
At worst two threads build the same table at the same time and one result replaces the other; both are correct. With this change the script above runs all 2000 attempts without a failure. I'm happy to open a PR if that's useful.
Activity