Repository navigation
fix: run extension hooks and Const functions with no Citry lock held - #319
Merged
Merged
Conversation
A render could hang when an extension hook, a Dependencies function or a Const function rendered another component while another thread reset a template or files, as a hot reload does: the user code ran under one Citry lock and the reset held the lock it then needed. A slow hook also held up renders of other components on the same engine. Every value Citry computes on first use now loads with no lock held and takes a short lock only to store the first finished result (Citry._load_and_store), which every caller then gets. This covers the template, JS, CSS and messages of a class, its merged Dependencies (including the bases' results, stored together after the merge), the script Citry sends the browser, standalone templates, the const-body cache (#315, now keyed by the loaded template's id too), the compiled form of a template and its body caches, nested template bodies, the tag rules templates are checked against, and the Events configuration and dispatcher. A reset moves an engine revision counter, before and again after its own hooks; registration moves separate counters for the standalone templates and the tag rules, and an eviction moves the const-body cache's counter. A load that sees its counter move while it ran runs again from the start, so the hooks of its last run act on the new source and their side effects, such as the i18n extension's catalog entry, end on the new text. After three runs the last result is stored anyway, so a stream of resets cannot stall a render; tag rules from such a run serve that one parse and are not stored. On one thread with no reset a hook still runs once per class. Without initialize(), the first render runs the engine's one-time setup (discovery and built-in components). Renders and lookups on other threads now wait for it, with no lock held, instead of raising CitryLifecycleInProgress, and then build the tag rules themselves if no thread has stored them yet. A thread that is importing a module or running a reset still raises, because the setup may be waiting for that import or for the reset's locks, and a wait gives up after 60 s, so a setup that waits for its waiter fails instead of hanging. Other competing lifecycle operations raise as before. Resets keep their locks; on_template_reset, on_files_reset and on_citry_cleared docstrings say those hooks must not wait for another thread. The load and compile hook docstrings, the extensions guide ("Make hooks safe to rerun"), the Const and discovery pages and the design docs say that a hook can run more than once and that side effects must replace earlier ones. This change also: - copies a live class or module namespace before reading all of it (_static_class_namespace_copy, vars(module).copy()), with a source check in tests/test_namespace_reads.py (#293); - reads Events State type hints again when a namespace changes mid-read, and reads per-field annotations through _annotation_introspection on Python 3.14; - converts each event schema to one class across threads. Tests: tests/test_hooks_run_without_locks.py has a two-thread test with a join timeout for each hang found while checking the locks, plus compile hooks that render each other's component, Const bodies across a reset, and reset hooks. tests/test_first_use_caches_threads.py covers one kept result for two threads inside a hook, resets during slow hooks, the bounded retry and one run per class on one thread. tests/test_first_renders_without_initialize.py covers concurrent first renders with and without discovery, a failed discovery, a render from inside the setup, a discovered module that joins a rendering thread, and a reset hook that renders during another thread's discovery. Six existing tests that run several threads at once now assert the new contract. Fixes #292 Fixes #293 Fixes #315 Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #292
Fixes #293
Fixes #315
Follow-up: #316 (cache backend calls while the cache extension's revision lock is held).
What changes
A render could hang in two situations. In both, user code ran while a Citry lock was held, and another thread doing a reset (as a hot reload does) held the lock that the user code then needed:
Dependenciesclass, or a function markedConst, rendered another component.A slow hook also held up renders of every other component on the same
Citryinstance.The rule is now that no user code runs while a Citry lock is held. User code here means:
on_template_loaded,on_js_loaded,on_css_loaded,on_messages_loaded);on_template_foreign_spans,on_template_foreign_compiled,on_template_compiled);Dependenciesfunctions and merges;Constfunctions and template expressions;Every value Citry computes on first use follows one pattern (
Citry._load_and_store):This covers:
Dependencies, including the bases' merged results, which are stored together after the merge;Resets
Resets keep their locks. A reset moves a revision counter before its hooks run and again after them.
A load that sees the counter move while it ran starts over: it reads the source again and runs the hooks again. So the hooks of the last run act on the new source, and their side effects end on the new text. One example is the i18n extension's catalog entry, which replaces the component's source.
The retries are bounded at 3 runs. After that the last result is stored anyway, so a stream of hot reloads cannot stall a render. The exception is tag rules from a run that saw the counter move: they serve that one parse and are not stored, because nothing would replace them later.
On one thread with no reset, a hook still runs exactly once per class. A test checks this.
The const-body cache key now names the template
A body built from the template that existed before a reset is stored under that template's id. Renders of the new template therefore never find it. Before this change, a reset during a
Constfunction made later renders show the old template.First renders without
initialize()With no
initialize()call, the first render runs the instance's one-time setup: discovery and built-in creation. Behaviour while that setup runs:CitryLifecycleInProgress. They then build the tag rules themselves if no thread has stored them yet.initialize()orautodiscover().This also fixes a failure that already existed on main: two different components rendered for the first time on two threads, without
initialize().The remaining wait has the same import-lock hazard as main. The exposed case is a render started inside a module import that the setup thread is also importing. The import-frame check covers the direct case, so it raises at once, as on main. A thread that the import starts and joins is covered by the 60 s bound. Calling
initialize()before starting threads avoids the wait and this hazard; the docs recommend it.Known residual, left as is. A reset hook that renders while no other thread runs the setup makes the resetting thread run discovery itself, while it holds the reset's locks. If a module imported then starts a thread that loads a template and joins it, that thread waits on the template source lock with no time limit. This needs a reset as the very first action, a render from its hook, and a module that joins a rendering thread at import time.
Making such a thread raise instead would break the single-threaded case, where a reset hook renders before anything else has run.
Also on this branch (#293 and an Events fix)
_static_class_namespace_copyorvars(module).copy(). A source check intests/test_namespace_reads.pyreports new whole reads in the common forms.Statetype hints are read again when a namespace changes mid-read. On Python 3.14, per-field annotations are read through_annotation_introspection.Docs
on_template_reset,on_files_reset,on_citry_cleared) say they must not wait for a thread that renders.#hooks-that-run-twice), with a wrong and a right example.CitryLifecycleInProgressdocstring updated to match.docs/design/asset_loading.mdsection 6 anddocs/design/extensions.mdupdated.Tests
New files:
tests/test_hooks_run_without_locks.py. Each hang found while checking the locks becomes a two-thread test with a join timeout:Dependencies;Constfunction duringreset_template;on_template_loadedthat no longer holds up warm renders;ConstBodyCacheeviction during a build, plus the bounded retry and the template-id key;tests/test_first_use_caches_threads.py, reworked. It covers:Dependenciesand the browser script;tests/test_first_renders_without_initialize.py. It covers:initialize(), under bothautodiscover=Falseandautodiscover=True: zero errors, and identical output once instance ids are removed;Existing tests changed. Every one of them runs several threads at once; no single-thread test changed:
test_assets.py::TestConcurrentLoading::test_concurrent_first_loads_share_one_template_recordtest_extension.py::TestTemplateHooks::test_lazy_nested_foreign_template_renders_the_same_across_threadstest_render_template.py::test_render_template_shares_load_span_and_compile_work_across_threadstest_autodiscovery.py::TestConcurrentDiscovery::test_lookups_on_other_threads_wait_for_discovery_to_finishtest_autodiscovery.py::TestConcurrentDiscovery::test_import_lock_cycle_fails_fasttest_tag_rules.py::TestBuildTagRules::test_concurrent_registration_cannot_publish_stale_rulesA new tag-rules test also covers rules that are never stored from a stale build.
Evidence
packages/py/citry/citry, including with--platform linux.scripts/check.py --profile fast) passed on 61d3a90, including the cargo phases, against citry_core rebuilt from this branch.--platform linuxpasses on every path the gate type-checks.Review
Constbody that kept the old template;get_dependencies(Component)returningNone;🤖 Generated with Claude Code