{"record":{"id":"bcb442baa3edcd53","repo":"microsoft/autogen","slug":"cannot-pop-a-layer-while-the-context-is-initialize","errorCode":null,"errorMessage":"Cannot pop a layer while the context is initialized.","messagePattern":"Cannot pop a layer while the context is initialized\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RunContext.cs","lineNumber":82,"sourceCode":"    }\n\n    // TODO: There is probably a way to have a sound manner by which pushing/popping a layer when initialized\n    // would be allowed. But this is not necessary for now, so we will keep it simple.\n    public void PushLayer(IRunContextLayer layer)\n    {\n        if (this.IsInitialized)\n        {\n            throw new InvalidOperationException(\"Cannot push a layer while the context is initialized.\");\n        }\n\n        this.Uninitialized.Push(layer);\n    }\n\n    public void PopLayer()\n    {\n        if (this.IsInitialized)\n        {\n            throw new InvalidOperationException(\"Cannot pop a layer while the context is initialized.\");\n        }\n    }\n\n    private Action? initializeError;\n    protected override void OnInitializeError()\n    {\n        (this.initializeError ?? base.OnInitializeError)();\n    }\n\n    private Action? deinitializeError;\n    protected override void OnDeinitializeError()\n    {\n        (this.deinitializeError ?? base.OnDeinitializeError)();\n    }\n\n    public static IRunContextLayer OverrideErrors(Action? initializeError = null, Action? deinitializeError = null)\n    {\n        return new ErrorOverrideLayer(initializeError, deinitializeError);","sourceCodeStart":64,"sourceCodeEnd":100,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RunContext.cs#L64-L100","documentation":"RunContextStack.PopLayer throws InvalidOperationException when a layer is removed after the run context has been initialized. Note the pop guard throws before any stack mutation regardless — once initialized, layer removal is disallowed (the method body contains only the guard, mirroring PushLayer).","triggerScenarios":"Calling RunContextStack.PopLayer() at any point after IsInitialized is true — typically from cleanup/disposal code that runs after a chat has started, or between runs of a long-lived Team.","commonSituations":"Implementing 'scoped' context layers with try/finally pop in a using-pattern where the push happened pre-initialization but the pop happens post-initialization; unwinding layers in an exception path after a run started; shared/persistent Team instances across requests.","solutions":["Do not use Push/Pop for scoped layers around a run; construct a new RunContextStack with exactly the layers needed per run.","Ensure symmetric push/pop code paths both execute before initialization begins, or drop the pattern entirely.","Recreate the Team/RunContext instead of mutating layer composition after a run."],"exampleFix":"// before\nctx.PushLayer(layer);\ntry { await team.RunAsync(task); }\nfinally { ctx.PopLayer(); } // throws if run initialized the context\n\n// after\nvar ctx = new RunContextStack(layer);\nawait team.RunAsync(task);","handlingStrategy":"validation","validationCode":"if (!runContextStack.IsInitialized)\n{\n    runContextStack.PopLayer();\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Never wrap a run in push/pop; scope layers by constructing a new stack per run.","Keep construction-time and cleanup-time layer code paths symmetric and both pre-initialization."],"tags":["agent-chat","run-context","state-machine","initialization"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}