Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions MIGRATION
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions docs/topics/sync-and-asyncio.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 31 additions & 6 deletions src/libvt/aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
--------
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down
64 changes: 64 additions & 0 deletions tests/test_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading