From 4a137dc71fd31976510a12c99f7d659cb6ce34d8 Mon Sep 17 00:00:00 2001 From: TejasLamba2006 Date: Sun, 22 Nov 2026 19:25:29 +0530 Subject: [PATCH] fix(compiler): validate disabled-state rx.State usage structurally across compiled domains Replace the JS substring check in compile_app with structural VarData state-dependency inspection across compiled pages, app wraps, explicit and automatic memos, prop-embedded components, hydrate fallbacks, and document head entries, and explain enable_state=False in the raised ReflexRuntimeError. Fixes #7579 --- reflex/app.py | 3 +- reflex/compiler/compiler.py | 238 ++++++++++++++++-- tests/units/compiler/test_compiler.py | 336 +++++++++++++++++++++++++- 3 files changed, 557 insertions(+), 20 deletions(-) diff --git a/reflex/app.py b/reflex/app.py index 3d9229c599c..3aff4b78dea 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -2241,7 +2241,8 @@ def _compile( the initial state. Raises: - ReflexRuntimeError: When any page uses state, but no rx.State subclass is defined. + ReflexRuntimeError: When any compiled frontend component uses rx.State + while state is disabled (``enable_state=False``). FileNotFoundError: When a plugin requires a file that does not exist. """ from reflex_base.utils.deterministic_hash import clear_hash_caches diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 83d72e5dd12..a83a8cd0dc0 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -41,7 +41,7 @@ ImportVar, ParsedImportDict, ) -from reflex_base.vars.base import LiteralVar, Var +from reflex_base.vars.base import LiteralVar, Var, VarData from reflex_base.vars.sequence import LiteralStringVar from reflex_components_core.base.app_wrap import AppWrap from reflex_components_core.base.fragment import Fragment @@ -51,7 +51,7 @@ from reflex.compiler import templates, utils from reflex.compiler.plugins import default_page_plugins from reflex.compiler.plugins.memoize import MemoizeStatefulPlugin, scope_memo_body_hooks -from reflex.state import BaseState, code_uses_state_contexts, state_snapshot_hashes +from reflex.state import BaseState, state_snapshot_hashes from reflex.utils import console, frontend_skeleton, path_ops, prerequisites from reflex.utils.exec import get_compile_context, is_prod_mode from reflex.utils.prerequisites import get_web_dir @@ -1285,6 +1285,198 @@ def _read_stateful_pages_marker() -> list[str] | None: raise +def _var_data_uses_state( + var_data: VarData | None, + seen_vars: set[int], + seen_components: set[int], +) -> bool: + """Return whether ``var_data`` carries a dependency on any ``rx.State``. + + Args: + var_data: The ``VarData`` to inspect. + seen_vars: Visited ``Var`` object IDs for cycle avoidance. + seen_components: Visited ``BaseComponent`` object IDs for cycle avoidance. + + Returns: + True if any state field dependency is reachable from ``var_data``. + """ + if var_data is None: + return False + if any(var_data.field_dependencies): + return True + if any(_var_uses_state(dep, seen_vars, seen_components) for dep in var_data.deps): + return True + if any( + _component_uses_state(comp, seen_vars, seen_components) + for comp in var_data.components + ): + return True + return any( + _component_uses_state(wrapper, seen_vars, seen_components) + for _, wrapper in var_data.app_wraps + ) + + +def _var_uses_state( + var: Var | None, + seen_vars: set[int], + seen_components: set[int], +) -> bool: + """Return whether ``var`` references any ``rx.State``. + + Args: + var: The ``Var`` to inspect. + seen_vars: Visited ``Var`` object IDs for cycle avoidance. + seen_components: Visited ``BaseComponent`` object IDs for cycle avoidance. + + Returns: + True if ``var`` carries a dependency on ``rx.State``. + """ + if var is None: + return False + var_id = id(var) + if var_id in seen_vars: + return False + seen_vars.add(var_id) + return _var_data_uses_state(var._get_all_var_data(), seen_vars, seen_components) + + +def _component_uses_state( + component: BaseComponent | None, + seen_vars: set[int], + seen_components: set[int], +) -> bool: + """Return whether ``component`` or any reachable descendant references ``rx.State``. + + Args: + component: The component tree root to inspect. + seen_vars: Visited ``Var`` object IDs for cycle avoidance. + seen_components: Visited ``BaseComponent`` object IDs for cycle avoidance. + + Returns: + True if any originating ``Var``, hook, prop-embedded component, app wrap, + or descendant carries a dependency on ``rx.State``. + """ + if component is None: + return False + comp_id = id(component) + if comp_id in seen_components: + return False + seen_components.add(comp_id) + + if isinstance(component, Component): + for var in component._get_vars(include_children=False): + if _var_uses_state(var, seen_vars, seen_components): + return True + + user_hooks = component._get_hooks() + if isinstance(user_hooks, Var) and _var_uses_state( + user_hooks, seen_vars, seen_components + ): + return True + if ( + isinstance(user_hooks, str) + and constants.REFLEX_VAR_OPENING_TAG in user_hooks + and _var_uses_state( + LiteralStringVar.create(user_hooks), seen_vars, seen_components + ) + ): + return True + + for hook_str, hook_var_data in component._get_added_hooks().items(): + if _var_data_uses_state(hook_var_data, seen_vars, seen_components): + return True + if ( + hook_var_data is None + and isinstance(hook_str, str) + and constants.REFLEX_VAR_OPENING_TAG in hook_str + and _var_uses_state( + LiteralStringVar.create(hook_str), seen_vars, seen_components + ) + ): + return True + + for hook_var_data in component._get_hooks_internal().values(): + if _var_data_uses_state(hook_var_data, seen_vars, seen_components): + return True + + for prop_component in component._get_components_in_props(): + if _component_uses_state(prop_component, seen_vars, seen_components): + return True + + if ( + type(component)._get_app_wrap_components + is not Component._get_app_wrap_components + ): + for wrap_component in component._get_app_wrap_components().values(): + if _component_uses_state(wrap_component, seen_vars, seen_components): + return True + + return any( + _component_uses_state(child, seen_vars, seen_components) + for child in component.children + ) + + +def _compiled_app_uses_state( + *, + pages: Iterable[BaseComponent], + app_root: BaseComponent, + memos: Iterable[MemoDefinition], + head_components: Iterable[BaseComponent] = (), + extra_vars: Iterable[Var | str | None] = (), +) -> bool: + """Return whether any final compilation domain references ``rx.State``. + + Inspects originating ``VarData`` metadata across compiled pages, the app + root (including app wraps), explicit and automatic memos (including hydrate + fallbacks), prop-embedded components, and document head entries instead of + matching substrings in emitted JavaScript. + + Args: + pages: Compiled root components for all pages. + app_root: The compiled app root component. + memos: All explicit and automatic memo definitions to be emitted. + head_components: Components rendered in the document head. + extra_vars: Additional document-level values (e.g. html attributes). + + Returns: + True if any compilation domain carries an ``rx.State`` dependency. + """ + seen_vars: set[int] = set() + seen_components: set[int] = set() + + for root in (*pages, app_root, *head_components): + if _component_uses_state(root, seen_vars, seen_components): + return True + + for memo in memos: + if isinstance(memo, MemoComponentDefinition): + if _component_uses_state(memo.component, seen_vars, seen_components): + return True + if _var_uses_state(memo.wrapper, seen_vars, seen_components): + return True + elif isinstance(memo, MemoFunctionDefinition): + if _var_uses_state(memo.function, seen_vars, seen_components): + return True + + for value in extra_vars: + if isinstance(value, Var) and _var_uses_state( + value, seen_vars, seen_components + ): + return True + if ( + isinstance(value, str) + and constants.REFLEX_VAR_OPENING_TAG in value + and _var_uses_state( + LiteralStringVar.create(value), seen_vars, seen_components + ) + ): + return True + + return False + + def compile_app( app: App, *, @@ -1460,17 +1652,6 @@ def compile_app( all_imports = compile_ctx.all_imports - if app._state is None and any( - code_uses_state_contexts(page_ctx.output_code or "") - for page_ctx in compile_ctx.compiled_pages.values() - ): - msg = ( - "To access rx.State in frontend components, at least one " - "subclass of rx.State must be defined in the app." - ) - raise ReflexRuntimeError(msg) - progress.advance(task) - 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()) @@ -1496,12 +1677,33 @@ def compile_app( else memo for memo in tuple(MEMOS.values()) ] - memo_component_files, memo_components_imports = compile_memo_components( - ( - *memos, - *compile_ctx.auto_memo_components.values(), - ), + all_memos = ( + *memos, + *compile_ctx.auto_memo_components.values(), ) + + if app._state is None and _compiled_app_uses_state( + pages=( + page_ctx.root_component for page_ctx in compile_ctx.compiled_pages.values() + ), + app_root=app_root, + memos=all_memos, + head_components=app.head_components, + extra_vars=( + app.html_lang, + *(app.html_custom_attrs.values() if app.html_custom_attrs else ()), + ), + ): + progress.stop() + msg = ( + "Cannot access rx.State in frontend components when state is " + "disabled (`enable_state=False`). Remove `enable_state=False` from " + "`rx.App` or remove the rx.State references." + ) + raise ReflexRuntimeError(msg) + progress.advance(task) + + memo_component_files, memo_components_imports = compile_memo_components(all_memos) compile_results.extend(memo_component_files) all_imports = utils.merge_imports(all_imports, memo_components_imports) progress.advance(task) diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..e17109e055c 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -14,7 +14,11 @@ from reflex_base.components.dynamic import bundle_library, reset_bundled_libraries from reflex_base.components.memo import MEMOS from reflex_base.constants.base import LiteralColorMode -from reflex_base.constants.compiler import PageNames +from reflex_base.constants.compiler import ( + MemoizationDisposition, + MemoizationMode, + PageNames, +) from reflex_base.environment import environment from reflex_base.plugins import CompileContext, CompilerHooks, PageContext from reflex_base.plugins.sitemap import SitemapPlugin @@ -23,6 +27,7 @@ from reflex_base.utils.exceptions import ( DynamicRouteArgShadowsStateVarError, PageValueError, + ReflexRuntimeError, RouteValueError, ) from reflex_base.utils.imports import ImportVar, ParsedImportDict @@ -2402,3 +2407,332 @@ 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 + + +@pytest.mark.parametrize("auto_memoize", [True, False]) +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_false_rejects_state_reads_in_pages_and_auto_memos( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + auto_memoize: bool, +): + """State reads fail compilation when state is disabled, memoized or not. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + auto_memoize: Whether stateful subtrees are auto-memoized. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config( + app_name="disabled_state_test", + plugins=[], + auto_memoize=auto_memoize, + ) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class DynState(rx.State): + label: str = "x" + + app = rx.App(enable_state=False) + app.add_page(lambda: rx.text(DynState.label), route="/") + + with pytest.raises(ReflexRuntimeError, match=r"enable_state=False"): + compiler.compile_app(app, dry_run=True, use_rich=False) + + +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_false_rejects_non_memoized_never_component( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +): + """A component opting out of memoization still triggers the disabled-state guard. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="disabled_state_never", plugins=[], auto_memoize=True) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class NeverMemoBox(rx.Component): + tag = "div" + label: Var[str] + _memoization_mode = MemoizationMode(disposition=MemoizationDisposition.NEVER) + + class DynState(rx.State): + label: str = "x" + + app = rx.App(enable_state=False) + app.add_page(lambda: NeverMemoBox.create(label=DynState.label), route="/") + + with pytest.raises(ReflexRuntimeError, match=r"enable_state=False"): + compiler.compile_app(app, dry_run=True, use_rich=False) + + +@pytest.mark.parametrize("state_in_body", [True, False]) +@pytest.mark.usefixtures("clean_registration_context", "preserve_memo_registries") +def test_enable_state_false_rejects_explicit_memo_state_reads( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + state_in_body: bool, +): + """Explicit ``@rx.memo`` components reading state fail when state is disabled. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + state_in_body: Whether state is read inside the memo body or passed as a prop. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="disabled_state_memo", plugins=[]) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class DynState(rx.State): + label: str = "x" + + app = rx.App(enable_state=False) + if state_in_body: + + @rx.memo + def stateful_memo() -> rx.Component: + return rx.text(DynState.label) + + app.add_page(lambda: stateful_memo(), route="/") + else: + + @rx.memo + def prop_memo(label: Var[str]) -> rx.Component: + return rx.text(label) + + app.add_page(lambda: prop_memo(label=DynState.label), route="/") + + with pytest.raises(ReflexRuntimeError, match=r"enable_state=False"): + compiler.compile_app(app, dry_run=True, use_rich=False) + + +@pytest.mark.parametrize( + "disposition", + [MemoizationDisposition.STATEFUL, MemoizationDisposition.NEVER], +) +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_false_rejects_prop_embedded_stateful_components( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + disposition: MemoizationDisposition, +): + """Stateful components embedded inside props fail when state is disabled. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + disposition: Memoization disposition of the outer host component. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="disabled_state_prop_comp", plugins=[]) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class SlotHost(rx.Component): + tag = "div" + header: Var[Component] + _memoization_mode = MemoizationMode(disposition=disposition) + + class DynState(rx.State): + label: str = "x" + + app = rx.App(enable_state=False) + app.add_page(lambda: SlotHost.create(header=rx.text(DynState.label)), route="/") + + with pytest.raises(ReflexRuntimeError, match=r"enable_state=False"): + compiler.compile_app(app, dry_run=True, use_rich=False) + + +@pytest.mark.parametrize("memoized_wrap", [True, False]) +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_false_rejects_stateful_app_wraps( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + memoized_wrap: bool, +): + """Stateful app wraps fail compilation when state is disabled. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + memoized_wrap: Whether the stateful wrap is auto-memoized or stays in app root. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="disabled_state_app_wrap", plugins=[]) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class NeverMemoWrap(rx.Component): + tag = "div" + label: Var[str] + _memoization_mode = MemoizationMode(disposition=MemoizationDisposition.NEVER) + + class DynState(rx.State): + label: str = "x" + + wrap_factory = ( + (lambda _stateful: rx.box(rx.text(DynState.label))) + if memoized_wrap + else (lambda _stateful: NeverMemoWrap.create(label=DynState.label)) + ) + app = rx.App( + enable_state=False, + extra_app_wraps={(10, "StatefulWrap"): wrap_factory}, + ) + app.add_page(lambda: rx.text("static"), route="/") + + with pytest.raises(ReflexRuntimeError, match=r"enable_state=False"): + compiler.compile_app(app, dry_run=True, use_rich=False) + + +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_false_rejects_stateful_hydrate_fallback( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +): + """A stateful hydrate fallback fails compilation when state is disabled. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="disabled_state_fallback", plugins=[]) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class DynState(rx.State): + label: str = "x" + + app = rx.App( + enable_state=False, + hydrate_fallback=lambda: rx.text(DynState.label), + ) + app.add_page(lambda: rx.text("static"), route="/") + + with pytest.raises(ReflexRuntimeError, match=r"enable_state=False"): + compiler.compile_app(app, dry_run=True, use_rich=False) + + +@pytest.mark.parametrize( + "literal_text", + [ + "useContext(StateContexts", + "useStateContext(", + ], +) +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_false_allows_literal_hook_spelling_text( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + literal_text: str, +): + """Literal text resembling state hook calls compiles cleanly with state disabled. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + literal_text: Text content matching old or current hook spellings. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="disabled_state_literal", plugins=[]) + mocker.patch("reflex_base.config._get_config", return_value=config) + + app = rx.App(enable_state=False) + app.add_page(lambda: rx.text(literal_text), route="/") + + assert compiler.compile_app(app, dry_run=True, use_rich=False) is True + + +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_false_allows_stateless_and_client_only_hooks( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +): + """Stateless pages with client-only state and hooks compile with state disabled. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="disabled_state_client_only", plugins=[]) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class ClientHookBox(rx.Component): + tag = "div" + + def add_imports(self) -> dict[str, str]: + """Import useState for the client-only hook. + + Returns: + The React hook import. + """ + return {"react": "useState"} + + def add_hooks(self) -> list[str]: + """Add a client-only React hook with no rx.State dependency. + + Returns: + A plain React state hook. + """ + return ["const [clientOnlyCount, setClientOnlyCount] = useState(0)"] + + counter = rx.client_state(0, name="counter") + app = rx.App(enable_state=False) + app.add_page( + lambda: rx.el.div( + rx.text("static"), + rx.text(counter.value), + rx.button("log", on_click=rx.console_log("hi")), + ClientHookBox.create(), + ), + route="/", + ) + + assert compiler.compile_app(app, dry_run=True, use_rich=False) is True + + +@pytest.mark.usefixtures("clean_registration_context") +def test_enable_state_true_allows_state_reads( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, +): + """State reads compile normally when state is enabled. + + Args: + tmp_path: Directory for compiler output. + monkeypatch: Fixture for changing the app directory. + mocker: Fixture for configuring the test app. + """ + monkeypatch.chdir(tmp_path) + config = rx.Config(app_name="enabled_state_control", plugins=[]) + mocker.patch("reflex_base.config._get_config", return_value=config) + + class DynState(rx.State): + label: str = "x" + + app = rx.App(enable_state=True) + app.add_page(lambda: rx.text(DynState.label), route="/") + + assert compiler.compile_app(app, dry_run=True, use_rich=False) is True