Skip to content
Open
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
4 changes: 2 additions & 2 deletions docs/behaviour.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <querying-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 <history-states>` |

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`
Expand Down
8 changes: 8 additions & 0 deletions docs/releases/3.3.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/states.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion statemachine/engines/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions statemachine/statemachine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
105 changes: 105 additions & 0 deletions tests/test_statechart_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,111 @@
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"]

Check warning on line 150 in tests/test_statechart_history.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Swap these 2 operands so the expected value comes first, to match the rest of this file.

See more on https://sonarcloud.io/project/issues?id=fgmacedo_python-statemachine&issues=AaIsM5eW9yxoWvBoncUF&open=AaIsM5eW9yxoWvBoncUF&pullRequest=738

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"]

Check warning on line 198 in tests/test_statechart_history.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Swap these 2 operands so the expected value comes first, to match the rest of this file.

See more on https://sonarcloud.io/project/issues?id=fgmacedo_python-statemachine&issues=AaIsM5eW9yxoWvBoncUG&open=AaIsM5eW9yxoWvBoncUG&pullRequest=738
assert {state.id for state in sm.history_values["review_recall"]} == {
"legal",
"checking",
"finance",
"submitted",
}

Check warning on line 204 in tests/test_statechart_history.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Swap these 2 operands so the expected value comes first, to match the rest of this file.

See more on https://sonarcloud.io/project/issues?id=fgmacedo_python-statemachine&issues=AaIsM5eW9yxoWvBoncUH&open=AaIsM5eW9yxoWvBoncUH&pullRequest=738
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 == {}

Check warning on line 210 in tests/test_statechart_history.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Swap these 2 operands so the expected value comes first, to match the rest of this file.

See more on https://sonarcloud.io/project/issues?id=fgmacedo_python-statemachine&issues=AaIsM5eW9yxoWvBoncUI&open=AaIsM5eW9yxoWvBoncUI&pullRequest=738

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)
Expand Down
1 change: 0 additions & 1 deletion tests/uml/pssm/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions tests/uml/pssm/test_pssm_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down