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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Warn in development when an expired SQLAlchemy model serializes without mapped values, and reject hybrid properties that are not included in serialized state.
20 changes: 20 additions & 0 deletions packages/reflex-base/src/reflex_base/utils/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
from typing import Any, Literal, NamedTuple, TypeVar, get_type_hints, overload
from uuid import UUID

from reflex_base import constants
from reflex_base.constants.colors import Color
from reflex_base.environment import environment
from reflex_base.utils import _serializer_types, types

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -656,6 +658,7 @@ class _SQLAlchemyLayout(NamedTuple):
_SQLALCHEMY_LAYOUTS: weakref.WeakKeyDictionary[type, _SQLAlchemyLayout] = (
weakref.WeakKeyDictionary()
)
_WARNED_EXPIRED_SQLALCHEMY_MODELS: weakref.WeakSet[type] = weakref.WeakSet()


def _get_sqlalchemy_layout(cls: type) -> _SQLAlchemyLayout:
Expand Down Expand Up @@ -734,6 +737,23 @@ def _serialize_sqlalchemy_model(
values = state.dict
committed = state.committed_state
has_identity_key = state.key is not None

if (
(expired_attributes := state.expired_attributes)
and has_identity_key
and layout.columns
and type(m) not in _WARNED_EXPIRED_SQLALCHEMY_MODELS
and environment.REFLEX_ENV_MODE.get() == constants.Env.DEV
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
and all(key in expired_attributes for key in layout.columns)
):
logger.warning(
"SQLAlchemy model %s has all mapped columns expired and will serialize "
"without them. Set expire_on_commit=False or reload the model in an open "
"session before serializing it.",
type(m).__name__,
)
_WARNED_EXPIRED_SQLALCHEMY_MODELS.add(type(m))

seen.add(id(m))

try:
Expand Down
15 changes: 13 additions & 2 deletions packages/reflex-base/src/reflex_base/utils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import ast
import builtins
import dataclasses
import inspect
import logging
import sys
import types
Expand Down Expand Up @@ -969,6 +970,12 @@ def get_attribute_descriptor(cls: GenericType, name: str) -> Any:
Returns:
The resolved attribute/descriptor, or ``None`` if it is absent.
"""
if isinstance(cls, type) and "__mapper__" in cls.__dict__:
sqlalchemy_hybrid = sys.modules.get("sqlalchemy.ext.hybrid")
if sqlalchemy_hybrid is not None:
descriptor = inspect.getattr_static(cls, name, None)
if isinstance(descriptor, sqlalchemy_hybrid.hybrid_property):
return descriptor
try:
return getattr(cls, name, None)
except NotImplementedError:
Expand All @@ -978,7 +985,7 @@ def get_attribute_descriptor(cls: GenericType, name: str) -> Any:
def is_unserialized_property(
cls: GenericType, name: str, descriptor: Any = _NO_DESCRIPTOR
) -> bool:
"""Check whether ``name`` is a property that the default serializer of ``cls`` omits.
"""Check whether a property that the default serializer of ``cls`` omits is accessed.

Dataclasses serialize their fields only. Pydantic models serialize with the stock
``model_dump()``, which adds ``computed_field`` properties only. A registered
Expand All @@ -1002,7 +1009,11 @@ def is_unserialized_property(
return False
descriptor = get_attribute_descriptor(cls, name)
if not isinstance(descriptor, property):
return False
sqlalchemy_hybrid = sys.modules.get("sqlalchemy.ext.hybrid")
if sqlalchemy_hybrid is None or not isinstance(
descriptor, sqlalchemy_hybrid.hybrid_property
):
return False

from reflex_base.utils import serializers

Expand Down
39 changes: 25 additions & 14 deletions packages/reflex-base/src/reflex_base/vars/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,31 @@ def _unserialized_property_error(var_type: GenericType, name: str) -> VarAttribu
"""
if types.is_union(var_type):
detail = f"union type '{var_type}' may not be included in serialized state."
elif isinstance(var_type, type) and dataclasses.is_dataclass(var_type):
detail = (
f"dataclass '{var_type.__name__}' is not included in serialized state. "
"Only declared dataclass fields are serialized; register an "
"`rx.serializer` for the dataclass to include it."
)
else:
detail = (
f"Pydantic model '{var_type.__name__}' is not included in serialized "
"state. Use `@pydantic.computed_field` to include the computed value in "
"model_dump()."
)
from reflex_base.utils import serializers

if (
isinstance(var_type, type)
and serializers.get_serializer(var_type)
is serializers.serialize_sqlalchemy_base
):
detail = (
f"SQLAlchemy model '{var_type.__name__}' is not included in serialized "
"state. Register an `rx.serializer` for the model to include the "
"value, or access a mapped attribute instead."
)
elif isinstance(var_type, type) and dataclasses.is_dataclass(var_type):
detail = (
f"dataclass '{var_type.__name__}' is not included in serialized state. "
"Only declared dataclass fields are serialized; register an "
"`rx.serializer` for the dataclass to include it."
)
else:
detail = (
f"Pydantic model '{var_type.__name__}' is not included in serialized "
"state. Use `@pydantic.computed_field` to include the computed value in "
"model_dump()."
)
return VarAttributeError(f"The property '{name}' on {detail}")


Expand Down Expand Up @@ -376,9 +389,7 @@ def __getattr__(self, name: str) -> Var:
)
raise VarAttributeError(msg)
return hybrid_var
if isinstance(descriptor, property) and types.is_unserialized_property(
fixed_type, name, descriptor
):
if types.is_unserialized_property(fixed_type, name, descriptor):
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
raise _unserialized_property_error(fixed_type, name)
Comment thread
harsh21234i marked this conversation as resolved.
Resolved
attribute_type = get_attribute_access_type(var_type, name, descriptor)
elif is_typeddict(fixed_type) or fixed_type in types.UnionTypes:
Expand Down
114 changes: 114 additions & 0 deletions tests/units/reflex_base/utils/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
selectinload,
synonym,
)
from sqlalchemy.orm.attributes import instance_state


def test_declarative_base_serializer_handles_loaded_and_unloaded_attributes():
Expand Down Expand Up @@ -113,6 +114,119 @@ class SerializerHero(SerializerBase):
engine.dispose()


@pytest.mark.parametrize(("mode", "warns"), [("dev", True), ("prod", False)])
def test_serialize_expired_sqlalchemy_model_warns_only_in_dev(
caplog, monkeypatch, mode: str, warns: bool
) -> None:
"""Warn once in development and skip expiration scans in production.

Args:
caplog: Fixture for inspecting serialization warnings.
monkeypatch: Fixture for selecting the mode and guarding production scans.
mode: The Reflex environment mode.
warns: Whether the serializer should emit a warning.
"""

class UnscannedExpiration(set[str]):
def __contains__(self, column: object) -> bool:
"""Reject a warning-only column scan in production.

Args:
column: The column being checked.

Raises:
AssertionError: If the serializer checks the column's expiration.
"""
msg = f"Production serializer checked whether {column!r} expired."
raise AssertionError(msg)

class ExpiredBase(DeclarativeBase):
pass

class ExpiredUser(ExpiredBase):
__tablename__ = "expired_user_warning"

id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]

engine = create_engine("sqlite://")
ExpiredBase.metadata.create_all(engine)
with Session(engine) as session:
user = ExpiredUser(name="Ada")
session.add(user)
session.commit()
if mode == "prod":
state = instance_state(user)
monkeypatch.setattr(
state,
"expired_attributes",
UnscannedExpiration(state.expired_attributes),
)

monkeypatch.setenv("REFLEX_ENV_MODE", mode)
with caplog.at_level("WARNING", logger=serializers.__name__):
assert serializers.serialize_sqlalchemy_base(user) == {}
assert serializers.serialize_sqlalchemy_base(user) == {}
assert set(user.__dict__) == {"_sa_instance_state"}
engine.dispose()

warnings = [
record.message
for record in caplog.records
if record.name == serializers.__name__
]
warning = (
"SQLAlchemy model ExpiredUser has all mapped columns expired and will "
"serialize without them. Set expire_on_commit=False or reload the model "
"in an open session before serializing it."
)
assert warnings == ([warning] if warns else [])


@pytest.mark.parametrize("expired_attribute", [None, "name"], ids=["loaded", "partial"])
def test_serialize_loaded_sqlalchemy_model_does_not_warn_about_expiration(
caplog, monkeypatch, expired_attribute: str | None
) -> None:
"""Avoid expiration warnings for loaded and partially expired models.

Args:
caplog: Fixture for inspecting serialization warnings.
monkeypatch: Fixture for selecting development mode.
expired_attribute: Optional mapped column to expire before serialization.
"""

class LoadedBase(DeclarativeBase):
pass

class LoadedUser(LoadedBase):
__tablename__ = "loaded_user_warning_check"

id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]

engine = create_engine("sqlite://")
LoadedBase.metadata.create_all(engine)
with Session(engine, expire_on_commit=False) as session:
user = LoadedUser(name="Ada")
session.add(user)
session.commit()
if expired_attribute is not None:
session.expire(user, [expired_attribute])

monkeypatch.setenv("REFLEX_ENV_MODE", "dev")
with caplog.at_level("WARNING", logger=serializers.__name__):
result = serializers.serialize_sqlalchemy_base(user)

expected = {"id": 1} if expired_attribute else {"id": 1, "name": "Ada"}
assert result == expected
assert not [
record
for record in caplog.records
if record.name == serializers.__name__ and "LoadedUser" in record.message
]
engine.dispose()


def test_declarative_base_serializer_handles_bidirectional_relationships():
"""Serialize bidirectional relationships without circular references."""

Expand Down
31 changes: 31 additions & 0 deletions tests/units/reflex_base/utils/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,3 +784,34 @@ def double(self) -> str:

assert is_unserialized_property(User, "double")
assert not is_unserialized_property(User, "first")


def test_unserialized_hybrid_property_on_sqlalchemy_dataclass():
"""Flag SQLAlchemy hybrid properties that are absent from serialized state."""
pytest.importorskip("sqlalchemy")
from reflex_base.utils.exceptions import VarAttributeError
from reflex_base.vars.object import ObjectVar
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column

class Base(MappedAsDataclass, DeclarativeBase):
pass

class User(Base):
__tablename__ = "test_user_hybrid_property"

id: Mapped[int] = mapped_column(primary_key=True)
first: Mapped[str]

@hybrid_property
def upper_name(self) -> str:
return self.first.upper()

assert is_unserialized_property(User, "upper_name")
with pytest.raises(VarAttributeError) as exc_info:
ObjectVar[User]("user", _var_type=User | None).upper_name
assert str(exc_info.value) == (
"The property 'upper_name' on SQLAlchemy model 'User' is not included in "
"serialized state. Register an `rx.serializer` for the model to include the "
"value, or access a mapped attribute instead."
)
Loading