-
-
Notifications
You must be signed in to change notification settings - Fork 32.2k
gh-116738: Make _json module safe in the free-threading build #119438
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
You need to include the file that defines that macro. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Revert newlines
Co-authored-by: Nice Zombies <[email protected]>
@nineteendo The implementation of free-threading (e.g. PEP703) is still work in progress, so things may change. But currently the critical sections for About the race condition: I think there are no guarantees for the result of the json encoder when the data to be encoded is mutated. So yes, race conditions can occur, and depending on how the data is mutated the json output may differ. But this is accepted behaviour. The goal of this PR is intended to prevent the interpreter crashing. |
Shouldn't the empty list always be on a single line? So, without indentation. You can test this by overwriting import io
import json
class BadDict(dict):
def __len__(self) -> int:
return 1
class BadList(list):
def __len__(self) -> int:
return 1
fp = io.StringIO()
json.dump([BadDict(), BadList()], fp, indent=4)
print(fp.getvalue()) [
{
},
]
] Oh well, I managed to output invalid JSON. Some assumptions shouldn't be made. |
@nineteendo Interesting example. Note for recent python versions (in particular the current main branch) the json output depends on whether
has output
This is something to do with the The good thing is that while your example produces funny results, the interpreter does not crash (I checked the C code to make sure the bad list and bad dict are handled correctly). |
It doesn't use the C encoder because it uses more memory than streaming to the file, but the Python implementation is 4x as slow. I thought about rewriting the C code to use streaming, but it will probably be slower as that would wrap _PyUnicodeWriter instead of using it directly. I opted to always use the C encoder. |
You are right. Using the C encoder works (i tried locally and it passes all the tests), but it would indeed use more memory. Would be nice to rewrite the C code so that it can work in streaming mode, but that is for another PR. |
I think we should create a separate issue. Do we fix the race condition or just sub classes (like float and int)? |
I am a bit lost here. Which race condition do you mean? |
The python implementation first checks if the list is empty and then iterates over it. Instead of making a shallow copy of the list, checking the length of the copy and iterating over it. A different thread could probably make the list empty between these two statements. (Like the subclass is simulating) if not lst:
yield "[]"
return
time.sleep(10) # allow thread to modify the list
for value in lst:
... My question is: do we fix just the broken subclass or also this? |
In my opinion there is nothing to fix: when different threads are mutating the underlying data, we give no guarantees on the output. But we do guarantee we will not crash the python interpreter. The python implementation will not crash (since all individual python statements are safe). In this PR we modify the C implementation so that no crashes can occur. On the C side we want to make sure that if the underlying list is emptied we do not index into deallocated memory (this would crash the interpreter). (note: for the json encoder the C method that is unsafe for the list access is There are some other PRs addressing safety under the free-threading builds and the feedback there was similar: address the crashes, but don't make guarantees on correct output (at the cost of performance). See |
There's a precedent for guarding against a broken |
Misc/NEWS.d/next/Core_and_Builtins/2024-06-04-20-26-21.gh-issue-116738.q_hPYq.rst
Outdated
Show resolved
Hide resolved
@colesbury @mpage Would one you be able to review the PR? Thanks |
(updated description)
Writing JSON files (or encoding to a string) is not thread-safe in the sense that when encoding data to json while another thread is mutating the data, the result is not well-defined (this is true for both the normal and free-threading build). But the free-threading build can crash the interpreter while writing JSON because of the usage of methods like
PySequence_Fast_GET_ITEM
. In this PR we make the free-threading build safe by adding locks in three places in the JSON encoder.Reading from a JSON file is safe: objects constructed are only known to the executing thread. Encoding data to JSON needs a bit more care: mutable Python objects such as a list or a dict could be modified by another thread during encoding.
Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST
to project against mutation the listPyDict_Next
is used there). The non-exact dicts usePyMapping_Items
to create a list of tuples.PyMapping_Items
itself is assumed to be thread safe, but the resulting list is not a copy and can be mutated.Update 2025-02-10: refactored to avoid using Py_EXIT_CRITICAL_SECTION_SEQUENCE_FAST
Test script
t=JsonThreadingTest(number_of_json_dumps=102, number_of_threads=8)
is a factor 25 faster using free-threading. Nice!