Skip to content

Commit a8474ce

Browse files
cmaloneymaurycy
andauthored
[3.14] gh-162246: Fix lost writes on BufferedRWPair dealloc (GH-162295) (#162345)
`socket.makefile("rwb")` passes the same raw stream to both sides of a `BufferedRWPair`. When the pair is deallocated, the reader closes the stream before the writer can flush its buffer. Release the writer first, matching the order in `BufferedRWPair.close()`. (cherry picked from commit dc222c8) Co-authored-by: Maurycy Pawłowski-Wieroński <maurycy@maurycy.com>
1 parent 697da9c commit a8474ce

3 files changed

Lines changed: 13 additions & 1 deletion

File tree

‎Lib/test/test_io.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2296,6 +2296,15 @@ def test_write(self):
22962296
pair.flush()
22972297
self.assertEqual(w._write_stack, [b"abc", b"def"])
22982298

2299+
def test_destructor_flushes_shared_stream(self):
2300+
raw = self.MockRawIO()
2301+
pair = self.tp(raw, raw)
2302+
pair.write(b"abc")
2303+
self.assertEqual(raw._write_stack, [])
2304+
del pair
2305+
support.gc_collect()
2306+
self.assertEqual(raw._write_stack, [b"abc"])
2307+
22992308
def test_peek(self):
23002309
pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO())
23012310

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :class:`io.BufferedRWPair` losing buffered writes on deallocation when the
2+
reader and writer share a raw stream.

‎Modules/_io/bufferedio.c‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2302,8 +2302,9 @@ static int
23022302
bufferedrwpair_clear(PyObject *op)
23032303
{
23042304
rwpair *self = rwpair_CAST(op);
2305-
Py_CLEAR(self->reader);
2305+
/* Let the writer flush before the reader closes a shared raw stream. */
23062306
Py_CLEAR(self->writer);
2307+
Py_CLEAR(self->reader);
23072308
Py_CLEAR(self->dict);
23082309
return 0;
23092310
}

0 commit comments

Comments
 (0)