From cf713dc60ff3c54ba0f3a325087fdec52f374526 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 10:18:45 -0600 Subject: [PATCH] snapshot(fix): Reject attribute deletion why: Snapshot guarded attribute assignment via __setattr__ without a matching __delattr__, letting callers delete slotted fields like cursor or _frozen from a cached Terminal.committed frame and corrupting reads for subsequent consumers. what: - Add Snapshot.__delattr__ and type __setattr__/__delattr__ as NoReturn - Initialize Snapshot slots via object.__setattr__ and drop _frozen - Add regression tests for cached, ?2026-held, and sibling views - Record the fix in CHANGES under 0.0.1a7 Fixes #198 --- CHANGES | 9 ++++ src/libvt/snapshot.py | 69 +++++++++++++------------ tests/test_screen.py | 84 +++++++++++++++++++++++++++++++ tests/test_terminal.py | 111 +++++++++++++++++++++++++++++++++++++++-- 4 files changed, 238 insertions(+), 35 deletions(-) diff --git a/CHANGES b/CHANGES index 9f042a29..ffd77819 100644 --- a/CHANGES +++ b/CHANGES @@ -26,6 +26,15 @@ directly. {func}`~libvt.modes.is_private_mode_supported` exposes profile mode support queries, and {class}`~libvt.snapshot.SnapshotDict` types the dictionary returned by {meth}`~libvt.snapshot.Snapshot.to_dict`. +### Fixes + +#### Reject attribute deletion on snapshots (#198) + +Deleting an attribute on {class}`~libvt.snapshot.Snapshot` now raises +{exc}`AttributeError`, keeping cached frames returned by +{attr}`~libvt.terminal.Terminal.committed` and +{meth}`~libvt.terminal.Terminal.snapshot` intact for subsequent readers. + ### Documentation #### Split API reference into per-module pages diff --git a/src/libvt/snapshot.py b/src/libvt/snapshot.py index e50cb1df..55b3bafa 100644 --- a/src/libvt/snapshot.py +++ b/src/libvt/snapshot.py @@ -424,40 +424,44 @@ def _make_snapshot( pen: _VtPen = _DEFAULT_VT_PEN, ) -> Snapshot: snap = object.__new__(Snapshot) - object.__setattr__(snap, "_frozen", False) - snap._rows = rows + set_attr = object.__setattr__ hist_obj = _FrozenHistory.from_sequence(history) - snap._history = hist_obj - snap._cols = cols - snap._profile = profile - snap._scroll_region = scroll_region - snap._vt_pen = pen eff_scrolled = ( (0 if active_is_alt else len(hist_obj)) if scrolled_total is None else scrolled_total ) - snap._scrolled_total = eff_scrolled - snap._evicted_total = ( + eff_evicted = ( (0 if active_is_alt else max(0, eff_scrolled - len(hist_obj))) if evicted_total is None else evicted_total ) - snap._unwrapped_text_cache = None - snap.cursor = cursor - snap.title = title - snap.cwd = cwd - snap.cwd_uri = cwd_uri - snap.modes = modes - snap.active_is_alt = active_is_alt - snap.prompt_zones = prompt_zones - snap.program_status = program_status - snap.program_statuses = types.MappingProxyType(dict(program_statuses)) - snap.generation = generation - snap.appearance = appearance - snap.images = types.MappingProxyType(dict(images) if images is not None else {}) - snap.placements = placements - object.__setattr__(snap, "_frozen", True) + set_attr(snap, "_rows", rows) + set_attr(snap, "_history", hist_obj) + set_attr(snap, "_cols", cols) + set_attr(snap, "_profile", profile) + set_attr(snap, "_scroll_region", scroll_region) + set_attr(snap, "_vt_pen", pen) + set_attr(snap, "_scrolled_total", eff_scrolled) + set_attr(snap, "_evicted_total", eff_evicted) + set_attr(snap, "_unwrapped_text_cache", None) + set_attr(snap, "cursor", cursor) + set_attr(snap, "title", title) + set_attr(snap, "cwd", cwd) + set_attr(snap, "cwd_uri", cwd_uri) + set_attr(snap, "modes", modes) + set_attr(snap, "active_is_alt", active_is_alt) + set_attr(snap, "prompt_zones", prompt_zones) + set_attr(snap, "program_status", program_status) + set_attr(snap, "program_statuses", types.MappingProxyType(dict(program_statuses))) + set_attr(snap, "generation", generation) + set_attr(snap, "appearance", appearance) + set_attr( + snap, + "images", + types.MappingProxyType(dict(images) if images is not None else {}), + ) + set_attr(snap, "placements", placements) return snap @@ -533,7 +537,6 @@ class Snapshot: __slots__ = ( "_cols", "_evicted_total", - "_frozen", "_history", "_profile", "_rows", @@ -558,7 +561,6 @@ class Snapshot: _cols: int _evicted_total: int - _frozen: bool _history: _FrozenHistory _profile: Profile _rows: tuple[_Row, ...] @@ -585,12 +587,15 @@ def __new__(cls, *args: object, **kwargs: object) -> t.NoReturn: msg = "Snapshot cannot be instantiated directly; call Terminal.snapshot()" raise TypeError(msg) - def __setattr__(self, name: str, value: object) -> None: - """Reject attribute mutation once snapshot initialization completes.""" - if getattr(self, "_frozen", False): - msg = f"Snapshot is immutable; cannot assign {name!r}" - raise AttributeError(msg) - object.__setattr__(self, name, value) + def __setattr__(self, name: str, value: object) -> t.NoReturn: + """Disallow attribute mutation on immutable snapshots.""" + msg = f"Snapshot is immutable; cannot assign {name!r}" + raise AttributeError(msg) + + def __delattr__(self, name: str) -> t.NoReturn: + """Disallow attribute deletion on immutable snapshots.""" + msg = f"Snapshot is immutable; cannot delete {name!r}" + raise AttributeError(msg) @property def profile(self) -> Profile: diff --git a/tests/test_screen.py b/tests/test_screen.py index c203fab6..33db6428 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -3,7 +3,9 @@ from __future__ import annotations import collections.abc +import copy import gc +import pickle import random import sys import time @@ -1266,3 +1268,85 @@ def test_row_view_runs_fast_paths_match_frozen_row() -> None: r_distinct_ext_runs = RowView(r_distinct_ext).runs assert len(r_distinct_ext_runs) == 2 assert r_distinct_ext_runs[0].text == "ab日" + + +def test_row_and_region_views_reject_public_mutation_and_support_copy_pickle() -> None: + """Read-only grid views reject public assignment/deletion and stay copyable.""" + term = libvt.Terminal(rows=2, cols=6) + term.feed(b"hist0\r\nrow 1\r\nrow 2") + snap = term.committed + + for row in (term.screen[0], snap[0]): + assert not hasattr(row, "__dict__") + with pytest.raises(AttributeError): + row.text = "mutated" # ty: ignore[invalid-assignment] + with pytest.raises(AttributeError): + del row.text # ty: ignore[invalid-assignment] + for attr in ( + "columns", + "used", + "text_used", + "full_row", + "wrapped", + "text", + "display_text", + "runs", + "extra_attr", + ): + with pytest.raises(AttributeError): + setattr(row, attr, None) + with pytest.raises(AttributeError): + delattr(row, attr) + + frozen_row = snap[0] + assert copy.copy(frozen_row) == frozen_row + assert copy.deepcopy(frozen_row) == frozen_row + assert pickle.loads(pickle.dumps(frozen_row)) == frozen_row + + for region in (term.screen[0:2, 0:4], snap[0:2, 0:4], snap.viewport(offset=1)): + assert not hasattr(region, "__dict__") + with pytest.raises(AttributeError): + region.rows = 1 # ty: ignore[invalid-assignment] + with pytest.raises(AttributeError): + del region.rows # ty: ignore[invalid-assignment] + for attr in ( + "columns", + "rows", + "cols", + "lines", + "display_lines", + "text", + "unwrapped_text", + "extra_attr", + ): + with pytest.raises(AttributeError): + setattr(region, attr, None) + with pytest.raises(AttributeError): + delattr(region, attr) + + frozen_region = snap[0:2, 0:4] + assert copy.copy(frozen_region).lines == frozen_region.lines + assert copy.deepcopy(frozen_region).lines == frozen_region.lines + assert pickle.loads(pickle.dumps(frozen_region)).lines == frozen_region.lines + + hist = snap.history + missing_attr = "extra_attr" + with pytest.raises(AttributeError): + setattr(hist, missing_attr, None) + with pytest.raises(AttributeError): + delattr(hist, missing_attr) + assert copy.copy(hist) == hist + assert copy.deepcopy(hist) == hist + assert pickle.loads(pickle.dumps(hist)) == hist + + cell = snap[0, 0] + with pytest.raises(AttributeError): + del cell.text # ty: ignore[invalid-assignment] + assert copy.copy(cell) == cell + assert pickle.loads(pickle.dumps(cell)) == cell + + cur = snap.cursor + with pytest.raises(AttributeError): + del cur.col # ty: ignore[invalid-assignment] + assert copy.copy(cur) == cur + assert pickle.loads(pickle.dumps(cur)) == cur diff --git a/tests/test_terminal.py b/tests/test_terminal.py index bc00dbac..1940ac9f 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -48,7 +48,7 @@ TerminalRecorder, find_flight_recorder, ) -from libvt.screen import CursorShape, RowView, ScrollRegion, format_rows_text +from libvt.screen import CursorShape, RowView, Screen, ScrollRegion, format_rows_text from libvt.style import AnsiColor, Hyperlink from libvt.terminal import ( Formatter, @@ -59,7 +59,7 @@ StopOn, SyncToken, ) -from libvt.testing import format_flight_recorder +from libvt.testing import format_flight_recorder, serialize_vt_snapshot class TmuxVersionCase(t.NamedTuple): @@ -364,7 +364,7 @@ def test_formatters_bce_xss_and_snapshot_immutability() -> None: assert snap.to_dict()["rows"] == 2 with pytest.raises(AttributeError): - snap.title = "mutated" + snap.title = "mutated" # ty: ignore[invalid-assignment] with pytest.raises(TypeError): t.cast("dict[str, object]", snap.program_statuses)["x"] = None @@ -2273,3 +2273,108 @@ def test_strided_memoryview_buffer_and_snapshot_format_profile_default() -> None vt_default = snap.format(OutputFormat.VT, profile=DEFAULT_PROFILE) assert "\x1b]10;rgb:0c0c/2222/3838\x1b\\" in vt_default assert "\x1b]11;rgb:c8c8/d2d2/dcdc\x1b\\" in vt_default + + +def test_snapshot_rejects_attribute_deletion_and_keeps_cached_frames_intact() -> None: + """Reject attribute deletion on cached and held snapshots and sibling tokens.""" + term = libvt.Terminal(rows=1, cols=4) + term.feed(b"A") + frame = term.committed + expected_box = ( + "size=4x1 cursor=(0,1,vis=True) alt=False modes=[]\n┌────┐\n│A │\n└────┘" + ) + expected_after_box = ( + "size=4x1 cursor=(0,1,vis=True) alt=False modes=[]\n┌────┐\n│B │\n└────┘" + ) + assert serialize_vt_snapshot(frame) == expected_box + + with pytest.raises(AttributeError, match="cannot delete 'cursor'"): + del frame.cursor # ty: ignore[invalid-assignment] + assert term.committed is frame + assert term.snapshot() is frame + assert serialize_vt_snapshot(term) == expected_box + assert frame.to_dict()["cursor"]["col"] == 1 + assert frame.format(OutputFormat.PLAIN) == "A" + assert frame.unwrapped_text == "A" + + # Reject assignment and deletion across every slot, property, and unknown name. + assert not hasattr(frame, "__dict__") + assert not hasattr(frame, "_frozen") + assert not dataclasses.is_dataclass(Snapshot) + for attr in ( + *Snapshot.__slots__, + "rows", + "cols", + "lines", + "display_lines", + "text", + "unwrapped_text", + "history", + "profile", + "scrolled_total", + "evicted_total", + "nonexistent_attr", + ): + with pytest.raises(AttributeError, match="Snapshot is immutable"): + delattr(frame, attr) + with pytest.raises(AttributeError, match="Snapshot is immutable"): + setattr(frame, attr, None) + assert term.committed is frame + assert serialize_vt_snapshot(term) == expected_box + assert frame.unwrapped_text == "A" + + # ?2026 synchronized hold keeps both held committed and live snapshots intact. + term.feed(b"\x1b[?2026h\x1b[2J\x1b[HB") + held = term.committed + live = term.snapshot() + assert held is not live + for target, expected_line in ((held, "A"), (live, "B")): + with pytest.raises(AttributeError, match="cannot delete 'cursor'"): + del target.cursor # ty: ignore[invalid-assignment] + with pytest.raises(AttributeError, match="cannot assign 'cursor'"): + target.cursor = target.cursor # ty: ignore[invalid-assignment] + assert target.lines == (expected_line,) + assert term.committed is held + assert term.snapshot() is live + assert serialize_vt_snapshot(term) == expected_box + + term.feed(b"\x1b[?2026l") + committed_after = term.committed + with pytest.raises(AttributeError, match="cannot delete 'cursor'"): + del committed_after.cursor # ty: ignore[invalid-assignment] + assert term.committed is committed_after + assert serialize_vt_snapshot(term) == expected_after_box + assert serialize_vt_snapshot(frame) == expected_box + assert serialize_vt_snapshot(held) == expected_box + + # Subsequent mutations stay isolated from previously captured snapshots. + term.feed(b"C") + assert serialize_vt_snapshot(committed_after) == expected_after_box + assert term.committed.lines == ("BC",) + assert term.committed.cursor.col == 2 + + # Sibling Screen.snapshot() caller shares Snapshot's immutability and CoW rules. + scr = Screen(rows=1, cols=4) + scr.put_text(0, 0, "S") + scr_snap = scr.snapshot() + with pytest.raises(AttributeError, match="cannot delete 'cursor'"): + del scr_snap.cursor # ty: ignore[invalid-assignment] + scr.put_text(0, 0, "X") + assert scr_snap.lines == ("S",) + assert scr.lines == ("X",) + + # Sibling SyncToken and ScreenDelta reject deletion and preserve copy/pickle. + tok = term.sync_token() + with pytest.raises(AttributeError, match="cannot delete attribute '_state'"): + del tok._state # ty: ignore[invalid-assignment] + assert copy.copy(tok) is tok + assert copy.deepcopy(tok) is tok + assert pickle.loads(pickle.dumps(tok)) == tok + + delta = term.changes_since(tok) + with pytest.raises(AttributeError): + del delta.snapshot # ty: ignore[invalid-assignment] + with pytest.raises(AttributeError): + delattr(delta, "dirty_rows") + assert delta.snapshot is term.snapshot() + assert copy.copy(delta) == delta