BufferedReader.readline(), read1(), readinto(), readinto1() and __next__() lose bytes that another thread buffered while they waited for the buffer lock · Issue #163243 · python/cpython
Repository navigation
BufferedReader.readline(), read1(), readinto(), readinto1() and __next__() lose bytes that another thread buffered while they waited for the buffer lock #163243
New issue
New issue
Backlog
Backlog
BufferedReader.readline(), read1(), readinto(), readinto1() and __next__() lose bytes that another thread buffered while they waited for the buffer lock #163243 Labels
extension-modules
topic-IO
type-bug
Description
@viftode4's profile viftode4 opened on Dec 6, 2026Bug report
Bug description
io.BufferedReader is documented as safe to use from several threads ("Binary buffered objects ... protect their internal structures using a lock; it is therefore safe to call them from multiple threads at once"). readline(), __next__(), read1(), readinto() and readinto1() look at the buffer before they take the buffer lock (ENTER_BUFFERED) and, after waiting for the lock, continue with that stale view. If the thread that held the lock has buffered data in the meantime, the waiting thread throws it away (_bufferedreader_reset_buf) or, in readline(), copies and skips a stale number of bytes. Bytes that were read from the raw stream are then returned to nobody, or to two callers.
Reproducer. A gated raw stream makes the timing deterministic (thread B holds the buffer lock inside raw.readinto(); thread A has already seen an empty buffer and waits for the lock):
import io, sys, threading, time
OP = sys.argv[1] if len(sys.argv) > 1 else "readline" # readline | read1 | readinto | readinto1 | next
class GatedRaw(io.RawIOBase):
"""The first readinto() blocks until released; the calling thread holds the BufferedReader lock meanwhile."""
def __init__(self):
self.chunks = [b"abcdefgh", b"ijk\n"]
self.entered = threading.Event()
self.gate = threading.Event()
self.calls = 0
def readable(self):
return True
def readinto(self, b):
self.calls += 1
if self.calls == 1:
self.entered.set()
self.gate.wait()
if not self.chunks:
return 0
c = self.chunks.pop(0)
b[:len(c)] = c
return len(c)
raw = GatedRaw()
r = io.BufferedReader(raw, buffer_size=8)
out = {}
def thread_b(): # takes the buffer lock, blocks in raw.readinto(), then leaves b"defgh" buffered
out["b"] = r.read(3)
def thread_a(): # sees an empty buffer, then waits for the buffer lock
if OP == "readline":
out["a"] = r.readline()
elif OP == "read1":
out["a"] = r.read1(100)
elif OP == "next":
out["a"] = next(r)
else:
buf = bytearray(100)
n = getattr(r, OP)(buf)
out["a"] = bytes(buf[:n])
tb = threading.Thread(target=thread_b); tb.start()
raw.entered.wait()
ta = threading.Thread(target=thread_a); ta.start()
time.sleep(0.3) # let thread A reach the lock wait
raw.gate.set()
tb.join(); ta.join()
print(OP, "->", out["b"], out["a"])
print("OK" if (out["b"] + out["a"]).startswith(b"abcdefgh") else "BUG: b'defgh' was read from the raw stream and returned to nobody")
Output on 3.14.10, default build and free-threaded build, for each of readline, read1, readinto, readinto1, next (10 of 10 combinations, repeated several times):
readline -> b'abc' b'ijk\n'
BUG: b'defgh' was read from the raw stream and returned to nobody
Expected: thread A returns b'defghijk\n' (for read1/readinto b'defgh').
The same thing happens without any gating on an ordinary file. One thread calling readline() and one or two threads calling read(211) on one shared open(path, 'rb') (3 MB file of 1000-byte lines) return a total number of bytes that differs from the file size in 4 of 10 rounds with the default buffer size on the default build (up to 551 bytes duplicated, tens of KB lost), and in 10 of 10 rounds with buffering=64. Threads that only call read() are always exact, because _bufferedreader_read_generic() reads READAHEAD again after it holds the lock.
Cause
Modules/_io/bufferedio.c, _buffered_readline(): n = READAHEAD(self) and start = self->buffer + self->pos are computed before ENTER_BUFFERED(self). When the lock is busy, _enter_buffered_busy() releases the GIL (or suspends the critical section in the free-threaded build) while the other thread reads from the raw stream. When it returns, the slow path writes n bytes from start, does self->pos += n, and the loop begins with _bufferedreader_reset_buf(self); all of it with values that the other thread may have invalidated (n == 0 while the other thread has buffered data: the data is discarded; n > 0 stale: bytes are duplicated, and pos can pass read_end).
_io__Buffered_read1_impl() (have) and _buffered_readinto_generic() (n, written) have the same shape and then call _bufferedreader_reset_buf().
The text is identical in v3.12.0, v3.13.0 and main (c76d734); I only ran 3.14.10.
Fix
I have a patch that re-reads READAHEAD after ENTER_BUFFERED (readline: repeat the newline/limit search; read1 and readinto: use the buffered bytes before the reset). It is being built and tested on more builds; I will attach it as a comment when the results are in, and can turn it into a PR with a regression test based on the reproducer if wanted.
CPython versions tested on
3.14.10 built from main (11 Nov 2026), default and free-threaded, Linux x86-64. The relevant source in main (c76d734) is unchanged.
Operating systems tested on
Linux
Written and run by an AI agent (Claude) for the GitHub account viftode4; the reproducer output above is from real runs, no human has reviewed the text. Made by SLIME.
Linked PRs
Metadata
Metadata
Assignees
No one assignedLabels
extension-modules
topic-IO
type-bug