{"record":{"id":"9f9573da819c570d","repo":"microsoft/autogen","slug":"cannot-push-a-layer-while-the-context-is-initializ","errorCode":null,"errorMessage":"Cannot push a layer while the context is initialized.","messagePattern":"Cannot push 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":72,"sourceCode":"}\n\npublic sealed class RunContextStack : LifecycleObject, IRunContextLayer\n{\n    private Stack<IRunContextLayer> Uninitialized { get; } = new();\n    private Stack<IRunContextLayer> Initialized { get; } = new();\n\n    public RunContextStack(params IEnumerable<IRunContextLayer> contextLayers)\n    {\n        this.Uninitialized = new Stack<IRunContextLayer>(contextLayers);\n    }\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    }","sourceCodeStart":54,"sourceCodeEnd":90,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RunContext.cs#L54-L90","documentation":"RunContextStack.PushLayer throws InvalidOperationException when a context layer is pushed after the run context has already been initialized (a chat/run has started). The stack is intentionally frozen once initialized: layers may only be added before the first InitializeAsync/Run call. The TODO comment in the source confirms this is a deliberate design simplification, not a bug.","triggerScenarios":"Calling RunContextStack.PushLayer(layer) (or team.RunContext.PushLayer) after the orchestration has begun — i.e., after IsInitialized returns true (the Uninitialized stack has been consumed into the live context and initialization completed).","commonSituations":"Adding middleware/context layers inside an agent callback, a message handler, or between multiple RunAsync calls on the same Team; refactoring setup code out of the construction path so that PushLayer now runs after the first run; reusing one RunContext across sequential runs and trying to reconfigure it between them.","solutions":["Move all PushLayer calls to construction/before the first run, e.g. pass layers via the RunContextStack(params IEnumerable<IRunContextLayer>) constructor or call PushLayer before team initialization.","If layers must vary per run, create a fresh RunContextStack per run instead of mutating an initialized one.","Deinitialize/reset the context before reconfiguring, if the API surface you use exposes such a reset; otherwise recreate the whole Team/RunContext."],"exampleFix":"// before\nvar ctx = new RunContextStack(baseLayer);\nawait team.RunAsync(task, cancellationToken: ct); // initializes context\nctx.PushLayer(new TracingLayer()); // throws: context is initialized\n\n// after\nvar ctx = new RunContextStack(baseLayer, new TracingLayer()); // layers up-front\nawait team.RunAsync(task, cancellationToken: ct);","handlingStrategy":"validation","validationCode":"if (!runContextStack.IsInitialized)\n{\n    runContextStack.PushLayer(newLayer);\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Pass all layers through the RunContextStack constructor instead of incremental PushLayer calls.","Treat RunContext configuration as immutable once a run begins; rebuild the context for a new configuration."],"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"}