Skip to content

First renders on several threads fail with "dictionary changed size during iteration" when a page uses simple="vue" components #271

Closed

Description

@JuroOravec

What happens

A server starts, calls engine.initialize(), and then several worker
threads render a page for the first time at once. The page contains
simple="vue" components (components Citry renders without creating a
Component instance). One or two of the threads fail with:

RuntimeError: An error occurred while rendering components Page > Row:
dictionary changed size during iteration

The other threads render normally, and once every class on the page has
rendered at least once the error stops. So it shows up as a few failed
requests right after a deploy or restart.

Reproduction

Sixteen threads render a page of 20 simple="vue" rows on a fresh engine.
The script lowers sys.setswitchinterval so that threads switch often enough
to show the race within a few attempts. With the default interval this small
page ran 200 attempts without a failure, so the race needs either a busy
server or bad luck to show up.

import sys
import threading
import traceback
from typing import Any

from citry import Citry, Component

sys.setswitchinterval(1e-6)
N_THREADS = 16
errors: list[BaseException] = []


def run_once() -> None:
    engine = Citry(secret="x" * 32, autodiscover=False)

    class Row(Component):
        citry = engine
        simple = "vue"

        class Kwargs:
            text: str

        template = """
            <li>{{ text }}</li>
        """

    class Page(Component):
        citry = engine

        def template_data(self, kwargs: Any, slots: Any) -> dict[str, Any]:
            return {"labels": [f"row {i}" for i in range(20)]}

        template = """
            <ul>
              <c-Row c-for="label in labels" c-text="label" />
            </ul>
        """

    engine.initialize()
    barrier = threading.Barrier(N_THREADS)

    def worker() -> None:
        barrier.wait()
        try:
            Page().render().serialize()
        except BaseException as exc:
            errors.append(exc)

    threads = [threading.Thread(target=worker) for _ in range(N_THREADS)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()


for attempt in range(200):
    run_once()
    if errors:
        print(f"attempt {attempt}: {len(errors)} of {N_THREADS} failed")
        traceback.print_exception(errors[0])
        break
else:
    print("no failure in 200 attempts")

Output (origin/main 88d7e4869, Python 3.14.9, trimmed):

  File ".../citry/component_render.py", line 582, in _render_simple_vue_leaf
    admission = _simple_vue_admission(component_class)
  File ".../citry/component_render.py", line 244, in _simple_vue_admission
    admission = _compute_simple_vue_admission(component_class, key)
  File ".../citry/component_render.py", line 348, in _compute_simple_vue_admission
    for member, value in _static_class_dict(base).items():
RuntimeError: An error occurred while rendering components Page > Row:
dictionary changed size during iteration
attempt 0: 2 of 16 failed

It fails within the first three attempts in every run, with
CITRY_NATIVE_RENDER=1 and with CITRY_NATIVE_RENDER=0, on Python 3.14.9
and on Python 3.12.15 with a release build of citry_core.

Cause

To decide whether a simple="vue" class can render without a Component
instance, _compute_simple_vue_admission loops over the class's own
namespace (packages/py/citry/citry/component_render.py:348) and stores
the answer on the class (the "admission record").
_static_class_dict (citry/_class_introspection.py:43) returns the live
mappingproxy, not a copy.

During the same first render, other threads add attributes to that same
class namespace, because several per-class results are computed on first use
and stored on the class:

  • _citry_template, stored by load_template (citry/assets.py:309)
  • _citry_dependencies_cache, _resolved_css, _resolved_js,
    _resolved_messages, _citry_component_script_capture
  • _citry_simple_vue_admission itself, stored by
    type.__setattr__ right after the computation
    (component_render.py:245)

When one of those writes lands while another thread is in the loop at line
348, Python raises RuntimeError. The same loop also runs again whenever the
admission record goes stale (for example after reset_template()), so a
later reload under load can hit it as well.

_plain_base_snapshot (component_render.py:251) iterates a live namespace
the same way, but it reads only plain (non-Component) bases, which Citry does
not write to. I checked the other render-time loops over class namespaces
(_linting.py:581, _simple_declarations.py:218, ext/events/handlers.py:431,
ext/events/state.py:122, extension.py:1923): they read nested
declaration classes or run at class definition, not classes that get cache
attributes written during a render.

Does it affect both render paths?

Yes. The admission check runs before Citry chooses between the native (Rust) and
the Python renderer (component_render.py:651), so CITRY_NATIVE_RENDER=0 fails the same way.

Suggested fix

  • Copy the namespace before looping: _static_class_dict(base).copy()
    (the mappingproxy.copy() call copies the underlying dict in one step) or
    tuple(...items()). This removes the error but still lets one thread see a
    half-filled namespace.
  • Better: compute the admission record under a per-class lock (for example
    the template's compile_lock, which the function already takes for the
    plan), so only one thread computes it and the others reuse its result.
  • Separately, consider skipping Citry's own cache attributes in the member
    check (they are added by Citry, not authored), so whether one was already
    written cannot change the answer. Today none of them is rejected, but
    nothing enforces that.
  • Add a regression test that renders a simple="vue" page from several
    threads on a fresh engine.

Found while shipping the native render levels (#263, #265-#269).

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