Skip to content

Commit dc222c8

Browse files
authored
gh-162246: Fix lost writes on BufferedRWPair dealloc (#162295)
`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()`.
1 parent ab5b8f8 commit dc222c8

3 files changed

Lines changed: 13 additions & 1 deletion

File tree

‎Lib/test/test_io/test_bufferedio.py‎

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

1119+
def test_destructor_flushes_shared_stream(self):
1120+
raw = self.MockRawIO()
1121+
pair = self.tp(raw, raw)
1122+
pair.write(b"abc")
1123+
self.assertEqual(raw._write_stack, [])
1124+
del pair
1125+
support.gc_collect()
1126+
self.assertEqual(raw._write_stack, [b"abc"])
1127+
11191128
def test_peek(self):
11201129
pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO())
11211130

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
@@ -2318,8 +2318,9 @@ static int
23182318
bufferedrwpair_clear(PyObject *op)
23192319
{
23202320
rwpair *self = rwpair_CAST(op);
2321-
Py_CLEAR(self->reader);
2321+
/* Let the writer flush before the reader closes a shared raw stream. */
23222322
Py_CLEAR(self->writer);
2323+
Py_CLEAR(self->reader);
23232324
PyObject_ClearManagedDict(op);
23242325
return 0;
23252326
}

0 commit comments

Comments
 (0)