feat: surface unprocessable state deltas as fatal client errors

Merged
FA
4mo ago
+713-20

Summary

When the backend sends a delta the frontend cannot process (no dispatch function registered for a substate), the app currently throws dispatch[substate] is not a function in the browser console and otherwise looks silently broken. This PR makes that failure loud, actionable, and visible in the backend terminal — where Python devs look first.

Fixes #6019. Supersedes #6128, rebuilt on top of the packages/reflex-base layout with the review findings from that PR addressed.

Frontend (reflex_base/.templates/web/utils/state.js)

  • The entire delta is validated before anything dispatches, so a bad substate can no longer partially apply an update or silently drop update.events.
  • On mismatch, the frontend logs an actionable error to the browser console and reports it to the backend via a new client_error socket event.
  • The mismatch is treated as fatal, as requested in #6019: a backend_state_mismatch flag stops all further event sending and drops incoming updates, so the error is reported once instead of on every interaction. A page reload (e.g. after rebuilding the frontend) resets it.
  • Unexpected errors while applying a delta are caught and reported to the backend too, instead of vanishing as unhandled promise rejections.

Backend (reflex/app.py)

  • New EventNamespace.on_client_error handler logs frontend-reported errors in the terminal with remediation steps (rebuild frontend / check api_url).
  • Hardened against abuse, since any socket can emit this event: non-dict payloads are ignored, client-supplied strings are sanitized (control chars/ANSI escapes stripped) and truncated before logging, and only sockets with a linked token can produce error-level log entries — unknown sids are logged at debug level.
  • emit_update gained debug logging of outgoing substates, guarded by console.is_debug() so the hot path doesn't pay for message construction.

Shared constants

  • SocketEvent.CLIENT_ERROR and a new ClientErrorType namespace in reflex_base.constants.event keep the error-type strings in one place, matched by the ERROR_TYPE_* constants in state.js.

Testing

  • New tests/units/test_client_error.py covers both error branches, malformed payloads (which previously raised AttributeError), unknown-sid gating, and sanitization/truncation.
  • tests/units/test_app.py and tests/units/utils/test_token_manager.py pass alongside (164 passed).