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

Stackoverflow when triggering state with substates and FiringMode.Immediate #439

Open
jawi opened this issue Feb 17, 2021 · 6 comments
Open

Comments

@jawi
Copy link

jawi commented Feb 17, 2021

What I want is to configure my statemachine with a state that consists of several substates (i.e., actions that need to be performed right after each other prior to allowing this state to leave). From the outside it should appear as Init -> StateA -> Exit. Internally, the state machine does: Init -> StateA -> SubstateA1 -> SubstateA2 -> Exit.

If I configure the statemachine using FiringMode.Immediate, a stackoverflow is triggered due to continuous triggering of StateA. When chainging the statemachine to use FiringMode.Queued this behaviour does not appear, and the statemachine works as expected.

From my tests, it looks like the stackoverflow is only triggered when using substates in combination with FiringMode.Immediate. I observed this behaviour in stateless versions from 5.0.0 until 5.10.1.

@jawi
Copy link
Author

jawi commented Feb 17, 2021

My test code which I used to find this behavior:

using NUnit.Framework;
using Stateless;
using System.Diagnostics;

namespace stateless_async_substate
{
    public class Tests
    {
        private readonly TraceListener listener = new ConsoleTraceListener();

        [SetUp]
        public void Setup()
        {
            Trace.Listeners.Add(listener);
        }

        [TearDown]
        public void TearDown()
        {
            Trace.Listeners.Remove(listener);
        }

        [Test]
        [MaxTime(5000)]
        [TestCase(FiringMode.Queued)] // Works!
        [TestCase(FiringMode.Immediate)] // BOOM!
        public void Test_FiringMode_InternalSubstates(FiringMode firingMode)
        {
            var sm = new InternalSubstates(firingMode);

            Assert.That(() => sm.State, Is.EqualTo(MyState.Init).After(5000, 5));

            sm.Fire(MyTrigger.StateA);

            Assert.That(() => sm.State, Is.EqualTo(MyState.Exit).After(5000, 5));
        }

        [Test]
        [MaxTime(5000)]
        [TestCase(FiringMode.Queued)] // Works!
        [TestCase(FiringMode.Immediate)] // Works!
        public void Test_FiringMode_ExplicitSubstates(FiringMode firingMode)
        {
            var sm = new ExplicitSubstates(firingMode);

            Assert.That(() => sm.State, Is.EqualTo(MyState.Init).After(5000, 5));

            sm.Fire(MyTrigger.StateA);

            Assert.That(() => sm.State, Is.EqualTo(MyState.Exit).After(5000, 5));
        }
    }

    public class InternalSubstates
    {
        private readonly StateMachine<MyState, MyTrigger> sm;

        public InternalSubstates(FiringMode firingMode)
        {
            sm = new StateMachine<MyState, MyTrigger>(MyState.Init, firingMode);
            sm.OnTransitioned(t => Trace.WriteLine($"Transitioning from {t.Source} to {t.Destination} (trigger = {t.Trigger})..."));
            sm.OnUnhandledTrigger((s, t) => Trace.WriteLine($"===> UNHANDLED TRIGGER {t} IN {s}!!!"));

            sm.Configure(MyState.Init)
                .Permit(MyTrigger.StateA, MyState.StateA);

            sm.Configure(MyState.StateA)
                .InitialTransition(MyState.SubstateA1);

            sm.Configure(MyState.SubstateA1)
                .SubstateOf(MyState.StateA)
                .OnEntry(() =>
                {
                    Trace.WriteLine("Entering SubstateA1...");
                    sm.Fire(MyTrigger.SubstateA1_ready);
                })
                .Permit(MyTrigger.SubstateA1_ready, MyState.SubstateA2);

            sm.Configure(MyState.SubstateA2)
                .SubstateOf(MyState.StateA)
                .OnEntry(() =>
                {
                    Trace.WriteLine("Entering InitSubB...");
                    sm.Fire(MyTrigger.SubstateA2_ready);
                })
                .Permit(MyTrigger.SubstateA2_ready, MyState.Exit);

            sm.Configure(MyState.Exit)
                .OnEntry(() => Trace.WriteLine("Exit..."));
        }

        public MyState State => sm.State;

        public void Fire(MyTrigger trigger)
        {
            sm.Fire(trigger);
        }
    }

    public class ExplicitSubstates
    {
        private readonly StateMachine<MyState, MyTrigger> sm;

        public ExplicitSubstates(FiringMode firingMode)
        {
            sm = new StateMachine<MyState, MyTrigger>(MyState.Init, firingMode);
            sm.OnTransitioned(t => Trace.WriteLine($"Transitioning from {t.Source} to {t.Destination} (trigger = {t.Trigger})..."));
            sm.OnUnhandledTrigger((s, t) => Trace.WriteLine($"===> UNHANDLED TRIGGER {t} IN {s}!!!"));

            sm.Configure(MyState.Init)
                .Permit(MyTrigger.StateA, MyState.SubstateA1);

            sm.Configure(MyState.SubstateA1)
                .OnEntry(() =>
                {
                    Trace.WriteLine("Entering SubstateA1...");
                    sm.Fire(MyTrigger.SubstateA1_ready);
                })
                .Permit(MyTrigger.SubstateA1_ready, MyState.SubstateA2);

            sm.Configure(MyState.SubstateA2)
                .OnEntry(() =>
                {
                    Trace.WriteLine("Entering InitSubB...");
                    sm.Fire(MyTrigger.SubstateA2_ready);
                })
                .Permit(MyTrigger.SubstateA2_ready, MyState.Exit);

            sm.Configure(MyState.Exit)
                .OnEntry(() => Trace.WriteLine("Exit..."));
        }

        public MyState State => sm.State;

        public void Fire(MyTrigger trigger)
        {
            sm.Fire(trigger);
        }
    }

    public enum MyState
    {
        Init, StateA, SubstateA1, SubstateA2, Exit
    }

    public enum MyTrigger
    {
        StateA, SubstateA1_ready, SubstateA2_ready, Exit
    }
}

@jawi
Copy link
Author

jawi commented Feb 17, 2021

Running Test_FiringMode_InternalSubstates(Immediate) in the debugger yields the following logging:

Transitioning from Init to StateA (trigger = StateA)...
Transitioning from StateA to SubstateA1 (trigger = StateA)...
Entering SubstateA1...
===> UNHANDLED TRIGGER SubstateA1_ready IN StateA!!!
Transitioning from StateA to SubstateA1 (trigger = StateA)...
Entering SubstateA1...
===> UNHANDLED TRIGGER SubstateA1_ready IN StateA!!!
Transitioning from StateA to SubstateA1 (trigger = StateA)...
Entering SubstateA1...
===> UNHANDLED TRIGGER SubstateA1_ready IN StateA!!!
Transitioning from StateA to SubstateA1 (trigger = StateA)...
Entering SubstateA1...
....

@HenningNT
Copy link
Contributor

Thanks, I'll have too look into it.
The state machine appears to have been set up correctly.
And it looks like there are two problems. The trigger should have been handled in the when it entered the substate, and it should not enter an infinite loop afterwards...

On a side note, I do not recommend using the Immediate firieng mode, as it can allow you to shoot yourself in the foot in subtle (and not so subtle) ways.

@jawi
Copy link
Author

jawi commented Feb 18, 2021

On a side note, I do not recommend using the Immediate firieng mode, as it can allow you to shoot yourself in the foot in subtle (and not so subtle) ways.

I could not find any information on the difference between firing modes. Could you elaborate on the difference between them?

@HenningNT
Copy link
Contributor

The major difference between the modes are what happens if a trigger is fired during a transition. For instance, if there is a call to Fire in a OnEntry handler, then Immediate will execute the code to process that trigger. Queued will put the trigger in a queue and it will be processed after all the actions associated with the current transition has been completed.

Queued mode guarantees Run-To-Completion (and atomic) state transitions, Immediate does not.

Atomic Run-to-Completion state transitions are usually preferred, but there are use cases for out-of-order trigger handling. If a device has detected a critical condition it would require emergency shut down, and not wait to process triggers already in the queue.

@DeepakParamkusam
Copy link
Contributor

@HenningNT The stack overflow seems to be caused by below clause in EnterState method:

if (FiringMode.Immediate.Equals(_firingMode) && !State.Equals(transition.Destination))
{
// This can happen if triggers are fired in OnEntry
// Must update current representation with updated State
representation = GetRepresentation(State);
transition = new Transition(transition.Source, State, transition.Trigger, args);
}

When a state has an initial transition in Immediate firing mode, this clause is reverting the state representation after entering the substate. This causes an infinite loop and thus the stack overflow. Changing the line GetRepresentation(State) to GetRepresentation(transition.Destination) solves the issue for @jawi's code but fails the test suite (specifically ImmediateFireingOnEntryEndsUpInCorrectState test in FireingModesFixture.cs).

I'm currently not sure how to fix that.

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

No branches or pull requests

3 participants