microsoft/autogen · error · InvalidOperationException

Cannot push a layer while the context is initialized.

Error message

Cannot push a layer while the context is initialized.

What it means

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.

Source

Thrown at dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RunContext.cs:72

}

public sealed class RunContextStack : LifecycleObject, IRunContextLayer
{
    private Stack<IRunContextLayer> Uninitialized { get; } = new();
    private Stack<IRunContextLayer> Initialized { get; } = new();

    public RunContextStack(params IEnumerable<IRunContextLayer> contextLayers)
    {
        this.Uninitialized = new Stack<IRunContextLayer>(contextLayers);
    }

    // TODO: There is probably a way to have a sound manner by which pushing/popping a layer when initialized
    // would be allowed. But this is not necessary for now, so we will keep it simple.
    public void PushLayer(IRunContextLayer layer)
    {
        if (this.IsInitialized)
        {
            throw new InvalidOperationException("Cannot push a layer while the context is initialized.");
        }

        this.Uninitialized.Push(layer);
    }

    public void PopLayer()
    {
        if (this.IsInitialized)
        {
            throw new InvalidOperationException("Cannot pop a layer while the context is initialized.");
        }
    }

    private Action? initializeError;
    protected override void OnInitializeError()
    {
        (this.initializeError ?? base.OnInitializeError)();
    }

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. 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.
  2. If layers must vary per run, create a fresh RunContextStack per run instead of mutating an initialized one.
  3. Deinitialize/reset the context before reconfiguring, if the API surface you use exposes such a reset; otherwise recreate the whole Team/RunContext.

Example fix

// before
var ctx = new RunContextStack(baseLayer);
await team.RunAsync(task, cancellationToken: ct); // initializes context
ctx.PushLayer(new TracingLayer()); // throws: context is initialized

// after
var ctx = new RunContextStack(baseLayer, new TracingLayer()); // layers up-front
await team.RunAsync(task, cancellationToken: ct);
Defensive patterns

Strategy: validation

Validate before calling

if (!runContextStack.IsInitialized)
{
    runContextStack.PushLayer(newLayer);
}

Prevention

When it happens

Trigger: 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).

Common situations: 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.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/9f9573da819c570d. Report an issue: GitHub.