Skip to content

Audit and fix latent finalizer / reimport bugs (follow-up to #1598/#1630) - #1647

Merged
JuroOravec merged 5 commits into
masterfrom
fix/finalizer-and-reimport-audit
May 29, 2026
Merged

JuroOravec merged 5 commits into
masterfrom
fix/finalizer-and-reimport-audit

Conversation

@JuroOravec

@JuroOravec JuroOravec commented May 29, 2026 •

Copy link
Copy Markdown
Collaborator

(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_test decorator 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.

# Concern Commit
2 util.weakref.cached_ref attached a fresh weakref.finalize to its target on every call (leak per call) 1c972de
3 @djc_test teardown popped every LOADED_MODULES entry from sys.modules, including modules that were already imported before the test - causing the next test's autodiscover() to re-execute them and produce class objects with colliding class_ids (the precondition behind #1598) 20b7e8f
4 ComponentRegistry.register() silently overwrote entries whenever the new class shared a class_id with the old one (the trapdoor #1598 went through). Per-name finalizer tracking now eagerly .detach()es on unregister() and the contract is strict. df1c7c1
1 component_node_subclasses_by_name was a module-global dict whose tuple values held strong references to both the subclass and the registry, forming a self-pinning cycle that the cleanup finalize callbacks could never break. Cache moved per-registry. 1d933cb

A fifth commit (c94d4d5) carries the changelog, the updated AlreadyRegistered docstring, 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 calling autodiscover() / import_libraries() repeatedly is safe). Any other class under an existing name raises AlreadyRegistered. The new message tells the caller to unregister() first. Three existing tests that relied on the silent-overwrite path were updated to call unregister() explicitly.
  • @djc_test teardown is stronger. It snapshots sys.modules at 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 different tag_formatter for the same start_tag isn't tripped).
  • Module-global component_node_subclasses_by_name is gone. A new regression test catches accidental reintroduction.

Test plan

  • uv run ruff check . - clean
  • uv run ruff format --check . - clean
  • uv run mypy . - clean (4 pre-existing errors in docs/scripts/people.py / site/scripts/people.py confirmed 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 successfully
  • Each fix has a regression test added alongside it. New tests:
    • tests/test_util_weakref.py (new file) - cached_ref does not stack finalizers, returns same ref, cleans up on GC
    • tests/test_autodiscover.py::TestSysModulesIsolation - module identity preserved across @djc_test cycles
    • tests/test_registry.py - strict register contract, finalizer detach on unregister, per-registry node cache
  • All five commits land their changes with the related test.

🤖 Generated with Claude Code

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.
@github-actions

Copy link
Copy Markdown
Contributor

Performance Benchmark Results

Comparing PR changes against master branch:

Benchmarks that have stayed the same:

Change Before [ec313ea] After [8d26f13] Ratio Benchmark (Parameter)
62.0±1ms 62.8±0.9ms 1.01 Components vs Django.timeraw_render_lg_first('django')
222±5ms 222±4ms 1 Components vs Django.timeraw_render_lg_first('django-components')

@JuroOravec

JuroOravec commented May 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Here's more context into individual issues this addressed:


Fix latent finalizer / reimport bugs in django-components

Context

PR #1630 (merged May 1) fixed
#1598: a stale
weakref.finalize callback could unregister the wrong component class after a reimport
collided two class objects on the same class_id. The fix patches the symptom in
ComponentRegistry.register(). Auditing adjacent code surfaces three remaining issues
(one a duplicate of the same pattern, one a finalizer-leak in a helper, one the
underlying root cause), plus a tightening opportunity on AlreadyRegistered.

This plan addresses all four.

Goals

  1. Make the component_node_subclasses_by_name cache safe and self-cleaning.
  2. Stop util.weakref.cached_ref from leaking a new finalize per call.
  3. Eliminate the underlying reimport trigger in @djc_test teardown (Option B/C from weakref.finalize causes registry corruption #1598).
  4. Tighten ComponentRegistry.register() to an additive contract (raise on any
    replacement) and track finalizers per-name so they can be detached eagerly.

The four are independent but related; sequencing #3 first means #1, #2 and #4 are exercised
in their normal (non-reimport) code paths during the rest of the work.


1. component_node_subclasses_by_name — make per-registry

Problem

src/django_components/component.py:3465 declares a module-global dict keyed by start_tag,
storing (subcls, registry) tuples. At 3618-3619
two finalize(...) calls try to pop the entry when either subcls or registry dies.

The dict holds a strong ref to the tuple; the tuple holds strong refs to both
subcls and registry. So neither can be GC'd while the entry exists, and the
entry can only be removed by these finalizers — a self-pinning cycle. The
finalizers are dead code in CPython.

If the cycle were ever broken (e.g. by switching to weak refs without an identity
check), the same stale-finalizer bug as #1598 would become live: stale callback
pops a newer entry under the same start_tag.

Tests force-clear the dict in _clear_djc_global_state (util/testing.py:490),
which is why the leak hasn't surfaced. In long-running production processes that
dynamically construct registries/components, every parsed tag pins a ComponentNode
subclass and a ComponentRegistry forever.

Recommended design

Move the cache to a per-registry attribute. Lifetime then follows the registry's
own lifetime automatically — no finalizers, no identity checks, no cross-registry
collisions.

  • Add _node_subcls_cache: dict[str, type[ComponentNode]] to ComponentRegistry.__init__
    (component_registry.py:241).
  • Rewrite ComponentNode.parse() to look up / create the subclass on registry._node_subcls_cache
    instead of the module-global dict.
  • The cached_registry is not registry RuntimeError at
    component.py:3623-3626 becomes structurally
    impossible and is dropped.
  • The cached_subcls.end_tag != end_tag RuntimeError at
    component.py:3627-3630 stays — it catches
    intra-registry tag-formatter inconsistency.
  • Delete the module-global component_node_subclasses_by_name dict and both
    finalize(...) calls.
  • Delete component_node_subclasses_by_name.clear() from
    util/testing.py:490 — no longer needed.

What we leave alone

  • subcls still subclasses the user's component class cls; that ref is unchanged.
  • No public API changes — component_node_subclasses_by_name is module-private
    (not in __init__.py).

2. util/weakref.cached_ref — stop leaking finalizers

Problem

util/weakref.py:10-23:

def cached_ref(obj):
    obj_id = id(obj)
    if obj_id not in GLOBAL_REFS:
        GLOBAL_REFS[obj_id] = ref(obj)
    finalize(obj, lambda: GLOBAL_REFS.pop(obj_id, None))   # attached every call
    return GLOBAL_REFS[obj_id]

Every call attaches a new finalize to obj, even on cache hit. Today this is
only called twice (__init_subclass__ and ComponentRegistry.__init__), so the
leak is one finalizer per class/registry — negligible. But the helper is in
util/ and intended for reuse; the contract is wrong.

Recommended design

Move the finalize(...) inside the if obj_id not in GLOBAL_REFS: branch.
One-line fix.

def cached_ref(obj):
    obj_id = id(obj)
    if obj_id not in GLOBAL_REFS:
        GLOBAL_REFS[obj_id] = ref(obj)
        finalize(obj, lambda: GLOBAL_REFS.pop(obj_id, None))
    return GLOBAL_REFS[obj_id]

Correctness note: id() reuse cannot occur while the original object's finalizer
is still pending (CPython doesn't reuse an address before the object is freed,
and the finalizer fires before freeing). So the existing key-by-id() scheme
remains sound.


3. Stop unnecessary sys.modules clearing in @djc_test teardown (Option B/C from #1598)

Problem

_clear_djc_global_state (util/testing.py:545-549)
pops every module in LOADED_MODULES from sys.modules. LOADED_MODULES is populated
in autodiscovery._import_modules (autodiscovery.py:108-109)
whenever is_testing() is true, regardless of whether importlib.import_module()
actually re-executed the file.

Concrete sequence:

  • Production startup imports tests.components.foo → sys.modules['tests.components.foo'] exists.
  • Test 1 @djc_test setup → autodiscover() calls import_module('tests.components.foo') → no-op
    (module cached), but LOADED_MODULES.append('tests.components.foo').
  • Test 1 teardown → pops 'tests.components.foo' from sys.modules.
  • Test 2 @djc_test setup → autodiscover() calls import_module('tests.components.foo') →
    re-executes the file → creates Foo_v2 with class_id == Foo_v1.class_id.
  • @register("foo") runs again → silent overwrite, stale finalizer attached to Foo_v1.

This is the exact precondition for #1598. PR #1630 fixed the consequence; this
plan removes the precondition.

Recommended design

Snapshot sys.modules keys at test setup; at teardown, only pop modules that
both appear in LOADED_MODULES and were absent from the setup snapshot.

  • Capture frozenset(sys.modules) inside the _wrapper_impl block at
    util/testing.py:336 (alongside
    _all_components and _all_registries_copies).

  • Pass it as a new parameter to _clear_djc_global_state.

  • At util/testing.py:545-549 replace the
    unconditional pop with:

    for mod in LOADED_MODULES:
        if mod not in initial_sys_modules:
            sys.modules.pop(mod, None)
    LOADED_MODULES.clear()

Edge cases

  • A test that explicitly del sys.modules[mod] (e.g.
    tests/test_autodiscover.py:62-65) still works:
    after that del, the next import_module re-executes; mod ends up in
    LOADED_MODULES and absent from the snapshot → cleared at teardown. Same as today.
  • Modules brought in by test fixtures (not in snapshot, in LOADED_MODULES) are still cleared.
  • This change does NOT alter LOADED_MODULES's population logic — only what's cleared at teardown.

4. ComponentRegistry.register() — strict contract + finalizer bookkeeping

Problem

component_registry.py:344-368 currently:

This is semantically odd: the user's intent in calling register(name, Y) after
register(name, X) is the same in both branches ("replace 'foo' with Y"). The
registry treats them differently only because of a hash collision. The silent
branch is also the trapdoor #1598 went through.

The PR #1630 defense (id-check inside the callback at fire time) is the only thing
keeping the silent branch from corrupting registry state.

Recommended design — always raise on replacement

register() becomes additive: same-object re-registration is a no-op, anything
else raises. No more class_id special-casing.

New register() logic (replacing component_registry.py:344-368):

existing_entry = self._registry.get(name)
if existing_entry is not None:
    if existing_entry.cls is component:
        return  # No-op: re-registering the exact same class object
    raise AlreadyRegistered(
        f'The component "{name}" has already been registered. '
        f'Call `registry.unregister("{name}")` before registering a different class.'
    )

# ...proceed to register...

This also drops the class_id != component.class_id check — is identity is the
real criterion for "same component."

Finalizer bookkeeping

Independent of the contract change, store the finalizer per-name and detach it
when the entry leaves the registry. This removes the dependency on #1630's
id-check-at-fire-time defense.

  • Add self._finalizers: dict[str, weakref.finalize] = {} to
    ComponentRegistry.__init__.
  • In register() (after the new contract check passes): store the new
    finalize(...) return value in self._finalizers[name].
  • In unregister(): pop self._finalizers[name] and call .detach() on it.
  • The id() identity check in the finalizer callback stays as defense in depth
    (cheap, no behavior change).

What this does to existing tests

  • test_allow_duplicated_registration_of_the_same_component
    (test_registry.py:139-145) — passes unchanged
    (same object, no-op).
  • test_prevent_registering_different_components_with_the_same_name
    (test_registry.py:133-137) — passes unchanged.
  • test_stale_component_finalizer_does_not_unregister_replacement
    (test_registry.py:147-161, added by Fix stale registry finalizer #1630) —
    rewrite to assert pytest.raises(AlreadyRegistered) on the second register,
    and add a separate test that exercises the new finalizer-detach behavior after
    an explicit unregister() + register() cycle.
  • tests/test_autodiscover.py and tests/test_component_dynamic.py — should be
    unaffected. After fix Add Django 1.7 to the build matrix #3 lands, the same-class_id-different-object scenario
    doesn't arise from autodiscover-driven reimports. The test_import_libraries
    tests already call unregister() explicitly before re-importing
    (test_autodiscover.py:55-65).

What this means for users

  • @register("name") decorator usage is unaffected (decorator runs once per
    module-execution, not per import).
  • autodiscover() / import_libraries() called multiple times: unaffected
    (modules in sys.modules aren't re-executed; @register doesn't re-run).
  • Users with explicit reload scripts (del sys.modules[m]; import m) must add
    a registry.unregister(name) call before re-importing. This is documented
    in the new AlreadyRegistered message itself.

Files to modify

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_registry in tests/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_tag in tests/test_registry.py:
    proves cross-registry collisions no longer raise the old RuntimeError.
  • More clearly define support #2 Add test_cached_ref_attaches_one_finalizer in tests/test_util_weakref.py
    (new file): call cached_ref(obj) N times, assert len(weakref.getweakrefs(obj)) is
    bounded (use the finalize count, not weakref count, since cached_ref only 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_test in
    tests/test_autodiscover.py: snapshot a module's id(), run two @djc_test cycles,
    assert the module object is the same.
  • Reviving the project #4 Rewrite test_stale_component_finalizer_does_not_unregister_replacement
    in tests/test_registry.py:
    • First assertion: registering a second class object under the same name (regardless
      of class_id) raises AlreadyRegistered.
    • Second assertion: after unregister("testcomponent") + register("testcomponent", v2),
      a gc.collect() of v1 does NOT touch the entry for v2 (i.e. the detach worked).
  • Reviving the project #4 Add test_register_after_unregister_replaces_finalizer_cleanly: register
    v1, unregister, register v2, assert len(registry._finalizers) == 1 and that the
    entry maps to v2.
  • Reviving the project #4 Add test_register_different_class_with_same_class_id_raises: covers the
    exact weakref.finalize causes registry corruption #1598 scenario — two fabricated classes with identical class_id but distinct
    identity; the second register() 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 touched

Docs 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; call unregister(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 --strict to validate.

Commit split (one branch, four commits)

  1. Fix More clearly define support #2 — cached_ref finalizer leak. Trivial one-line move, independent of everything else.
  2. Fix Add Django 1.7 to the build matrix #3 — sys.modules snapshot in @djc_test teardown. Eliminates the
    reimport that drives the rest. Should land before Reviving the project #4 so the strict register
    contract doesn't trip existing tests.
  3. 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.
  4. Fix A better setup for CI #1 — per-registry ComponentNode subclass cache. Independent of Add Django 1.7 to the build matrix #3/Reviving the project #4
    but touches component.py and component_registry.py like 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]] = {}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This cache is no longer global, but now scoped to ComponentRegistry

@JuroOravec

Copy link
Copy Markdown
Collaborator Author

Hey @EmilStenstrom, look who's back :D

@JuroOravec
JuroOravec merged commit 83962e4 into master May 29, 2026
16 checks passed
@JuroOravec
JuroOravec deleted the fix/finalizer-and-reimport-audit branch May 29, 2026 22:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant