Skip to content

Commit df1c7c1

Browse files
committed
fix: make ComponentRegistry.register() additive; track finalizers per name
`register()` now treats re-registration strictly: - Same class object under same name -> no-op (covers the common autodiscover- runs-twice case, since `@register` decorators only re-run when their module is actually re-executed). - Any other class under an existing name -> raise `AlreadyRegistered`. Callers that intentionally replace a registration (hot-reload scripts, settings re-application) must `unregister()` first. The new exception message says so. The old loose behavior - silent overwrite whenever `class_id` collided - was the trapdoor #1598 went through. With strict registration plus the sys.modules snapshot landed in the previous commit, the only way to reach the "different object under same name" branch is an explicit reimport, which is always intentional. Track the `weakref.finalize` handle per registered name in `_finalizers` so `unregister()` can `.detach()` it eagerly. This makes the registry state deterministic regardless of GC timing, and turns #1630's id-check-at-fire- time defense into pure defense-in-depth. Strengthen `@djc_test` teardown to restore each registry's initial entries (not just remove what was added). Necessary because the strict contract forces tests that re-init a registration to `unregister` + `register` rather than rely on silent overwrite; without restoration, those removals leaked into later tests. Update three tests that relied on the old loose behavior to call `unregister()` explicitly before re-registering.
1 parent 20b7e8f commit df1c7c1

5 files changed

Lines changed: 109 additions & 22 deletions

File tree

‎src/django_components/component_registry.py‎

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,10 @@ def __init__(
240240
) -> None:
241241
self._registry: dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping
242242
self._tags: dict[str, set[str]] = {} # tag -> list[component names]
243+
# `finalize` handle per registered name, so we can `.detach()` the previous
244+
# one when the entry is replaced or removed. Without this, stale finalizers
245+
# would fire later and pop the wrong entry from `self._registry` (see #1598).
246+
self._finalizers: dict[str, finalize] = {}
243247
self._library = library
244248
self._settings = settings
245249

@@ -325,14 +329,22 @@ def register(self, name: str, component: type["Component"]) -> None:
325329
{% endcomponent %}
326330
```
327331
332+
`register()` is additive. Calling it again with the exact same class object
333+
is a no-op. Calling it with any other class - even one whose
334+
[`class_id`](./api.md#django_components.Component.class_id) collides with the
335+
existing one - raises
336+
[`AlreadyRegistered`](./exceptions.md#django_components.AlreadyRegistered).
337+
Call [`unregister()`](#django_components.ComponentRegistry.unregister) first
338+
if you intend to replace the registered class.
339+
328340
Args:
329341
name (str): The name under which the component will be registered. Required.
330342
component (type[Component]): The component class to register. Required.
331343
332344
**Raises:**
333345
334346
- [`AlreadyRegistered`](./exceptions.md#django_components.AlreadyRegistered)
335-
if a different component was already registered under the same name.
347+
if `name` is already registered with any class other than `component` itself.
336348
337349
**Example:**
338350
@@ -341,9 +353,18 @@ def register(self, name: str, component: type["Component"]) -> None:
341353
```
342354
343355
"""
344-
existing_component = self._registry.get(name)
345-
if existing_component and existing_component.cls.class_id != component.class_id:
346-
raise AlreadyRegistered(f'The component "{name}" has already been registered')
356+
existing_entry = self._registry.get(name)
357+
if existing_entry is not None:
358+
if existing_entry.cls is component:
359+
# Same class object - re-registration is a no-op. Happens naturally
360+
# when `autodiscover()` / `import_libraries()` run more than once and
361+
# touch the same module (whose `@register` decorator was already
362+
# evaluated on first import).
363+
return
364+
raise AlreadyRegistered(
365+
f'The component "{name}" has already been registered. '
366+
f'Call `registry.unregister("{name}")` before registering a different class.',
367+
)
347368

348369
entry = self._register_to_library(name, component)
349370

@@ -357,15 +378,17 @@ def register(self, name: str, component: type["Component"]) -> None:
357378
self._registry[name] = entry
358379

359380
# If the component class is deleted, unregister it from this registry.
360-
# Use the object ID so the finalizer does not keep the class alive.
381+
# The id-check inside the callback is defense-in-depth - the primary mechanism
382+
# for avoiding stale finalizer fires is `.detach()` on entry removal, see
383+
# `unregister()` below.
361384
registered_cls_object_id = id(entry.cls)
362385

363386
def unregister_component() -> None:
364387
current_entry = self._registry.get(name)
365388
if current_entry is not None and id(current_entry.cls) == registered_cls_object_id:
366389
self.unregister(name)
367390

368-
finalize(entry.cls, unregister_component)
391+
self._finalizers[name] = finalize(entry.cls, unregister_component)
369392

370393
extensions.on_component_registered(
371394
OnComponentRegisteredContext(
@@ -428,6 +451,12 @@ def unregister(self, name: str) -> None:
428451
entry = self._registry[name]
429452
del self._registry[name]
430453

454+
# Detach the finalizer so it cannot later fire and pop a replacement entry
455+
# registered under the same name.
456+
stale_finalizer = self._finalizers.pop(name, None)
457+
if stale_finalizer is not None:
458+
stale_finalizer.detach()
459+
431460
extensions.on_component_unregistered(
432461
OnComponentUnregisteredContext(
433462
registry=self,

‎src/django_components/util/testing.py‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from django_components.component_media import ComponentMedia
3131

3232
RegistryRef: TypeAlias = ReferenceType[ComponentRegistry]
33-
RegistriesCopies: TypeAlias = list[tuple[ReferenceType[ComponentRegistry], list[str]]]
33+
RegistriesCopies: TypeAlias = list[tuple[ReferenceType[ComponentRegistry], dict[str, type[Component]]]]
3434
InitialComponents: TypeAlias = list[ReferenceType[type[Component]]]
3535

3636

@@ -331,7 +331,9 @@ def _wrapper_impl(*args: Any, **kwargs: Any) -> Any:
331331
reg = reg_ref()
332332
if not reg:
333333
continue
334-
_all_registries_copies.append((reg_ref, list(reg._registry.keys())))
334+
_all_registries_copies.append(
335+
(reg_ref, {name: entry.cls for name, entry in reg._registry.items()}),
336+
)
335337

336338
# Snapshot which modules were already imported before the test ran.
337339
# See `_clear_djc_global_state` for why this matters.
@@ -528,24 +530,32 @@ def _clear_djc_global_state(
528530
if is_ref_deleted or registry_ref not in initial_registries_set:
529531
del ALL_REGISTRIES[len(ALL_REGISTRIES) - index - 1]
530532

531-
# For the remaining registries, unregistr components that were registered
532-
# during tests.
533-
# NOTE: The approach below does NOT take into account:
534-
# - If a component was UNregistered during the test
535-
# - If a previously-registered component was overwritten with different registration.
536-
for reg_ref, init_keys in initial_registries_copies:
533+
# For the remaining registries, restore the registry contents to their pre-test state:
534+
# - Unregister keys that were added during the test
535+
# - Restore any initial entry that was removed or replaced during the test
536+
# (re-applying with the original class object so tests that swap out a registration
537+
# for new settings - e.g. re-running `ComponentsConfig.ready()` - don't leak the
538+
# substituted entry into the next test)
539+
for reg_ref, init_entries in initial_registries_copies:
537540
registry_original = reg_ref()
538541
if not registry_original:
539542
continue
540543

541-
# Get the keys that were registered during the test
542-
initial_registered_keys = set(init_keys)
544+
# Remove keys that were added during the test.
543545
after_test_registered_keys = set(registry_original._registry.keys())
544-
keys_registered_during_test = after_test_registered_keys - initial_registered_keys
545-
# Remove them
546+
keys_registered_during_test = after_test_registered_keys - init_entries.keys()
546547
for key in keys_registered_during_test:
547548
registry_original.unregister(key)
548549

550+
# Restore initial entries that were removed or replaced during the test.
551+
for name, original_cls in init_entries.items():
552+
current_entry = registry_original._registry.get(name)
553+
if current_entry is None:
554+
registry_original.register(name, original_cls)
555+
elif current_entry.cls is not original_cls:
556+
registry_original.unregister(name)
557+
registry_original.register(name, original_cls)
558+
549559
# Drop modules that the test brought in itself, so a later test sees a clean import.
550560
# Modules that were already in `sys.modules` before the test ran are left alone -
551561
# popping them would force `importlib.import_module()` to re-execute the file on

‎tests/test_autodiscover.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,14 @@ def test_import_libraries(self):
8282
},
8383
)
8484
def test_import_libraries_map_modules(self):
85+
# Strict `register()` requires explicit unregister before a reimport produces
86+
# a fresh class object under the same name.
87+
all_components = registry.all().copy()
88+
if "single_file_component" in all_components:
89+
registry.unregister("single_file_component")
90+
if "multi_file_component" in all_components:
91+
registry.unregister("multi_file_component")
92+
8593
# Ensure that the modules are executed again after import
8694
if "tests.components.single_file" in sys.modules:
8795
del sys.modules["tests.components.single_file"]

‎tests/test_component_dynamic.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,11 @@ def test_component_as_class(self, components_settings):
156156
def test_shorthand_formatter(self, components_settings):
157157
from django_components.apps import ComponentsConfig
158158

159+
# `ComponentsConfig.ready()` re-registers "dynamic" so it picks up the new
160+
# tag_formatter. Strict `register()` requires an explicit unregister first.
161+
if registry.has("dynamic"):
162+
registry.unregister("dynamic")
163+
159164
ComponentsConfig.ready(None) # type: ignore[arg-type]
160165

161166
registry.register(name="test", component=self._gen_simple_component())
@@ -180,6 +185,11 @@ def test_shorthand_formatter(self, components_settings):
180185
def test_component_name_is_configurable(self, components_settings):
181186
from django_components.apps import ComponentsConfig
182187

188+
# See `test_shorthand_formatter` for why `ComponentsConfig.ready()` needs an
189+
# explicit unregister under the strict `register()` contract.
190+
if registry.has("dynamic"):
191+
registry.unregister("dynamic")
192+
183193
ComponentsConfig.ready(None) # type: ignore[arg-type]
184194

185195
registry.register(name="test", component=self._gen_simple_component())

‎tests/test_registry.py‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -144,22 +144,52 @@ def test_allow_duplicated_registration_of_the_same_component(self):
144144
except AlreadyRegistered:
145145
pytest.fail("Should not raise AlreadyRegistered")
146146

147-
def test_stale_component_finalizer_does_not_unregister_replacement(self):
147+
def test_register_different_class_with_same_class_id_raises(self):
148+
# Two distinct class objects with identical `class_id` is the exact #1598
149+
# scenario. Replacement must require an explicit unregister.
148150
custom_registry = ComponentRegistry()
149151

150152
component_v1 = gen_reimported_component()
151-
custom_registry.register(name="testcomponent", component=component_v1)
152-
153153
component_v2 = gen_reimported_component()
154154
assert component_v1 is not component_v2
155155
assert component_v1.class_id == component_v2.class_id
156156

157+
custom_registry.register(name="testcomponent", component=component_v1)
158+
with pytest.raises(AlreadyRegistered):
159+
custom_registry.register(name="testcomponent", component=component_v2)
160+
161+
# Original entry is untouched.
162+
assert custom_registry.get("testcomponent") is component_v1
163+
164+
def test_unregister_then_reregister_with_replacement_class_succeeds(self):
165+
custom_registry = ComponentRegistry()
166+
167+
component_v1 = gen_reimported_component()
168+
custom_registry.register(name="testcomponent", component=component_v1)
169+
170+
custom_registry.unregister(name="testcomponent")
171+
172+
component_v2 = gen_reimported_component()
157173
custom_registry.register(name="testcomponent", component=component_v2)
174+
assert custom_registry.get("testcomponent") is component_v2
175+
176+
# Exactly one finalizer is tracked for the live entry.
177+
assert len(custom_registry._finalizers) == 1
178+
179+
# Garbage-collecting the prior class object must NOT touch the live entry,
180+
# since `unregister()` detached its finalizer.
158181
del component_v1
159182
gc.collect()
160-
161183
assert custom_registry.get("testcomponent") is component_v2
162184

185+
def test_unregister_detaches_finalizer(self):
186+
custom_registry = ComponentRegistry()
187+
custom_registry.register(name="testcomponent", component=MockComponent)
188+
assert "testcomponent" in custom_registry._finalizers
189+
190+
custom_registry.unregister(name="testcomponent")
191+
assert "testcomponent" not in custom_registry._finalizers
192+
163193
def test_simple_unregister(self):
164194
custom_registry = ComponentRegistry()
165195
custom_registry.register(name="testcomponent", component=MockComponent)

0 commit comments

Comments
 (0)