Skip to content

Free-threading race conditions in mimetypes lazy initialization and add_type() #163237

Backlog

Description

@eg-bole

Bug report

Bug report

Bug description:

In Lib/mimetypes.py, module-level functions (guess_type(), guess_file_type(), guess_extension(), guess_all_extensions(), and add_type()) lazily initialize the global _db instance without synchronization:

if _db is None:
    init()
return _db.add_type(type, ext, strict)

(Historical context: gh-50103 previously moved _db = db to the end of init() to prevent infinite recursion, but left lazy initialization and module-level mutations unsynchronized.)

Under multi-threaded execution (particularly reproducible on free-threaded builds --disable-gil), this leads to three thread-safety issues:

  1. Lost add_type() registrations during concurrent lazy initialization:
    If one thread calls mimetypes.add_type() while another thread concurrently calls mimetypes.guess_file_type() before _db is initialized, both threads execute init(), create separate MimeTypes instances, and overwrite _db = db. Whichever thread finishes init() later silently wipes out custom MIME types registered by the earlier thread.
  2. Premature inited = True visibility:
    init() sets inited = True at entry before reading files/registry and assigning _db and module-level maps (types_map, suffix_map, etc.), allowing concurrent MimeTypes() callers to observe inited == True before initialization completes.
  3. Duplicate extensions in module-level mimetypes.add_type():
    Module-level mimetypes.add_type() mutates the shared global _db without synchronization, performing a non-atomic check-then-append (if ext not in exts: exts.append(ext)) on _db.types_map_inv, which can insert duplicate extensions returned by mimetypes.guess_all_extensions().

Minimal reproducer:

import mimetypes
import threading

for round_idx in range(20):
    mimetypes.inited = False
    mimetypes._default_mime_types()
    mimetypes._db = None

    barrier = threading.Barrier(6)

    def register_custom(idx):
        barrier.wait()
        mimetypes.add_type(f"application/x-custom-{idx}", f".custom{idx}")

    def reader():
        barrier.wait()
        mimetypes.guess_file_type("index.html")

    threads = [
        *(threading.Thread(target=register_custom, args=(i,)) for i in range(3)),
        *(threading.Thread(target=reader) for _ in range(3)),
    ]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    for i in range(3):
        got, _ = mimetypes.guess_file_type(f"sample.custom{i}")
        assert got == f"application/x-custom-{i}", f"round {round_idx}: lost .custom{i} ({got})"

On a free-threaded build (python3.15t / main with --disable-gil), this assertion fails reliably on the first round.

CPython versions tested on:

  • CPython main branch
  • 3.15 free-threaded build

Operating systems tested on:

  • Windows / Linux

CPython versions tested on:

3.15

Operating systems tested on:

Windows, Linux

Linked PRs

Activity

  1. added
    type-bug
    on Dec 6, 2026
  2. added
    stdlib
    on Dec 6, 2026
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

    stdlibtopic-free-threadingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions