Skip to content

Fix thread-unsafe cache initialization in encode() and decode() - #29

Open
JonathanLStoff wants to merge 1 commit into
executablebooks:masterfrom
JonathanLStoff:fix/thread-safe-cache
Open

JonathanLStoff wants to merge 1 commit into
executablebooks:masterfrom
JonathanLStoff:fix/thread-safe-cache

Conversation

@JonathanLStoff

Copy link
Copy Markdown

Hi @hukkin and the executablebooks maintainers — thank you for maintaining mdurl! We rely on it in our Python tooling via markdown-it-py.

Fixes #27.

Problem

Both get_encode_cache() in src/mdurl/_encode.py and get_decode_cache() in src/mdurl/_decode.py store a newly allocated empty list in the module-level cache (encode_cache[exclude] = cache / decode_cache[exclude] = cache) before populating its 128 ASCII entries and applying the exclude overrides.

When multiple threads call mdurl.encode() or mdurl.decode() concurrently with an uncached exclude string (for example, markdown-it-py's normalizeLink() and normalizeLinkText() running across worker threads on startup, under GIL thread switches or free-threaded Python 3.13t/3.14t):

  1. A second thread reading encode_cache / decode_cache while the first loop (range(128)) is still appending observes a partial list and raises IndexError: list index out of range when indexing cache[code] or cache[b1].
  2. A second thread reading the cache after the 128 entries are appended but before the exclude loop finishes silently observes an incomplete lookup table without exclude applied — causing encode() to percent-encode excluded URL delimiters or decode() to decode excluded sequences such as %2F, %3F, and %25.

Solution

  • Build and populate cache completely as a local list in get_encode_cache() and get_decode_cache() before publishing encode_cache[exclude] = cache and decode_cache[exclude] = cache.
  • Use a single .get(exclude) lookup on the fast path instead of in followed by [].
  • Add multi-threaded regression tests in tests/test_encode.py and tests/test_decode.py exercising concurrent cold-cache calls to encode() and decode().

Verification

  • Verified that both test_encode_thread_safety and test_decode_thread_safety fail deterministically before this change (IndexError and unexcluded decode corruption) and pass with the fix (pytest, 191 passed).
  • Verified formatting and lint compliance with black --check and flake8/isort-equivalent checks.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant