Skip to content

encode() is not thread-safe: get_encode_cache() publishes the table before filling it (IndexError on free-threaded Python) #27

Open

Description

@achojar-seasand

get_encode_cache() stores the new lookup table in encode_cache before filling it:

cache: list[str] = []
encode_cache[exclude] = cache   # visible to other threads now, still empty

for i in range(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):

import threading
import mdurl
from mdurl import _encode

errors = []
for attempt in range(2000):
    _encode.encode_cache.clear()          # simulate a fresh process
    barrier = threading.Barrier(16)

    def work():
        barrier.wait()
        try:
            mdurl.encode("https://example.com/a b/\u00e9?q=1#x")
        except Exception as e:
            errors.append(repr(e))

    threads = [threading.Thread(target=work) for _ in range(16)]
    for t in threads: t.start()
    for t in threads: t.join()
    if errors:
        print(f"attempt {attempt}: {len(errors)} thread(s) failed, e.g. {errors[0]}")
        break
else:
    print("no failure in 2000 attempts")

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] = []
for i in range(128):
    ...
for ch in exclude:
    cache[ord(ch)] = ch
encode_cache[exclude] = cache   # publish only when complete
return cache

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

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions