From e50cb4f611a856fab1bf04d4312a87815c09801e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:09:01 -0600 Subject: [PATCH 1/2] aio(fix[drain]): Report aborted writes why: Drain can report success after close discards queued bytes. what: - Report local write interruption through errno.ECANCELED. - Reject PTY writes during close. - Exercise both streaming transports under backpressure. Fixes #81 --- MIGRATION | 7 ++++ docs/topics/sync-and-asyncio.md | 7 ++++ src/libvt/aio.py | 37 +++++++++++++++---- tests/test_aio.py | 64 +++++++++++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 6 deletions(-) diff --git a/MIGRATION b/MIGRATION index da3a2379..fd294625 100644 --- a/MIGRATION +++ b/MIGRATION @@ -65,6 +65,13 @@ Update wire expectations for classic releases to include their Shift, Alt, and Ctrl bits. X10 sends plain button codes for left, middle and right presses. Select `?1000h`, `?1002h` or `?1003h` to report wheel presses. +### Drain interrupted by close (#81) + +Concurrent close can interrupt a pending `drain()` with +`OSError(errno.ECANCELED)`. Await the stream drain before closing when +queued writes should flush. For a PTY, pass `write_high_water=0` to +{func}`~libvt.aio.open_pty` to drain its entire outbound queue. + ## libvt 0.0.1a2 (2026-11-28) ### Curated PEP 562 `libvt` root exports (#43) diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index b95a5aa4..85c26a1e 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -116,6 +116,13 @@ background flusher on {class}`~libvt.aio.AsyncTerminalStream`, paired with {meth}`~libvt.aio.PtySession.drain`) to flush or apply backpressure; exceeding `max_write_buffer` raises {exc}`BufferError`. +Await a stream's `drain()` before closing to flush its queue. A PTY drain +waits until buffered bytes drop to `write_high_water` or below. Use +`write_high_water=0` to wait for its entire queue. If a concurrent +`aclose()` aborts pending writes, `drain()` raises +`OSError` with `errno.ECANCELED`. Writes started during close raise +`OSError`. + You can prepare a replacement stream around the same terminal before closing the current stream. Close the current stream before starting the replacement. Pending terminal replies flow to the replacement before the diff --git a/src/libvt/aio.py b/src/libvt/aio.py index f6fbfb16..a43f3586 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -225,6 +225,11 @@ async def aclose(self) -> object: _COALESCE_SLAB = 16_384 +def _write_aborted() -> OSError: + message = "terminal session closed before queued writes drained" + return OSError(errno.ECANCELED, message) + + def _validate_nonneg_seconds(value: float, name: str) -> None: if ( isinstance(value, bool) @@ -991,7 +996,8 @@ async def drain(self) -> None: Raises ------ OSError - If a non-EOF transport error occurred while flushing ``writer``. + If flushing fails or :meth:`aclose` interrupts queued writes. + A local interruption has errno ``ECANCELED``. Examples -------- @@ -1019,7 +1025,6 @@ async def drain(self) -> None: if ( self._write_error is not None and self._write_error.errno not in _PEER_EOF_ERRNOS - and not self._closed ): raise self._write_error @@ -1216,6 +1221,8 @@ async def aclose(self) -> None: if task is None: if self._closed: return + if self._write_buffered_bytes and self._write_error is None: + self._write_error = _write_aborted() self._closed = True task = self._close_task = asyncio.create_task(self._close_stream()) try: @@ -1540,7 +1547,12 @@ def _remove_writer(self) -> None: self._loop.remove_writer(self._master_fd) def _ensure_writer(self) -> None: - if self._writer_registered or self._closed or self._fd_closed: + if ( + self._writer_registered + or self._closed + or self._fd_closed + or self._write_closed + ): return loop = self._loop if loop is None: @@ -1625,7 +1637,7 @@ def _enqueue_write( return if self._write_error is not None: raise self._write_error - raise OSError(errno.EIO, "PTY master write end is closed") + raise OSError(errno.EBADF, "PTY session is closing") if self._write_buffered_bytes + n_total > self.max_write_buffer: if is_reply: return @@ -1706,7 +1718,14 @@ def _on_writable(self) -> None: self._drain_event.set() async def drain(self) -> None: - """Pause while outbound buffered bytes exceed :attr:`write_high_water`.""" + """Pause while outbound buffered bytes exceed :attr:`write_high_water`. + + Raises + ------ + OSError + If writing fails or :meth:`aclose` interrupts queued writes. + A local interruption has errno ``ECANCELED``. + """ if self._write_buffered_bytes <= self.write_high_water: if self._write_buffered_bytes > 0: self._ensure_writer() @@ -1722,7 +1741,6 @@ async def drain(self) -> None: if ( self._async_write_error is not None and self._async_write_error.errno not in _PEER_EOF_ERRNOS - and not self._closed ): raise self._async_write_error @@ -1951,6 +1969,13 @@ async def aclose(self) -> int: if task is None: if self._closed: return self.process.returncode or 0 + if self._write_buffered_bytes and self._async_write_error is None: + failure = _write_aborted() + self._async_write_error = failure + self._write_error = failure + self._write_closed = True + self._remove_writer() + self._drain_event.set() task = self._close_task = asyncio.create_task(self._close_pty()) try: return await _join_close_task(task) diff --git a/tests/test_aio.py b/tests/test_aio.py index a368a249..3347bb6c 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -467,6 +467,70 @@ async def wait_closed(self) -> None: await asyncio.sleep(0) +@pytest.mark.parametrize("close_first", [False, True]) +async def test_stream_drain_reports_writes_aborted_by_close(close_first: bool) -> None: + """Report an aborted queue and preserve successful FIFO delivery.""" + writer = _StalledDrainWriter() + async with AsyncTerminalStream(asyncio.StreamReader(), writer) as stream: + stream.send(b"one/") + stream.send(b"two") + waiter = asyncio.create_task(stream.drain()) + await asyncio.sleep(0) + assert not waiter.done() + if close_first: + await stream.aclose() + with pytest.raises( + OSError, match="session closed before queued writes" + ) as failure: + await waiter + assert failure.value.errno == errno.ECANCELED + else: + writer.release.set() + await waiter + await stream.aclose() + await stream.drain() + assert writer.frames == ([b"one/"] if close_first else [b"one/", b"two"]) + + +@pytest.mark.skipif(os.name != "posix", reason="requires a POSIX PTY") +async def test_pty_drain_reports_writes_aborted_by_close() -> None: + """Wake a drain waiting for a real PTY that has stopped reading.""" + child = (sys.executable, "-u", "-c", "import time; print('ready'); time.sleep(12)") + async with open_pty(child, tty_mode="raw", write_high_water=0) as session: + await session.wait_for("ready", timeout=3) + session.send(b"X" * 262_144) + assert session.write_buffer_size > 0 + waiter = asyncio.create_task(session.drain()) + await asyncio.sleep(0) + assert not waiter.done() + await session.aclose() + with pytest.raises( + OSError, match="session closed before queued writes" + ) as failure: + await waiter + assert failure.value.errno == errno.ECANCELED + + +@pytest.mark.skipif(os.name != "posix", reason="requires a POSIX PTY") +async def test_pty_closing_rejects_new_writes() -> None: + """Stop accepting writes before signaling the process group.""" + code = ( + "import signal,time;" + "signal.signal(signal.SIGHUP, signal.SIG_IGN);" + "print('ready', flush=True);time.sleep(12)" + ) + async with open_pty((sys.executable, "-u", "-c", code)) as session: + await session.wait_for("ready", timeout=3) + closing = asyncio.create_task(session.aclose()) + try: + await asyncio.sleep(0) + with pytest.raises(OSError, match="PTY session is closing") as failure: + session.send(b"new input") + assert failure.value.errno == errno.EBADF + finally: + await closing + + async def test_async_session_bidirectional_nonblocking_paste_and_mouse_dedup() -> None: """``AsyncTerminalStream`` satisfies ``AsyncSession`` without reader deadlocks.""" reader = asyncio.StreamReader() From 9bc09ee578d9f21a0d80f28cb5e05df2c357c1d3 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:32:40 -0600 Subject: [PATCH 2/2] CHANGES(docs): Explain interrupted output drains why: Closing a transport with queued input can prevent the child from receiving it. what: - Document ECANCELED and show how to drain before closing. --- CHANGES | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/CHANGES b/CHANGES index b7b3dbfa..e6a39d92 100644 --- a/CHANGES +++ b/CHANGES @@ -208,6 +208,29 @@ The compiled Ghostty comparison preserves spaces printed by the application. An erase-to-end-of-line control still leaves unused cells out of the extracted text. +### Breaking changes + +#### Report outbound writes interrupted by close (#162) + +{meth}`~libvt.aio.AsyncTerminalStream.drain` and +{meth}`~libvt.aio.PtySession.drain` raise `OSError` with `errno.ECANCELED` +when a local close aborts queued writes. + +For a stream, await `drain()` before closing to flush queued input. For a +PTY, set `write_high_water=0` and await `drain()` to empty the outbound +queue. + +```python +# Before +stream.send(b"done\r") +await stream.aclose() + +# After +stream.send(b"done\r") +await stream.drain() +await stream.aclose() +``` + ## libvt 0.0.1a5 (2026-11-30) `libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and