Repository navigation
Make core's reducers pure by moving time, new IDs and side effects out of them - #6073
Eugene (OEvgeny) wants to merge 17 commits into
Conversation
… after them The reducers read the time and new IDs from the action's meta, which a new innermost middleware adds (prepareAction(), one registry by action type), and the breakpoint and the warnings run once after the reducers (afterDispatch()). The host middleware, the sagas and dispatch() see the action as dispatched. The reducer factories become module-level reducers, and the ponyfill of a store moves from getState().internal to StorePonyfillRegistry.
In packages/core/src/reducers/ (not the specs): no clock, timer, random ID, microtask, console or ponyfill.
The reducers need the values of prepareAction() in meta; an action dispatched around the store (e.g. by hand in the DevTools) now gets a message that says so.
… transcript As on main (where the microtask closed over the reassigned variable): with received-at, local ID and send status. afterDispatch() gets it from the same pure function as the reducer, toIncomingActivity().
Unchanged code, now shared by the reducer and afterDispatch(); the lint rule of reducers/ keeps it pure.
The breakpoint and the warnings were run after next(): after the store listeners and their nested dispatches, and never when a reducer threw. Run them before next() instead: they read only the state the reducers get. Rename afterDispatch() to runEffects().
…ucers The warning was the last side effect inside a reducer. Whether the session was concluded is known from the state the reducers get and the activity's livestream metadata, so runEffects() warns instead. Its warnings now come in upsert()'s order, and the incoming activity is made once for the breakpoint and the warnings.
createStore() puts it in the initial state, merged into the host's, and the internal reducer returns its state as it is. <Composer> reads it as before, so StorePonyfillRegistry and its export go.
…er rules Lint reducer.ts, prepareAction.ts and the 4 utils that reducers import, not only reducers/. Reuse the base config's bans on Date and the timers instead of copying them: no-console without its allow list, and one no-restricted-syntax list for the rest.
…it reads no clock
…hen the store rejects the activity An activity without "from" makes the typing reducer throw before the grouped-activities reducer queues the breakpoint on main. Queueing it with the dispatched activity first called it anyway.
…in does On main, getLogicalTimestamp() returns a numeric "webchat:sequence-id" first and never reaches the Date warning. An adapter that orders by sequence ID got a new warning on every activity.
… main prepareAction() and runEffects() read action.type before Redux checks the action, so a host got "Cannot read properties of undefined" instead of "Actions must be plain objects". Read it with ?. as assertPrepared() does.
There was a problem hiding this comment.
🟡 Changes recommended
The preparation guard checks only for metadata key presence, allowing undefined or string timestamps to pass validation and be stored as invalid notification timestamps.
1 open issue
What changed in this PR
This PR separates nondeterministic work from core’s Redux reducers so prepared actions can be replayed consistently, while preserving the actions seen by host middleware and sagas.
Changes:
- Adds middleware that supplies timestamps and IDs through action metadata and runs warnings and debug effects outside reducers.
- Replaces reducer factories with module-level reducers and removes clock dependencies from activity processing.
- Adds preparation and replay tests, updates sorting tests, and introduces reducer-purity lint rules.
| File | Description |
|---|---|
packages/core/src/utils/parseTimestamp.ts |
Adds timestamp parsing without reading the clock. |
packages/core/src/utils/isDate.ts |
Adds cross-realm Date detection. |
packages/core/src/types/internal/ReduxState.ts |
Updates the reducer reference in a TODO comment. |
packages/core/src/reducers/voiceActivity.ts |
Moves the transition warning out of the reducer. |
packages/core/src/reducers/typing.ts |
Uses prepared timestamps for typing state. |
packages/core/src/reducers/notifications.ts |
Uses prepared timestamps for notifications. |
packages/core/src/reducers/createTypingReducer.ts |
Removes the clock-dependent typing factory. |
packages/core/src/reducers/createNotificationsReducer.ts |
Removes the clock-dependent notification factory. |
packages/core/src/reducers/createInternalReducer.ts |
Removes the ponyfill-capturing reducer factory. |
packages/core/src/reducers/activities/toIncomingActivity.ts |
Extracts shared, deterministic incoming-activity processing. |
packages/core/src/reducers/activities/sort/upsert.ts |
Removes ponyfill dependencies and warning effects. |
packages/core/src/reducers/activities/sort/upsert.livestream.spec.ts |
Updates livestream tests for the new signature. |
packages/core/src/reducers/activities/sort/upsert.howToWithLivestream.spec.ts |
Updates grouped livestream tests. |
packages/core/src/reducers/activities/sort/upsert.howTo.spec.ts |
Updates HowTo grouping tests. |
packages/core/src/reducers/activities/sort/upsert.activity.spec.ts |
Updates activity-ordering tests. |
packages/core/src/reducers/activities/sort/property/LocalId.ts |
Accepts prepared local IDs instead of generating them. |
packages/core/src/reducers/activities/sort/private/getLogicalTimestamp.ts |
Removes clock injection and timestamp warnings. |
packages/core/src/reducers/activities/sort/private/getLogicalTimestamp.spec.ts |
Updates logical-timestamp calls. |
packages/core/src/reducers/activities/sort/deleteActivityByLocalId.livestream.spec.ts |
Updates livestream deletion setup. |
packages/core/src/reducers/activities/sort/deleteActivityByLocalId.howToWithLivestream.spec.ts |
Updates grouped livestream deletion setup. |
packages/core/src/reducers/activities/sort/deleteActivityByLocalId.howTo.spec.ts |
Updates grouped activity deletion setup. |
packages/core/src/reducers/activities/sort/deleteActivityByLocalId.activity.spec.ts |
Updates activity deletion setup. |
packages/core/src/reducers/activities/patchActivity.ts |
Accepts an explicit received-at timestamp. |
packages/core/src/reducers/activities/groupedActivities.ts |
Adds the module-level reducer using prepared metadata. |
packages/core/src/reducers/activities/createGroupedActivitiesReducer.ts |
Removes the factory containing clock, ID, and effect work. |
packages/core/src/reducers/activities/combineActivitiesReducer.ts |
Composes the module-level activity reducer. |
packages/core/src/reducer.ts |
Adds the shared root reducer and preparation guard. |
packages/core/src/prepare/types.ts |
Defines preparation dependencies and metadata types. |
packages/core/src/prepare/runEffects.ts |
Centralizes warnings and debug breakpoint scheduling. |
packages/core/src/prepare/prepareAction.ts |
Adds metadata preparation and a prepared-action guard. |
packages/core/src/prepare/createPrepareMiddleware.ts |
Prepares reducer inputs while preserving dispatch results. |
packages/core/src/prepare/createPrepareMiddleware.spec.ts |
Covers preparation, effects, isolation, and deterministic replay. |
packages/core/src/createStore.ts |
Installs preparation middleware and initializes ponyfill state. |
packages/core/src/createReducer.ts |
Removes the root reducer factory. |
packages/core/.eslintrc.yml |
Adds restrictions against impure reducer operations. |
.changelog/6073-fix-pure-reducers.md |
Records the reducer-purity change. |
Review effort: Balanced
| export function assertPrepared<T extends Action>(action: T): T { | ||
| const preparers = PREPARERS.get(action?.type); | ||
|
|
||
| if (preparers && !Object.keys(preparers).every(key => action.meta && key in action.meta)) { |
There was a problem hiding this comment.
Done in e510098: each preparer pairs how to make the value with its valibot schema, and assertPrepared() checks meta against one object() schema per action type (a number now, LocalIdSchema for localId, a string fallbackId). New tests cover a missing, undefined or string now, a numeric fallbackId and a localId that is not an identifier.
`assertPrepared()` let a direct reducer call or a replay through with
`meta: { now: undefined }` or a string `now`. Each preparer now pairs
how to make the value with its valibot schema, and `assertPrepared()`
checks the action's meta against one `object()` schema per action type.

Changelog Entry
Changed
meta, in PR #6073, by @OEvgenyDescription
Core's reducers read the clock, made random IDs, queued a debug breakpoint and logged warnings. Run twice on the same action (time travel, a future
useReducer), they gave another state and logged again.Now an innermost middleware puts the time and new IDs in the
metaof a copy of the action, and runs the side effects just before the reducers. Host middleware, sagas anddispatch()see the action as dispatched. A lint rule keeps the reducers pure.Design
prepare, but in a middleware: hosts and sagas dispatch plain objects, not action creators. A clock passed to the reducers would still make new IDs on each re-run.useReducerport reusesprepareAction()and the reducers; the side effects read the reducer's input state, whichuseReducerdoes not expose.meta. ADatetimestamp that is not the ponyfill's now counts.Specific Changes
prepare/:prepareAction,runEffects, the middleware, spectoIncomingActivity.tsis the movedINCOMING_ACTIVITYcase.eslintrc.yml: purity rulesReview with
git diff -M10% -w main: the reducers lost an indent, so git shows delete + add..changelog/<PR#>-<slug>.md