From f81480c98c3e73ba9a9bb618394022cebfea02dd Mon Sep 17 00:00:00 2001 From: noooooooookro <325986997+noooooooookro@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:21:53 +0000 Subject: [PATCH] feat: add an option to clear history when a region completes Signed-off-by: noooooooookro <325986997+noooooooookro@users.noreply.github.com> --- docs/behaviour.md | 4 +- docs/releases/3.3.0.md | 8 +++ docs/states.md | 4 ++ statemachine/engines/base.py | 10 ++- statemachine/statemachine.py | 4 ++ tests/test_statechart_history.py | 105 ++++++++++++++++++++++++++++++ tests/uml/pssm/conftest.py | 1 - tests/uml/pssm/test_pssm_cases.py | 1 + 8 files changed, 133 insertions(+), 4 deletions(-) diff --git a/docs/behaviour.md b/docs/behaviour.md index 72896dfe..eba106be 100644 --- a/docs/behaviour.md +++ b/docs/behaviour.md @@ -43,9 +43,9 @@ GHSA-v4jc-pm6r-3vj8. | `enable_self_transition_entries` | `True` | `False` | Execute entry/exit actions on self-transitions | | `atomic_configuration_update` | `False` | `True` | When to update {ref}`configuration ` during a microstep | | `catch_errors_as_events` | `True` | `False` | Catch action errors as `error.execution` events | +| `clear_history_on_final` | `False` | `False` | Clear a completed region's {ref}`history ` | -Each attribute is described below, with cross-references to the pages that -cover the topic in depth. +The sections below describe the settings whose defaults differ between the two classes. ## `allow_event_without_transition` diff --git a/docs/releases/3.3.0.md b/docs/releases/3.3.0.md index 163556be..3d76f219 100644 --- a/docs/releases/3.3.0.md +++ b/docs/releases/3.3.0.md @@ -28,6 +28,14 @@ its output. See [](../contributing.md#uml-cases-based-on-pssm). [#697](https://github.com/fgmacedo/python-statemachine/pull/697). +### Clear history when a region completes + +Set `clear_history_on_final = True` on a statechart to start a completed region +from its history default on re-entry. By default, history still restores the +previous final state. See {ref}`history-states`. + +[#702](https://github.com/fgmacedo/python-statemachine/issues/702). + ## Behavior changes to check when upgrading Each item below fixes behavior that did not match the documented contract. Code that relied diff --git a/docs/states.md b/docs/states.md index a7fbb409..60789530 100644 --- a/docs/states.md +++ b/docs/states.md @@ -223,6 +223,10 @@ of the transition that led to the history state run exactly once. ``` +By default, history can restore a final state. Set `clear_history_on_final = True` +on the statechart class to clear a region's history when it completes. The next +transition to that history then follows its default, just as on the first visit. +Leaving an unfinished region still records its history. ```{seealso} See {ref}`querying-configuration` for how to inspect which states are currently diff --git a/statemachine/engines/base.py b/statemachine/engines/base.py index c457957f..44199162 100644 --- a/statemachine/engines/base.py +++ b/statemachine/engines/base.py @@ -459,6 +459,8 @@ def _prepare_exit_states( # Update history for info in ordered_states: state = info.state + if self.sm.clear_history_on_final and state.history and self.is_in_final_state(state): + continue for history in state.history: if history.type.is_deep: history_value = [s for s in self.sm.configuration if s.is_descendant(state)] @@ -539,10 +541,16 @@ def _prepare_entry_states( return ordered_states, states_for_default_entry, default_history_content, new_configuration def _add_state_to_configuration(self, target: State): - """Add a state to the configuration if not using atomic updates.""" + """Enter a state and clear completed regions' history before entry callbacks.""" if not self.sm.atomic_configuration_update: self.sm._config.add(target) + if target.final and self.sm.clear_history_on_final: + for region in target.ancestors(): + if region.history and self.is_in_final_state(region): + for history in region.history: + self.sm.history_values.pop(history.id, None) + def stop(self): """Stop this engine externally (e.g. when a parent cancels a child invocation).""" self._debug("%s Stopping engine", self._log_id) diff --git a/statemachine/statemachine.py b/statemachine/statemachine.py index 639a21e0..e495f3fc 100644 --- a/statemachine/statemachine.py +++ b/statemachine/statemachine.py @@ -105,6 +105,10 @@ class StateChart(Generic[TModel], metaclass=StateMachineMetaclass): produce an ``error.execution`` internal event instead of propagating, as mandated by the SCXML specification. If ``False``, exceptions propagate normally.""" + clear_history_on_final: bool = False + """If ``True``, clear a completed region's history so subsequent history entry + follows its default transition. By default, history also records final states.""" + start_configuration_values: list[Any] = [] """Default state values to be entered when the state machine starts. diff --git a/tests/test_statechart_history.py b/tests/test_statechart_history.py index 51210cec..ff34ce22 100644 --- a/tests/test_statechart_history.py +++ b/tests/test_statechart_history.py @@ -111,6 +111,111 @@ async def test_history_with_default_transition(self, sm_runner): assert "gollum" in sm.configuration_values +@pytest.mark.timeout(5) +@pytest.mark.parametrize("kind", ["shallow", "deep"]) +@pytest.mark.parametrize( + ("clear_history", "expected_leaf"), + [(False, "completed"), (True, "ready")], + ids=["default", "clear-on-final"], +) +async def test_reenter_history_after_completion(sm_runner, kind, clear_history, expected_leaf): + class Review(StateChart): + if clear_history: + clear_history_on_final = True + + class region(State.Compound): + draft = State(initial=True) + ready = State() + reviewing = State() + completed = State(final=True) + recall = HistoryState(type=kind) + recall.to(ready) + + submit = draft.to(reviewing) | ready.to(reviewing) + finish = reviewing.to(completed) + + outside = State() + leave = region.to(outside) + back = outside.to(region.recall) + + def on_enter_completed(self): + self.history_at_completion = self.history_values.get("recall") + + sm = await sm_runner.start(Review) + await sm_runner.send(sm, "submit") + await sm_runner.send(sm, "leave") + await sm_runner.send(sm, "back") + assert {"region", "reviewing"} == set(sm.configuration_values) + saved_history = sm.history_values["recall"] + assert [state.id for state in saved_history] == ["reviewing"] + + await sm_runner.send(sm, "finish") + assert {"region", "completed"} == set(sm.configuration_values) + expected_history = None if clear_history else saved_history + assert sm.history_values.get("recall") == expected_history + assert sm.history_at_completion == expected_history + + await sm_runner.send(sm, "leave") + await sm_runner.send(sm, "back") + assert {"region", expected_leaf} == set(sm.configuration_values) + + +@pytest.mark.timeout(5) +async def test_parallel_history_clears_only_when_its_owner_completes(sm_runner): + class Review(StateChart): + clear_history_on_final = True + + class workflow(State.Compound): + class review(State.Parallel): + review_recall = HistoryState(type="deep") + + class legal(State.Compound): + checking = State(initial=True) + legal_done = State(final=True) + approve_legal = checking.to(legal_done) + + class finance(State.Compound): + draft = State(initial=True) + submitted = State() + finance_done = State(final=True) + finance_recall = HistoryState(type="deep") + finance_recall.to(draft) + submit = draft.to(submitted) + resume_finance = submitted.to(finance_recall) + approve_finance = submitted.to(finance_done) + + outside = State() + leave = workflow.to(outside) + back = outside.to(workflow.review.review_recall) + + sm = await sm_runner.start(Review) + await sm_runner.send(sm, "submit") + await sm_runner.send(sm, "leave") + await sm_runner.send(sm, "back") + assert "submitted" in sm.configuration_values + + await sm_runner.send(sm, "approve_legal") + assert [state.id for state in sm.history_values["finance_recall"]] == ["submitted"] + assert {state.id for state in sm.history_values["review_recall"]} == { + "legal", + "checking", + "finance", + "submitted", + } + await sm_runner.send(sm, "resume_finance") + assert {"legal_done", "submitted"} <= set(sm.configuration_values) + + await sm_runner.send(sm, "approve_finance") + assert {"legal_done", "finance_done"} <= set(sm.configuration_values) + assert sm.history_values == {} + + await sm_runner.send(sm, "leave") + await sm_runner.send(sm, "back") + assert {"workflow", "review", "legal", "checking", "finance", "draft"} == set( + sm.configuration_values + ) + + def _build_traced_machine(kind, with_default=False): class Traced(StateChart): outside = State(initial=True) diff --git a/tests/uml/pssm/conftest.py b/tests/uml/pssm/conftest.py index 8238605c..5c958aa4 100644 --- a/tests/uml/pssm/conftest.py +++ b/tests/uml/pssm/conftest.py @@ -31,7 +31,6 @@ "Exiting_004": "requires:exit_point: exit point effect runs before the state exit", "Fork_002": "requires:fork: fork branch effects interleave with entries", "History_002-B": "unclassified: completions of two regions share one microstep", - "History_002-D": "conflict:K10: history restores a final state, completion loops", "Join_001": "requires:join: join effects run after all exits", "Join_002": "requires:join: join effects run after all exits", "Join_003": "requires:join: join guard evaluated once per incoming transition", diff --git a/tests/uml/pssm/test_pssm_cases.py b/tests/uml/pssm/test_pssm_cases.py index ca884023..cd88e56d 100644 --- a/tests/uml/pssm/test_pssm_cases.py +++ b/tests/uml/pssm/test_pssm_cases.py @@ -149,6 +149,7 @@ def build_machine(case: dict, recorder: TraceRecorder): """ cls = load(json.dumps(case), format="json", trusted=False, validate=True) cls.catch_errors_as_events = False + cls.clear_history_on_final = True original_send = cls.send def send(self, event, *args, **kwargs):