Skip to content

Conversation

@fatelei
Copy link
Contributor

@fatelei fatelei commented Dec 11, 2025

The original defdict_missing function in

cpython/Modules/_collectionsmodule.c:2216-2239 had a race

condition where:

  1. When missing is called, the factory function is invoked
  2. Between the factory call and PyObject_SetItem(), another thread could insert a value for the same key
  3. PyObject_SetItem() would overwrite the existing value, violating atomic

fix

  1. Atomic Behavior: Uses PyDict_SetDefaultRef() which provides atomic "get or insert default" behavior
  2. No Overwrites: Guarantees that existing values are never replaced
  3. Thread Safety: The function handles concurrent access correctly
  4. Factory Called Only When Needed: The factory is still only called when a key is initially missing
  5. Preserves Semantics: The existing behavior and API remain unchanged

@picnixz
Copy link
Member

picnixz commented Dec 11, 2025

Note that someone actually asked on the issue if they could work on it. Please, communicate with them. cc @LindaSummer

In addition, read our policy about https://devguide.python.org/getting-started/generative-ai/ (the PR summary looks like AI-generated so I want to be sure that the PR hasn't been so).

@fatelei fatelei force-pushed the ___missing__race_condition branch from 2afea50 to 4310b88 Compare December 11, 2025 13:15
@fatelei
Copy link
Contributor Author

fatelei commented Dec 11, 2025

Note that someone actually asked on the issue if they could work on it. Please, communicate with them. cc @LindaSummer

In addition, read our policy about https://devguide.python.org/getting-started/generative-ai/ (the PR summary looks like AI-generated so I want to be sure that the PR hasn't been so).

the test code is generate by llm, the source code is not

@picnixz
Copy link
Member

picnixz commented Dec 11, 2025

Tests shouldn't be written by LLM as they are exactly here to exercise whether the change is correct. In addition, it takes too much to review AI-generated test code so I'm going to close this, sorry.

@picnixz picnixz closed this Dec 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants