From 3aa3cdac343052abd58838513543a608df3868d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maurycy=20Paw=C5=82owski-Wiero=C5=84ski?= Date: Sat, 21 Nov 2026 02:29:36 +0100 Subject: [PATCH] [3.15] gh-162246: Fix lost writes on `BufferedRWPair` dealloc (GH-162295) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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 dc222c8d6c366e3d52d4b0d0053ad7bb8a601fff) Co-authored-by: Maurycy Pawłowski-Wieroński --- Lib/test/test_io/test_bufferedio.py | 9 +++++++++ .../2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst | 2 ++ Modules/_io/bufferedio.c | 3 ++- 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst diff --git a/Lib/test/test_io/test_bufferedio.py b/Lib/test/test_io/test_bufferedio.py index e83dd0d4e28d006..a9acdc5669ce3b0 100644 --- a/Lib/test/test_io/test_bufferedio.py +++ b/Lib/test/test_io/test_bufferedio.py @@ -1096,6 +1096,15 @@ def test_write(self): pair.flush() self.assertEqual(w._write_stack, [b"abc", b"def"]) + def test_destructor_flushes_shared_stream(self): + raw = self.MockRawIO() + pair = self.tp(raw, raw) + pair.write(b"abc") + self.assertEqual(raw._write_stack, []) + del pair + support.gc_collect() + self.assertEqual(raw._write_stack, [b"abc"]) + def test_peek(self): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) diff --git a/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst b/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst new file mode 100644 index 000000000000000..702b38215ed6efb --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst @@ -0,0 +1,2 @@ +Fix :class:`io.BufferedRWPair` losing buffered writes on deallocation when the +reader and writer share a raw stream. diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c index 5537947f6a51c11..ec90a7636de20f6 100644 --- a/Modules/_io/bufferedio.c +++ b/Modules/_io/bufferedio.c @@ -2315,8 +2315,9 @@ static int bufferedrwpair_clear(PyObject *op) { rwpair *self = rwpair_CAST(op); - Py_CLEAR(self->reader); + /* Let the writer flush before the reader closes a shared raw stream. */ Py_CLEAR(self->writer); + Py_CLEAR(self->reader); Py_CLEAR(self->dict); return 0; }