Skip to content

First renders on several threads run on_js_loaded once per thread and build event schemas more than once #292

Closed

Description

@JuroOravec

What happens

Citry computes some values the first time a component or engine needs
them and stores them for later calls. A few of these stores check and
store without a lock. When several threads reach one at the same time, as
a server's workers do right after it starts, each thread does the work,
and the last one to store wins.

An extension's on_js_loaded hook runs once per thread. The hook's
docstring says it is "called once per class". With eight threads making
the first render of one component at the same moment, it ran eight times:

import threading, time
from citry import Citry, Component, Extension

calls = []

class Minify(Extension):
    name = "minify"

    def on_js_loaded(self, ctx):
        calls.append(ctx.component_class.__name__)
        time.sleep(0.01)  # stands in for real work
        return None

app = Citry(autodiscover=False, extensions=[Minify])

class Card(Component):
    citry = app
    template = """
        <p>Card</p>
    """
    js = """
        $component({data() { return {}; }});
    """

barrier = threading.Barrier(8)

def worker():
    barrier.wait()
    Card().render().serialize()

threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(len(calls))
8

Without the sleep it printed 1 in three runs. Any hook that waits
on I/O or otherwise lets another thread run (reading a file, calling a
minifier) opens the same window. on_css_loaded shares the code. Run on
Python 3.14.9 with the GIL, with citry from #288's branch
(fix/sandbox-surrogate-literals), which does not change these files.

An event schema is converted into more than one class. Eight threads
calling convert_schema_class on a new schema class at once got more than
one converted class in 50 of 50 attempts (with
sys.setswitchinterval(1e-6)). Its docstring says the conversion is
"computed once per class and reused, so nested schema instances keep a
stable class identity across calls". I did not find a code path that
fails because of the second class, so the effect on a running app is
unproven.

Cause

All on main; #285 does not change these files.

  • _load_asset_content in packages/py/citry/citry/assets.py:412-430
    checks for the stored value (:418), runs the hook (:425 and
    :427), then stores (:429), with no lock between.
  • convert_schema_class and _schema_info in
    packages/py/citry/citry/ext/events/schemas.py:133 and :244 use
    functools.cache, which does not stop two threads from running the
    function for the same argument. Each caller gets its own result, and
    the cache keeps the last one stored.
  • dispatcher_for and configure_render_encoder in
    packages/py/citry/citry/ext/events/renderers.py:101-140 read and write
    _CONFIGURATIONS and config.dispatcher without a lock. Two first
    event requests can each build a configuration and a dispatcher, and
    can end up using different ones.
    configure_render_encoder runs at setup, so a race there needs two
    setup calls at once.

#285 fixed two races of this kind that made renders fail (Fixes #271)
and listed these as left over, because they repeat work instead of
raising.

Who hits it

  • Extension authors whose on_js_loaded or on_css_loaded hook has a
    side effect or is slow: the hook runs once per thread on a server's
    first concurrent renders of a component, not once per class.
  • Apps with Events on a threaded server: the first concurrent event calls
    for a schema each convert it, and two dispatchers can exist briefly.

Fix direction

Use the pattern #285 used for default_events_producer: compute outside a
lock, then store with setdefault under a lock and return the stored
value, so every thread gets the same object. For the asset hooks, which
should run only once, hold a per-engine lock while loading, as
load_template already does with _template_source_lock
(assets.py:289). Replace functools.cache on the two schema functions
with a dict filled by setdefault. Add a barrier test for each, like
#285's test_default_producer_is_one_object_when_threads_build_it_at_once.

Found while working on #285 (fixes #271).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions