Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/+auto-memo-route-modules.performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Auto-memoized components now compile into modules chosen by the pages that use them, not by the Python module that defined each page. A page imports them from its own module in `.web/utils/components/routes/`, which defines the memos only that page uses and re-exports the ones several pages share from a module in `.web/utils/components/shared/`, one per set of pages. A page no longer loads the memos of every other page registered from the same module, and pages from different modules no longer each carry a copy of the memos they share. `@rx.memo` components still compile into modules mirroring their source modules.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`create_passthrough_component_memo` no longer takes a `source_module`, since the compiler places auto memos by the pages using them, and its `scope_vars` is keyword-only, so a call passing a source module fails instead of binding it to `scope_vars`.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`memo_components_template` takes the names a memo module re-exports, and `memo_paths.AUTO_MEMO_LIBRARY` names the placeholder an auto-memo wrapper imports from until the compiler places it.
10 changes: 9 additions & 1 deletion packages/reflex-base/src/reflex_base/compiler/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1142,6 +1142,7 @@ def memo_components_template(
functions: list[dict[str, Any]],
dynamic_imports: Iterable[str],
custom_codes: Iterable[str],
reexports: Mapping[str, Iterable[str]] | None = None,
) -> str:
"""Template for custom component.

Expand All @@ -1151,11 +1152,18 @@ def memo_components_template(
functions: List of function definitions.
dynamic_imports: List of dynamic import statements.
custom_codes: List of custom code snippets.
reexports: Names the module exports from other modules, by library.

Returns:
Rendered custom component code as string.
"""
imports_str = "\n".join([_RenderUtils.get_import(imp) for imp in imports])
imports_str = "\n".join([
*(_RenderUtils.get_import(imp) for imp in imports),
*(
f'export {{{", ".join(names)}}} from "{library}";'
for library, names in (reexports or {}).items()
),
])
dynamic_imports_str = "\n".join(dynamic_imports)
custom_code_str = "\n".join(custom_codes)

Expand Down
17 changes: 12 additions & 5 deletions packages/reflex-base/src/reflex_base/components/memo.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,14 +489,20 @@ def _get_memo_component_class(
boundary, so they opt out of being auto-memoized themselves;
user-authored ``@rx.memo`` components do not, so their stateful
props land in a generated wrapper instead of the page module.
Their module is chosen after every page compiled, from the pages
using them, so they import from a placeholder until then.

Returns:
A cached component subclass with the tag set at class definition time.
"""
# With a source module the memo is grouped into a file mirroring its
# Python module; otherwise each memo gets its own per-file module so Vite
# has distinct module boundaries per memo, enabling code-split by page.
library, symbol = memo_paths.library_and_symbol(source_module, export_name)
library, symbol = (
(memo_paths.AUTO_MEMO_LIBRARY, export_name)
if auto_memo_wrapper
else memo_paths.library_and_symbol(source_module, export_name)
)
attrs: dict[str, Any] = {
"__module__": __name__,
"tag": symbol,
Expand Down Expand Up @@ -2130,7 +2136,7 @@ def memo_tag(component: Component) -> str:

def create_passthrough_component_memo(
component: Component,
source_module: str | None = None,
*,
scope_vars: Sequence[str] = (),
) -> tuple[
Callable[..., MemoComponent],
Expand All @@ -2148,10 +2154,12 @@ def create_passthrough_component_memo(
in their children — whose generated memo bodies are identical — collapse
to one wrapper.

The memo has no source module: the compiler places it by the pages that
use it, and its tag alone names it, so identical subtrees anywhere in the
app share one definition.

Args:
component: The component to wrap.
source_module: The user-app Python module that triggered creation of
this memo (typically the page that contained the wrapped subtree).
scope_vars: The loop variables that the body reads; the memo
receives each one as a prop.

Expand Down Expand Up @@ -2251,7 +2259,6 @@ def passthrough(children: Var[Component]) -> Component:
fn=passthrough,
python_name=passthrough.__name__,
params=scoped_params,
source_module=source_module,
export_name=tag,
_component=_LazyBody.ready(preview),
_rest_target_fields=rest_target_fields,
Expand Down
6 changes: 3 additions & 3 deletions packages/reflex-base/src/reflex_base/plugins/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -682,9 +682,9 @@ class CompileContext(BaseContext):
# ``MemoizeStatefulPlugin``).
memoize_wrappers: dict[str, None] = dataclasses.field(default_factory=dict)
# Compiler-generated memo definitions for auto-memoized stateful wrappers.
# Keyed by ``(tag, source_module)`` so identical-rendering subtrees from
# different user modules each get their own entry and emit into the right
# mirrored memo file. Stored as ``Any`` to avoid an import cycle with
# Keyed like ``MEMOS`` by ``(tag, source_module)``; an auto memo carries no
# source module, as its tag names it by content and the compiler places it
# by the pages using it. Stored as ``Any`` to avoid an import cycle with
# ``reflex_base.components.memo``.
auto_memo_components: dict[tuple[str, str | None], Any] = dataclasses.field(
default_factory=dict
Expand Down
57 changes: 56 additions & 1 deletion packages/reflex-base/src/reflex_base/utils/memo_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
instance), skipping framework frames to reach the real user module.
- Translate a dotted Python module name into mirrored JSX path segments and
the corresponding ``$/...`` library specifier consumed by the import system.

Auto-memo wrappers are not mirrored: they are placed by the pages that use
them (see :data:`AUTO_MEMO_LIBRARY`).
"""

from __future__ import annotations
Expand All @@ -20,7 +23,7 @@
import importlib.util
import inspect
import sys
from collections.abc import Callable
from collections.abc import Callable, Iterable
from pathlib import Path

from reflex_base.constants.base import Dirs
Expand Down Expand Up @@ -315,3 +318,55 @@ def library_and_symbol(source_module: str | None, name: str) -> tuple[str, str]:
name, source_module
)
return unmirrored_library_specifier(name), name


# The library an auto-memo wrapper imports from until the compiler places it. A
# page resolves it to its own route module and a memo module to the module
# that holds each memo, so it never reaches the output.
AUTO_MEMO_LIBRARY = f"$/{Dirs.COMPONENTS_PATH}/auto-memo"

# The route module of the app root (``root.jsx``). A page's route module is
# named like its page module, which ends in ``_index`` or ``$``, so they never
# clash.
APP_ROOT_MEMO_STEM = "root"


def route_memo_segments(stem: str) -> tuple[str, ...]:
"""Return the path segments of a route's auto-memo module.

Args:
stem: The file stem of the route's page module.

Returns:
The segments to join under ``.web/``.
"""
return (*Dirs.COMPONENTS_PATH.split("/"), Dirs.ROUTES, stem)


def shared_memo_segments(tags: Iterable[str]) -> tuple[str, ...]:
"""Return the path segments of a module holding memos shared by several routes.

The name hashes the memos it holds rather than the routes using them, so it
stays stable when unrelated pages are added.

Args:
tags: The tags of the memos in the module.

Returns:
The segments to join under ``.web/``.
"""
digest = hashlib.sha256(",".join(sorted(tags)).encode()).hexdigest()[:16]
return (*Dirs.COMPONENTS_PATH.split("/"), "shared", digest)


def generated_library_specifier(segments: tuple[str, ...]) -> str:
"""Build the ``$/...`` import specifier for a route or shared memo module.

Args:
segments: Segments from :func:`route_memo_segments` or
:func:`shared_memo_segments`.

Returns:
A ``$/`` prefixed module specifier.
"""
return "$/" + "/".join(segments)
2 changes: 1 addition & 1 deletion pyi_hashes.json
Original file line number Diff line number Diff line change
Expand Up @@ -120,5 +120,5 @@
"packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "b195e3845260389ced026d2f5c4adb93",
"reflex/__init__.pyi": "067a60e22fb825072f2f0b690662da5a",
"reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388",
"reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e"
"reflex/experimental/memo.pyi": "d763e68d952e6dcbf403e3b7df71f4bc"
}
Loading
Loading