← 输入框|github.com|刷新
Skip to content

gh-157601: Protect bytearray reads during concurrent mutation - #162787

Draft
nascheme wants to merge 1 commit into
python:mainfrom
nascheme:ft-bytearray-critical-section
Draft

nascheme wants to merge 1 commit into
python:mainfrom
nascheme:ft-bytearray-critical-section

Conversation

@nascheme

@nascheme nascheme commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

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()
  • c format unit in getargs.c, and the Argument Clinic char converter (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 %b without a width in bytes formatting. %b now copies a bytearray straight into the writer under the lock, with no temporary bytes object.
  • ctypes c_set
  • _struct s and p pack. The two branches are merged into one.
  • _ssl password callback (_pwinfo_set split into _pwinfo_copy)
  • pyexpat readinst

Copy 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() (in pycore_bytesobject.h):

  • int(ba) and int(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)
  • Source passed to compile(), exec() and eval() (_Py_SourceAsString)
  • et / et# in getargs.c when the argument is a bytearray (es requires str)
  • A bytearray returned by a codec inside PyUnicode_AsEncodedString
  • socket idna_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 with PyObject_GetBuffer. For large payloads the bytearray itself is passed to write(), 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

  • If another thread resizes a bytearray while it is being pickled with protocol 5, the resizing thread now gets 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.
  • The struct error for a non-bytes s/p argument is now produced with PyErr_Format. The message text is unchanged.

Performance

These measurements are from an earlier revision, before the latest ord() and formatting changes. Method: four builds (base c0ee4bb03e3 and patched, each with the GIL and free-threaded), GCC 14.2, -O3, no PGO/LTO, i7-14700K. pyperf timeit, 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.

Case GIL base GIL patched Change FT base FT patched Change
b[0] on bytes (control) 7.29 7.29 0% 7.11 7.21 +1%
len(ba) (control) 5.20 4.86 -6% 5.80 5.83 +1%
ba[0] (control) 7.53 7.47 -1% 12.90 12.89 0%
ba[:8] (control) 25.4 25.1 -1% 25.0 24.9 -1%
ba.copy() (control) 20.8 20.6 -1% 21.9 22.1 +1%
ord(ba) 6.07 6.03 -1% 6.65 13.70 +106%
int(ba) 27.0 35.5 +32% 28.8 36.7 +28%
float(ba) 33.5 41.9 +25% 35.6 42.8 +20%
b'%b' % ba, 16 B 26.1 26.1 0% 30.4 27.3 -10%
b'%b' % ba, 4 KiB 61.6 53.2 -14% 42.7 43.3 +1%
Struct('16s').pack(ba) 25.1 25.3 +1% 26.9 27.9 +4%
Struct('4096s').pack(ba) 75.6 68.7 -9% 58.9 57.5 -2%
pickle.dumps(ba, 5), 16 B 181 187 +3% 145 162 +11%
pickle.dumps(ba, 5), 4 KiB 200 217 +8% 194 207 +7%

Why some cases got slower:

  • ord(ba), about 7 ns, free-threaded only: the cost of an uncontended critical section. The percentage is large only because ord() is so cheap.
  • int(ba) and float(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 %b path writes directly into the output buffer. The measured speedup depends on both the build and the input size. Plain indexing, slicing, len() and copy() are unchanged. The -6% for len() on the GIL build is the same in both passes, and len() is not touched by the patch, so it is likely a code layout effect.

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.
@nascheme

Copy link
Copy Markdown
Member Author

CC @ngoldbaum since this relates to your buffer protocol work, I think.

@cmaloney

cmaloney commented Nov 28, 2026 •

Copy link
Copy Markdown
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 memoryview, this hazard only exists for C code.

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.

2 participants