Skip to content

Render hangs when a Const callable renders a component while another thread resets a template #315

Closed

Description

@JuroOravec

A render can hang forever when a function marked Const(...) renders another component for the first time while another thread resets a template on the same Citry instance (for example during a hot reload).

How to reproduce

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

app = Citry(autodiscover=False)
in_build = threading.Event()

class Leaf(Component):
    citry = app
    template = """
        <b>{{ value }}</b>
    """

def helper(v):
    in_build.set()
    time.sleep(0.5)  # gives the reset time to take its locks
    return Leaf(value=v).render().serialize()

class Page(Component):
    citry = app
    template = """
        <div>{{ helper(value) }}</div>
    """

class Other(Component):
    citry = app
    template = """
        <p>other</p>
    """

def render():
    Page(
        value=Const("fixed"),
        helper=Const(helper),
    ).render().serialize()

def reset():
    in_build.wait()
    Other.reset_template()

threads = [threading.Thread(target=f) for f in (render, reset)]
for t in threads:
    t.start()
for t in threads:
    t.join()  # never returns on main (01ba48efd)

Other is unrelated to Page and Leaf; resetting any template on the engine is enough.

Why it hangs

The two threads take the same two locks in opposite order:

  1. Render thread. ConstBodyCache.get_or_build (packages/py/citry/citry/constness.py:1151) holds the cache's lock while build() computes the constant parts of Page's body. That calls helper(...), which renders Leaf for the first time. load_template (assets.py:289) then waits for Citry._template_source_lock.
  2. Reset thread. reset_template (assets.py:461) holds _template_source_lock and calls _evict_component_cache, which reaches ConstBodyCache.evict_component (constness.py:1166) and waits for the cache's lock.

The root cause is that get_or_build runs user code (the Const callable, through build()) while it holds a lock.

Suggested fix

Same approach as #292 and #293: run build() outside the lock, then store the result with a check-then-set under the lock (keep the entry that was stored first). On concurrent first renders build() may then run more than once, but only one result is kept. Add a regression test with the two threads above and a timeout.

Found while auditing locks for #292 and #293. It is separate from them because it needs no extension hook.

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