Skip to content
Merged
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
20 changes: 20 additions & 0 deletions .github/workflows/hot-reload-regressions.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Pydux hot reload and Inspector regressions
on:
pull_request:
push:
branches: [fixes/inspector-state-hot-reload]
jobs:
hot-reload:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
python-version: ['3.12']
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: python -m pip install -e . pytest
- run: python -m pytest -q tests/test_hot_reload_schema.py
2 changes: 2 additions & 0 deletions pydux/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
# Redux Toolkit style modern API
from pydux.toolkit.slice import create_slice, Slice
from pydux.toolkit.configure_store import configure_store, combine_reducers
from pydux.toolkit.hot_reload import reconfigure_store
from pydux.toolkit.async_thunk import create_async_thunk, create_thunk_middleware

# Core Store & Selectors
Expand Down Expand Up @@ -35,6 +36,7 @@
"create_async_thunk",
"create_thunk_middleware",
"combine_reducers",
"reconfigure_store",
"Slice",

# Core Store & Selectors
Expand Down
13 changes: 13 additions & 0 deletions pydux/core/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ def get_state(self) -> TState:
with self._lock:
return self._state

def replace_reducer(self, reducer: Reducer[TState], state: TState) -> None:
"""Atomically install a new reducer and migrated state, notifying selectors.

Used by the development hot-reload coordinator, not by normal dispatch.
The replacement does not create a fake user action or rebuild middleware.
"""
with self._lock:
if self._is_dispatching:
raise RuntimeError("Cannot replace a reducer during dispatch.")
self._reducer = reducer
self._state = state
self._notify_subscribers()

def dispatch(self, action: Any) -> Any:
"""Dispatches an action through the middleware chain to the reducer."""
return self._dispatch(action)
Expand Down
18 changes: 9 additions & 9 deletions pydux/devtools/static/inspector.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const state = {
selectedIndex: -1,
activeIndex: -1,
currentState: null,
tab: "diff",
tab: "state",
stream: null,
replaying: false,
};
Expand Down Expand Up @@ -69,14 +69,9 @@ function renderHistory() {
els.summary.textContent = `${state.history.length} traces, active #${state.activeIndex}`;
els.history.innerHTML = "";

if (state.history.length === 0) {
els.empty.style.display = "block";
els.content.style.display = "none";
return;
}

els.empty.style.display = "none";
els.content.style.display = "block";
if (state.history.length === 0) return;

for (const trace of state.history) {
const li = document.createElement("li");
Expand Down Expand Up @@ -111,7 +106,11 @@ function renderHistory() {
function renderDetail() {
const trace = selectedTrace();
if (!trace) {
els.content.textContent = "No trace selected.";
if (state.tab === "state") {
setContent(state.currentState);
} else {
els.content.textContent = "No actions dispatched yet.";
}
return;
}

Expand All @@ -126,7 +125,7 @@ function renderDetail() {
}

if (state.tab === "state") {
setContent(trace.next_state ?? state.currentState);
setContent(state.selectedIndex === state.activeIndex ? state.currentState : trace.next_state);
return;
}

Expand Down Expand Up @@ -251,6 +250,7 @@ for (const tab of els.tabs) {
}

(async () => {
for (const t of els.tabs) t.classList.toggle("active", t.dataset.tab === state.tab);
await fetchSnapshot();
connectStream();
})();
2 changes: 2 additions & 0 deletions pydux/toolkit/configure_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ def configure_store(
initial_state = preloaded_state if preloaded_state is not None else root_reducer(None, Action(type="@@PYDUX/INIT"))

store = Store(reducer=root_reducer, initial_state=initial_state, middlewares=all_middlewares)
if isinstance(reducer, dict):
store._pydux_slice_definitions = dict(reducer)

# Attach devtools instance attribute if active
if active_devtools:
Expand Down
74 changes: 74 additions & 0 deletions pydux/toolkit/hot_reload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Development-only state-schema reconciliation for coordinated hot reload.

The coordinator calls reconfigure_store with freshly evaluated slice definitions.
Existing values win; new default keys and newly introduced slices are added.
No new store, middleware chain, subscriptions, or inspector server are created.
"""

from __future__ import annotations

import copy
from collections.abc import Mapping
from typing import Any

from pydux.core.store import Store
from pydux.core.types import Action
from pydux.toolkit.configure_store import combine_reducers
from pydux.toolkit.slice import Slice


def _merge_defaults(defaults: Any, current: Any) -> Any:
"""Preserve runtime values and keys while filling missing default keys."""
if isinstance(defaults, dict) and isinstance(current, dict):
merged = copy.deepcopy(current)
for key, default in defaults.items():
if key in current:
merged[key] = _merge_defaults(default, current[key])
else:
merged[key] = copy.deepcopy(default)
return merged
# The current value is authoritative, including None/False/empty containers.
return copy.deepcopy(current)


def reconfigure_store(store: Store, slices: Mapping[str, Any]) -> Store:
"""Hot-swap slices and defaults into an existing store.

Call only after the new Python module has evaluated successfully. This API
is intended for development; production/frozen apps should not invoke it.
A slice absent from the new mapping is preserved until explicitly migrated.
"""
if not isinstance(slices, Mapping):
raise TypeError("slices must be a mapping of names to reducers or Slice objects")

previous = getattr(store, "_pydux_slice_definitions", {})
combined = dict(previous)
combined.update(slices)
reducers = {
name: value.reducer if isinstance(value, Slice) else value
for name, value in combined.items()
}
if not all(callable(r) for r in reducers.values()):
raise TypeError("All slice reducers must be callable")

# Build and validate everything before mutating the live store.
old_state = store.get_state()
if not isinstance(old_state, dict):
raise TypeError("Slice reconciliation requires a dictionary root state")
next_state = copy.deepcopy(old_state)
for name, reducer in reducers.items():
initial = reducer(None, Action(type="@@PYDUX/INIT"))
next_state[name] = (
_merge_defaults(initial, old_state[name])
if name in old_state else copy.deepcopy(initial)
)
new_reducer = combine_reducers(reducers)
# Atomic swap retains the store identity, middleware and subscriptions.
store.replace_reducer(new_reducer, next_state)
setattr(store, "_pydux_slice_definitions", combined)

inspector = getattr(store, "inspector", None)
broadcast = getattr(inspector, "_broadcast_snapshot", None)
if callable(broadcast):
broadcast()
return store
73 changes: 73 additions & 0 deletions tests/test_hot_reload_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Regression tests for development-time slice reconciliation and inspector bootstrap."""

from pydux import configure_store, create_slice, reconfigure_store


def slice_user(initial):
return create_slice(
name="user",
initial_state=initial,
reducers={"set_data": lambda state, action: {**state, **action.payload}},
)


def test_reconfigure_preserves_live_values_and_adds_defaults():
old = slice_user({"name": "fredo", "nested": {"a": 1}})
store = configure_store({"user": old}, devtools=False)
seen = []
store.select(lambda state: state["user"], seen.append)
store.dispatch(old.actions.set_data({"name": "Luis"}))

updated = slice_user({
"name": "initial",
"email": "alfredo@neuri.ai",
"nested": {"a": 0, "b": 2},
})
same_store = reconfigure_store(store, {"user": updated})
assert same_store is store
assert store.get_state()["user"] == {
"name": "Luis",
"email": "alfredo@neuri.ai",
"nested": {"a": 1, "b": 2},
}
assert seen[-1]["email"] == "alfredo@neuri.ai"


def test_new_slice_and_new_reducer_are_active_without_recreating_store():
original = slice_user({"name": "fredo"})
store = configure_store({"user": original}, devtools=False)
new_user = create_slice(
name="user",
initial_state={"name": "default"},
reducers={"set_data": lambda state, action: {"name": action.payload.upper()}},
)
settings = create_slice(name="settings", initial_state={"theme": "dark"}, reducers={})
reconfigure_store(store, {"user": new_user, "settings": settings})
assert store.get_state()["settings"] == {"theme": "dark"}
store.dispatch(new_user.actions.set_data("luis"))
assert store.get_state()["user"]["name"] == "LUIS"
assert store.get_state()["settings"] == {"theme": "dark"}


def test_invalid_reconfiguration_does_not_damage_live_store():
user = slice_user({"name": "fredo"})
store = configure_store({"user": user}, devtools=False)
try:
reconfigure_store(store, {"bad": lambda state, action: 1 / 0})
except ZeroDivisionError:
pass
else:
raise AssertionError("expected malformed slice failure")
store.dispatch(user.actions.set_data({"name": "safe"}))
assert store.get_state()["user"]["name"] == "safe"


def test_inspector_snapshot_contains_initial_state_before_actions():
user = slice_user({"name": "fredo"})
store = configure_store({"user": user}, devtools=True, inspector_auto_start=False)
from pydux.devtools.inspector import PyDuxInspectorServer
inspector = PyDuxInspectorServer(store.devtools, port=0)
snapshot = inspector._snapshot_payload()
assert snapshot["history"] == []
assert snapshot["active_index"] == -1
assert snapshot["state"] == {"user": {"name": "fredo"}}
Loading