Skip to content

Commit 1396e75

Browse files
maurycycmaloney
authored andcommitted
[3.15] gh-162246: Fix lost writes on BufferedRWPair dealloc (GH-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()`. (cherry picked from commit dc222c8) Co-authored-by: Maurycy Pawłowski-Wieroński <maurycy@maurycy.com>
1 parent 7f4409a commit 1396e75

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
@@ -1096,6 +1096,15 @@ def test_write(self):
10961096
pair.flush()
10971097
self.assertEqual(w._write_stack, [b"abc", b"def"])
10981098

1099+
def test_destructor_flushes_shared_stream(self):
1100+
raw = self.MockRawIO()
1101+
pair = self.tp(raw, raw)
1102+
pair.write(b"abc")
1103+
self.assertEqual(raw._write_stack, [])
1104+
del pair
1105+
support.gc_collect()
1106+
self.assertEqual(raw._write_stack, [b"abc"])
1107+
10991108
def test_peek(self):
11001109
pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO())
11011110

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
@@ -2315,8 +2315,9 @@ static int
23152315
bufferedrwpair_clear(PyObject *op)
23162316
{
23172317
rwpair *self = rwpair_CAST(op);
2318-
Py_CLEAR(self->reader);
2318+
/* Let the writer flush before the reader closes a shared raw stream. */
23192319
Py_CLEAR(self->writer);
2320+
Py_CLEAR(self->reader);
23202321
Py_CLEAR(self->dict);
23212322
return 0;
23222323
}

0 commit comments

Comments
 (0)