Skip to main content

Fixed: Cannot use a Workflow that is already owned by another runner or parent workflow

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

I started three runs of one Microsoft Agent Framework workflow at the same time, and only the first one worked. The other two threw InvalidOperationException: Cannot use a Workflow that is already owned by another runner or parent workflow. after 0.03 seconds. By default a run owns the workflow until it ends; declaring the executor shareable and running with InProcessExecution.Concurrent let all three finish together after 1.04 seconds.

What I Was Doing​

I was writing a small console app, ConcurrentGreetings, to see how one Microsoft Agent Framework workflow handles several requests at the same time. The project uses Microsoft.Agents.AI.Workflows 1.28.0 and Microsoft.Agents.AI.Workflows.Generators 1.28.0. The workflow has one step, Greet, a class-based executor that waits one second, as a call to a model or another service would, and returns a greeting.

The app builds the workflow once. Then it starts three runs of it together with Task.WhenAll, one each for Ana, Ben and Chen, and prints how many seconds after the start each result arrived:

Program.cs (as it was)
using System.Diagnostics;
using Microsoft.Agents.AI.Workflows;

GreetExecutor greet = new();
Workflow workflow = new WorkflowBuilder(greet).WithOutputFrom(greet).Build();

string[] names = ["Ana", "Ben", "Chen"];
Stopwatch stopwatch = Stopwatch.StartNew();

// Three requests arrive at the same time, and all three run the one workflow.
await Task.WhenAll(names.Select(async name =>
{
try
{
await using Run run = await InProcessExecution.RunAsync(workflow, name);
foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
if (workflowEvent is WorkflowOutputEvent output)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {output.Data}");
}
}
}
catch (Exception exception)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {name}: {exception.GetType().Name}: {exception.Message}");
}
}));

// A step that takes a second, like a call to a model or another service.
internal sealed partial class GreetExecutor() : Executor("Greet")
{
[MessageHandler]
private async ValueTask<string> HandleAsync(string name, IWorkflowContext context, CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
return $"Hello, {name}!";
}
}

What I Expected​

Three greetings, all about one second after the start. Each run waits one second, and all three started together.

What I Got​

Terminal
dotnet run
Output
0.03 s Ben: InvalidOperationException: Cannot use a Workflow that is already owned by another runner or parent workflow.
0.03 s Chen: InvalidOperationException: Cannot use a Workflow that is already owned by another runner or parent workflow.
1.04 s Hello, Ana!

macOS-style terminal window titled Terminal — ConcurrentGreetings showing dotnet run: after 0.03 s, the runs for Ben and Chen failed with InvalidOperationException: Cannot use a Workflow that is already owned by another runner or parent workflow., and after 1.04 s the run for Ana printed Hello, Ana!

Ana's run worked and greeted her after 1.04 seconds. Ben's and Chen's failed 0.03 seconds after the start, both with the same InvalidOperationException.

What I Checked​

When the two runs failed. At 0.03 seconds, long before a one-second step could finish. The workflow turned them away as they started.

Which run worked. Ana's, the first one the app started. Ben's and Chen's started while hers was still going.

What the message means by owned. Microsoft's documentation on resettable executors describes what happens when a run starts: when a workflow run starts, the runtime takes ownership of the workflow instance and notes which executors need resetting. The run gives that ownership back when the run completes (or is disposed). While Ana's run was going, the workflow instance belonged to it.

Which execution mode I was using. The Workflow Execution Modes page says Non-streaming execution uses the default OffThread mode, and that's the mode InProcessExecution.RunAsync uses. The same page describes the other choice, InProcessExecution.Concurrent: OffThread also supports a concurrent variant that allows multiple runs to share the same workflow instance simultaneously. It comes with one condition: Concurrent execution requires that all executors in the workflow be declared crossRunShareable (on the constructor) or be provided as factory methods.

Whether Greet is safe to share. Its handler uses only the name it receives and keeps nothing in fields, so one instance can serve several runs at once.

Why It Happens​

InProcessExecution.RunAsync uses the default execution environment, where a run owns the workflow instance until it ends. Ana's run started first and owned the workflow. Ben's and Chen's started while it was still owned, and each was refused at once with this exception. One workflow instance serves several runs at the same time only in the concurrent environment, and only when every executor in it is declared shareable or created by a factory.

The Fix​

Two changes. First, declare the executor shareable. The Executor base class's constructor has a third parameter, declareCrossRunShareable, which is false by default:

Program.cs (the executor)
// A step that takes a second, like a call to a model or another service. It keeps nothing
// in its fields, so one instance can serve several runs at the same time.
internal sealed partial class GreetExecutor() : Executor("Greet", declareCrossRunShareable: true)

Agent Framework 1.28's documentation describes the parameter: Declare that this executor may be used simultaneously by multiple runs safely. It's a declaration, so make it only for an executor that, like Greet, keeps nothing in its fields.

Second, run each request with the concurrent environment. Replace the line that starts the run with:

Program.cs (the run)
await using Run run = await InProcessExecution.Concurrent.RunAsync(workflow, name);

Both changes are needed. With the second one alone, every run fails with a different exception, Workflow must only consist of cross-run share-capable or factory-created executors., which has its own fix.

After the Fix​

Terminal
dotnet run
Output
1.04 s Hello, Chen!
1.04 s Hello, Ben!
1.04 s Hello, Ana!

macOS-style terminal window titled Terminal — ConcurrentGreetings showing dotnet run after the fix: Hello, Chen!, Hello, Ben! and Hello, Ana!, all three printed 1.04 s after the start

All three greetings arrived 1.04 seconds after the start: the three runs shared the one workflow at the same time. They print in the order they finished, which isn't the order they started.

Another Way: A New Workflow for Each Request​

Sharing one workflow isn't the only fix. Microsoft's documentation on workflow state recommends the opposite as the default way to keep runs apart: it is recommended to create a new workflow instance from the builder for each task or request to ensure proper state isolation and thread safety. Each run then has a workflow of its own, so no two runs ever ask for the same one. The documentation keeps sharing instances for cases where it's a deliberate choice, for example when executor construction is expensive. I kept the shared workflow here and didn't run this variant.

Common Mistakes​

MistakeWhat happensDo this instead
Starting several runs of one workflow with InProcessExecution.RunAsyncThe first run owns the workflow, and the others throw this exceptionUse InProcessExecution.Concurrent with shareable or factory-created executors
Switching to InProcessExecution.Concurrent and nothing elseEvery run throws Workflow must only consist of cross-run share-capable or factory-created executors.Declare every executor shareable, or create it with a factory
Declaring an executor shareable while it keeps data in fieldsEvery run uses the same instance, and with it the same fieldsCreate it with a factory, so each run gets its own

Troubleshooting​

SymptomLikely causeFix
The first run works, and runs started while it's going fail at onceA run owns the workflow until it endsRun with InProcessExecution.Concurrent and shareable executors
After switching to InProcessExecution.Concurrent, every run fails at onceAn executor isn't declared shareable or created by a factoryPass declareCrossRunShareable: true to its constructor

FAQ​

Does declaring the executor shareable make it safe?​

No. The parameter declares that this executor may be used simultaneously by multiple runs safely. Making that true is up to the executor: Greet is safe because it keeps nothing in its fields. For an executor that keeps data in fields, give each run its own instance with a factory, as the guide to running one workflow for many requests at once shows.

Why did only Ana's run work?​

It started first. The app starts the runs in the order of the names array, and Ana's run took ownership of the workflow before Ben's and Chen's began.

Conclusion​

Cannot use a Workflow that is already owned by another runner or parent workflow. means a run tried to use a workflow instance that another run still owned. With InProcessExecution.RunAsync, one workflow instance serves one run at a time. To run it for several requests at once, declare its executors shareable with declareCrossRunShareable: true, or create them with a factory, and run with InProcessExecution.Concurrent. Or build a new workflow for each request, the default the documentation recommends.

Additional Resources​