Repository navigation
Conversation
Use per-object critical sections to read or copy bytearray contents. Keep private copies where parsing or other work may run after the lock is released, and pin the pickle buffer across streaming writes.
Member
Author
|
CC @ngoldbaum since this relates to your buffer protocol work, I think. |
Contributor
|
I'm not sure this is an actual issue; that you cannot resize while another thread is direct-accessing bytes is expected. The threadsafe way to do it is a |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Several C call sites read bytearray storage directly with
PyByteArray_AS_STRING()/PyByteArray_GET_SIZE()and no lock. On the free-threaded build, another thread can resize the bytearray during the read. A resize can free the buffer while the reader still holds its address. Some sites are unsafe on the GIL build too: a Python callback can resize the bytearray in the same thread, or another thread can resize it while the GIL is released.This PR fixes those sites with one of three approaches, chosen per site.
Changes
Lock and read in place. The data is consumed while a per-object critical section is held, and no Python code runs inside it:
ord()cformat unit ingetargs.c, and the Argument Cliniccharconverter (clinic files regenerated). The converter emits the inline code only when targeting the full C API, because it uses a private bytearray helper.%c(byte_converter) and%bwithout a width in bytes formatting.%bnow copies a bytearray straight into the writer under the lock, with no temporary bytes object.c_set_structsandppack. The two branches are merged into one._sslpassword callback (_pwinfo_setsplit into_pwinfo_copy)pyexpatreadinstCopy under the lock. These sites use the data after the lock is released or while Python code may run. Most take a full snapshot with
_PyBytes_FromByteArray()(inpycore_bytesobject.h):int(ba)andint(ba, base), via the new_PyLong_FromByteArrayString(). For long decimal inputs, parsing calls into_pylong, which is Python code. This site is a real hazard on the GIL build as well.float(ba)compile(),exec()andeval()(_Py_SourceAsString)et/et#ingetargs.cwhen the argument is a bytearray (esrequiresstr)PyUnicode_AsEncodedStringidna_converter: the name is used with the GIL released.%b(and its alias%s) with an explicit width: copy only the prefix selected by the precision, or the whole bytearray if precision is omitted.Export the buffer. In
_pickle.c,save_bytearray(protocol 5) now pins the buffer withPyObject_GetBuffer. For large payloads the bytearray itself is passed towrite(), and the size in the header must match the bytes that are written. Pinning keeps the storage and length stable without copying the payload.Pickle follow-up: A buffer export does not synchronize same-length writes with the pickler’s reads. That race is left for a separate issue; this fix does not promise a consistent snapshot during concurrent mutation.
Behaviour changes
BufferError. Elsewhere this patch deliberately locks or copies so that a concurrent resize does not fail. Pickle is the exception for the reason given above.structerror for a non-bytess/pargument is now produced withPyErr_Format. The message text is unchanged.Performance
These measurements are from an earlier revision, before the latest
ord()and formatting changes. Method: four builds (basec0ee4bb03e3and patched, each with the GIL and free-threaded), GCC 14.2,-O3, no PGO/LTO, i7-14700K. pyperftimeit, 10 processes, pinned to one P-core. The full run was repeated with the builds in reverse order, and both passes agree within about 1 ns. Values are ns per call. The control rows are operations this patch does not touch.b[0]on bytes (control)len(ba)(control)ba[0](control)ba[:8](control)ba.copy()(control)ord(ba)int(ba)float(ba)b'%b' % ba, 16 Bb'%b' % ba, 4 KiBStruct('16s').pack(ba)Struct('4096s').pack(ba)pickle.dumps(ba, 5), 16 Bpickle.dumps(ba, 5), 4 KiBWhy some cases got slower:
ord(ba), about 7 ns, free-threaded only: the cost of an uncontended critical section. The percentage is large only becauseord()is so cheap.int(ba)andfloat(ba), about 8 ns on both builds for the measured inputs: both now copy before parsing. The cost of copying grows with input length.pickle.dumps(ba, 5), 6-17 ns: the cost of taking and releasing the buffer export. The GIL 4 KiB patched number has about 7% spread in both passes, but its mean is stable.struct.pack: the critical section adds about 1 ns on the free-threaded build.The no-width
%bpath writes directly into the output buffer. The measured speedup depends on both the build and the input size. Plain indexing, slicing,len()andcopy()are unchanged. The -6% forlen()on the GIL build is the same in both passes, andlen()is not touched by the patch, so it is likely a code layout effect.