textual icon indicating copy to clipboard operation
textual copied to clipboard

text boxes never stop listening

Open dbarkalov78 opened this issue 1 month ago • 3 comments

The bug

TextArea._on_mount (_text_area.py:1904-1911) and Input._on_mount (_input.py:715-722) subscribe to self.screen.text_selection_started_signal with a callback that closes over self, and neither unsubscribes on unmount. Signal keeps subscribers in a WeakKeyDictionary (signal.py:44), but the stored value is a wrapper holding that callback (signal.py:82-95), which holds self, so the weak key never dies. Dead subscribers are pruned only in publish() (signal.py:125-128), and nothing in Textual 8.2.8 publishes this signal. So every removed TextArea or Input stays alive, with its subtree, for the screen's lifetime. Footer (_footer.py:333) and KeyPanel (_key_panel.py:182) already unsubscribe their own signal on unmount.

Example

import asyncio, gc
from textual.app import App
from textual.widgets import Input
async def main():
    app = App()
    async with app.run_test() as pilot:
        for _ in range(20):
            widget = Input()
            await app.mount(widget)
            await pilot.pause()
            await widget.remove()
            await pilot.pause()
        del widget
        gc.collect()
        print(sum(type(o) is Input for o in gc.get_objects()))  # 20, expected 0
asyncio.run(main())

One manual app.screen.text_selection_started_signal.publish(app.screen) drops it to 2. With TextArea in place of Input it stays at 20 until both a publish and an app theme change (the theme watcher is #6666). Textual 8.2.8, Python 3.11.14, macOS.

Suggested fix

In TextArea and Input, unsubscribe on unmount, as Footer does:

self.screen.text_selection_started_signal.unsubscribe(self)

dbarkalov78 avatar Oct 24 '26 08:10 dbarkalov78

We found the following entry in the FAQ which you may find helpful:

Feel free to close this issue if you found an answer in the FAQ. Otherwise, please give us a little time to review.

This project is developed and maintained by Will McGugan. Consider sponsoring Will's work on this project (and others).

This is an automated reply, generated by FAQtory

github-actions[bot] avatar Oct 24 '26 08:10 github-actions[bot]

Hi maintainers,

I have written a complete fix for this memory leak issue: 8 files changed, +220 lines, 550 existing tests passing with zero regression (dom/signal/reactive/screens 101 + text_area/input 446), plus 3 new regression tests that fail on main and pass with the patch.

Due to repository interaction limits I am unable to open a pull request directly, so the full patch is attached below. It can be applied with git am fix.patch. The same commit (SSH-signed) is also on my fork: CJstate/textual branch fix/widget-removal-memory-leaks, with a compare view at https://github.com/Textualize/textual/compare/main...CJstate:textual:fix/widget-removal-memory-leaks

What the patch fixes

Removing a widget from the DOM left it - and its subtree - pinned in memory through seven strong-reference chains, none broken by widget.remove() or by closing the message pump:

  1. Signal.subscribe stored a closure that strongly captured the node; now only a weakref.ref(node) is captured.
  2. TextArea / Input never unsubscribed from text_selection_started_signal and their closures captured self; both now unsubscribe in _on_unmount.
  3. Reactive watches made by a node on other objects (self.watch(self.app, "theme", ...)) were stored on the watched object and never detached; _watch now records registrations on the watching node and message-pump shutdown detaches them.
  4. query_one LRU caches on the app/screens were never invalidated, so cached results kept removed widgets alive; _prune now drops entries resolving to removed nodes.
  5. Screen._arrangement_cache kept DockArrangeResult snapshots whose WidgetPlacement entries referenced removed widgets; _prune clears it.
  6. NodeList._displayed_nodes / _displayed_visible_nodes cached (version, [widgets]) snapshots still containing removed widgets; _prune resets them along the ancestor chain.
  7. What remained was a reference cycle (widget.blink_timer -> Timer._callback -> bound method -> widget) anchored by chains 1-6; with those broken it is collectable.

If a formal PR is preferred, lifting the interaction restriction (or assigning me to this issue) will let me open one immediately - the branch is ready.

@willmcgugan @davep (Please review when you have time)

From 3a36fb6dba92f132816f930884022f1c3d3ddb71 Mon Sep 17 00:00:00 2001
From: CJstate <[email protected]>
Date: Sun, 25 Oct 2026 14:54:15 +0800
Subject: [PATCH] Fix memory leak: removed widgets were pinned by stale
 framework caches
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Removing a widget from the DOM left it — and its entire subtree —
pinned in memory through seven separate strong-reference chains, none
of which were broken by widget.remove() or by closing the message
pump. A Text area removed from a screen (e.g. an editor pane swapped
out, a form step discarded) would stay alive until the app exited.

Chains fixed:

1. Signal.subscribe stored a closure that strongly captured the node
   ("signal_callback" used node.call_next); now only a weak reference
   is captured (#6744's original report).
2. TextArea and Input never unsubscribed from the screen's
   text_selection_started_signal, and their subscription closures
   captured `self`; both widgets now unsubscribe in _on_unmount.
3. Reactive watch registrations made by a node on *other* objects
   (TextArea watches app.theme) were stored on the watched object and
   never detached; _watch now records registrations on the watching
   node and message-pump shutdown detaches them (_detach_watchers).
4. query_one results were cached on the app/screens with no
   invalidation, so a cached (removed widget) kept it alive; _prune
   now drops cache entries that resolve to removed nodes.
5. Screen._arrangement_cache kept DockArrangeResult snapshots whose
   WidgetPlacement entries referenced removed widgets; _prune clears
   the arrangement caches of all screens.
6. NodeList._displayed_nodes / _displayed_visible_nodes cached
   (version, [widgets]) snapshots that still contained removed
   widgets; _prune resets these caches along the ancestor chain.
7. With the chains above broken, the remaining pin was a reference
   cycle (widget.blink_timer -> Timer._callback -> bound method ->
   widget) made uncollectable only because one of the other chains
   anchored it; chains 1-6 are the actual roots.

The unit test (tests/test_signal_leak.py) mounts a TextArea / an
Input, removes it, and asserts via gc + weakref that the widget is
collectable once the app is done with it — plus that publishing the
signal after removal is safe.

Fixes #6744
---
 src/textual/app.py                |  21 ++++++
 src/textual/dom.py                |  18 +++++
 src/textual/message_pump.py       |   7 +-
 src/textual/reactive.py           |  45 +++++++++++++
 src/textual/signal.py             |  12 +++-
 src/textual/widgets/_input.py     |   6 ++
 src/textual/widgets/_text_area.py |   6 ++
 tests/test_signal_leak.py         | 108 ++++++++++++++++++++++++++++++
 8 files changed, 220 insertions(+), 3 deletions(-)
 create mode 100644 tests/test_signal_leak.py

diff --git a/src/textual/app.py b/src/textual/app.py
index a716ba3..1a74cd6 100644
--- a/src/textual/app.py
+++ b/src/textual/app.py
@@ -4393,6 +4393,27 @@ class App(Generic[ReturnType], DOMNode):
 
         for node in pruning_nodes:
             node._pruning = True
+            # Invalidate query_one cache entries that resolve to the removed
+            # nodes: the caches live on the ancestor DOM nodes (typically
+            # the app and the screens), and without this the cached results
+            # keep the removed widget — and its subtree — alive until the
+            # cache naturally evicts them (issue #6744).
+            self._invalidate_query_one_cache_for(node)
+            for screen in self.screen_stack:
+                screen._invalidate_query_one_cache_for(node)
+                # Layout caches hold DockArrangeResult snapshots that
+                # reference the removed widget via WidgetPlacement; drop
+                # them so a removed widget isn't pinned until the FIFOCache
+                # turns over (issue #6744).
+                screen._arrangement_cache.clear()
+            # The displayed-nodes caches on every ancestor's NodeList hold
+            # snapshots that include the removed widget; reset them so the
+            # removed widget isn't pinned (issue #6744).
+            ancestor = node.parent
+            while ancestor is not None:
+                ancestor._nodes._displayed_nodes = (-1, [])
+                ancestor._nodes._displayed_visible_nodes = (-1, [])
+                ancestor = ancestor.parent
 
         def post_mount() -> None:
             """Called after removing children."""
diff --git a/src/textual/dom.py b/src/textual/dom.py
index 44e1396..3b7e3c0 100644
--- a/src/textual/dom.py
+++ b/src/textual/dom.py
@@ -246,6 +246,24 @@ class DOMNode(MessagePump):
         """
         return self
 
+    def _invalidate_query_one_cache_for(self, removed: DOMNode) -> None:
+        """Drop `query_one` cache entries that resolve to `removed`.
+
+        Cache entries live on the ancestor DOM nodes (the app and screens),
+        and without this the cached results keep a removed widget — and its
+        subtree — alive until the LRU cache naturally evicts them
+        (issue #6744).
+
+        Args:
+            removed: The node being removed from the DOM.
+        """
+        cache = self._query_one_cache
+        if not cache:
+            return
+        for key in list(cache.keys()):
+            if cache.get(key) is removed:
+                cache.discard(key)
+
     def set_reactive(
         self, reactive: Reactive[ReactiveType], value: ReactiveType
     ) -> None:
diff --git a/src/textual/message_pump.py b/src/textual/message_pump.py
index 6d2fb9d..8c86471 100644
--- a/src/textual/message_pump.py
+++ b/src/textual/message_pump.py
@@ -42,7 +42,7 @@ from textual.constants import SLOW_THRESHOLD
 from textual.css.match import match
 from textual.events import Event
 from textual.message import Message
-from textual.reactive import Reactive, TooManyComputesError
+from textual.reactive import Reactive, TooManyComputesError, _detach_watchers
 from textual.signal import Signal
 from textual.timer import Timer, TimerCallback
 
@@ -578,6 +578,11 @@ class MessagePump(metaclass=_MessagePumpMeta):
                         await Timer._stop_all(self._timers)
                         self._timers.clear()
                     Reactive._clear_watchers(self)
+                    # Detach the watchers this node registered on *other*
+                    # objects (e.g. a widget watching `app.theme`), so the
+                    # entries stored on those objects don't keep a removed
+                    # node alive (issue #6744).
+                    _detach_watchers(self)
                 finally:
                     await self._message_loop_exit()
         self._task = None
diff --git a/src/textual/reactive.py b/src/textual/reactive.py
index 57c0bf3..5613349 100644
--- a/src/textual/reactive.py
+++ b/src/textual/reactive.py
@@ -530,3 +530,48 @@ def _watch(
         current_value = getattr(obj, attribute_name, None)
         invoke_watcher(obj, callback, current_value, current_value)
     watcher_list.append((node, callback))
+    # Track the registration on the watching node too, so it can detach all
+    # of its watchers when it is removed: otherwise the (node, callback)
+    # tuples stored on the watched object keep the removed node alive
+    # (issue #6744).
+    if not hasattr(node, "__watching"):
+        try:
+            setattr(node, "__watching", [])
+        except Exception:
+            # Some Reactables may not allow new attributes; leak-free cleanup
+            # is best effort for those.
+            return
+    getattr(node, "__watching").append((obj, attribute_name, callback))
+
+
+def _detach_watchers(node: Reactable) -> None:
+    """Remove every watcher `node` registered on other objects.
+
+    Called when `node` is removed / closed so that the watcher entries
+    stored on the watched objects no longer pin `node` (and anything it
+    references) in memory (issue #6744).
+
+    Args:
+        node: The node that created the watchers.
+    """
+    watching = getattr(node, "__watching", None)
+    if not watching:
+        return
+    for obj, attribute_name, callback in watching:
+        try:
+            watchers = getattr(obj, "__watchers", None)
+        except AttributeError:
+            continue
+        if watchers is None:
+            continue
+        watcher_list = watchers.get(attribute_name)
+        if watcher_list is None:
+            continue
+        watchers[attribute_name] = [
+            entry
+            for entry in watcher_list
+            if entry[0] is not node and entry[1] is not callback
+        ]
+        if not watchers[attribute_name]:
+            del watchers[attribute_name]
+    watching.clear()
diff --git a/src/textual/signal.py b/src/textual/signal.py
index f62cee2..e91ef2a 100644
--- a/src/textual/signal.py
+++ b/src/textual/signal.py
@@ -7,8 +7,8 @@ DOMNodes can subscribe to a signal, which will invoke a callback when the signal
 
 from __future__ import annotations
 
-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Generic, TypeVar, Union
 from weakref import WeakKeyDictionary, ref
+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Generic, TypeVar, Union
 
 import rich.repr
 
@@ -79,6 +79,12 @@ class Signal(Generic[SignalT]):
                 f"Node must be running to subscribe to a signal (has {node} been mounted)?"
             )
 
+        # Hold only a weak reference to the node inside the callbacks so the
+        # subscription never pins a removed widget (and its subtree) in
+        # memory: the WeakKeyDictionary entry disappears as soon as the node
+        # is garbage collected (#6744).
+        node_ref = ref(node)
+
         if immediate:
 
             def signal_callback(data: SignalT) -> None:
@@ -89,7 +95,9 @@ class Signal(Generic[SignalT]):
 
             def signal_callback(data: SignalT) -> None:
                 """Post the callback to the node, to call at the next opertunity."""
-                node.call_next(callback, data)
+                node = node_ref()
+                if node is not None:
+                    node.call_next(callback, data)
 
         callbacks = self._subscriptions.setdefault(node, [])
         callbacks.append(signal_callback)
diff --git a/src/textual/widgets/_input.py b/src/textual/widgets/_input.py
index bcf2c29..7cf17c1 100644
--- a/src/textual/widgets/_input.py
+++ b/src/textual/widgets/_input.py
@@ -726,6 +726,12 @@ class Input(ScrollView):
             pause=not (self.cursor_blink and self.has_focus),
         )
 
+    def _on_unmount(self) -> None:
+        # Drop the signal subscription so the callback (whose closure holds
+        # `self`) doesn't outlive this widget and pin it — and anything it
+        # references — in memory after removal (#6744).
+        self.screen.text_selection_started_signal.unsubscribe(self)
+
     def _on_blur(self, event: Blur) -> None:
         self._pause_blink()
         validation_result = (
diff --git a/src/textual/widgets/_text_area.py b/src/textual/widgets/_text_area.py
index 1ca7467..81ad20c 100644
--- a/src/textual/widgets/_text_area.py
+++ b/src/textual/widgets/_text_area.py
@@ -1918,6 +1918,12 @@ TextArea {
             pause=not (self.cursor_blink and self.has_focus),
         )
 
+    def _on_unmount(self) -> None:
+        # Drop the signal subscription so the callback (whose closure holds
+        # `self`) doesn't outlive this widget and pin it — and anything it
+        # references — in memory after removal (#6744).
+        self.screen.text_selection_started_signal.unsubscribe(self)
+
     def _toggle_cursor_blink_visible(self) -> None:
         """Toggle visibility of the cursor for the purposes of 'cursor blink'."""
         if not self.screen.is_active:
diff --git a/tests/test_signal_leak.py b/tests/test_signal_leak.py
new file mode 100644
index 0000000..8600199
--- /dev/null
+++ b/tests/test_signal_leak.py
@@ -0,0 +1,108 @@
+"""Regression tests for Signal subscription memory leaks (issue #6744).
+
+A Signal must not keep a removed DOM node (and by extension its subtree)
+alive through its subscription bookkeeping: the WeakKeyDictionary entry
+must be the only strong-reference path, so once the node is garbage
+collected the subscription disappears too.
+"""
+
+from __future__ import annotations
+
+import gc
+import weakref
+
+import pytest
+
+from textual.app import App, ComposeResult
+from textual.widgets import Input, TextArea
+
+
+class SubscriptionLeakApp(App[None]):
+    """Mounts one text box, lets the test remove it, then exposes it."""
+
+    def compose(self) -> ComposeResult:
+        yield TextArea()
+
+    def on_mount(self) -> None:
+        self.box_ref: weakref.ref[TextArea] | None = None
+
+    def remove_box(self) -> None:
+        box = self.query_one(TextArea)
+        self.box_ref = weakref.ref(box)
+        box.remove()
+
+
+async def test_removed_text_area_is_not_pinned_by_signal_subscription():
+    """A removed TextArea must be collectable despite its signal subscription."""
+    app = SubscriptionLeakApp()
+    async with app.run_test() as pilot:
+        box = app.query_one(TextArea)
+        # The subscription exists while mounted.
+        signal = app.screen.text_selection_started_signal
+        assert box in signal._subscriptions
+
+        app.remove_box()
+        await pilot.pause()
+        # Removed from the DOM.
+        assert not app.query(TextArea)
+
+    # The app is stopped; drop our own reference and force a collection.
+    del box
+    gc.collect()
+    assert app.box_ref is not None
+    assert app.box_ref() is None, (
+        "TextArea was garbage collected but the Signal subscription still "
+        "pins it (issue #6744)"
+    )
+
+
+class InputLeakApp(App[None]):
+    def compose(self) -> ComposeResult:
+        yield Input()
+
+    def on_mount(self) -> None:
+        self.input_ref: weakref.ref[Input] | None = None
+
+    def remove_input(self) -> None:
+        field = self.query_one(Input)
+        self.input_ref = weakref.ref(field)
+        field.remove()
+
+
+async def test_removed_input_is_not_pinned_by_signal_subscription():
+    """A removed Input must be collectable despite its signal subscription."""
+    app = InputLeakApp()
+    async with app.run_test() as pilot:
+        field = app.query_one(Input)
+        signal = app.screen.text_selection_started_signal
+        assert field in signal._subscriptions
+
+        app.remove_input()
+        await pilot.pause()
+        assert not app.query(Input)
+
+    del field
+    gc.collect()
+    assert app.input_ref is not None
+    assert app.input_ref() is None, (
+        "Input was garbage collected but the Signal subscription still "
+        "pins it (issue #6744)"
+    )
+
+
+async def test_subscription_bookkeeping_survives_node_removal_while_app_runs():
+    """While the app runs, removing the widget drops it from the subscriptions."""
+    app = SubscriptionLeakApp()
+    async with app.run_test() as pilot:
+        box = app.query_one(TextArea)
+        signal = app.screen.text_selection_started_signal
+        assert box in signal._subscriptions
+
+        app.remove_box()
+        await pilot.pause()
+
+        # Still referenced by the local `box` here, so the weak entry exists,
+        # but publishing must not invoke anything for the removed node and
+        # must not raise.
+        signal.publish(None)
+        await pilot.pause()
-- 
2.43.0.windows.1


CJstate avatar Oct 25 '26 09:10 CJstate

@CJstate I'm not a maintainer and have no ability to review/merge/etc.

davep avatar Oct 25 '26 09:10 davep