Skip to content

Type JSON and other opaque DeclarativeBase columns by Mapped[...] - #7798

Merged
FarhanAliRaza merged 5 commits into
mainfrom
fix/declarative-json-column-type
Nov 11, 2026
Merged

FarhanAliRaza merged 5 commits into
mainfrom
fix/declarative-json-column-type

Conversation

@masenf

@masenf masenf commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes FINDING-011 from the reflex 0.11.0a1 pre-release testing (artifacts on branch claude/vibrant-pasteur-3921g3, prerelease-testing/runs/2026-11-11-v0.11.0a1/db_models/ and verify_dbm/).

Defect

On a SQLAlchemy DeclarativeBase model (plain or MappedAsDataclass), a column like data: Mapped[dict] = mapped_column(JSON) read through a state var was typed object, because get_attribute_access_type used only the column type's python_type (object for JSON, JSONB, PickleType on SQLAlchemy 2.1; types whose python_type raises leaked the raw Mapped[dict]). So State.model.data["city"] failed at compile time with TypeError: Var of type <class 'object'> does not support item access., and Mapped[list[str]] JSON columns had no array operations or rx.foreach. The rx.Model equivalent (profile: dict = Field(sa_column=Column(JSON))) is typed dict, so the rewrite to DeclarativeBase that the 0.11 docs recommend broke such pages. Not a regression vs 0.10.1.

Fix

packages/reflex-base/src/reflex_base/utils/types.py: the column branch now goes through _get_column_access_type(cls, name) (cached per class and attribute):

  1. The column type's python_type stays the primary source (existing logic incl. the ARRAY item type, moved unchanged into _get_column_python_type).
  2. If it is uninformative (object, or raises NotImplementedError), the attribute's Mapped[T] annotation is used.
  3. If it is a bare class and T refines it without changing the runtime class (get_origin(T) or T is the same class, e.g. Mapped[dict[str, int]] over dict, or T is a TypedDict over dict), T is used; otherwise python_type wins, because the database returns that type (Mapped[str] over Enum(Color) stays Color; Mapped[bool] over Integer stays int; ARRAY results are unchanged).
  4. Mapped[Any] / Mapped[object] never override; nullability still comes from the column alone.

Only that one attribute's annotation is resolved (found through the MRO, evaluated in the declaring class's module, Annotated/aliases unwrapped), as reflex does for state fields, so a TYPE_CHECKING-only annotation elsewhere in the class cannot break it; works with from __future__ import annotations and Python 3.14 lazy annotations. Legacy __allow_unmapped__ plain annotations are not used (deferred). The rx.Model / SQLModel branch is untouched and cannot reach the new code.

Cases (annotation + column type → main → this PR)

Declaration main this PR
Mapped[dict] + JSON object dict
Mapped[dict | None] + JSON object | None dict | None
Mapped[dict[str, str] | None] + JSON object | None dict[str, str] | None
Mapped[list[str]] + JSON / JSONB object list[str]
Mapped[dict | None] + PickleType object | None dict | None
Mapped[dict] + type whose python_type raises Mapped[dict] (leaked) dict
Mapped[dict[str, int]] + type with python_type dict dict dict[str, int]
Mapped[list[str]] / Mapped[Sequence[str]] + ARRAY(String) List[str] List[str] (unchanged)
Mapped[str] + Enum(Color) Color Color (unchanged)
Mapped[TypedDict] + type with python_type dict dict the TypedDict
Mapped[bool] + Integer, Mapped[IntEnum] + Integer, Mapped[StrEnum] + String int / int / str unchanged (the database returns 0/1, 1, "a")
Mapped[int], Mapped[str], Mapped[Decimal], Mapped[datetime], nullable variants as before unchanged
Imperative Column(JSON) (no annotation) object | None unchanged
rx.Model Field(sa_column=Column(JSON)) dict dict (unchanged)

Test plan

  • tests/units/test_attribute_access_type.py: test_get_attribute_access_type_declarative_column, parametrized over 36 attributes × plain DeclarativeBase / MappedAsDataclass × with / without from __future__ import annotations; mixin and imperative-column tests; two rx.Model guard tests.
  • tests/units/vars/test_object.py: test_sqlalchemy_json_columns_on_state_var — State.m.profile is a dict ObjectVar and profile["city"] compiles to ?.["profile"]?.["city"] (same as the .to(dict) form); tags is a list[str] ArrayVar and tags.length() / rx.foreach(tags, rx.text) match the .to(list[str]) forms.
  • Failing before against main's types.py: 54 failed, 192 passed (every JSON / JSONB / PickleType / renamed-column / not-implemented / refinement case × 4, assert <class 'object'> is dict in the state test); every "unchanged" row passes on main, confirming those expectations are the pre-fix values.
  • After: the two files 246 passed (Python 3.12: 245 passed, 1 skipped 3.14-only); tests/units/reflex_base + tests/units/vars + related modules 2302 passed; full unit suite 15761 passed, 66 skipped, coverage 81.43% (the Playwright browser-driver module could not run locally for lack of a Chromium binary). ruff check, ruff format, pyright reflex tests: clean. The QA probes verify_dbm/v2_json_types.py and db_models/probes/probe_types.py now type every case dict / dict | None / list[str] and all item accesses compile.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Notes for reviewers

  • Mapped[list[dict]] over ARRAY(JSON) stays List[object] (parametrized python_type is kept).
  • A subclass annotation does not refine a scalar column: Mapped[bool] over Integer stays int, as the database returns 0/1. Typing it bool rendered .to_string() as "1" and passed checked={1} to rx.switch; with int, rx.switch(checked=...) gives the compile-time .bool() hint, as on main.
  • @cache keys are bounded by mapped columns in a real app.

News fragment: packages/reflex-base/news/+declarative-mapped-column-type.bugfix.md.


Generated by Claude Code

View guided diff Turn on auto-fix

A column of a SQLAlchemy DeclarativeBase model (dataclass or plain) was
typed only by its column type's python_type when accessed through a state
var. For JSON/JSONB/PickleType that is `object` (SQLAlchemy 2.1), so
`State.m.d["city"]` raised "Var of type <class 'object'> does not support
item access" and list/dict operations were unavailable, while the
equivalent rx.Model column worked. A python_type raising
NotImplementedError (the default before SQLAlchemy 2.1) leaked the raw
`Mapped[T]` annotation instead.

The column's python_type (including the ARRAY item type) stays the
primary source. The `Mapped[T]` annotation is used only when that python
type is uninformative (`object` or not implemented), or when T refines
it: the origin of T is the same as or a subclass of a bare python type
(`Mapped[dict[str, int]]` over `dict`). So `Mapped[str]` over
`Enum(MyEnum)` stays `MyEnum`, ARRAY columns stay `List[T]`, and
`Mapped[float]` over `Numeric` stays `Decimal`. `Mapped[Any]` and
`Mapped[object]` never override. Nullability is decided by the column
alone, as before.

Only that one annotation is resolved, in the declaring class's module (as
reflex does for state fields), so a TYPE_CHECKING-only symbol elsewhere
in the class does not break it. The whole column typing is cached per
(class, name). The SQLModel (rx.Model) branch is untouched; a test pins
that it never reaches the new code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
@masenf
masenf requested a review from a team as a code owner November 11, 2026 07:41
@masenf masenf added this to the v0.11.0 milestone Nov 11, 2026
@masenf masenf added the on deck PRs lined up to review / merge next label Nov 11, 2026
@greptile-apps

greptile-apps Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; the latest change fixes the previously reported item-access failure.

Summary

The PR uses Mapped[...] annotations to improve column types when SQLAlchemy provides no useful type.

  • SQLAlchemy JSON columns follow their Mapped[...] types in state vars.

Reviews (6) · Last reviewed commit: "Keep a dict column under a parametrized ..." · Reviewed by Greptile

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 4 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/reflex-base/src/reflex_base/utils/types.py">

<violation number="1" location="packages/reflex-base/src/reflex_base/utils/types.py:1109">
P2: For ARRAY columns whose element type is uninformative, the annotation fallback never runs, so `Mapped[list[dict[...]]]` still resolves to `List[object]`. The fallback check should also cover an item type that is `object`, not only a top-level `object`. Otherwise the element type stays opaque, as in the original bug.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

@codspeed

codspeed Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 3 benchmarks

2 warnings

⚠️ 12 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 6 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚡ 3 improved benchmarks
❌ 3 regressed benchmarks
✅ 145 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_state_collection_assignment[1000] 10.7 ms 12 ms -10.81%
❌ test_arithmetic_operations[bare] 11.4 ms 11.9 ms -4.24%
❌ test_arithmetic_operations[state] 11.4 ms 11.9 ms -4.14%
⚡ test_state_access[read_inherited] 45.5 ms 39 ms +16.67%
⚡ test_process_event_burst_independent_tokens[1] 2.8 ms 2.7 ms +5.25%
⚡ test_state_access[write_inherited] 219.7 ms 210.6 ms +4.31%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix/declarative-json-column-type (3074592) with main (f13348a)

Open in CodSpeed

@masenf

masenf commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

The failing CodSpeed Performance Analysis check is not caused by this PR. The two flagged benchmarks are test_route_matching[1000] / [10] (−6 %), and this diff only changes how get_attribute_access_type types SQLAlchemy DeclarativeBase columns, which route matching never calls. CodSpeed warns that "3 benchmarks with a significant change ran on different hardware". The same test_route_matching pair regresses by the same amount on the unrelated #7795. The required performance-tests-gate passes, and the CodSpeed check is not in the required set. This needs an acknowledgement on CodSpeed (or a re-run on matching hardware); there is no code fix to make here.


Generated by Claude Code

An ARRAY column whose item type has no useful Python type, such as
ARRAY(JSON), typed as List[object] and never used its Mapped[...]
annotation, so Mapped[list[dict]] stayed opaque. The bare list type is now
kept for such an item type, which the annotation refines as it does for
other columns.

Bound the column type cache with lru_cache(maxsize=1024), like the other
per-type caches in types.py, and cover key access on a JSON column typed
by a TypedDict.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
`Mapped[bool]` over `Integer` typed the column `bool`, but the database
returns `0`/`1`, so `.to_string()` rendered "1" and `rx.switch(checked=...)`
got `aria-checked="1"` instead of the compile-time `.bool()` hint. The
same applied to an IntEnum over `Integer` and a StrEnum over `String`.

A `Mapped[...]` annotation now refines a bare python type only by type
parameters (`dict[str, int]` over `dict`) or TypedDict keys over `dict`,
which keep the runtime class.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

typing.is_typeddict misses typing_extensions.TypedDict classes, and a
parametrized generic TypedDict is only recognized through its origin, so
both fell back to the bare dict. Check the origin with
typing_extensions.is_typeddict.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
Var key access does not resolve the keys of a parametrized generic
TypedDict, so refining a dict column to `GenericPrefs[int]` turned
`model.generic_prefs["value"]` from working item access into a
VarAttributeError at compile time. Such an annotation now leaves the
column `dict`; a non-generic TypedDict still refines it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi
@masenf

masenf commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator Author

CodSpeed on 3074592 flags test_state_collection_assignment[1000] (−10.8%) and test_arithmetic_operations[bare|state] (−4%). Neither comes from this PR.

  • 3074592 changes one condition in _get_column_access_type and one test relative to 51331cb. CodSpeed measured 51331cb against the same main base (f13348a) with no regressions.
  • _get_column_access_type runs only for columns of SQLAlchemy DeclarativeBase models and its result is cached. test_var_operations.py and test_state_delta.py build no models.
  • test_state_collection_assignment[1000] swings ±11% across unrelated PRs, and this run reports six benchmarks measured on different hardware.

Generated by Claude Code

@FarhanAliRaza
FarhanAliRaza merged commit 45ee83c into main Nov 11, 2026
167 of 168 checks passed
@FarhanAliRaza
FarhanAliRaza deleted the fix/declarative-json-column-type branch November 11, 2026 18:18
masenf added a commit that referenced this pull request Nov 11, 2026
)

* Type JSON and other opaque DeclarativeBase columns by Mapped[...]

A column of a SQLAlchemy DeclarativeBase model (dataclass or plain) was
typed only by its column type's python_type when accessed through a state
var. For JSON/JSONB/PickleType that is `object` (SQLAlchemy 2.1), so
`State.m.d["city"]` raised "Var of type <class 'object'> does not support
item access" and list/dict operations were unavailable, while the
equivalent rx.Model column worked. A python_type raising
NotImplementedError (the default before SQLAlchemy 2.1) leaked the raw
`Mapped[T]` annotation instead.

The column's python_type (including the ARRAY item type) stays the
primary source. The `Mapped[T]` annotation is used only when that python
type is uninformative (`object` or not implemented), or when T refines
it: the origin of T is the same as or a subclass of a bare python type
(`Mapped[dict[str, int]]` over `dict`). So `Mapped[str]` over
`Enum(MyEnum)` stays `MyEnum`, ARRAY columns stay `List[T]`, and
`Mapped[float]` over `Numeric` stays `Decimal`. `Mapped[Any]` and
`Mapped[object]` never override. Nullability is decided by the column
alone, as before.

Only that one annotation is resolved, in the declaring class's module (as
reflex does for state fields), so a TYPE_CHECKING-only symbol elsewhere
in the class does not break it. The whole column typing is cached per
(class, name). The SQLModel (rx.Model) branch is untouched; a test pins
that it never reaches the new code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Type ARRAY columns of opaque items by Mapped[...]

An ARRAY column whose item type has no useful Python type, such as
ARRAY(JSON), typed as List[object] and never used its Mapped[...]
annotation, so Mapped[list[dict]] stayed opaque. The bare list type is now
kept for such an item type, which the annotation refines as it does for
other columns.

Bound the column type cache with lru_cache(maxsize=1024), like the other
per-type caches in types.py, and cover key access on a JSON column typed
by a TypedDict.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Keep the column python type over a scalar subclass annotation

`Mapped[bool]` over `Integer` typed the column `bool`, but the database
returns `0`/`1`, so `.to_string()` rendered "1" and `rx.switch(checked=...)`
got `aria-checked="1"` instead of the compile-time `.bool()` hint. The
same applied to an IntEnum over `Integer` and a StrEnum over `String`.

A `Mapped[...]` annotation now refines a bare python type only by type
parameters (`dict[str, int]` over `dict`) or TypedDict keys over `dict`,
which keep the runtime class.

* Recognize typing_extensions and generic TypedDicts over a dict column

typing.is_typeddict misses typing_extensions.TypedDict classes, and a
parametrized generic TypedDict is only recognized through its origin, so
both fell back to the bare dict. Check the origin with
typing_extensions.is_typeddict.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

* Keep a dict column under a parametrized generic TypedDict annotation

Var key access does not resolve the keys of a parametrized generic
TypedDict, so refining a dict column to `GenericPrefs[int]` turned
`model.generic_prefs["value"]` from working item access into a
VarAttributeError at compile time. Such an annotation now leaves the
column `dict`; a non-generic TypedDict still refines it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Farhan <[email protected]>
(cherry picked from commit 45ee83c)
@masenf masenf added the release-train Issues found during agentic /prerelease-testing fanout, not necessarily validated bugs. label Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

on deck PRs lined up to review / merge next release-train Issues found during agentic /prerelease-testing fanout, not necessarily validated bugs.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants