botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

Conversation.ResumeAsync returns "Operation is not valid due to the current state of the object"

Open jsiegmund opened this issue 9 years ago • 20 comments

I am trying to resume a conversation after completion of an external even. I'm using Conversation.ResumeAsync to do so, passing in the resumptionCookie and a message. I'm getting the above error in return which is not very helpful. So now I'm stuck trying to find out what it going wrong and why. Would be nice to have some pointers as to where to look!

Exception: System.InvalidOperationException: Operation is not valid due to the current state of the object. at Microsoft.Bot.Builder.Dialogs.Conversation.<>c31.<ResumeAsync>b3_0() at Microsoft.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d31.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.d21.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.LocalizedDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__21.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.ScoringDialogTask1.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.d31.MoveNext() — End of stack trace from previous location where exception was thrown — at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d31.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.SerializingDialogTask.&lt;Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync&gt;d__41.MoveNext() — End of stack trace from previous location where exception was thrown — at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__51.MoveNext()

jsiegmund avatar Jan 03 '17 17:01 jsiegmund

It's coming from this line.

https://github.com/Microsoft/BotBuilder/blob/develop/CSharp/Library/Microsoft.Bot.Builder.Autofac/Dialogs/Conversation.cs#L103

I believe it's occurring because the ResumptionCookie is being used to resume a conversation where there is no state storage for that conversation.

This may be caused because the state storage for that conversation

  1. has been cleared explicitly, or
  2. it has been made invalid because the dialog stack could not be deserialized (perhaps the code changed?)

willportnoy avatar Jan 04 '17 01:01 willportnoy

I don't think either of those is the case, but I'm not super sure. Can I somehow check whether there is any state storage for a specific conversation?

The scenario is the following: user chats with the bot, bot sends back a card for OAuth authentication (Azure AD). User clicks the link and eventually Azure calls the return URL which is in the same Bot Service (I'm actually reusing the messages endpoint for that, see http://stackoverflow.com/questions/41444626/bot-service-with-oauth-endpoint?noredirect=1#comment70098112_41444626).

Now in the code that handles the OAuth return, I need to resume the conversation. That's where this happens. So definitely no code change as the above is all in one chat session. If there was a problem with serialization I'd expect that to pop-up earlier, right?

jsiegmund avatar Jan 04 '17 06:01 jsiegmund

As far as I understand, working backward:

  1. InvalidOperationException is thrown, because
  2. Func<IDialog> is called, because
  3. there is no dialog on the stack to which to post the activity, because
  4. either a. the stack could not be deserialized from storage (code change), or b. the stack was not found in storage (ResumptionCookie address fields don't match storage keys)
  5. That's my thinking - can you debug during the oauth callback and see if there are any exceptions?

    willportnoy avatar Jan 05 '17 21:01 willportnoy

    This is actually the exception that happens during the oauth callback, the rest of it works as expected. I'm trying to understand what is happening; if I understand correctly it will try to restore state based on the address stored in the ResumptionCookie. Does that also imply that this needs to take place on the same server / in the same process, or is the storage located somewhere shared (azure store account? and on localhost?)? Cause I am working on creating a separate (Function) endpoint for the oauth callback flow because I didn't want that to use the messages endpoint. But if that somehow could interfere with resuming the dialog I'll need to find a different solution.

    Interesting btw: when I return the oauth callback to another function and try to call the Conversation.Resume method, the bot replies to the channel:

    Exception: Operation is not valid due to the current state of the object. [File of type 'text/plain']

    So that at least proves (to me...) that I should be able to manipulate the bot conversation from another endpoint. I also tried moving all of that code into the same endpoint just to be sure, made no difference. In some cases, the bot just returns:

    Sorry, my bot code is having an issue.

    So something is definitely wrong, but I'm finding it hard to debug without proper error messages.

    jsiegmund avatar Jan 06 '17 15:01 jsiegmund

    I've got a (very rough) version of the source code up here: https://github.com/mstack/bots-jennifer. If you're able to take a quick look, that would be highly appreciated :)

    jsiegmund avatar Jan 07 '17 10:01 jsiegmund

    Any chance someone could take a look? I'm still stuck :(

    jsiegmund avatar Jan 18 '17 06:01 jsiegmund

    @msft-shahins any thoughts?

    @jsiegmund it looks like you're using the correct ResumptionCookie to set up the lifetime scope so that the IStateClient points to the same bot state bags so that the dialog stack should be able to be restored without needing to try to instantiate a new root dialog.

    willportnoy avatar Jan 19 '17 21:01 willportnoy

    Sorry to have to bump this but still haven't found the issue or a solution and this is becoming a blocking issue. Would be awesome if someone could take a further look. @msft-shahins @willportnoy

    jsiegmund avatar Feb 03 '17 09:02 jsiegmund

    I have the idea that when the callback returns, there's no conversation left to resume. If I understand the concept correctly, the stack should hold dialogs that are waiting for incoming messages, and the one on top will be processing the incoming message. So is the stack is empty, the message cannot be processed by a dialog.

    I know there's something wrong there, because during debug starting the same dialog twice and then performing the callback does seem to work. Of course in that case the wrong dialog is handling the Conversation.Resume call, but at least it's not returning that stack exception. So I must be missing something that causes the auth dialog not to be added onto the stack for resumption. I'm just not sure what.

    Update there's definitely something wrong with the state. In another part of the code I have a LUIS intent at which I start a new FormFlow dialog:

    var timeRegistrationDialog = new FormDialog<TimeRegistrationDialog>(new TimeRegistrationDialog(), TimeRegistrationDialog.BuildForm, FormOptions.PromptInStart, entities);
    context.Call<TimeRegistrationDialog>(timeRegistrationDialog, this.ResumeAfterTimeRegistration);
    

    The new dialog prompts the user for the first field. I provide a (valid) value, but instead of the form continuing it just returns to the default LUIS intent not understanding the message. So the reply is sent to the LUIS dialog instead of the FormFlow dialog for which is was meant. Seems like here too the FormFlow dialog is not on the stack and when the message returns it pops off the wrong item from the Stack. What could be causing this?

    jsiegmund avatar Feb 03 '17 10:02 jsiegmund

    I finally seem to have found something. I'm debugging using local functions-cli. I had been moving dialogs into a precompiled DLL so that I could have intellisense when writing the dialog code, since CSX doens't have intellisense yet.

    Now for the post above this one: when I move the exact same code into a CSX file and load that one instead: the response is being passed to the correct dialog! This is most likely also the issue with the authentication stuff, because I have that dialog in the DLL as well. It seems the bug here is that when a dialog is loaded from a precompiled DLL, there's a problem with resuming the correct dialog. Again: the code in the CSX and in the precompiled DLL file is exactly the same, I literally copy/pasted it and only removed the namespace for the CSX file.

    jsiegmund avatar Feb 09 '17 07:02 jsiegmund

    We have some code in the Azure Bot Service to handle the serialization of delegates involving dialogs:

    https://github.com/Microsoft/BotBuilder-Azure/blob/master/CSharp/Library/Microsoft.Bot.Builder.Azure/AzureModule.cs#L126

    It seems related to your issue. @msft-shahins for visibility.

    willportnoy avatar Feb 09 '17 17:02 willportnoy

    @jsiegmund do you have a simple bot that repros this issue? If so, can you share the code for that bot?

    msft-shahins avatar Feb 09 '17 19:02 msft-shahins

    Not a simple one, no. But I suspect you can repro with a simple LUIS (or probably any type of) dialog that calls a formflow which comes from a precompiled DLL. I now moved everything into a WebAPI project and all problems completely disappeared.

    jsiegmund avatar Feb 09 '17 20:02 jsiegmund

    Here's a simple repo that has the same issue: https://github.com/jsiegmund/repsaj-bot-repro. The call dialog will never get beyond the first question, it's like a groundhog day dialog :)

    jsiegmund avatar Feb 15 '17 08:02 jsiegmund

    so a little more to add. i think this is the right thread

    i get the same error using the ResumptionCookie but can fix it. I think my fix then causes proactive bots messages i am trying to do not work though. Not 100% on that yet

    so in my Global.asx while building the Autofac container if I do the following

            builder.Update(Conversation.Container);
            var container = Conversation.Container;
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    

    the errors doesn't occur and I can do Conversation.ResumeAsync just fine however I have to add

                    var dialog = scope.Resolve<IDialog<object>>();
                    DialogModule_MakeRoot.Register(scope, () => dialog);
    

    to my MessageController before calling

                    var postToBot = scope.Resolve<IPostToBot>();
                    await postToBot.PostAsync(activity, token);
    

    to make sure i don't get a Autofac Exception. If do the following in Global.asx

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    

    the Convesation.ResumeAsync gives me the "Operation is not valid due to the current state of the object" error, but I do not have to call

                    var dialog = scope.Resolve<IDialog<object>>();
                    DialogModule_MakeRoot.Register(scope, () => dialog);
    

    anymore and the IPostToBot resolves just fine. All this roots from trying to get proactive dialogs working and i simply cannot. the bot gets the first response in the proactive dialog but routes it to the root dialog. Scoured every example including the AlarmBot, etc and cannot get this to work. Hopefully some of this helps. I am on 3.5.2

    haligasd avatar Feb 16 '17 19:02 haligasd

    Could you please help me with my question : https://stackoverflow.com/questions/42298992/how-to-call-formflow-after-user-choose-an-option-from-quickreply-in-chatbot

    I want to call formflow from my dialog...

    stelazh avatar Feb 17 '17 13:02 stelazh

    @stelazh is your issue related to this issue? you might consider opening a top level issue for your question.

    willportnoy avatar Feb 24 '17 04:02 willportnoy

    @jsiegmund have you found a workaround, or has the issue been resolved?

    JasonSowers avatar May 23 '17 19:05 JasonSowers

    @JasonSowers thanks for the notification. I worked around the issue by not using a precompiled Azure Function to handle the bot conversation. For some reason when using a precompiled DLL the logic is unable to reconstruct the conversation from the conversation state. When I used exactly the same code in a normal Web API project, it worked fine.

    Haven't tried it since, so I'm not sure whether the issue has been fixed or not.

    jsiegmund avatar May 24 '17 10:05 jsiegmund

    @jsiegmund thanks for the update

    nwhitmont avatar May 24 '17 23:05 nwhitmont