Skip to content

Explicit state and event id minification - #6100

Open
benedikt-bartscher wants to merge 184 commits into
reflex-dev:mainfrom
benedikt-bartscher:explicit-event-id-minification
Open

benedikt-bartscher wants to merge 184 commits into
reflex-dev:mainfrom
benedikt-bartscher:explicit-event-id-minification

Conversation

@benedikt-bartscher

@benedikt-bartscher benedikt-bartscher commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add state and event name minification with CLI management tools.

  • Introduces minify.json config file to map state/event names to short IDs (e.g., myapp.state.AppState → "a")
  • Adds reflex minify CLI command group for managing minification
  • Reduces frontend bundle size and WebSocket payload size by replacing long state/event paths with compact identifiers

CLI Commands

# Initialize minify.json with IDs for all states and events
reflex minify init

# Sync minify.json after code changes
reflex minify sync
reflex minify sync --prune --reassign-deleted

# Validate config against current codebase
reflex minify validate

# List state tree with minified names
reflex minify list
reflex minify list --json

# Lookup a minified path
reflex minify lookup "a.bU"

based on #6098

@codspeed

codspeed Bot commented Jan 24, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 9.67%

2 warnings

⚠️ 15 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

⚠️ 3 benchmarks with a significant change ran in a different software environment

Their base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the changes might come from this difference rather than from the code. Open an affected benchmark to see what changed.

See affected benchmarks

⚡ 3 improved benchmarks
✅ 143 untouched benchmarks
⏩ 8 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_from_event_type[event_spec] 11.5 ms 9.7 ms +19.65%
⚡ test_from_event_type[lambda_event_handler] 35 ms 33.1 ms +5.48%
⚡ test_hydration_snapshot[200] 8 ms 7.7 ms +4.52%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing benedikt-bartscher:explicit-event-id-minification (c25cc3e) with main (df7f157)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@benedikt-bartscher benedikt-bartscher changed the title Explicit event id minification Explicit state and event id minification Jan 25, 2026
Comment thread reflex/reflex.py Resolved
@benedikt-bartscher

benedikt-bartscher commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor Author

TODO: best-effort-mode

  • walk trough the state id registry after the app module get's imported
  • filter out all states with explicit state id
  • sort the remaining states without state id by full name
  • assign state ids - start with the highest user defined state id - users might have fragmentation by choice

a similar thing can be implemented for event handler id's

edit: not that easy, as state names are baked into to many things (events, vars etc). we would need to defer init_subclass and possibly parts of @rx.var and @rx.event

edit2: i have found a better approach with a minify.json which makes this obsolete

@benedikt-bartscher

benedikt-bartscher commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Open for discussion: Should reflex reserve the first 5/10 state id's for internal states? Current reflex uses 0-3, but that might change in the future.

edit: with sibling uniqueness we would just need to reserve the state id's on the first rx.State subclass level.

edit2: i have found a better approach with a minify.json which makes this obsolete

@benedikt-bartscher

benedikt-bartscher commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor Author

TODO: think about sibling uniqueness for states. currently using global uniqueness

edit: adjusted in 6b4c5fa

@benedikt-bartscher
benedikt-bartscher force-pushed the explicit-event-id-minification branch from 35ad1c6 to 1647c1e Compare February 1, 2026 10:25
@benedikt-bartscher

Copy link
Copy Markdown
Contributor Author

Idea: store ids in a minify.json file

  • allows overwriting state ids for upstream dependencies and reflex core
  • one centralized place for the ids
  • keep track of reserved numbers
  • better automatic instrumentation - state and event ids can all be managed with cli - without manual code changes
  • can be loaded once on startup and is frozen - probably faster
  • no best effort mode needed

When a parent and child state have the same minified name, substate
resolution can fail because the leading segment is stripped incorrectly. This
change adds a flag to skip stripping only on the initial recursive call, ensuring
correct resolution even in name collision scenarios.
Comment thread reflex/reflex.py Resolved
@masenf masenf added the roadmap https://github.com/reflex-dev/reflex/issues/2727 label Oct 23, 2026
_assign_next_ids compared decoded ids, so a held "aa" kept "a" from being
handed out to a new state, event, or duplicate. It now compares the id
strings, as validate and the wire do.
A segment that is one handler's Python name and another handler's id
resolved only to the id holder. lookup now lists both and warns which one
applies with REFLEX_MINIFY_EVENTS on or off.
@benedikt-bartscher
benedikt-bartscher force-pushed the explicit-event-id-minification branch from 9e7e2e1 to d4a7d69 Compare October 25, 2026 15:52
@FarhanAliRaza FarhanAliRaza added the enhancement Anything you want improved label Nov 12, 2026 — with ChatGPT Codex Connector
Comment thread tests/units/test_reflex.py Resolved
The frontend keys plain objects by root state name, so a root state on
'constructor' or 'toString' found an inherited member as its dispatcher and
its deltas went nowhere. Loading refuses such an id, validate reports it and
sync reassigns it.

@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 4 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

View guided diff | Re-trigger cubic

Comment thread reflex/minify.py Resolved
The frontend keys its state maps by dotted state path, so only a root's
key is its id alone; a nested state on 'constructor' is keyed
'parent.constructor' and stays valid.
The default state name is snake-cased, so 'cartItem' and 'cart_item'
named the same state and the second create() hit the sibling-shadowing
guard. A key without capitals keeps its spelling in that name.
Log messages wrap to the terminal width, so their output is compared
with the wrapping undone. The validate test configures every other
state, so its output is the one error alone.
Comment thread reflex/minify.py Resolved
Comment thread tests/units/test_minify.py Resolved
A background task passes its StateProxy as state, so type() gave the proxy
class, which the minify resolver can't place.
'reflex minify validate' decided whether an entry is a root by its recorded
parent alone, so a root whose parent was stale but not null passed on an
id such as 'constructor', which the frontend would key as a bare root. The
app loads the file by the recorded parent and the frontend keys the state by
its actual one, so the id is now checked as a root's when either says root.
The minify tests matched errors, warnings and the stale-config log line by
a fragment, which passes when the rest of the message is wrong. They now
compare each one whole, as does the duplicate component state key test.

from python_multipart.multipart import MultipartParser, parse_options_header
from reflex_base.registry import RegistrationContext
from reflex_base.registry import RegistrationContext, scheme_digest

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.

P1 Allowed versions fail to load

_upload.py now imports scheme_digest, but reflex-components-core still allows reflex-base >= 0.11.0. That released version has no scheme_digest, so an allowed installation fails when it imports uploads.

Raise the package's reflex-base floor to the first version containing this function. The repository guide requires raising the dependency floor when a package uses an unreleased change from a sibling package.

Context Used: CLAUDE.md (source)

try_get went through get() and caught its LookupError. BaseContext.get only
reads the context var, so ContextVar.get(None) gives the same answer without
the extra call and exception: try_get drops from ~49 to 18 ns, which every
event pays several times via format_event_handler.
get_event_handler_parts and format_event_handler imported the registry on
every call. The registry only imports reflex_base.context.base and
reflex_base.utils.exceptions, neither of which imports format, so the import
moves to the module. With the try_get change, _connect_supersedes (every
enqueue) drops from ~340 to ~155 ns and get_hydrate_event (every event) from
~194 to ~106 ns.
set_name_resolver called cache_clear on get_name, get_full_name,
_get_substate_path and get_class_substate for every registered state, but
each is one functools cache shared by all state classes, so the first
class's calls already cleared them. Clear them once.
test_lookup_resolves_minified_path defines AppState and ChildState inside
the test, so they move to reflex.istate.dynamic and take a suffix when a
state of that name already lives there. Run after other tests defining a
local ChildState (e.g. with pytest-randomly, seed 2 over test_reflex,
test_state, test_var and test_minify), the lookup printed ChildState_2 and
the hard-coded expectation failed.
…inification

- reflex-dev#7583's field subscription goes on the state's local, which a resolver
  can prefix with `$rx_`; the two hook tests expect the field list.
- reflex-dev#7938's wait for the lost-and-found subscription runs after the per-SID
  setup, which has to happen before the connect's first await, and still
  before link_token_to_sid stores the socket record.
A renamed state's local carries the `$rx_` prefix, which the hook merge's
`\w+` did not match. A component reading two fields of a minified state
kept both hooks, so its compiled code declared the local twice and the
production build failed.
A text reading `label` and `count` of the minified root state compiles
both field subscriptions into one hook. Before c99f0e0 the merge
skipped the `$rx_` local, and the build failed with
"Identifier `$rx_reflex___state____state__k` has already been declared".

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement Anything you want improved perf Performance-improving changes roadmap https://github.com/reflex-dev/reflex/issues/2727

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants