diff --git a/news/+auto-memo-route-modules.performance.md b/news/+auto-memo-route-modules.performance.md new file mode 100644 index 00000000000..a7c8551b58a --- /dev/null +++ b/news/+auto-memo-route-modules.performance.md @@ -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. diff --git a/packages/reflex-base/news/+auto-memo-route-modules.breaking.md b/packages/reflex-base/news/+auto-memo-route-modules.breaking.md new file mode 100644 index 00000000000..682f9bb52df --- /dev/null +++ b/packages/reflex-base/news/+auto-memo-route-modules.breaking.md @@ -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`. diff --git a/packages/reflex-base/news/+auto-memo-route-modules.misc.md b/packages/reflex-base/news/+auto-memo-route-modules.misc.md new file mode 100644 index 00000000000..09ddbb0a516 --- /dev/null +++ b/packages/reflex-base/news/+auto-memo-route-modules.misc.md @@ -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. diff --git a/packages/reflex-base/src/reflex_base/compiler/templates.py b/packages/reflex-base/src/reflex_base/compiler/templates.py index 77f28862881..5f9392c7080 100644 --- a/packages/reflex-base/src/reflex_base/compiler/templates.py +++ b/packages/reflex-base/src/reflex_base/compiler/templates.py @@ -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. @@ -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) diff --git a/packages/reflex-base/src/reflex_base/components/memo.py b/packages/reflex-base/src/reflex_base/components/memo.py index fdfb151db80..aa9f1c2cc53 100644 --- a/packages/reflex-base/src/reflex_base/components/memo.py +++ b/packages/reflex-base/src/reflex_base/components/memo.py @@ -489,6 +489,8 @@ 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. @@ -496,7 +498,11 @@ def _get_memo_component_class( # 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, @@ -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], @@ -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. @@ -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, diff --git a/packages/reflex-base/src/reflex_base/plugins/compiler.py b/packages/reflex-base/src/reflex_base/plugins/compiler.py index a30aa95fd39..9cbe1f2be1b 100644 --- a/packages/reflex-base/src/reflex_base/plugins/compiler.py +++ b/packages/reflex-base/src/reflex_base/plugins/compiler.py @@ -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 diff --git a/packages/reflex-base/src/reflex_base/utils/memo_paths.py b/packages/reflex-base/src/reflex_base/utils/memo_paths.py index 6ab58c59b33..ac22952ea67 100644 --- a/packages/reflex-base/src/reflex_base/utils/memo_paths.py +++ b/packages/reflex-base/src/reflex_base/utils/memo_paths.py @@ -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 @@ -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 @@ -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) diff --git a/pyi_hashes.json b/pyi_hashes.json index fec0b8f2474..3891bc72888 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -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" } diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 83d72e5dd12..41ed8fe6472 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -6,7 +6,7 @@ import dataclasses import json import logging -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from inspect import getattr_static, getmodule from pathlib import Path from typing import TYPE_CHECKING, Any, cast @@ -189,7 +189,9 @@ def _compile_app( library for library in window_libraries if library[1] in core_libraries ] - app_root_imports = app_root._get_all_imports() + app_root_imports = _import_auto_memos_from_route_module( + app_root._get_all_imports(), None + ) _apply_common_imports(app_root_imports) return templates.app_root_template( @@ -204,6 +206,31 @@ def _compile_app( ) +def _import_auto_memos_from_route_module( + imports: ParsedImportDict, route: str | None +) -> dict[str, list[ImportVar]]: + """Import a page's auto memos from its own route module. + + The route module defines or re-exports them wherever the compiler places + them, so the page's code doesn't depend on the other pages. + + Args: + imports: The page's imports. + route: The route of the page, or None for the app root. + + Returns: + A copy of the imports, the placeholder library replaced. + """ + return { + ( + utils.get_route_memo_specifier(route) + if library == memo_paths.AUTO_MEMO_LIBRARY + else library + ): list(fields) + for library, fields in imports.items() + } + + def _compile_theme(theme: str) -> str: """Compile the theme. @@ -492,13 +519,15 @@ def _compile_component(component: Component) -> str: @dataclasses.dataclass class _MemoGroup: - """Accumulator for memos that share a mirrored output path.""" + """Accumulator for memos compiled into one module.""" components: list[dict] = dataclasses.field(default_factory=list) functions: list[dict] = dataclasses.field(default_factory=list) imports: dict[str, list[ImportVar]] = dataclasses.field(default_factory=dict) dynamic_imports: list[str] = dataclasses.field(default_factory=list) custom_code: list[str] = dataclasses.field(default_factory=list) + # Memos the module exports from the modules holding them, by library. + reexports: dict[str, set[str]] = dataclasses.field(default_factory=dict) def add_component( self, render: dict, memo_imports: dict[str, list[ImportVar]] @@ -525,68 +554,288 @@ def add_function( } +def _auto_memo_tags(imports: ParsedImportDict) -> set[str]: + """Return the auto memos a module imports. + + Args: + imports: The module's imports. + + Returns: + The tags imported from :data:`memo_paths.AUTO_MEMO_LIBRARY`. + """ + return {var.tag for var in imports.get(memo_paths.AUTO_MEMO_LIBRARY, ()) if var.tag} + + +def _reachable_auto_memos( + imports: ParsedImportDict, + auto_memo_imports: dict[str, dict[str, list[ImportVar]]], + module_imports: dict[str, dict[str, list[ImportVar]]], +) -> set[str]: + """Return the auto memos a module loads, directly or through other memos. + + Args: + imports: The module's imports. + auto_memo_imports: The imports of each auto memo, by tag. + module_imports: The imports of each ``@rx.memo`` module, by library. + + Returns: + The tags of the auto memos reachable from the module. + """ + tags: set[str] = set() + modules: set[str] = set() + pending = [imports] + while pending: + current = pending.pop() + for tag in _auto_memo_tags(current) - tags: + tags.add(tag) + if (nested := auto_memo_imports.get(tag)) is not None: + pending.append(nested) + for library in (current.keys() & module_imports.keys()) - modules: + modules.add(library) + pending.append(module_imports[library]) + return tags + + +def _place_auto_memos( + auto_memo_imports: dict[str, dict[str, list[ImportVar]]], + module_imports: dict[str, dict[str, list[ImportVar]]], + route_imports: dict[tuple[str, ...], ParsedImportDict], +) -> dict[str, tuple[str, ...]]: + """Choose the module each auto memo is defined in. + + A memo that one route loads is defined in that route's module, a memo that + the app root loads in the app root's module, and the memos loaded by the + same set of routes share a module, so a page loads no memo it doesn't use. + + Args: + auto_memo_imports: The imports of each auto memo, by tag. + module_imports: The imports of each ``@rx.memo`` module, by library. + route_imports: The imports of each page, and of the app root, by the + segments of their route module. + + Returns: + The path segments of the module holding each memo, by tag. + """ + users: dict[str, set[tuple[str, ...]]] = {tag: set() for tag in auto_memo_imports} + for route_segments, imports in route_imports.items(): + for tag in _reachable_auto_memos(imports, auto_memo_imports, module_imports): + if tag in users: + users[tag].add(route_segments) + app_root = utils.get_route_memo_segments(None) + by_users: collections.defaultdict[frozenset[tuple[str, ...]], list[str]] = ( + collections.defaultdict(list) + ) + for tag, routes in users.items(): + # The app root loads on every page. + by_users[frozenset({app_root} if app_root in routes else routes)].append(tag) + holders: dict[str, tuple[str, ...]] = {} + for routes, tags in by_users.items(): + segments = ( + next(iter(routes)) + if len(routes) == 1 + else memo_paths.shared_memo_segments(tags) + ) + holders.update(dict.fromkeys(tags, segments)) + return holders + + +def _auto_memo_holder(holders: dict[str, tuple[str, ...]], tag: str) -> tuple[str, ...]: + """Return the path segments of the module holding an auto memo. + + Args: + holders: The path segments of the module holding each auto memo. + tag: The memo's tag. + + Returns: + The segments. + + Raises: + ReflexError: If the memo was not compiled. + """ + if (segments := holders.get(tag)) is None: + msg = f"The auto-memoized component {tag!r} is imported but was not compiled." + raise ReflexError(msg) + return segments + + +def _resolve_auto_memo_imports( + imports: dict[str, list[ImportVar]], + holders: dict[str, tuple[str, ...]], + own_segments: tuple[str, ...] | None = None, +) -> dict[str, list[ImportVar]]: + """Import each auto memo from the module holding it. + + Args: + imports: A memo module's imports. + holders: The path segments of the module holding each auto memo. + own_segments: The segments of the module itself, whose own memos it + doesn't import. + + Returns: + The imports without the placeholder library. + """ + fields = imports.get(memo_paths.AUTO_MEMO_LIBRARY) + if not fields: + return imports + resolved = { + library: library_fields + for library, library_fields in imports.items() + if library != memo_paths.AUTO_MEMO_LIBRARY + } + for field in fields: + segments = _auto_memo_holder(holders, field.tag or "") + if segments != own_segments: + resolved.setdefault( + memo_paths.generated_library_specifier(segments), [] + ).append(field) + return resolved + + +def _compile_memo_group(group: _MemoGroup) -> str: + """Render a memo module. + + Args: + group: The memos and re-exports of the module, its imports resolved. + + Returns: + The module code. + """ + if group.components or group.functions: + imports = utils.merge_imports(_MEMO_BASE_IMPORTS, group.imports) + _apply_common_imports(imports) + else: + imports = {} + return templates.memo_components_template( + imports=utils.compile_imports(imports), + components=group.components, + functions=group.functions, + dynamic_imports=sorted(set(group.dynamic_imports)), + custom_codes=list(dict.fromkeys(group.custom_code)), + reexports={ + library: sorted(names) for library, names in sorted(group.reexports.items()) + }, + ) + + def _compile_memo_components( memos: Iterable[MemoDefinition] = (), + page_imports: Mapping[str, ParsedImportDict] | None = None, + app_root_imports: ParsedImportDict | None = None, ) -> tuple[list[tuple[str, str]], dict[str, list[ImportVar]]]: - """Compile memos grouped by their source module's mirrored output path. + """Compile memos into modules. - Memos that captured a source module land in a single combined file at - ``.web/app_components/.jsx`` so the page-side import surface - matches the source layout. Memos that can't be mirrored (``__main__``, - unsafe module names) fall back to one file per memo at + ``@rx.memo`` definitions that captured a source module land in a single + combined file at ``.web/app_components/.jsx`` so the page-side + import surface matches the source layout. Memos that can't be mirrored + (``__main__``, unsafe module names) fall back to one file per memo at ``.web/utils/components/.jsx`` that page-side code imports directly. + Auto memos are placed by the routes that load them (see + :func:`_place_auto_memos`). Each page imports its auto memos from its own + route module at ``.web/utils/components/routes/.jsx``, which defines + the memos only that page uses and re-exports the others from modules at + ``.web/utils/components/shared/.jsx``, one per set of routes. + Args: memos: The memos to compile. + page_imports: The imports of each page, by route. + app_root_imports: The imports of the app root. Returns: A list of ``(path, code)`` pairs to write and the aggregated imports across all memo modules. """ - output_files: list[tuple[str, str]] = [] aggregate_imports: dict[str, list[ImportVar]] = {} - unmirrored_files: list[tuple[str, str]] = [] - unmirrored_base_dir = utils.get_memo_components_dir() + unmirrored: list[ + tuple[ + Callable[[dict, dict], tuple[str, dict[str, list[ImportVar]]]], + dict, + dict[str, list[ImportVar]], + ] + ] = [] groups: collections.defaultdict[tuple[str, ...], _MemoGroup] = ( collections.defaultdict(_MemoGroup) ) - - def _emit_unmirrored( - compile_fn: Callable[[dict, dict], tuple[str, dict[str, list[ImportVar]]]], - render: dict, - render_imports: dict, - ) -> None: - code, file_imports = compile_fn(render, render_imports) - unmirrored_files.append(( - _memo_component_file_path(unmirrored_base_dir, render["name"]), - code, - )) - _extend_imports_in_place(aggregate_imports, file_imports) + auto_memos: dict[str, tuple[dict, dict[str, list[ImportVar]]]] = {} for memo in memos: if isinstance(memo, MemoComponentDefinition): + if memo.auto_memo_wrapper and memo.export_name in auto_memos: + continue memo_render, memo_imports = utils.compile_experimental_component_memo(memo) + if memo.auto_memo_wrapper: + auto_memos[memo.export_name] = (memo_render, memo_imports) + continue segments = memo_paths.module_to_mirrored_segments(memo.source_module) if segments is None: - _emit_unmirrored( - _compile_single_memo_component, memo_render, memo_imports - ) + unmirrored.append(( + _compile_single_memo_component, + memo_render, + memo_imports, + )) else: groups[segments].add_component(memo_render, memo_imports) elif isinstance(memo, MemoFunctionDefinition): memo_render, memo_imports = utils.compile_experimental_function_memo(memo) segments = memo_paths.module_to_mirrored_segments(memo.source_module) if segments is None: - _emit_unmirrored( - _compile_single_memo_function, memo_render, memo_imports - ) + unmirrored.append(( + _compile_single_memo_function, + memo_render, + memo_imports, + )) else: groups[segments].add_function(memo_render, memo_imports) - if groups: + route_imports: dict[tuple[str, ...], ParsedImportDict] = { + utils.get_route_memo_segments(route): imports + for route, imports in (page_imports or {}).items() + } + if app_root_imports is not None: + route_imports[utils.get_route_memo_segments(None)] = app_root_imports + module_imports = { + memo_paths.mirrored_library_specifier(segments): group.imports + for segments, group in groups.items() + } + module_imports.update( + (memo_paths.unmirrored_library_specifier(render["name"]), render_imports) + for _, render, render_imports in unmirrored + ) + holders = _place_auto_memos( + {tag: memo_imports for tag, (_, memo_imports) in auto_memos.items()}, + module_imports, + route_imports, + ) + + generated: collections.defaultdict[tuple[str, ...], _MemoGroup] = ( + collections.defaultdict(_MemoGroup) + ) + for tag in sorted(auto_memos): + generated[holders[tag]].add_component(*auto_memos[tag]) + for route_segments, imports in route_imports.items(): + for tag in _auto_memo_tags(imports): + if (segments := _auto_memo_holder(holders, tag)) != route_segments: + generated[route_segments].reexports.setdefault( + memo_paths.generated_library_specifier(segments), set() + ).add(tag) + + unmirrored_files: list[tuple[str, str]] = [] + unmirrored_base_dir = utils.get_memo_components_dir() + for compile_fn, render, render_imports in unmirrored: + code, file_imports = compile_fn( + render, _resolve_auto_memo_imports(render_imports, holders) + ) + unmirrored_files.append(( + _memo_component_file_path(unmirrored_base_dir, render["name"]), + code, + )) + _extend_imports_in_place(aggregate_imports, file_imports) + + if groups or auto_memos: _extend_imports_in_place(aggregate_imports, _MEMO_BASE_IMPORTS) _apply_common_imports(aggregate_imports) + output_files: list[tuple[str, str]] = [] # Maps a case-folded output path to the module that claimed it, so two # modules differing only by case (which collide on case-insensitive # filesystems) are caught instead of one silently overwriting the other. @@ -607,18 +856,17 @@ def _emit_unmirrored( # Strip self-imports — when memos in this group reference each other, # their compiled imports point at this group's own mirrored specifier. # Importing from the same file would shadow the module's own exports. - self_specifier = memo_paths.mirrored_library_specifier(segments) - group.imports.pop(self_specifier, None) - merged_imports = utils.merge_imports(_MEMO_BASE_IMPORTS, group.imports) - _apply_common_imports(merged_imports) - code = templates.memo_components_template( - imports=utils.compile_imports(merged_imports), - components=group.components, - functions=group.functions, - dynamic_imports=sorted(set(group.dynamic_imports)), - custom_codes=list(dict.fromkeys(group.custom_code)), - ) - output_files.append((module_path, code)) + group.imports.pop(memo_paths.mirrored_library_specifier(segments), None) + group.imports = _resolve_auto_memo_imports(group.imports, holders) + output_files.append((module_path, _compile_memo_group(group))) + _extend_imports_in_place(aggregate_imports, group.imports) + + for segments, group in sorted(generated.items()): + group.imports = _resolve_auto_memo_imports(group.imports, holders, segments) + output_files.append(( + utils.get_generated_memo_module_path(segments), + _compile_memo_group(group), + )) _extend_imports_in_place(aggregate_imports, group.imports) return [*unmirrored_files, *output_files], aggregate_imports @@ -813,12 +1061,10 @@ def compile_page_from_context(page_ctx: PageContext) -> tuple[str, str]: The path and code of the compiled page. """ output_path = utils.get_page_path(page_ctx.route) - imports = { - lib: list(fields) - for lib, fields in ( - page_ctx.frontend_imports or page_ctx.merged_imports(collapse=True) - ).items() - } + imports = _import_auto_memos_from_route_module( + page_ctx.frontend_imports or page_ctx.merged_imports(collapse=True), + page_ctx.route, + ) _apply_common_imports(imports) code = templates.page_template( @@ -835,17 +1081,22 @@ def compile_page_from_context(page_ctx: PageContext) -> tuple[str, str]: def compile_memo_components( memos: Iterable[MemoDefinition] = (), + page_imports: Mapping[str, ParsedImportDict] | None = None, + app_root_imports: ParsedImportDict | None = None, ) -> tuple[list[tuple[str, str]], dict[str, list[ImportVar]]]: - """Compile the memos into one module per memo. + """Compile the memos into modules. Args: memos: The memos to compile. + page_imports: The imports of each page, by route, which place the + auto memos and give each page its route module. + app_root_imports: The imports of the app root. Returns: A list of ``(path, code)`` pairs (one per memo module) alongside the aggregated imports across all memo modules. """ - return _compile_memo_components(memos) + return _compile_memo_components(memos, page_imports, app_root_imports) def purge_web_pages_dir(): @@ -1473,7 +1724,8 @@ def compile_app( app_wrappers = _resolve_app_wrap_components(app, compile_ctx.app_wrap_components) app_root = _memoize_stateful_app_wraps(app._app_root(app_wrappers), compile_ctx) - all_imports = utils.merge_imports(all_imports, app_root._get_all_imports()) + app_root_imports = app_root._get_all_imports() + all_imports = utils.merge_imports(all_imports, app_root_imports) hydrate_fallback = app._resolve_hydrate_fallback() hydrate_fallback_export = None @@ -1501,6 +1753,11 @@ def compile_app( *memos, *compile_ctx.auto_memo_components.values(), ), + page_imports={ + route: page_ctx.frontend_imports + for route, page_ctx in compile_ctx.compiled_pages.items() + }, + app_root_imports=app_root_imports, ) compile_results.extend(memo_component_files) all_imports = utils.merge_imports(all_imports, memo_components_imports) diff --git a/reflex/compiler/plugins/memoize.py b/reflex/compiler/plugins/memoize.py index 933f7c1e647..bba4fbad820 100644 --- a/reflex/compiler/plugins/memoize.py +++ b/reflex/compiler/plugins/memoize.py @@ -9,9 +9,10 @@ Each unique subtree shape contributes: -- One generated experimental memo component definition, compiled into a module - mirroring its source module under ``$/app_components/`` (or, when it can't be - mirrored, a per-memo module at ``$/utils/components/``). +- One generated experimental memo component definition. Pages import it from + their own route module; after every page compiled, the compiler defines it + there when one route uses it, in the app root's module when the app root + uses it, or else in a module shared by the routes using it. - ``useCallback`` hook lines for each non-lifecycle event trigger, emitted into the generated memo body so handler hooks stay inside that rendering domain. @@ -428,7 +429,6 @@ def scope_memo_body_hooks( name=definition.export_name, route=definition.python_name, root_component=component, - source_module=definition.source_module, ) scoped = _scope_branch_hooks( component, @@ -660,14 +660,11 @@ def _build_wrapper( # is substituted, so passthrough wrappers that differ only in their # children collapse to a single definition. wrapper_factory, definition = create_passthrough_component_memo( - comp, source_module=page_context.source_module, scope_vars=scope_vars + comp, scope_vars=scope_vars ) tag = definition.export_name compile_context.memoize_wrappers[tag] = None - # Key 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. - compile_context.auto_memo_components[tag, definition.source_module] = definition + compile_context.auto_memo_components[tag, None] = definition # The body's hooks leave the page module, but the page still has to own # the local client state they use. page_context.client_state_names.update( diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index e0b490938b3..73ee44b6b82 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -1103,6 +1103,46 @@ def get_memo_module_path(segments: tuple[str, ...]) -> str: return str(memo_paths.mirrored_jsx_path(get_web_dir(), segments)) +def get_route_memo_segments(route: str | None) -> tuple[str, ...]: + """Get the path segments of the module a page imports its auto memos from. + + Args: + route: The route of the page, or None for the app root. + + Returns: + The segments, named like the page module. + """ + return memo_paths.route_memo_segments( + memo_paths.APP_ROOT_MEMO_STEM if route is None else _path_to_file_stem(route) + ) + + +def get_route_memo_specifier(route: str | None) -> str: + """Get the ``$``-aliased specifier of the module a page imports its auto memos from. + + Args: + route: The route of the page, or None for the app root. + + Returns: + The import specifier. + """ + return memo_paths.generated_library_specifier(get_route_memo_segments(route)) + + +def get_generated_memo_module_path(segments: tuple[str, ...]) -> str: + """Get the on-disk path of a route or shared auto-memo module. + + Args: + segments: Segments from :func:`memo_paths.route_memo_segments` or + :func:`memo_paths.shared_memo_segments`. A route stem can hold + dots, so the extension is appended rather than substituted. + + Returns: + The path the compiler writes the module to. + """ + return str(get_web_dir().joinpath(*segments[:-1], segments[-1] + constants.Ext.JSX)) + + def add_meta( page: Component, title: str | Var, diff --git a/tests/integration/test_prod_build_pipeline.py b/tests/integration/test_prod_build_pipeline.py index 7fda32d5591..8301f109993 100644 --- a/tests/integration/test_prod_build_pipeline.py +++ b/tests/integration/test_prod_build_pipeline.py @@ -5,6 +5,7 @@ from __future__ import annotations +import json from collections.abc import Generator from pathlib import Path @@ -23,20 +24,53 @@ ) ENCODING_IDS = [case[0] for case in ENCODING_CASES] +# The marker in the auto memos of each page, by its id in the react-router manifest. +_PAGE_MARKERS = { + "routes/_index": "only-on-index", + "routes/[b]._index": "only-on-b", + "routes/[c]._index": "only-on-c", +} +_MARKERS = (*_PAGE_MARKERS.values(), "shared-marker") + def ProdBuildPipelineApp(): - """A minimal app for build pipeline testing.""" + """A small app for build pipeline testing. + + Its pages share a stateful navbar and have a stateful part of their own. + ``/`` and ``/b`` are registered from one module, ``/c`` as if from another. + """ import reflex as rx - app = rx.App() + menu = rx.client_state(False) - @app.add_page - def index(): + def page(marker: str) -> rx.Component: + clicks = rx.client_state(0) return rx.el.main( rx.heading("Build Pipeline Test"), - rx.text("Hello"), + rx.el.nav( + rx.el.button( + "Menu", on_click=menu.set(~menu.value), aria_label="shared-marker" + ), + ), + rx.el.button(marker, on_click=clicks.set(1), aria_label=marker), ) + def index() -> rx.Component: + return page("only-on-index") + + def b() -> rx.Component: + return page("only-on-b") + + def c() -> rx.Component: + return page("only-on-c") + + c.__module__ = "prod_build_pipeline_pages.c" + + app = rx.App() + app.add_page(index, route="/") + app.add_page(b, route="/b") + app.add_page(c, route="/c") + @pytest.fixture(scope="module") def all_compression_formats_env() -> Generator[None, None, None]: @@ -177,3 +211,50 @@ def test_bundles_exclude_embedded_core_js(prod_app: AppHarness): ] assert not offenders, f"bundles embed a core-js runtime: {offenders}" + + +def _route_code(harness: AppHarness, route_id: str) -> str: + """Read the JS a route loads: its module and every chunk it imports. + + Args: + harness: The running prod harness. + route_id: The route's id in the react-router manifest. + + Returns: + The code of those files. + """ + static_dir = harness.app_path / prerequisites.get_web_dir() / constants.Dirs.STATIC + (manifest_file,) = _find_build_files(harness, "assets/manifest-*.js") + manifest = json.loads( + manifest_file + .read_text() + .removeprefix("window.__reactRouterManifest=") + .removesuffix(";") + ) + route = manifest["routes"][route_id] + return "\n".join( + (static_dir / path.lstrip("/")).read_text() + for path in {route["module"], *route["imports"]} + ) + + +def test_pages_load_only_their_own_auto_memos(prod_app: AppHarness): + """A page's chunks hold its own memos and the shared ones, not another page's.""" + loaded = { + route_id: { + marker for marker in _MARKERS if marker in _route_code(prod_app, route_id) + } + for route_id in _PAGE_MARKERS + } + assert loaded == { + route_id: {marker, "shared-marker"} + for route_id, marker in _PAGE_MARKERS.items() + } + + +def test_auto_memos_are_emitted_once(prod_app: AppHarness): + """Every memo is in one chunk: a memo several pages use is not copied into each.""" + chunks = [path.read_text() for path in _find_build_files(prod_app, "assets/*.js")] + assert { + marker: sum(marker in code for code in chunks) for marker in _MARKERS + } == dict.fromkeys(_MARKERS, 1) diff --git a/tests/integration/tests_playwright/test_auto_memo.py b/tests/integration/tests_playwright/test_auto_memo.py index 51c8683d619..5d1f81344da 100644 --- a/tests/integration/tests_playwright/test_auto_memo.py +++ b/tests/integration/tests_playwright/test_auto_memo.py @@ -1,5 +1,6 @@ """Integration tests for compiler-generated experimental memos.""" +import re from collections.abc import Generator import pytest @@ -7,6 +8,10 @@ from reflex.testing import AppHarness +_MEMO_IMPORT = re.compile( + r'^import \{([^}]*)\} from "(\$/utils/components/[^"]+)"$', re.MULTILINE +) + def AutoMemoAcrossPagesApp(): """Reflex app that shares one stateful subtree across two pages.""" @@ -58,11 +63,20 @@ def test_auto_memo_shared_across_pages(auto_memo_app: AppHarness, page: Page): """ assert auto_memo_app.app_instance is not None, "app is not running" - web_sources = "\n".join( - path.read_text() for path in (auto_memo_app.app_path / ".web").rglob("*.jsx") - ) - assert "$/app_components" in web_sources + web_dir = auto_memo_app.app_path / ".web" + web_sources = "\n".join(path.read_text() for path in web_dir.rglob("*.jsx")) assert "$/utils/stateful_components" not in web_sources + # Each page imports the shared memo from its own route module. + memo_imports = { + path.name: _MEMO_IMPORT.findall(path.read_text()) + for path in (web_dir / "app" / "routes").glob("*.jsx") + } + ((tag, _),) = memo_imports["_index.jsx"] + assert memo_imports == { + "[404]._index.jsx": [], + "[other]._index.jsx": [(tag, "$/utils/components/routes/[other]._index")], + "_index.jsx": [(tag, "$/utils/components/routes/_index")], + } assert auto_memo_app.frontend_url is not None page.goto(auto_memo_app.frontend_url) diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..5a2a5acafb8 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -5,20 +5,23 @@ import re import shutil import sys +from collections.abc import Callable, Iterable, Mapping, Sequence from pathlib import Path, PureWindowsPath +from typing import Any import pytest from pytest_mock import MockerFixture from reflex_base import constants from reflex_base.components.component import BaseComponent, Component from reflex_base.components.dynamic import bundle_library, reset_bundled_libraries -from reflex_base.components.memo import MEMOS +from reflex_base.components.memo import MEMOS, MemoComponentDefinition, MemoDefinition from reflex_base.constants.base import LiteralColorMode from reflex_base.constants.compiler import PageNames from reflex_base.environment import environment from reflex_base.plugins import CompileContext, CompilerHooks, PageContext from reflex_base.plugins.sitemap import SitemapPlugin from reflex_base.registry import RegistrationContext +from reflex_base.utils import memo_paths from reflex_base.utils.console import PoorProgress from reflex_base.utils.exceptions import ( DynamicRouteArgShadowsStateVarError, @@ -26,16 +29,19 @@ RouteValueError, ) from reflex_base.utils.imports import ImportVar, ParsedImportDict -from reflex_base.vars.base import Var +from reflex_base.vars import VarData +from reflex_base.vars.base import LiteralVar, Var from reflex_base.vars.sequence import LiteralStringVar from reflex_components_core.base import Description, document from reflex_components_core.base.document import Links, Scripts +from reflex_components_core.base.fragment import Fragment from reflex_components_core.el.elements.metadata import Head, Link, Meta from reflex_components_core.el.elements.other import Html import reflex as rx from reflex.compiler import compiler, utils from reflex.compiler.plugins import default_page_plugins +from reflex.compiler.plugins.memoize import scope_memo_body_hooks from reflex.state import BaseState from reflex.utils import prerequisites @@ -2402,3 +2408,426 @@ def page() -> Component: assert any("const refs = {};" in code for _, code in memo_files) for code in modules: assert not _IMPORTS_REFS.search(code), code + + +class _PlacementState(BaseState): + """State the loops of the auto-memo placement tests iterate.""" + + items: list[str] = ["a"] + others: list[str] = ["b"] + flag: bool = False + + +@dataclasses.dataclass(slots=True) +class _FakePage: + """A page definition the compile context accepts.""" + + route: str + component: Callable[[], Component] + title: Any = None + description: Any = None + image: str = "" + meta: tuple[dict[str, Any], ...] = () + _source_module: str | None = None + + +def _stateful(name: str) -> Component: + """A component the compiler wraps in an auto memo of its own. + + Args: + name: What distinguishes its memo from the others. + + Returns: + The component. + """ + value = LiteralVar.create(name)._replace( + merge_var_data=VarData(hooks={f"useTest_{name}": None}, state="TestState") + ) + return rx.el.p(title=value) + + +def _chrome() -> Component: + """Chrome every page renders: two components with an auto memo each. + + Returns: + The chrome. + """ + return Fragment.create(_stateful("nav"), _stateful("footer")) + + +_MEMO_EXPORT = re.compile(r"^export const (\w+) = ", re.MULTILINE) +_MEMO_REEXPORT = re.compile(r'^export \{([^}]*)\} from "([^"]+)";$', re.MULTILINE) +_MEMO_MODULE_IMPORT = re.compile( + r'^import \{([^}]*)\} from "(\$/(?:utils/components|app_components)/[^"]+)"$', + re.MULTILINE, +) + + +def _memo_names(names: str) -> tuple[str, ...]: + """Split the names of an import or export statement. + + Args: + names: The text between its braces. + + Returns: + The names. + """ + return tuple(name.strip() for name in names.split(",")) + + +@dataclasses.dataclass(frozen=True) +class _MemoModule: + """What a memo module defines, re-exports and imports from other memo modules.""" + + defines: tuple[str, ...] = () + reexports: tuple[tuple[str, tuple[str, ...]], ...] = () + imports: tuple[tuple[str, tuple[str, ...]], ...] = () + + @classmethod + def parse(cls, code: str) -> "_MemoModule": + """Read a compiled memo module. + + Args: + code: The module code. + + Returns: + Its memo definitions, re-exports and memo imports. + """ + return cls( + tuple(_MEMO_EXPORT.findall(code)), + tuple( + (m.group(2), _memo_names(m.group(1))) + for m in _MEMO_REEXPORT.finditer(code) + ), + tuple( + (m.group(2), _memo_names(m.group(1))) + for m in _MEMO_MODULE_IMPORT.finditer(code) + ), + ) + + +@dataclasses.dataclass +class _MemoBuild: + """A compile and the layout of the memo modules it emits.""" + + ctx: CompileContext + modules: dict[str, _MemoModule] + + def tags(self, route: str) -> set[str]: + """The auto memos a page imports. + + Args: + route: The page's route. + + Returns: + Their tags. + """ + imports = self.ctx.compiled_pages[route].frontend_imports + return {var.tag for var in imports[memo_paths.AUTO_MEMO_LIBRARY] if var.tag} + + def page_imports(self, route: str) -> tuple[tuple[str, tuple[str, ...]], ...]: + """The memo modules a compiled page imports from. + + Args: + route: The page's route. + + Returns: + The imported names by module. + """ + return _MemoModule.parse( + self.ctx.compiled_pages[route].output_code or "" + ).imports + + +def _compile_memo_layout( + pages: Mapping[str, Callable[[], Component]], + *, + source_module: str | None = None, + memos: Sequence[MemoDefinition] = (), + app_root: str | None = None, +) -> _MemoBuild: + """Compile pages and lay out their memo modules. + + Args: + pages: The page functions, by route. + source_module: The module every page reports it was defined in. + memos: ``@rx.memo`` definitions to compile with the auto memos. + app_root: A route whose imports stand in for the app root's. + + Returns: + The build. + """ + ctx = CompileContext( + pages=[ + _FakePage(route=route, component=page, _source_module=source_module) + for route, page in pages.items() + ], + hooks=CompilerHooks(plugins=default_page_plugins()), + ) + with ctx: + ctx.compile() + scoped = [ + scope_memo_body_hooks(memo, ctx) + if isinstance(memo, MemoComponentDefinition) + else memo + for memo in memos + ] + files, _ = compiler.compile_memo_components( + (*scoped, *ctx.auto_memo_components.values()), + page_imports={ + route: page.frontend_imports for route, page in ctx.compiled_pages.items() + }, + app_root_imports=( + ctx.compiled_pages[app_root].frontend_imports if app_root else None + ), + ) + web_dir = prerequisites.get_web_dir() + return _MemoBuild( + ctx, + { + "$/" + Path(path).relative_to(web_dir).as_posix().removesuffix(".jsx"): ( + _MemoModule.parse(code) + ) + for path, code in files + }, + ) + + +def _route_module(route: str | None) -> str: + """The specifier of a route's auto-memo module. + + Args: + route: The route, or None for the app root. + + Returns: + The specifier. + """ + return utils.get_route_memo_specifier(route) + + +def _shared_module(tags: Iterable[str]) -> str: + """The specifier of the module holding memos several routes share. + + Args: + tags: The tags of the memos it holds. + + Returns: + The specifier. + """ + return memo_paths.generated_library_specifier(memo_paths.shared_memo_segments(tags)) + + +def test_auto_memo_one_route_uses_is_defined_in_its_route_module(): + """A page imports its memos from its own route module, which defines them.""" + build = _compile_memo_layout({"index": lambda: _stateful("only")}) + + (tag,) = build.tags("index") + assert build.page_imports("index") == ((_route_module("index"), (tag,)),) + assert build.modules == {_route_module("index"): _MemoModule(defines=(tag,))} + + +def test_auto_memos_shared_by_routes_are_defined_once(): + """The memos of several routes live in one module, re-exported by each route.""" + build = _compile_memo_layout({ + "index": lambda: Fragment.create(_chrome(), _stateful("index")), + "b": lambda: Fragment.create(_chrome(), _stateful("b")), + }) + + shared = tuple(sorted(build.tags("index") & build.tags("b"))) + (only_index,) = build.tags("index") - set(shared) + (only_b,) = build.tags("b") - set(shared) + assert len(shared) == 2 + assert build.page_imports("b") == ( + (_route_module("b"), tuple(sorted(build.tags("b")))), + ) + assert build.modules == { + _route_module("b"): _MemoModule( + defines=(only_b,), reexports=((_shared_module(shared), shared),) + ), + _route_module("index"): _MemoModule( + defines=(only_index,), reexports=((_shared_module(shared), shared),) + ), + _shared_module(shared): _MemoModule(defines=shared), + } + + +def test_auto_memo_placement_is_deterministic_and_stable_when_pages_are_added(): + """Two compiles emit the same modules, and a new page leaves the others alone.""" + pages = { + "index": lambda: Fragment.create(_chrome(), _stateful("index")), + "b": lambda: Fragment.create(_chrome(), _stateful("b")), + } + first = _compile_memo_layout(pages) + assert _compile_memo_layout(pages).modules == first.modules + + third = _compile_memo_layout({**pages, "c": lambda: _stateful("c")}) + (only_c,) = third.tags("c") + assert third.modules == { + **first.modules, + _route_module("c"): _MemoModule(defines=(only_c,)), + } + + +def _loop_item(value: Var) -> Component: + """A loop item whose lifecycle event gets it an auto memo inside the loop's. + + Args: + value: The item. + + Returns: + The item's component. + """ + return rx.text(value, on_mount=rx.console_log(value)) + + +def test_auto_memo_nested_in_memos_follows_their_routes(): + """A memo used only inside other memos is placed by the routes loading them.""" + build = _compile_memo_layout({ + "index": lambda: rx.box(rx.foreach(_PlacementState.items, _loop_item)), + "b": lambda: rx.box(rx.foreach(_PlacementState.items, _loop_item)), + "c": lambda: rx.box(rx.foreach(_PlacementState.others, _loop_item)), + }) + + (loop,) = build.tags("index") + (other_loop,) = build.tags("c") + (item,) = set(build.ctx.memoize_wrappers) - {loop, other_loop} + assert build.tags("b") == {loop} + item_import = ((_shared_module([item]), (item,)),) + assert build.modules == { + _route_module("b"): _MemoModule(reexports=((_shared_module([loop]), (loop,)),)), + _route_module("c"): _MemoModule(defines=(other_loop,), imports=item_import), + _route_module("index"): _MemoModule( + reexports=((_shared_module([loop]), (loop,)),) + ), + _shared_module([item]): _MemoModule(defines=(item,)), + _shared_module([loop]): _MemoModule(defines=(loop,), imports=item_import), + } + + +def test_auto_memos_of_pages_registered_through_one_helper_stay_apart(): + """Pages whose functions share a module still load only their own memos.""" + build = _compile_memo_layout( + { + "index": lambda: Fragment.create(_chrome(), _stateful("index")), + "b": lambda: Fragment.create(_chrome(), _stateful("b")), + }, + source_module="site", + ) + + shared = tuple(sorted(build.tags("index") & build.tags("b"))) + (only_index,) = build.tags("index") - set(shared) + (only_b,) = build.tags("b") - set(shared) + assert build.modules == { + _route_module("b"): _MemoModule( + defines=(only_b,), reexports=((_shared_module(shared), shared),) + ), + _route_module("index"): _MemoModule( + defines=(only_index,), reexports=((_shared_module(shared), shared),) + ), + _shared_module(shared): _MemoModule(defines=shared), + } + + +def _localized( + page: Callable[[str], Component], locale: str +) -> Callable[[], Component]: + """Render a page in one locale, as an i18n plugin registers its routes. + + Args: + page: The page function, taking the locale. + locale: The locale. + + Returns: + The page function of the locale's route. + """ + + def render() -> Component: + return Fragment.create(page(locale)) + + render.__module__ = f"site.{locale}" + return render + + +def test_auto_memos_rendered_alike_in_every_locale_are_defined_once(): + """A page wrapped per locale shares the memos it renders the same way.""" + + def page(locale: str) -> Component: + return Fragment.create(_chrome(), _stateful(f"greeting-{locale}")) + + build = _compile_memo_layout({ + "index": _localized(page, "de"), + "en": _localized(page, "en"), + }) + + shared = tuple(sorted(build.tags("index") & build.tags("en"))) + (only_de,) = build.tags("index") - set(shared) + (only_en,) = build.tags("en") - set(shared) + assert len(shared) == 2 + assert build.modules == { + _route_module("en"): _MemoModule( + defines=(only_en,), reexports=((_shared_module(shared), shared),) + ), + _route_module("index"): _MemoModule( + defines=(only_de,), reexports=((_shared_module(shared), shared),) + ), + _shared_module(shared): _MemoModule(defines=shared), + } + + +@pytest.mark.usefixtures("preserve_memo_registries") +def test_explicit_memo_keeps_its_source_module_and_places_its_auto_memos(): + """``@rx.memo`` mirrors its module; auto memos in its body follow its routes.""" + + @rx.memo + def toggle_card(label: rx.Var[str]) -> Component: + return rx.box( + rx.cond( + _PlacementState.flag, + rx.text(label, on_mount=rx.console_log(label)), + ) + ) + + build = _compile_memo_layout( + { + "index": lambda: Fragment.create(toggle_card(label="a")), + "b": lambda: Fragment.create(toggle_card(label="a"), _stateful("b")), + }, + memos=[toggle_card._definition], + ) + + explicit = memo_paths.library_for(__name__, "") + symbol = memo_paths.mirrored_symbol(toggle_card._definition.export_name, __name__) + (only_b,) = build.tags("b") + (scoped,) = set(build.ctx.memoize_wrappers) - {only_b} + assert build.page_imports("index") == ((explicit, (symbol,)),) + assert build.modules == { + explicit: _MemoModule( + defines=(symbol,), imports=((_shared_module([scoped]), (scoped,)),) + ), + _route_module("b"): _MemoModule(defines=(only_b,)), + _shared_module([scoped]): _MemoModule(defines=(scoped,)), + } + + +def test_auto_memos_the_app_root_uses_live_in_its_module(): + """A memo the app root loads is defined in its module, which every page loads.""" + build = _compile_memo_layout( + { + "index": lambda: Fragment.create(_chrome(), _stateful("index")), + "b": lambda: Fragment.create(_chrome(), _stateful("b")), + }, + app_root="index", + ) + + root_tags = tuple(sorted(build.tags("index"))) + shared = tuple(sorted(build.tags("index") & build.tags("b"))) + (only_b,) = build.tags("b") - set(shared) + assert build.modules == { + _route_module(None): _MemoModule(defines=root_tags), + _route_module("b"): _MemoModule( + defines=(only_b,), reexports=((_route_module(None), shared),) + ), + _route_module("index"): _MemoModule( + reexports=((_route_module(None), root_tags),) + ), + } diff --git a/tests/units/compiler/test_memoize_plugin.py b/tests/units/compiler/test_memoize_plugin.py index ddc0e13129e..a58580c8b9c 100644 --- a/tests/units/compiler/test_memoize_plugin.py +++ b/tests/units/compiler/test_memoize_plugin.py @@ -61,7 +61,9 @@ _should_memoize, scope_memo_body_hooks, ) +from reflex.compiler.utils import get_route_memo_specifier from reflex.state import BaseState +from reflex.utils.prerequisites import get_web_dir STATE_VAR = LiteralVar.create("value")._replace( merge_var_data=VarData(hooks={"useTestState": None}, state="TestState") @@ -247,7 +249,7 @@ def test_memoize_wrapper_uses_memo_component_and_call_site() -> None: wrapper_tag = next(iter(ctx.memoize_wrappers)) assert (wrapper_tag, None) in ctx.auto_memo_components output = page_ctx.output_code or "" - assert f'import {{{wrapper_tag}}} from "$/utils/components/{wrapper_tag}"' in output + assert f'import {{{wrapper_tag}}} from "{get_route_memo_specifier("/p")}"' in output assert f"jsx({wrapper_tag}," in (page_ctx.output_code or "") assert f"const {wrapper_tag} = memo" not in output @@ -275,7 +277,7 @@ def test_memoize_wrapper_deduped_across_repeated_subtrees() -> None: wrapper_tag = next(iter(ctx.memoize_wrappers)) assert list(ctx.auto_memo_components) == [(wrapper_tag, None)] assert (page_ctx.output_code or "").count( - f'import {{{wrapper_tag}}} from "$/utils/components/{wrapper_tag}"' + f'import {{{wrapper_tag}}} from "{get_route_memo_specifier("/p")}"' ) == 1 @@ -446,7 +448,9 @@ def accordion() -> Component: memos=tuple(ctx.auto_memo_components.values()), ) foreach_code = next( - code for path, code in memo_files if "/Foreach" in path or "\\Foreach" in path + block + for name, block in _module_by_export(memo_files).items() + if name.startswith("Foreach_") ) assert '["width"] : "400px"' in foreach_code @@ -1039,9 +1043,7 @@ def stateful_card(label: rx.Var[str]) -> Component: memo_files, _memo_imports = compile_memo_components( memos=tuple(ctx.auto_memo_components.values()), ) - wrapper_code = next( - code for path, code in memo_files if definition.export_name in path - ) + wrapper_code = _module_by_export(memo_files)[definition.export_name] assert "useStateContext(" in wrapper_code assert f"jsx({wrapped.tag}," in wrapper_code @@ -1087,9 +1089,7 @@ def clickable( memo_files, _memo_imports = compile_memo_components( memos=tuple(ctx.auto_memo_components.values()), ) - wrapper_code = next( - code for path, code in memo_files if definition.export_name in path - ) + wrapper_code = _module_by_export(memo_files)[definition.export_name] assert "useCallback" in wrapper_code @@ -1129,9 +1129,7 @@ def slot_card(label: rx.Var[str], children: rx.Var[Component]) -> Component: memo_files, _memo_imports = compile_memo_components( memos=tuple(ctx.auto_memo_components.values()), ) - wrapper_code = next( - code for path, code in memo_files if wrapper_definition.export_name in path - ) + wrapper_code = _module_by_export(memo_files)[wrapper_definition.export_name] inner_tag = wrapper_definition.component.tag assert f"jsx({inner_tag}," in wrapper_code # The hole, not the authored child, is what the memo body renders. @@ -1234,14 +1232,10 @@ def test_passthrough_memo_definitions_are_not_shared_globally(monkeypatch) -> No def fake_create_passthrough_component_memo( component: Component, - source_module: str | None = None, + *, scope_vars: tuple[str, ...] = (), ): - definition = SimpleNamespace( - export_name=tag, - component=component, - source_module=source_module, - ) + definition = SimpleNamespace(export_name=tag, component=component) return (lambda definition=definition, **_props: definition), definition monkeypatch.setattr( @@ -1291,22 +1285,16 @@ def test_shared_subtree_across_pages_uses_same_tag() -> None: assert list(ctx.auto_memo_components) == [(tag, None)] for route in ("/a", "/b"): output = ctx.compiled_pages[route].output_code or "" - assert f'import {{{tag}}} from "$/utils/components/{tag}"' in output + assert f'import {{{tag}}} from "{get_route_memo_specifier(route)}"' in output assert f"jsx({tag}," in output -def test_shared_subtree_in_distinct_source_modules_emits_per_module() -> None: - """Identical subtrees in different user modules emit one memo per module. +def test_shared_subtree_in_distinct_source_modules_registers_once() -> None: + """Identical subtrees on pages from different user modules share one memo. - Regression: the auto-memo registry was keyed by tag only, so when two - pages from different user modules produced the same memoizable subtree - (and therefore the same tag), the second registration overwrote the - first. Only the surviving definition's source module got a mirrored - memo file, leaving the other page importing a tag from a file that - never exported it. + The tag names the memo by content, so it carries no source module, and each + page imports it from its own route module. """ - from reflex.compiler.compiler import compile_memo_components - ctx = CompileContext( pages=[ FakePage( @@ -1327,43 +1315,12 @@ def test_shared_subtree_in_distinct_source_modules_emits_per_module() -> None: assert len(ctx.memoize_wrappers) == 1 tag = next(iter(ctx.memoize_wrappers)) - # Both source modules survive registration as distinct entries. - assert set(ctx.auto_memo_components) == { - (tag, "memo_collision_test.module_a"), - (tag, "memo_collision_test.module_b"), - } - - # Each module emits and imports the tag under a per-module symbol so the - # two pages never collide on a shared JS identifier. - symbol_a = memo_paths.mirrored_symbol(tag, "memo_collision_test.module_a") - symbol_b = memo_paths.mirrored_symbol(tag, "memo_collision_test.module_b") - page_a_output = ctx.compiled_pages["/a"].output_code or "" - page_b_output = ctx.compiled_pages["/b"].output_code or "" - assert ( - f'import {{{symbol_a}}} from "$/app_components/memo_collision_test/module_a"' - in page_a_output - ) - assert ( - f'import {{{symbol_b}}} from "$/app_components/memo_collision_test/module_b"' - in page_b_output - ) - - output_files, _ = compile_memo_components( - memos=tuple(ctx.auto_memo_components.values()), - ) - emitted = {Path(path).as_posix(): code for path, code in output_files} - - def find_emitted(suffix: str) -> str | None: - return next( - (code for path, code in emitted.items() if path.endswith(suffix)), None - ) - - matched_a = find_emitted("memo_collision_test/module_a.jsx") - matched_b = find_emitted("memo_collision_test/module_b.jsx") - assert matched_a is not None, f"missing module_a memo file in {sorted(emitted)}" - assert matched_b is not None, f"missing module_b memo file in {sorted(emitted)}" - assert f"const {symbol_a} = memo" in matched_a - assert f"const {symbol_b} = memo" in matched_b + assert list(ctx.auto_memo_components) == [(tag, None)] + for route in ("/a", "/b"): + output = ctx.compiled_pages[route].output_code or "" + assert [ + line for line in output.splitlines() if '"$/utils/components/' in line + ] == [f'import {{{tag}}} from "{get_route_memo_specifier(route)}"'] def test_shared_parent_instance_across_pages_preserves_original() -> None: @@ -1400,7 +1357,7 @@ def test_shared_parent_instance_across_pages_preserves_original() -> None: tag = next(iter(ctx.memoize_wrappers)) for route in ("/a", "/b"): output = ctx.compiled_pages[route].output_code or "" - assert f'import {{{tag}}} from "$/utils/components/{tag}"' in output, ( + assert f'import {{{tag}}} from "{get_route_memo_specifier(route)}"' in output, ( f"route {route} missing memo tag import" ) assert f"jsx({tag}," in output, f"route {route} does not render the memo tag" @@ -1445,7 +1402,7 @@ def test_shared_nested_parent_mirroring_common_elements_preserves_original() -> tag = next(iter(ctx.memoize_wrappers)) for route in ("/a", "/b", "/c"): output = ctx.compiled_pages[route].output_code or "" - assert f'import {{{tag}}} from "$/utils/components/{tag}"' in output + assert f'import {{{tag}}} from "{get_route_memo_specifier(route)}"' in output assert f"jsx({tag}," in output @@ -1891,11 +1848,7 @@ def page() -> Component: memo_files, _memo_imports = compile_memo_components( memos=tuple(ctx.auto_memo_components.values()), ) - match_memo_code = next( - code - for path, code in memo_files - if Path(path).name == f"{match_wrapper_tag}.jsx" - ) + match_memo_code = _module_by_export(memo_files)[match_wrapper_tag] assert "children?.at?.(0)" in match_memo_code, ( "Match memo body should select case 0 via children indexing.\n" @@ -2000,8 +1953,8 @@ def page() -> Component: memo_files, _memo_imports = compile_memo_components( memos=tuple(ctx.auto_memo_components.values()), ) - memo_code = next( - code for path, code in memo_files if Path(path).name == f"{wrapper_tag}.jsx" + (memo_code,) = ( + code for _path, code in memo_files if f"export const {wrapper_tag} = " in code ) assert "counterRxClientStateSet(42)" in memo_code, ( @@ -2134,8 +2087,8 @@ def page() -> Component: memo_files, _memo_imports = compile_memo_components( memos=tuple(ctx.auto_memo_components.values()), ) - memo_code = next( - code for path, code in memo_files if Path(path).name == f"{wrapper_tag}.jsx" + (memo_code,) = ( + code for _path, code in memo_files if f"export const {wrapper_tag} = " in code ) assert re.search( @@ -3090,41 +3043,30 @@ def test_restricted_content_element_with_id_and_stateful_child_still_memoizes() ) -def test_each_memo_wrapper_emits_one_component_module_file() -> None: - """Every wrapper tag corresponds to exactly one ``utils/components/{tag}.jsx`` file. - - Locks the per-wrapper file invariant for un-mirrored memos: - ``compile_memo_components`` must emit one module per wrapper, so that React - can code-split per wrapper. A wrapper without a file (or a file without a - wrapper) would mean broken imports at runtime. - """ +def test_each_memo_wrapper_is_defined_in_its_route_module() -> None: + """Every wrapper a single page uses is defined once, in that page's route module.""" from reflex.compiler.compiler import compile_memo_components - ctx, _page_ctx = _compile_single_page( + ctx, page_ctx = _compile_single_page( lambda: Fragment.create( Plain.create(STATE_VAR), WithProp.create(label=STATE_VAR), LeafComponent.create(Plain.create(STATE_VAR)), ) ) - memo_files, _imports = compile_memo_components( - memos=tuple(ctx.auto_memo_components.values()), - ) - component_module_names = { - Path(path).name - for path, _ in memo_files - if Path(path).parent.name == "components" - } - expected = {f"{tag}.jsx" for tag in ctx.memoize_wrappers} - assert component_module_names == expected, ( - f"Per-wrapper file invariant broken. wrappers={sorted(ctx.memoize_wrappers)} " - f"files={sorted(component_module_names)}" - ) assert len(ctx.memoize_wrappers) == 3, ( "Test should exercise the multi-wrapper case: one passthrough wrapper " "for Plain, one for WithProp, and one snapshot wrapper for the " f"LeafComponent boundary. Got: {sorted(ctx.memoize_wrappers)}" ) + memo_files, _imports = compile_memo_components( + memos=tuple(ctx.auto_memo_components.values()), + page_imports={"/p": page_ctx.frontend_imports}, + ) + assert [path for path, _code in memo_files] == [ + str(Path(get_web_dir(), get_route_memo_specifier("/p")[2:] + ".jsx")) + ] + assert sorted(_module_by_export(memo_files)) == sorted(ctx.memoize_wrappers) def _memo_export_line(files: object, symbol: str) -> str: @@ -3709,9 +3651,8 @@ def _scoped_memo_modules(memo: Any) -> tuple[bool, dict[str, str]]: memos=(definition, *ctx.auto_memo_components.values()) ) names = {memo_paths.mirrored_symbol(definition.export_name, __name__): "Memo"} - # A wrapper lands in the module of the memo whose body it came from. for tag, _module in ctx.auto_memo_components: - names[memo_paths.mirrored_symbol(tag, __name__)] = "Wrapper" + names[tag] = "Wrapper" modules = {} for name, block in _module_by_export(files).items(): for symbol, token in names.items(): diff --git a/tests/units/compiler/test_plugins.py b/tests/units/compiler/test_plugins.py index c0a4a8dc7b5..b5fe00aab9e 100644 --- a/tests/units/compiler/test_plugins.py +++ b/tests/units/compiler/test_plugins.py @@ -39,6 +39,7 @@ DefaultPagePlugin, default_page_plugins, ) +from reflex.compiler.utils import get_route_memo_specifier @dataclasses.dataclass(slots=True) @@ -1209,7 +1210,7 @@ def test_compile_context_memoize_wrappers_registers_shared_subtree_tag() -> None # Each page imports the generated experimental memo component. page_a_code = compile_ctx.compiled_pages["/a"].output_code or "" assert ( - f'import {{{wrapper_tag}}} from "$/utils/components/{wrapper_tag}"' + f'import {{{wrapper_tag}}} from "{get_route_memo_specifier("/a")}"' in page_a_code ) assert f"jsx({wrapper_tag}," in page_a_code diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 588d3a87162..8e6ed2590d3 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -2749,9 +2749,11 @@ def test_app_wrap_compile_theme( # the memoized ``onError`` handler instead of the AppWrap chain. memo_contents = ( web_dir - / constants.Dirs.COMPONENTS_PATH - / f"{error_boundary_tag}{constants.Ext.JSX}" - ).read_text() + .joinpath(*memo_paths.route_memo_segments(memo_paths.APP_ROOT_MEMO_STEM)) + .with_suffix(constants.Ext.JSX) + .read_text() + ) + assert f"export const {error_boundary_tag} = " in memo_contents assert "fallbackRender" in memo_contents assert "handle_frontend_exception" in memo_contents # The fallback icon's stroke attributes must reach React in camelCase: @@ -3312,7 +3314,7 @@ class AppWrapState(State): memo_dir = web_dir / constants.Dirs.COMPONENTS_PATH assert any( "useStateContext(" in memo_file.read_text() - for memo_file in memo_dir.glob(f"*{constants.Ext.JSX}") + for memo_file in memo_dir.rglob(f"*{constants.Ext.JSX}") )