Repository navigation
Audit and fix latent finalizer / reimport bugs (follow-up to #1598/#1630) - #1647
Conversation
The first call to `cached_ref(obj)` inserts a weakref into `GLOBAL_REFS` and attaches a `weakref.finalize` callback to evict it on GC. Every subsequent call returned the cached weakref correctly, but also attached another `finalize` to the same object, leaking one finalize per call. Move the `finalize` attach inside the `if obj_id not in GLOBAL_REFS:` branch so it runs exactly once per cached object. Repeated callers no longer accumulate weakref entries; `weakref.getweakrefcount(obj)` stays flat across calls.
…cause) #1630 patched the registry-corruption symptom from #1598, but the underlying trigger remained: `_clear_djc_global_state` popped every entry from `LOADED_MODULES` out of `sys.modules`, including modules that had already been imported before the test ran. The next test's `autodiscover()` then re-executed those modules, producing a fresh class object with the same `class_id` as the original - exactly the input PR #1630 had to defend against. Snapshot `sys.modules.keys()` in `_wrapper_impl` and pass it through to `_clear_djc_global_state`, which now only pops `LOADED_MODULES` entries that were absent from the snapshot. Modules the test itself imported are still cleared; modules carried in from production startup or earlier tests stay put. This implements Options B/C suggested in #1598.
… 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.
…stry `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.
- Add CHANGELOG entries under v0.150.1 for the four fixes landed in this branch. - Expand `AlreadyRegistered` docstring to spell out the new contract: same class -> no-op, anything else -> raise (and unregister first to replace). - Ruff autofix removed two unused `# noqa: PLC0415` directives. The import in the autodiscover regression test is now explicit via `importlib.import_module` so the test's precondition is self- documenting and lint-clean.
Performance Benchmark ResultsComparing PR changes against master branch: Benchmarks that have stayed the same:
|
|
Here's more context into individual issues this addressed: Fix latent finalizer / reimport bugs in django-componentsContextPR #1630 (merged May 1) fixed This plan addresses all four. Goals
The four are independent but related; sequencing #3 first means #1, #2 and #4 are exercised 1.
|
| Concern | File | Change |
|---|---|---|
| 1 | src/django_components/component.py | Delete module-global cache + finalizers; rewrite ComponentNode.parse() to use registry._node_subcls_cache |
| 1 | src/django_components/component_registry.py | Add _node_subcls_cache to __init__ |
| 1 | src/django_components/util/testing.py | Remove component_node_subclasses_by_name.clear() and its import |
| 2 | src/django_components/util/weakref.py | Move finalize(...) inside the if branch |
| 3 | src/django_components/util/testing.py | Snapshot sys.modules keys in _wrapper_impl; pass through to _clear_djc_global_state; conditional pop |
| 4 | src/django_components/component_registry.py | Add _finalizers dict; detach in register() overwrite path; detach in unregister() |
Tests
- A better setup for CI #1 Add
test_node_subcls_cache_dies_with_registryintests/test_registry.py:
create registry, parse a component, drop the registry, verify the subclass becomes
collectible. - A better setup for CI #1 Add
test_two_registries_can_reuse_same_start_tagintests/test_registry.py:
proves cross-registry collisions no longer raise the oldRuntimeError. - More clearly define support #2 Add
test_cached_ref_attaches_one_finalizerintests/test_util_weakref.py
(new file): callcached_ref(obj)N times, assertlen(weakref.getweakrefs(obj))is
bounded (use the finalize count, not weakref count, sincecached_refonly creates
one weak ref but currently many finalizers). - Add Django 1.7 to the build matrix #3 Add
test_djc_test_does_not_reimport_modules_present_before_testin
tests/test_autodiscover.py: snapshot a module'sid(), run two@djc_testcycles,
assert the module object is the same. - Reviving the project #4 Rewrite
test_stale_component_finalizer_does_not_unregister_replacement
intests/test_registry.py:- First assertion: registering a second class object under the same name (regardless
ofclass_id) raisesAlreadyRegistered. - Second assertion: after
unregister("testcomponent")+register("testcomponent", v2),
agc.collect()ofv1does NOT touch the entry forv2(i.e. the detach worked).
- First assertion: registering a second class object under the same name (regardless
- Reviving the project #4 Add
test_register_after_unregister_replaces_finalizer_cleanly: register
v1, unregister, register v2, assertlen(registry._finalizers) == 1and that the
entry maps to v2. - Reviving the project #4 Add
test_register_different_class_with_same_class_id_raises: covers the
exactweakref.finalizecauses registry corruption #1598 scenario — two fabricated classes with identicalclass_idbut distinct
identity; the secondregister()must raise.
Verification
CLAUDE.md requires repo-wide checks:
uv run ruff check .
uv run ruff format --check .
uv run mypy .
uv run pytest tests/test_registry.py tests/test_autodiscover.py
uv run pytest # full suite
uv run mkdocs build --strict # only if any docstrings touchedDocs touches:
- docs/reference/exceptions.md —
AlreadyRegistered
is auto-rendered from the class docstring via mkdocstrings. Update the docstring
to reflect the new contract ("raised whenever a name is already registered with
any class other than the exact one being passed; callunregister(name)first
to replace"). - Skim docs/concepts/ and docs/reference/ for
any text that promises silent overwrite of identically-named components and
update if found. - Run
uv run mkdocs build --strictto validate.
Commit split (one branch, four commits)
- Fix More clearly define support #2 —
cached_reffinalizer leak. Trivial one-line move, independent of everything else. - Fix Add Django 1.7 to the build matrix #3 —
sys.modulessnapshot in@djc_testteardown. Eliminates the
reimport that drives the rest. Should land before Reviving the project #4 so the strict register
contract doesn't trip existing tests. - Fix Reviving the project #4 — strict
register()contract + per-name finalizer tracking.
Depends on Add Django 1.7 to the build matrix #3 landing first to keep the test suite green. - Fix A better setup for CI #1 — per-registry
ComponentNodesubclass cache. Independent of Add Django 1.7 to the build matrix #3/Reviving the project #4
but touchescomponent.pyandcomponent_registry.pylike Reviving the project #4, so easier to
land last to avoid merge churn.
Each commit lands its own regression test plus the structural fix.
| # as individual subclasses of `ComponentNode`. However, multiple components | ||
| # may use the same start & end tag combination, e.g. `{% component %}` and `{% endcomponent %}`. | ||
| # So we cache the already-created subclasses to be reused. | ||
| component_node_subclasses_by_name: dict[str, tuple[type["ComponentNode"], ComponentRegistry]] = {} |
There was a problem hiding this comment.
This cache is no longer global, but now scoped to ComponentRegistry
|
Hey @EmilStenstrom, look who's back :D |
(Juro)
After reading through #1598 and #1630, I explored whether there are more bugs of the same class (where we set up ref finalizers to act on to act on some registered name instead of on the object identity itself).
Also decided to implement option B from #1598 - ie the
@djc_testdecorator should clean up / reset only those imports that were actually done DURING the test function, and leave alone those imports that have already ran before@djc_test.(Opus 4.8)
Summary
Audit of weak-reference and
finalize-callback patterns adjacent to the registry, prompted by PR #1630 (which patched the symptom of #1598). The audit surfaced three more latent issues and one tightening opportunity. All four are fixed here as separate reviewable commits on one branch.util.weakref.cached_refattached a freshweakref.finalizeto its target on every call (leak per call)1c972de@djc_testteardown popped everyLOADED_MODULESentry fromsys.modules, including modules that were already imported before the test - causing the next test'sautodiscover()to re-execute them and produce class objects with collidingclass_ids (the precondition behind #1598)20b7e8fComponentRegistry.register()silently overwrote entries whenever the new class shared aclass_idwith the old one (the trapdoor #1598 went through). Per-name finalizer tracking now eagerly.detach()es onunregister()and the contract is strict.df1c7c1component_node_subclasses_by_namewas a module-global dict whose tuple values held strong references to both the subclass and the registry, forming a self-pinning cycle that the cleanupfinalizecallbacks could never break. Cache moved per-registry.1d933cbA fifth commit (
c94d4d5) carries the changelog, the updatedAlreadyRegistereddocstring, and ruff cleanup.Behaviour changes worth highlighting
register()is now strict. Re-registering the exact same class object under the same name is a no-op (so callingautodiscover()/import_libraries()repeatedly is safe). Any other class under an existing name raisesAlreadyRegistered. The new message tells the caller tounregister()first. Three existing tests that relied on the silent-overwrite path were updated to callunregister()explicitly.@djc_testteardown is stronger. It snapshotssys.modulesat setup (Fix Add Django 1.7 to the build matrix #3), restores initial registry entries that tests removed/replaced (needed for the strict register contract), and clears each registry's_node_subcls_cache(so a follow-up test using a differenttag_formatterfor the same start_tag isn't tripped).component_node_subclasses_by_nameis gone. A new regression test catches accidental reintroduction.Test plan
uv run ruff check .- cleanuv run ruff format --check .- cleanuv run mypy .- clean (4 pre-existing errors indocs/scripts/people.py/site/scripts/people.pyconfirmed unrelated by running mypy on master)uv run pytest(excluding benchmarks and e2e) - 1240 passed, 6 skipped, 0 failures. The 111 e2e errors are pre-existing Playwright-not-installed.uv run mkdocs build --strict- built successfullytests/test_util_weakref.py(new file) -cached_refdoes not stack finalizers, returns same ref, cleans up on GCtests/test_autodiscover.py::TestSysModulesIsolation- module identity preserved across@djc_testcyclestests/test_registry.py- strict register contract, finalizer detach on unregister, per-registry node cache🤖 Generated with Claude Code