Skip to content

feat(events): experimental, typed _render_inputs option for Render actions - #800

Merged
JuroOravec merged 5 commits into
mainfrom
feat/events-render-inputs
Nov 19, 2026
Merged

JuroOravec merged 5 commits into
mainfrom
feat/events-render-inputs

Conversation

@JuroOravec

@JuroOravec JuroOravec commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

(Opus 5.5)

Summary

When an event handler returns a component, Citry renders it again with no template globals and no provided values. A template that reads a request value, such as the current user, Django's request, a context processor value, or the locale, fails the call. This adds an Experimental Events option, _render_inputs, that supplies those values.

What the function returns: the keyword arguments Citry passes to .render() for each component a Render re-renders. These are the same template_globals= and provides= you would pass when rendering the component yourself. When the function returns

{"template_globals": {"user": user}, "provides": {"locale": user.locale}}

Citry renders the returned component as if you had written

TaskList(tasks=tasks).render(
    template_globals={"user": user},
    provides={"locale": user.locale},
)

Typed: the return value is RenderInputs, a TypedDict exported from citry.ext.events. Its two optional fields reuse the types of the render() parameters of the same name: shared aliases in citry/citry_element.py, which render()'s own signature also uses. The function type is Callable[[EventRequest], RenderInputs] | None, declared for type checkers on the typed citry.Events base.

from citry.ext.events import EventRequest, RenderInputs

def render_inputs(request: EventRequest) -> RenderInputs:
    user = request.native.user  # Django's HttpRequest
    return {
        "template_globals": {"user": user},
        "provides": {"locale": user.locale},
    }

Where to set it. You can set it for the whole app, or on one component's nested Events class:

# App-wide
citry = Citry(
    extensions_defaults={"events": {"_render_inputs": render_inputs}},
)

# For one component: assign a function defined outside the class
class TaskList(Component):
    class Events:
        _render_inputs = render_inputs

        def add(self, data: TaskIn): ...

Precedence: a component's own value wins over extensions_defaults["events"], and _render_inputs = None on a component turns the app-wide function off. This is the same three-level resolution as _context and _csrf (component, then extensions_defaults, then the built-in default, which is None). Citry uses the value of the component whose handler ran, for every Render in that call, including a different component the handler returns.

When it runs: once per event call, after the handler, and only when Citry renders a CitryElement for a Render. That covers the HTML fragment, the Vue prepared render, <c-mark> targets on both renderers, and the no-JavaScript answer. A render the handler built itself (a CitryRender) keeps its own inputs.

Error modes:

  • A value that is not a function or None, an async def function, or a function that cannot take exactly one argument raises ValueError. That includes a method written inside the Events class, because a method also expects self. The app-wide value fails at Citry(...) and a component's value at class definition.
  • A function that raises, or returns anything but a mapping with only template_globals/provides (each a mapping or None), fails the call with handler_error. The TypeError names the setting.
  • An EventError from the function answers with its own status.

This is change E1 of the citry-django redesign. citry-django will use it to give event re-renders request, context processor values and the locale.

Plan (Mechanism 2)

Prior art

  • CitryElement.render(template_globals=, provides=) (citry/citry_element.py:143) and render_prepared_direct(..., template_globals=, provides=) (citry/_vue/capture.py:304) already accept the inputs. The Events encoders called them with no arguments: ext/events/results.py:102 (HTML), _vue/events.py:663 (Vue), and _vue/capture.py:335 (the <c-mark> payload).
  • Per-component Events options resolve through EventsExtension._resolve_config_value (ext/events/extension.py, component, then extensions_defaults, then _FACTORY_DEFAULTS) in _compute_info, the same path _guard, _context and _csrf take. _csp_nonce (ext/events/handlers.py ENGINE_CONFIG_NAMES, dispatcher.py _page_csp_nonce) is the model for a per-call function carried on RenderEncodingContext (ext/events/results.py:72-85).
  • Citry.template_globals (citry/settings.py:874) is engine-wide but fixed, so it cannot hold per-request values. No existing hook supplies render inputs for Events.
  • How the _ options are listed in the versioning page: covered options at versioning.md:215-224, Experimental list at :290-320.

Chosen design

  • _render_inputs is an ordinary per-component Events option, resolved once at class definition into EventsInfo.render_inputs.
  • _call_render_inputs in _complete_call calls the calling component's function after CSRF, the State token check, the handler and the renderer check.
  • Two new RenderEncodingContext fields carry the result to every encoder's render() call.
  • The return value is typed as a TypedDict that reuses render()'s parameter types.
  • The name is in the Experimental list and not in the covered _ options, and the "Other _ names" bullet names it as an exception.

Alternatives considered

  1. Engine-wide only (the first version of this PR, like _csp_nonce). Rejected after maintainer review: a component, or a library of components, may need its own inputs. The per-component form costs nothing on the call path, because it is resolved at class definition.
  2. Pass the per-call Events instance (state, context, request) instead of EventRequest. Rejected: it gives the function handler-specific inputs, which would make it a second handler.
  3. Let each handler call .render(template_globals=..., provides=...) itself. It works today and stays supported, because such a render is left alone. Rejected as the main path because every handler would repeat it.
  4. An on_event_result hook. Rejected: actions are already encoded by then.

What would show the design is wrong:

  • a Citry render for an event call that does not get the inputs: a render path outside RenderEncodingContext, such as a future encoder or encode_actions(render_context=None) reached from production code;
  • real apps needing different inputs per rendered component within one call, rather than per calling component.

Security (Mechanism 7)

Places touched: text and markup ({{ }} of globals), JavaScript and JSON (Vue prepared data, fragment JSON), translated messages (a citry_i18n provide sets the locale), the CSP nonce (unchanged, still from _csp_nonce).

  • Author-only: the function is app code only, at both levels. The docs say so, and docs/design/trust_boundaries.md has a row in section 5.
  • Escaping: the values go through CitryElement.render() to render_impl, the same path as any render(template_globals=, provides=). They get the same sandbox, escaping and serialization. Provide keys still pass validate_provide_key.
  • Which code runs: the function cannot change which component or handler runs, because the handler has already returned the element.
  • Order of checks: it never runs before the request is checked. Citry's CSRF floor and the handler's _csrf policy, State token verification, _guard, and Django's CSRF middleware all run first. Tests cover a bad State token, and a missing X-Citry-Events header on WSGI, ASGI and Django.
  • Independent review: a reviewer with a security brief listed every route (HTML fragment, Vue prepared, <c-mark> on both renderers, no-JS answer, citry_i18n locale, nonce) and found each safe or author-only by design. It also checked the Mechanism 8 advisory survey (classes xss-escape, ssr-serialize, sanitizer-bypass, i18n-locale, csrf, island, xreq-state, cache-xuser). The cache-xuser finding led to a Cache.vary() note in the docs. The follow-up review of the per-component change did not reopen the survey. That change alters only which function is chosen, not how the values reach the page.

Versioning

  • This is a new Experimental option and a new Experimental type (RenderInputs). It breaks no covered behavior, so it needs a minor release (citry 1.1.0).
  • Both are named in the Experimental list, and the changelog line under Unreleased › Added is marked Experimental.
  • The "recognized names" error text gains _render_inputs. Error text is not covered.
  • No wire format changes, and no citry-core change.

Benchmark

This is a focused timing of one stateful Render call through EventsDispatcher.dispatch (a component with a 20-row loop). There is no Events render benchmark under benchmarks/. Threshold: flag more than 3% on the default path (no function set). Budget: about 10 minutes. The runs were repeated after the lookup moved from the settings dict to EventsInfo: 10 interleaved before/after rounds, each the median of 15 x 300 calls, on macOS with Python 3.13. The machine had load bursts on both sides (about 600 vs 645 us), so the table shows the median of the round medians and the best minimum:

Path before (main) after, no function
html-fragment/1, median of medians 602.8 us/call 611.8 us/call (+1.5%)
html-fragment/1, best minimum 595.3 594.3 (-0.2%)
vue-prepared/1, median of medians 458.0 463.2 (+1.1%)
vue-prepared/1, best minimum 454.7 456.5 (+0.4%)

All four figures are below the 3% threshold. Setting a function made no measurable difference in the first round of runs.

Tests

  • test_events_dispatch.py::TestRenderInputs (30 tests) covers:
    • HTML, Vue and <c-mark> renders, the no-JS answer, and an on_event answer all get the inputs;
    • the function gets the EventRequest and runs once per call;
    • it is not called for a handler-built render, a call without a render, or a bad State token;
    • the error modes;
    • the per-component form, component over app-wide precedence, None turning the app-wide value off, the calling component's function applying to a different returned component, a lambda or staticmethod in the class body, and a method refused at class definition.
  • test_events_host_parity.py (6 tests): WSGI, ASGI and Django each apply it, and none calls it before a failing CSRF check.
  • test_events_typing.py: checked by mypy and pyright in the gate.
    • Statically, a typed function assigned on a component and None are accepted, and element.render(**inputs) proves the TypedDict keys and types match render().
    • A manual negative check confirmed both checkers flag a wrong key, a wrong value type and a wrong parameter count. Pyright also checks the parameter type; mypy treats a Callable class attribute as a method, so it does not.
  • test_events.py: the recognized-names error text.
  • Checks:
    • ruff check and ruff format --check (ruff 0.14.13, the locked version), mypy both natively and with --platform linux, and pyright on the typing test: all clean.
    • Related pytest files (test_events*.py, Vue Events and markers, Django and request adapters, test_provide.py, test_extension.py, test_render.py): 2839 passed, 2 skipped, 1 xfailed, 1 failed.
    • The failure, test_events_pydantic_bounded.py::test_a_state_write_with_an_alias_key_under_a_forbidding_model_takes_the_json_answer, also fails on unchanged main in this venv (citry-core 2.1.2 from PyPI, not the lockfile environment).
  • Not run: scripts/check.py, and the docs build checks (python -m docs_site build-check), which need the docs extras. RenderInputs is added to docs_site/reference.yml, so the crossref guard can resolve its link.

Review

  • First version: an independent reviewer (technical, security, Mechanism 8, versioning, prose) and docs-cold-reader. Their findings are folded in: the call ordering, the no-JS and on_event tests, the async-host claim, the Cache.vary() note, and the docs restructure.
  • Maintainer follow-up (typed output, plain .render() statement, per-component form): an independent technical and prose review. Folded in:
    • RenderInputs added to the reference page;
    • a call-shape check replaces a check on the function's name, which allows a lambda or staticmethod;
    • the docs' error rule for the app-wide value is corrected;
    • the mypy limitation is documented in comments;
    • prose fixes.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KUhrHaXagmW5ZxpRAMwyom

JuroOravec and others added 4 commits November 19, 2026 16:07
…actions

A Render from an event handler had no template globals and no provided
values, so a template that reads a request value (the user, the locale,
Django's request) failed on re-render. The new engine-wide
extensions_defaults["events"]["_render_inputs"] function takes the call's
EventRequest and returns the template_globals and provides that Citry
passes to every component it renders for that call, on the HTML, Vue and
<c-mark> paths. It runs after the handler, so after the CSRF and State
token checks, and a render the handler built itself is left alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KUhrHaXagmW5ZxpRAMwyom
Ask for the render inputs only after the renderer check, test the
no-JavaScript answer and an extension's on_event answer, correct the
docs claim about which hosts call the function on the event loop, and
move and rewrite the docs section for first-time readers. The
versioning page now names _render_inputs as an exception to the
"Other _ names" rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KUhrHaXagmW5ZxpRAMwyom
The function now returns a RenderInputs TypedDict whose fields reuse the
types of CitryElement.render()'s template_globals and provides (shared
aliases in citry_element.py), and the typed Events base declares
_render_inputs as Callable[[EventRequest], RenderInputs] | None for type
checkers. RenderInputs is exported from citry.ext.events.

_render_inputs is now an ordinary per-component Events option: a
component's Events class may assign one, which wins over
extensions_defaults["events"], and None turns the app-wide function off.
The calling component's value applies to every Render in the call. A
method written inside the Events class is refused at class definition,
because Citry calls the function with the request alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KUhrHaXagmW5ZxpRAMwyom
…s in the reference

Refuse a _render_inputs value that cannot take exactly one argument (such
as a method written in the Events class) at Citry(...) or class
definition, and accept a lambda or staticmethod in the class body. Add
RenderInputs to the Events reference page, correct the docs' error rule
for the app-wide value, and note that mypy checks the return type and
the number of parameters but not the parameter type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KUhrHaXagmW5ZxpRAMwyom
@JuroOravec JuroOravec changed the title feat(events): experimental _render_inputs setting for Render actions feat(events): experimental, typed _render_inputs option for Render actions Nov 19, 2026
@JuroOravec
JuroOravec merged commit 68f6353 into main Nov 19, 2026
6 of 17 checks passed
@JuroOravec
JuroOravec deleted the feat/events-render-inputs branch November 19, 2026 15:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant