Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Nested states (compound / parallel) and support for SCXML (test suit) #501

Open
wants to merge 45 commits into
base: develop
Choose a base branch
from

Conversation

fgmacedo
Copy link
Owner

@fgmacedo fgmacedo commented Nov 22, 2024

Another approach for #329.

By supporting the test cases defined at https://www.w3.org/Voice/2013/scxml-irp/ we can incorporate small functionalities until we get covered by the full spec.

Experimental Python class API

from statemachine import State
from statemachine import StateChart

class MicroWave(StateChart):
    door_closed: bool = True

    class oven(State.Parallel, name="Microwave oven"):
        class engine(State.Compound):
            off = State(initial=True)

            class on(State.Compound):
                idle = State(initial=True)
                cooking = State()

                idle.to(cooking, cond="In('closed')")
                cooking.to(idle, cond="In('open')")
                time = cooking.to.itself(internal=True, on="increment_timer")

                def increment_timer(self):
                    self.timer += 1

            assert isinstance(on, State)  # so mypy stop complaining
            on.to(off, event="turn-off")
            off.to(on, event="turn-on")
            on.to(off, cond="timer >= cook_time")  # eventless transition

        class door(State.Compound):
            closed = State(initial=True)
            open = State()

            closed.to(open, event="door.open")
            open.to(closed, event="door.close")

            def on_enter_open(self):
                self.door_closed = False

            def on_enter_closed(self):
                self.door_closed = True

    def __init__(self):
        self.cook_time = 5
        self.timer = 0

Tests:

sm = MicroWave()

assert {"door", "closed", "oven", "engine", "off"} == {*sm.current_state_value}
assert sm.door_closed is True

sm.send("turn-on")
assert {"door", "closed", "oven", "engine", "on", "cooking"} == {*sm.current_state_value}

sm.send("door.open")
assert {"door", "open", "oven", "engine", "on", "idle"} == {*sm.current_state_value}
assert sm.door_closed is False

sm.send("door.close")
assert {"door", "closed", "oven", "engine", "on", "cooking"} == {*sm.current_state_value}
assert sm.door_closed is True

for _ in range(5):
    sm.send("time")

assert {"door", "closed", "oven", "engine", "off"} == {*sm.current_state_value}
assert sm.door_closed is True

Pending tasks

  • Exceptions should put "error.execution" in the internal queue
  • Graphviz diagram not representing well parallel states
  • Graphviz diagram not representing well compound states
  • SCXML test case 364 failing (allow multiple targets)
  • SCXML test case 413 is intermittent
  • Add statechart support for the async engine
  • Add testcases and examples using the Python Syntax

Donedata failing tests (test.scxml)

Those tests have a corresponding test<id>.fail.scxml describing the error output.

  • 294 -> Parse and assign donedata. Can be an on_enter_<state> that returns a dict.
  • 298 -> Parse and assign donedata. Can be an on_enter_<state> that returns a dict.
  • 343 → donedata invalid param
  • 488 → donedata
  • 527 → target
  • 528 → target
  • 529 → key

Copy link

codecov bot commented Nov 22, 2024

Codecov Report

Attention: Patch coverage is 93.60269% with 114 lines in your changes missing coverage. Please review.

Project coverage is 96.21%. Comparing base (4449a9c) to head (93eaa58).

Files with missing lines Patch % Lines
statemachine/io/scxml/actions.py 92.12% 17 Missing and 9 partials ⚠️
statemachine/contrib/diagram.py 69.23% 11 Missing and 5 partials ⚠️
statemachine/io/scxml/parser.py 93.02% 7 Missing and 8 partials ⚠️
statemachine/engines/base.py 96.26% 5 Missing and 7 partials ⚠️
statemachine/orderedset.py 81.57% 7 Missing ⚠️
statemachine/engines/sync.py 92.30% 4 Missing and 1 partial ⚠️
statemachine/statemachine.py 92.75% 3 Missing and 2 partials ⚠️
statemachine/engines/async_.py 73.33% 3 Missing and 1 partial ⚠️
statemachine/factory.py 94.11% 2 Missing and 2 partials ⚠️
statemachine/io/scxml/processor.py 97.27% 0 Missing and 4 partials ⚠️
... and 9 more
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #501      +/-   ##
===========================================
- Coverage   100.00%   96.21%   -3.79%     
===========================================
  Files           25       31       +6     
  Lines         1631     3227    +1596     
  Branches       257      466     +209     
===========================================
+ Hits          1631     3105    +1474     
- Misses           0       71      +71     
- Partials         0       51      +51     
Flag Coverage Δ
unittests 96.21% <93.60%> (-3.79%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@fgmacedo fgmacedo force-pushed the macedo/scxml branch 5 times, most recently from f1edb7f to 1e7f40d Compare December 3, 2024 19:21
@fgmacedo fgmacedo force-pushed the macedo/scxml branch 3 times, most recently from 0890680 to 35f4bed Compare December 12, 2024 10:48
@fgmacedo fgmacedo changed the title feat: Basic support for SCXML test suit feat: Nested states (compound / parallel) and support for SCXML (test suit) Dec 14, 2024
@comalice
Copy link
Contributor

comalice commented Jan 7, 2025

Is this in a state (🤣) that I could try it out? I have several use-cases where the sub-state functionality would be useful and I'd be glad to give feedback if I run into issues.

Note, the user experience I had expected looked something like this:

class SubMachine(StateMachine):
    test = State(initial=True)
    test_complete = State(final=True)

    next = test.to(test_complete)


class TestSM(StateMachine):
    initial_state = State(initial=True)
    sub_machine_as_state = SubMachine()
    some_other_state = State(final=True)

    goto_sub_machine = initial_state.to(sub_machine_as_state)
    goto_finish = sub_machine_as_state.to(some_other_state)

And then something like

sm = TestSM()

sm.send('goto_sub_machine')
sm.send('next')   # TestSM now has the submachine states as states it can traverse.
sm.send('goto_finish')

…es parameter since scxml don't expect that the graph should have a single component
@fgmacedo
Copy link
Owner Author

@comalice Thanks for your interest on this. I think the internals are usable, but the external API may still change as I've not yet finished documenting and exploring examples using the Python API.

There are many new *.scxml files that I've used to fine tune the internal behaviour for composite and parallel states, and the create_machine_class_from_definition is more stable and mature as a way to construct the statemachine from a dict-like definition similar to the way SCXML works. I'm planning to also add a YAML parser.

The only notable non implemented feature is the <invoke> and thus cross sending events between distinct statemachines.

Note, the user experience I had expected looked something like this:

class SubMachine(StateMachine):
    test = State(initial=True)
    test_complete = State(final=True)

    next = test.to(test_complete)


class TestSM(StateMachine):
    initial_state = State(initial=True)
    sub_machine_as_state = SubMachine()
    some_other_state = State(final=True)

    goto_sub_machine = initial_state.to(sub_machine_as_state)
    goto_finish = sub_machine_as_state.to(some_other_state)

I may try to implement this syntax, but I think that will be hard to get it right. The initial proposal that I'm implement is the one that is in the description, using the internal namespace of nested Parallel and Compose classes to build hierarchy.

Feel free to fork and test, please let me know if you expecience any issues.

Since this got into a huge PR and almost stable, I'm considering merging and finish the work with smaller PRs.

@fgmacedo fgmacedo added this to the 3.0.0 - StateCharts milestone Jan 26, 2025
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
4 Security Hotspots

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants