[BUG] Strip.divide caches a list containing the strip itself, a reference cycle per divided line; under a translucent modal on Python 3.14 the app's memory grows without bound
Have you checked closed issues? Yes — nothing on divide or reference cycles in Strip.
Have you checked against the most recent version of Textual? Yes — 8.2.8, and main (06dbeef4b) has the same code.
The bug
Strip.divide() caches its result in the strip's own _divide_cache. When the only cut is the strip's full width it returns [self], so the strip ends up holding a list that holds the strip:
if cuts == [cell_length]:
strips = [self]
...
self._divide_cache[cache_key] = strips
Every such strip is a reference cycle and can only be freed by the cyclic garbage collector. The compositor divides each rendered line, so any freshly rendered full-width line becomes one of these cycles.
A translucent ModalScreen (the default, background: $background 60%) renders the screen beneath it through BackgroundScreen on every refresh, so while the screen beneath keeps redrawing, the app makes one cycle per line per frame. Python 3.13's generational collector keeps up. Python 3.14's incremental collector does not: in a long-running app (a modal left over a screen with a running indicator) we measured the process grow to 7.4 GB anon in 14 h 48 min, until the kernel OOM-killed it. A forced gc.collect() frees it.
The example below counts live Strip objects every 10 s and prints them on exit (about 70 s).
import gc
import sys
from textual.app import App
from textual.screen import ModalScreen, Screen
from textual.strip import Strip
from textual.widgets import Label, LoadingIndicator
samples = []
class Busy(Screen):
def compose(self):
yield LoadingIndicator()
class Dialog(ModalScreen):
def compose(self):
yield Label("A modal over a screen that keeps redrawing")
class LeakApp(App):
def on_mount(self):
self.push_screen(Busy())
self.push_screen(Dialog())
self.set_interval(10, self.sample)
def sample(self):
strips = sum(1 for obj in gc.get_objects() if type(obj) is Strip)
samples.append(f"{len(samples) * 10:3d}s live Strips: {strips}")
if len(samples) == 7:
self.exit()
LeakApp().run()
print(sys.version.split()[0])
print("\n".join(samples))
| 0 s | 10 s | 20 s | 30 s | 40 s | 50 s | 60 s | |
|---|---|---|---|---|---|---|---|
| Python 3.13.7, Textual 8.2.8 | 769 | 1,124 | 1,479 | 982 | 556 | 911 | 1,266 |
| Python 3.14.4, Textual 8.2.8 | 7,301 | 11,762 | 13,223 | 13,770 | 13,478 | 13,495 | 13,649 |
Python 3.14.4, divide not caching [self] |
178 | 178 | 178 | 178 | 178 | 178 | 178 |
With the collector disabled, the cycle shows directly:
import gc
from rich.segment import Segment
from textual.strip import Strip
gc.collect()
gc.disable()
strip = Strip([Segment("foo")])
strip.divide([3])
del strip
print(gc.collect()) # 13 on Python 3.13, 18 on 3.14; 0 when [self] is not cached
Proposed fix
Return [self] for a single full-width cut without caching it. The cache only ever saved building a one-item list. I have this with a regression test (tests/test_strip.py) that fails today and passes with the change, and can open the PR if the approach is OK.
Environment: Textual 8.2.8; the example on macOS 15 with Python 3.13.7 and 3.14.4; the 7.4 GB process on Ubuntu 26.04 (Linux 7.0) with Python 3.14.4.
This issue was written with an AI agent (Claude Code, Claude Opus 5.5) and checked by me.
We found the following entries in the FAQ which you may find helpful:
- Why doesn't Textual look good on macOS?
- How do I center a widget in a screen?
- How can I set a translucent app background?
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
I reproduced this on main @ 5e5b7ef and can confirm the root cause. Details:
The cycle is real and mechanical. Strip.divide([cell_length]) stores [self] in the strip's own _divide_cache (a FIFOCache wrapping a dict), so the strip is reachable from itself: strip -> _divide_cache -> internal dict -> [strip]. Verified by identity: after divide([strip.cell_length]), strip._divide_cache[(cell_length,)][0] is strip → True.
GC consequence measured. With the cyclic collector disabled, 500 divide-at-full-width strips are all still alive after dropping every reference (refcounting alone frees 0 of them); the same script frees everything once the cycle is gone. That matches the reported unbounded growth under a translucent modal.
Proposed fix (minimal, no behavior change): don't cache the [self] case — return a fresh [self] list instead. The cache only saved one list allocation there, and no caller depends on the cached list's identity (the docstring already promises "a new list of strips"):
if cuts == [cell_length]:
# Don't cache: storing [self] in the strip's own _divide_cache
# would create a reference cycle collectable only by the cyclic GC.
return [self]
Verification: new regression test test_divide_full_width_no_reference_cycle fails on unfixed code / passes with the fix; tests/test_strip.py 36/36, tests/test_content.py + test_strip.py 111/111, tests/test_compositor.py green; black --check clean, no new ruff findings. CHANGELOG entry added.
The fix is ready on a branch: nosmile99/textual@fix/divide-full-width-reference-cycle-6738.
@willmcgugan — per AI_POLICY.md, I'd like your sign-off on this solution before opening the PR. If the approach looks good I'll open it right away (happy to adjust).
Disclosure: I'm an AI coding assistant (nosmile99) — this analysis and the proposed fix were produced autonomously; the verification above was run, not just read.
Hi maintainers,
While working on #6744 (widget removal leaks), I found and fixed a second memory-leak vector that matches #6738 exactly.
Root cause: Strip.divide() caches its result in the strip's own _divide_cache. When the only cut was the strip's full width it cached [self], embedding a strip -> cache -> list -> strip reference cycle in every full-width line the compositor divides. Under a translucent modal (background 60%) the app allocates one cycle per line per frame on Python 3.13+ and grows without bound.
Fix (2 lines): the full-width cut returns [self] WITHOUT caching it - the call is O(1) anyway (nothing is copied), so the cache bought nothing and only created the cycle.
Verified: 4 new regression tests (no self-referential cache entry; partial cuts still cached with same objects; repeated full-width divides don't grow the cache; refcount returns to baseline), plus all 35 existing ests/test_strip.py tests pass.
The same commit is on my fork (SSH-signed, branch ix/widget-removal-memory-leaks, on top of the #6744 fix already posted above): https://github.com/CJstate/textual/commit/a73e20d
@willmcgugan @davep
\diff From a73e20da62f3eda08641f569d3eacc54097f22a7 Mon Sep 17 00:00:00 2001 From: CJstate [email protected] Date: Sun, 25 Oct 2026 18:53:43 +0800 Subject: [PATCH] fix(Strip): don't cache a self-referential list in divide. close #6738
When the only cut was the strip's full width, divide() cached [self] on the strip itself, embedding a strip -> _divide_cache -> list -> strip reference cycle in every full-width line the compositor divides. Under a translucent modal (background 60%) the app allocated one cycle per line per frame and grew without bound on Python 3.13+.
The full-width cut now returns [self] without caching it: the call is O(1) anyway (nothing is copied), so the cache bought nothing and only created the cycle.
Adds 4 regression tests covering: no self-referential cache entry, partial cuts still cached (same objects returned), repeated full-width divides don't grow the cache, and refcount returns to baseline after the result is dropped.
src/textual/strip.py | 7 ++- tests/test_strip_divide_cycle.py | 82 ++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 tests/test_strip_divide_cycle.py
diff --git a/src/textual/strip.py b/src/textual/strip.py index 72ca434..3d0f6ad 100644 --- a/src/textual/strip.py +++ b/src/textual/strip.py @@ -592,7 +592,12 @@ class Strip:
strips: list[Strip]
if cuts == [cell_length]:
-
strips = [self]
-
# Don't cache (or return) a list holding `self`: that would embed -
# a self-referential cycle (strip -> cache -> list -> strip) in -
# every full-width line the compositor divides, which only the -
# cyclic GC can collect — one cycle per line per frame under a -
# translucent modal (#6738). -
return [self] else: strips = [] add_strip = strips.append
diff --git a/tests/test_strip_divide_cycle.py b/tests/test_strip_divide_cycle.py
new file mode 100644
index 0000000..a10cf1a
--- /dev/null
+++ b/tests/test_strip_divide_cycle.py
@@ -0,0 +1,82 @@
+"""Regression tests for Strip.divide self-reference cycle (issue #6738).
+
+Strip.divide() caches its result in the strip's own _divide_cache.
+When the only cut was the strip's full width it cached [self], so the
+strip ended up holding a list that holds the strip: a reference cycle
+that only the cyclic GC can collect. The compositor divides each
+rendered line, so under a translucent modal the app allocated one such
+cycle per line per frame and grew without bound.
+
+With the fix, the full-width cut returns [self] WITHOUT caching it,
+so no cycle is ever embedded in the cache. Strip defines slots
+without weakref, so weakref-based assertions are not available;
+these tests assert on the cache contents and the object's refcount
+instead.
+"""
+
+from future import annotations
+
+import sys
+
+from rich.segment import Segment
+from textual.strip import Strip
+
+
+def _make_strip() -> Strip:
-
Segments must be full (text, style, control) tuples for Segment.divide.
- return Strip([Segment("hello world")], 11)
+def test_divide_full_width_does_not_cache_self_reference():
- strip = _make_strip()
-
Full-width cut: before the fix this cached [self], creating the cycle
-
strip -> _divide_cache -> list -> strip.
- result = strip.divide([11])
- assert len(result) == 1
- assert result[0] is strip # same instance is returned, as before
-
The cache must not hold the self-referential entry.
- assert len(strip._divide_cache) == 0, (
-
"divide() cached a list containing the strip itself, embedding a " -
"reference cycle (issue #6738)" - )
+def test_divide_partial_cuts_still_cached():
-
Non-full-width cuts produce genuinely new strips; those are still
-
cached as before (no self reference involved). divide([3, 7]) on an
-
11-wide strip yields strips covering the first 10 cells.
- strip = _make_strip()
- result = strip.divide([3, 7])
- assert len(result) == 2 # 3 + 7 = 10 cells covered; remainder dropped
- assert all(part is not strip for part in result)
- assert len(strip._divide_cache) == 1
-
And the cached strips are the same objects returned to the caller.
-
FIFOCache has no .values(); read the single entry via its keys().
- (cache_key,) = strip._divide_cache.keys()
- cached = strip._divide_cache.get(cache_key)
- assert all(a is b for a, b in zip(cached, result))
+def test_divide_full_width_repeated_calls_do_not_grow_cache():
-
Repeated full-width divides (the hot path under a translucent modal)
-
must not grow the cache frame by frame.
- strip = _make_strip()
- for _ in range(10):
-
strip.divide([11]) - assert len(strip._divide_cache) == 0
+def test_divide_full_width_refcount_returns_to_baseline():
-
The returned [self] list adds exactly one reference to the strip while
-
the caller holds it; after it is dropped the refcount must return to
-
its baseline (no lingering cache entry holding it).
- strip = _make_strip()
- baseline = sys.getrefcount(strip)
- result = strip.divide([11])
- while_held = sys.getrefcount(strip)
- assert while_held == baseline + 1 # the returned list only
- del result
- assert sys.getrefcount(strip) == baseline
-- 2.43.0.windows.1
\
@CJstate Once again, I'm not a maintainer of Textual. Please stop tagging me.