textual icon indicating copy to clipboard operation
textual copied to clipboard

Memory leak — `StylesCache.get_inner_outer` retains whole `StylesCache` objects via `lru_cache`

Open cdxjcl opened this issue 4 months ago • 5 comments

The bug

In a TUI that re-renders many widgets on scroll/refresh (a list that rebuilds ~40 cards each time), RSS grows without bound — I measured 75 MB → 170 MB+ with no plateau.

The retained objects turn out to be Strip instances held by StylesCache. The ownership chain is:

orphaned Strip -> StylesCache -> functools._lru_cache_wrapper (key "get_inner_outer")

Minimal example

from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import Label

class LeakApp(App):
    def compose(self) -> ComposeResult:
        yield Vertical(id="list")

    def on_mount(self) -> None:
        self.set_interval(0.1, self.rebuild)

    def rebuild(self) -> None:
        # Rebuild ~40 styled widgets every 100ms; old StylesCache objects are
        # retained forever by lru_cache on StylesCache.get_inner_outer.
        self.query_one("#list").remove_children()
        self.query_one("#list").mount(*(Label(f"card {i}") for i in range(40)))

if __name__ == "__main__":
    LeakApp().run()

Run it and watch RSS (e.g. textual diagnose + a memory profiler). It climbs without plateau; the leaked objects are whole StylesCache instances pinned by the lru_cache.

Root cause

textual/_styles_cache.py decorates the instance method get_inner_outer with @lru_cache(1024):

@lru_cache(1024)
def get_inner_outer(cls, base_background: Color, background: Color) -> tuple[Style, Style]:
    return (
        Style(background=base_background + background),
        Style(background=base_background),
    )

Because it is an instance method, calling self.get_inner_outer(a, b) passes the StylesCache instance as cls. The function body only uses the two Color arguments and never cls/self.

So the lru_cache key includes the entire StylesCache object, which holds self._cache (every rendered line's Strip), and each Strip carries 7 FIFOCache instances. Up to 1024 whole StylesCache objects are retained forever.

Expected behavior

The cache key should depend only on the two colors. Make it a staticmethod (or drop cls from the signature). Minimal fix:

@staticmethod
@lru_cache(1024)
def get_inner_outer(base_background: Color, background: Color) -> tuple[Style, Style]:
    ...

Environment

  • Textual: 8.2.8
  • Rich: 15.0.0
  • Python: 3.14.6 (CPython, MSC v.1944 64 bit AMD64)
  • OS: Windows 11 (10.0.26200)
  • Terminal: Windows Terminal

Textual Diagnostics

Versions

Name Value
Textual 8.2.8
Rich 15.0.0

Python

Name Value
Version 3.14.6
Implementation CPython
Compiler MSC v.1944 64 bit (AMD64)
Executable C:\Users\foo\bar.venv\Scripts\python.exe

Operating System

Name Value
System Windows
Release 11
Version 10.0.26200

Terminal

Name Value
Terminal Application Windows Terminal
TERM Not set
COLORTERM Not set
FORCE_COLOR Not set
NO_COLOR Not set

Rich Console options

Name Value
size width=119, height=40
legacy_windows False
min_width 1
max_width 119
is_terminal True
encoding utf-8
max_height 40
justify None
overflow None
no_wrap False
highlight None
markup None
height None

cdxjcl avatar Jul 22 '26 19:07 cdxjcl

Thank you for your issue. Give us a little time to review it.

PS. You might want to check the FAQ if you haven't done so already.

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 Jul 22 '26 19:07 github-actions[bot]

Would you approve the staticmethod approach proposed in this issue?

I reproduced the retention with a weak-reference regression. Before the change, same-color calls from two StylesCache instances create two cache entries and retain both instances. Making get_inner_outer static produces one color-keyed entry, preserves the existing 1,024-entry LRU cache, and allows both instances to be collected. The focused style-cache tests pass.

If this approach is acceptable, I can submit the patch and regression test.

dk3yyyy avatar Jul 30 '26 16:07 dk3yyyy

Would you approve the staticmethod approach proposed in this issue?您是否同意本期报告中提出的 staticmethod 方法?

I reproduced the retention with a weak-reference regression. Before the change, same-color calls from two StylesCache instances create two cache entries and retain both instances. Making get_inner_outer static produces one color-keyed entry, preserves the existing 1,024-entry LRU cache, and allows both instances to be collected. The focused style-cache tests pass.我通过弱引用回归测试来验证这种保留方式的有效性。在改变之前,两个 StylesCache 实例中相同颜色的调用会生成两个缓存条目,并保留这两个实例。而将 get_inner_outer 设置为静态后,只会生成一个颜色对应的缓存条目,同时保留现有的 1,024 个条目的 LRU 缓存,从而能够同时收集两个实例的信息。经过测试后,这种聚焦式的样式缓存方法确实有效。

If this approach is acceptable, I can submit the patch and regression test.如果这种方法是可以接受的,那么我可以提交这个补丁以及相关的回归测试报告。

Of course, feel free to submit the patch and the regression test.

cdxjcl avatar Jul 31 '26 03:07 cdxjcl

Confirming this on Linux too, with a small reproduction and numbers, plus one more consequence.

Environment: textual 8.2.4 and 8.2.8 (same result), Python 3.11.14, Linux.

Reproduction (textual only): run 50 small apps one after another under App.run_test(), then count the StylesCache instances still alive after a full collection:

import asyncio
import gc

from textual._styles_cache import StylesCache
from textual.app import App, ComposeResult
from textual.widgets import Label


class SmallApp(App[None]):
    CSS = "Label { background: $panel; }"

    def compose(self) -> ComposeResult:
        yield from (Label(f"row {i}") for i in range(20))


async def main() -> None:
    for _ in range(50):
        async with SmallApp().run_test() as pilot:
            await pilot.pause()
    gc.collect()
    print(sum(isinstance(o, StylesCache) for o in gc.get_objects()),
          StylesCache.get_inner_outer.cache_info())


asyncio.run(main())
After 50 apps have closed Before get_inner_outer.cache_clear() After
StylesCache instances alive 1,024 (the cache is full) 21
Traced memory (tracemalloc) 10.9 MiB 1.2 MiB
One full gc.collect() 34–37 ms 5 ms

A second effect: longer garbage-collection pauses. Each retained StylesCache keeps its rendered Strips, and each Strip has 7 FIFOCaches, so a full cache keeps a large number of GC-tracked objects alive, and every full (generation-2) collection has to walk them. In a long-running process that creates many apps or screens one after another (a test suite using run_test() is the clearest case), this was the largest single source of retained objects we found, and clearing the cache after each app removed about 90% of them.

The @staticmethod fix proposed above looks right to us, since the body only uses the two colors. Until it lands, calling StylesCache.get_inner_outer.cache_clear() after an app or screen closes works as a workaround. Happy to test a patch.

yinglongmiao2tutor avatar Oct 19 '26 15:10 yinglongmiao2tutor

Confirming on Textual 8.2.8 (Python 3.11, macOS). One correction: the retention is capped by the LRU size, not unbounded. With identical colours, 2,048 StylesCache instances leave exactly 1,024 alive after gc.collect(); get_inner_outer.cache_clear() frees all of them:

import gc, weakref
from textual._styles_cache import StylesCache
from textual.color import Color
StylesCache.get_inner_outer.cache_clear()
refs = []
for _ in range(2048):
    cache = StylesCache()
    refs.append(weakref.ref(cache))
    cache.get_inner_outer(Color(0, 0, 0), Color(1, 2, 3))
del cache
gc.collect()
print(sum(r() is not None for r in refs))  # 1024
StylesCache.get_inner_outer.cache_clear()
gc.collect()
print(sum(r() is not None for r in refs))  # 0

The cap is per process, but each kept StylesCache holds its rendered Strips (seven FIFOCaches each), so in a viewer that rebuilds rows it adds up: about 60k objects and 7 MB per process in ours. Keying the cache on the two colours only (the staticmethod approach proposed above) halved our live objects with identical rendering. +1 for that fix.

dbarkalov78 avatar Oct 24 '26 08:10 dbarkalov78