Skip to content

fix: run extension hooks and Const functions with no Citry lock held - #319

Merged
JuroOravec merged 1 commit into
mainfrom
fix/first-use-cache-races
Oct 24, 2026
Merged

JuroOravec merged 1 commit into
mainfrom
fix/first-use-cache-races

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

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:

  • an extension hook rendered another component;
  • a function in a component's Dependencies class, or a function marked Const, rendered another component.

A slow hook also held up renders of every other component on the same Citry instance.

The rule is now that no user code runs while a Citry lock is held. User code here means:

  • the load hooks (on_template_loaded, on_js_loaded, on_css_loaded, on_messages_loaded);
  • the compile hooks (on_template_foreign_spans, on_template_foreign_compiled, on_template_compiled);
  • Dependencies functions and merges;
  • Const functions and template expressions;
  • autodiscovery imports.

Every value Citry computes on first use follows one pattern (Citry._load_and_store):

  1. Read the cache with no lock.
  2. On a miss, compute the value with no lock held, including the hooks.
  3. Take a short lock and store the first result that finished. Every caller gets that stored result.

This covers:

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 Const function 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:

  • Renders and lookups on other threads now wait for it to finish, with no lock held, instead of raising CitryLifecycleInProgress. They then build the tag rules themselves if no thread has stored them yet.
  • An owner that fails wakes its waiters. Each waiter then runs the setup itself and raises the same error.
  • These cases still raise instead of waiting:
    • a thread inside a module import;
    • a thread running a reset;
    • any wait that lasts over 60 s, so a setup that waits for its waiter fails instead of hanging;
    • a second thread calling initialize() or autodiscover().

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)

  • Whole-namespace reads of a live class or module namespace now go through _static_class_namespace_copy or vars(module).copy(). A source check in tests/test_namespace_reads.py reports new whole reads in the common forms.
  • Events State type hints are read again when a namespace changes mid-read. On Python 3.14, per-field annotations are read through _annotation_introspection.
  • Each event schema converts to one class across threads.

Docs

  • Hook docstrings. The load and compile hooks give the usual case (once per class) and say when a hook runs again: once per thread on concurrent first loads, and up to three times on each thread around a reset. Side effects must replace earlier ones. The reset hooks (on_template_reset, on_files_reset, on_citry_cleared) say they must not wait for a thread that renders.
  • Extensions guide. A new section, "Make hooks safe to rerun" (anchor #hooks-that-run-twice), with a wrong and a right example.
  • Const page and discovery page. The Const page says an expression can be evaluated more than once. The discovery page says when renders wait and when they raise.
  • CitryLifecycleInProgress docstring updated to match.
  • Design docs. docs/design/asset_loading.md section 6 and docs/design/extensions.md updated.

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:
    • a JS or template hook that renders a cached component during a reset;
    • cross-engine Dependencies;
    • a Const function during reset_template;
    • a slow on_template_loaded that no longer holds up warm renders;
    • compile hooks that render each other's component;
    • a reset hook rendering on its own thread;
    • ConstBodyCache eviction during a build, plus the bounded retry and the template-id key;
    • the render-path reset test, which shows the new template;
    • reset-hook state being kept.
  • tests/test_first_use_caches_threads.py, reworked. It covers:
    • a hook running once per class on one thread;
    • registering a class during a hook, which does not rerun it;
    • two threads inside one hook keeping one result;
    • resets during slow hooks for JS, template, messages (the i18n catalog ends on the new text), Dependencies and the browser script;
    • the bounded retry;
    • one schema class and one dispatcher across threads.
  • tests/test_first_renders_without_initialize.py. It covers:
    • 8 threads × 10 rounds of first renders of the same component, with no initialize(), under both autodiscover=False and autodiscover=True: zero errors, and identical output once instance ids are removed;
    • two different components rendered on two threads;
    • a failed discovery, where no waiter hangs;
    • a render from inside the setup;
    • a discovered module that joins a rendering thread;
    • a reset hook rendering during another thread's discovery.

Existing tests changed. Every one of them runs several threads at once; no single-thread test changed:

Test Reason
test_assets.py::TestConcurrentLoading::test_concurrent_first_loads_share_one_template_record 8 threads: asserts one shared record instead of one hook call.
test_extension.py::TestTemplateHooks::test_lazy_nested_foreign_template_renders_the_same_across_threads 8 threads: the compile hook may run once per thread; every render is correct.
test_render_template.py::test_render_template_shares_load_span_and_compile_work_across_threads 4 workers: hooks may run once per worker, and later renders run none.
test_autodiscovery.py::TestConcurrentDiscovery::test_lookups_on_other_threads_wait_for_discovery_to_finish Lookups during another thread's discovery now wait and get the full registry instead of raising.
test_autodiscovery.py::TestConcurrentDiscovery::test_import_lock_cycle_fails_fast Parametrized: discovery started by a first lookup must also fail fast inside a module import.
test_tag_rules.py::TestBuildTagRules::test_concurrent_registration_cannot_publish_stale_rules A registration during a rules build no longer raises; the stored rules include it.

A new tag-rules test also covers rules that are never stored from a stale build.

Evidence

  • The six lockaudit scripts (d1, d2, d3, d4, d4b, p1) print FINISHED. In p1 the warm render took 0.000 s while the slow hook ran. On main, d2 and d4 hang. d1, d3, d4b and p1 failed only with this branch's earlier version, which held locks around more user code.
  • A run of the lock-order tracer over the new thread tests and the asset, extension and i18n suites recorded no lock-order cycles.
  • The citry and citry_ui suites pass: 9,205 tests.
  • mypy passes on packages/py/citry/citry, including with --platform linux.
  • ruff check and ruff format pass.
  • The fast gate (scripts/check.py --profile fast) passed on 61d3a90, including the cargo phases, against citry_core rebuilt from this branch.
  • mypy --platform linux passes on every path the gate type-checks.

Review

  • An independent adversarial review, run three rounds at high effort with separate prose passes. It found these problems, all now fixed:
    • a Const body that kept the old template;
    • hook state lost during reset hooks;
    • get_dependencies(Component) returning None;
    • the messages fallback order;
    • the simple-runtime template check;
    • a setup wait that could hang;
    • stale tag rules.
  • A docs cold read of the changed public text, run twice.

🤖 Generated with Claude Code

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]>
@JuroOravec
JuroOravec merged commit 2c822b1 into main Oct 24, 2026
26 of 27 checks passed
@JuroOravec
JuroOravec deleted the fix/first-use-cache-races branch October 24, 2026 15:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant