dotnet-state-machine / stateless

A simple library for creating state machines in C# code
Other
5.52k stars 760 forks source link

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

Open jawi opened 3 years ago

jawi commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

@HenningNT The stack overflow seems to be caused by below clause in EnterState method: https://github.com/dotnet-state-machine/stateless/blob/e25f4da41d53eb3fed9c6ed51ce107afe0a29841/src/Stateless/StateMachine.cs#L480-L486

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.