Skip to content

Commit 1d933cb

Browse files
committed
fix: move ComponentNode subclass cache from module global to per registry
`component_node_subclasses_by_name` was a module-global dict keyed by `start_tag`, storing `(subcls, registry)` tuples. The tuple held strong references to both the subclass and the registry; the dict held the tuple; the only thing that would remove the entry was either of two `finalize` callbacks. Since the tuple kept both targets reachable, the finalizers could never fire and the cache pinned both forever - dead code in CPython, and the same `start_tag` collision pattern as #1598 waiting to surface if the cycle ever broke. Move the cache to `ComponentRegistry._node_subcls_cache`. Lifetime follows the registry: when the registry goes away, so does its cache. Cross-registry collisions are now structurally impossible (each registry has its own cache), so the `cached_registry is not registry` RuntimeError is dropped. The intra-registry "different end_tag for same start_tag" RuntimeError stays - it still catches tag-formatter inconsistency. `@djc_test` teardown now clears each surviving registry's cache, so a follow-up test using a different `tag_formatter` for the same start_tag isn't tripped by a leftover entry.
1 parent df1c7c1 commit 1d933cb

4 files changed

Lines changed: 61 additions & 30 deletions

File tree

‎src/django_components/component.py‎

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3457,14 +3457,6 @@ def _call_data_methods(
34573457
return template_data, js_data, css_data
34583458

34593459

3460-
# Perf
3461-
# Each component may use different start and end tags. We represent this
3462-
# as individual subclasses of `ComponentNode`. However, multiple components
3463-
# may use the same start & end tag combination, e.g. `{% component %}` and `{% endcomponent %}`.
3464-
# So we cache the already-created subclasses to be reused.
3465-
component_node_subclasses_by_name: dict[str, tuple[type["ComponentNode"], ComponentRegistry]] = {}
3466-
3467-
34683460
class ComponentNode(BaseNode):
34693461
"""
34703462
Renders one of the components that was previously registered with
@@ -3608,23 +3600,16 @@ def parse( # type: ignore[override]
36083600
# Set the component-specific start and end tags by subclassing the BaseNode
36093601
subcls_name = cls.__name__ + "_" + name
36103602

3611-
# We try to reuse the same subclass for the same start tag, so we can
3612-
# avoid creating a new subclass for each time `{% component %}` is called.
3613-
if start_tag not in component_node_subclasses_by_name:
3614-
subcls: type[ComponentNode] = type(subcls_name, (cls,), {"tag": start_tag, "end_tag": end_tag})
3615-
component_node_subclasses_by_name[start_tag] = (subcls, registry)
3616-
3617-
# Remove the cache entry when either the registry or the component are deleted
3618-
finalize(subcls, lambda: component_node_subclasses_by_name.pop(start_tag, None))
3619-
finalize(registry, lambda: component_node_subclasses_by_name.pop(start_tag, None))
3620-
3621-
cached_subcls, cached_registry = component_node_subclasses_by_name[start_tag]
3622-
3623-
if cached_registry is not registry:
3624-
raise RuntimeError(
3625-
f"Detected two Components from different registries using the same start tag '{start_tag}'",
3626-
)
3627-
if cached_subcls.end_tag != end_tag:
3603+
# Reuse the same subclass for the same start tag inside this registry, so we
3604+
# don't create a fresh subclass per `{% component %}` token. Cached per-registry
3605+
# rather than module-globally: lifetime follows the registry's own, and two
3606+
# registries can reuse the same start_tag without colliding.
3607+
cache = registry._node_subcls_cache
3608+
cached_subcls: type[ComponentNode] | None = cache.get(start_tag)
3609+
if cached_subcls is None:
3610+
cached_subcls = type(subcls_name, (cls,), {"tag": start_tag, "end_tag": end_tag})
3611+
cache[start_tag] = cached_subcls
3612+
elif cached_subcls.end_tag != end_tag:
36283613
raise RuntimeError(
36293614
f"Detected two Components using the same start tag '{start_tag}' but with different end tags",
36303615
)
@@ -3633,7 +3618,7 @@ def parse( # type: ignore[override]
36333618
node: ComponentNode = super(cls, cached_subcls).parse( # type: ignore[attr-defined]
36343619
parser,
36353620
token,
3636-
registry=cached_registry,
3621+
registry=registry,
36373622
name=name,
36383623
)
36393624
return node

‎src/django_components/component_registry.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,11 @@ def __init__(
244244
# one when the entry is replaced or removed. Without this, stale finalizers
245245
# would fire later and pop the wrong entry from `self._registry` (see #1598).
246246
self._finalizers: dict[str, finalize] = {}
247+
# start_tag -> ComponentNode subclass. Cache reused on every template parse
248+
# so we don't create a fresh subclass per `{% component %}` token. Per-registry,
249+
# so the cache dies with the registry instead of pinning it forever via a
250+
# module-global dict.
251+
self._node_subcls_cache: dict[str, type] = {}
247252
self._library = library
248253
self._settings = settings
249254

‎src/django_components/util/testing.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from django.test import override_settings
2121

2222
from django_components import ComponentsSettings
23-
from django_components.component import ALL_COMPONENTS, Component, component_node_subclasses_by_name
23+
from django_components.component import ALL_COMPONENTS, Component
2424
from django_components.component_registry import ALL_REGISTRIES, ComponentRegistry
2525
from django_components.extension import extensions
2626
from django_components.perfutil.provide import provide_cache
@@ -494,9 +494,6 @@ def _clear_djc_global_state(
494494
if provide_cache:
495495
provide_cache.clear()
496496

497-
# Remove cached Node subclasses
498-
component_node_subclasses_by_name.clear()
499-
500497
# Clean up any loaded media (HTML, JS, CSS)
501498
for comp_cls_ref in ALL_COMPONENTS:
502499
comp_cls = comp_cls_ref()
@@ -556,6 +553,12 @@ def _clear_djc_global_state(
556553
registry_original.unregister(name)
557554
registry_original.register(name, original_cls)
558555

556+
# Drop the parsed ComponentNode subclass cache. Otherwise a follow-up test
557+
# that uses the same start_tag with a different end_tag (e.g. via a custom
558+
# tag_formatter) would trip the "different end tags" RuntimeError in
559+
# `ComponentNode.parse()`.
560+
registry_original._node_subcls_cache.clear()
561+
559562
# Drop modules that the test brought in itself, so a later test sees a clean import.
560563
# Modules that were already in `sys.modules` before the test ran are left alone -
561564
# popping them would force `importlib.import_module()` to re-execute the file on

‎tests/test_registry.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,44 @@ def test_unregister_detaches_finalizer(self):
190190
custom_registry.unregister(name="testcomponent")
191191
assert "testcomponent" not in custom_registry._finalizers
192192

193+
def test_node_subcls_cache_is_per_registry(self):
194+
# Each registry owns its own `_node_subcls_cache`. Replaces the previous
195+
# module-global `component_node_subclasses_by_name` that pinned both the
196+
# subclass and the registry forever.
197+
library_a = Library()
198+
library_b = Library()
199+
registry_a = ComponentRegistry(library=library_a)
200+
registry_b = ComponentRegistry(library=library_b)
201+
202+
assert registry_a._node_subcls_cache == {}
203+
assert registry_b._node_subcls_cache == {}
204+
assert registry_a._node_subcls_cache is not registry_b._node_subcls_cache
205+
206+
def test_module_global_node_subcls_cache_no_longer_exists(self):
207+
# Pre-fix, `django_components.component` exposed a module-global
208+
# `component_node_subclasses_by_name` that pinned subclasses + registries
209+
# forever. The cache now lives per-registry. Catch any accidental
210+
# reintroduction of the global.
211+
import django_components.component as component_module # noqa: PLC0415
212+
213+
assert not hasattr(component_module, "component_node_subclasses_by_name")
214+
215+
def test_node_subcls_cache_populated_on_parse(self):
216+
library = Library()
217+
registry_local = ComponentRegistry(library=library)
218+
registry_local.register("simple", MockComponent)
219+
220+
engine = Engine.get_default()
221+
engine.template_builtins.append(library)
222+
try:
223+
assert registry_local._node_subcls_cache == {}
224+
Template("{% component 'simple' / %}")
225+
# `_register_to_library` uses `formatter.start_tag(comp_name)`, which
226+
# for the default formatter returns "component" regardless of comp_name.
227+
assert list(registry_local._node_subcls_cache.keys()) == ["component"]
228+
finally:
229+
engine.template_builtins.remove(library)
230+
193231
def test_simple_unregister(self):
194232
custom_registry = ComponentRegistry()
195233
custom_registry.register(name="testcomponent", component=MockComponent)

0 commit comments

Comments
 (0)