Skip to content

A programming framework for agentic AI

fix: Recurrent SendMessageAsync deadlock in message handler (#5916)

Jacob Alber0a988b63939a
diff --git a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
index bf18b1da2..dddee1845 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
@@ -14,8 +14,8 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
public bool DeliverToSelf { get; set; } //= false;
internal Dictionary<AgentId, IHostableAgent> agentInstances = new();
- Dictionary<string, ISubscriptionDefinition> subscriptions = new();
- Dictionary<AgentType, Func<AgentId, IAgentRuntime, ValueTask<IHostableAgent>>> agentFactories = new();
+ private Dictionary<string, ISubscriptionDefinition> subscriptions = new();
+ private Dictionary<AgentType, Func<AgentId, IAgentRuntime, ValueTask<IHostableAgent>>> agentFactories = new();
private ValueTask<T> ExecuteTracedAsync<T>(Func<ValueTask<T>> func)
{
@@ -104,14 +104,15 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, AgentId? sender = null, string? messageId = null, CancellationToken cancellationToken = default)
{
- return this.ExecuteTracedAsync(() =>
+ return this.ExecuteTracedAsync(async () =>
{
MessageDelivery delivery = new MessageEnvelope(message, messageId, cancellationToken)
.WithSender(sender)
.ForSend(recepient, this.SendMessageServicer);
this.messageDeliveryQueue.Enqueue(delivery);
- return delivery.Future;
+
+ return await delivery.Future;
});
}
@@ -242,7 +243,7 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
return ValueTask.FromResult(new AgentProxy(agentId, this));
}
- public ValueTask ProcessNextMessage(CancellationToken cancellation = default)
+ public ValueTask ProcessNextMessageAsync(CancellationToken cancellation = default)
{
Debug.WriteLine("Processing next message...");
if (this.messageDeliveryQueue.TryDequeue(out MessageDelivery? delivery))
@@ -258,11 +259,34 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
private CancellationTokenSource? finishSource;
private async Task RunAsync(CancellationToken cancellation)
{
+ Dictionary<Guid, Task> pendingTasks = new();
while (!cancellation.IsCancellationRequested && shouldContinue())
{
- await this.ProcessNextMessage(cancellation);
+ // Get a unique task id
+ Guid taskId;
+ do
+ {
+ taskId = Guid.NewGuid();
+ } while (pendingTasks.ContainsKey(taskId));
+
+ // There is potentially a race condition here, but even if we leak a Task, we will
+ // still catch it on the Finish() pass.
+ ValueTask processTask = this.ProcessNextMessageAsync(cancellation);
+ await Task.Yield();
+
+ // Check if the task is already completed
+ if (processTask.IsCompleted)
+ {
+ continue;
+ }
+ else
+ {
+ Task actualTask = processTask.AsTask();
+ pendingTasks.Add(taskId, actualTask.ContinueWith(t => pendingTasks.Remove(taskId), TaskScheduler.Current));
+ }
}
+ await Task.WhenAll(pendingTasks.Values.ToArray());
await this.FinishAsync(this.finishSource?.Token ?? CancellationToken.None);
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs b/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
index ab97dac84..a0e76d9c6 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
@@ -1,17 +1,18 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// MessageDelivery.cs
+using System.Reflection;
using Microsoft.AutoGen.Contracts;
namespace Microsoft.AutoGen.Core;
-internal sealed class MessageDelivery(MessageEnvelope message, Func<MessageEnvelope, CancellationToken, ValueTask> servicer, IResultSink<object?>? resultSink = null)
+internal sealed class MessageDelivery(MessageEnvelope message, Func<MessageEnvelope, CancellationToken, ValueTask> servicer, IResultSink<object?> resultSink)
{
public MessageEnvelope Message { get; } = message;
public Func<MessageEnvelope, CancellationToken, ValueTask> Servicer { get; } = servicer;
- public IResultSink<object?>? ResultSink { get; } = resultSink;
+ public IResultSink<object?> ResultSink { get; } = resultSink;
- public ValueTask<object?> Future => this.ResultSink != null ? this.ResultSink.Future : ValueTask.FromResult((object?)null);
+ public ValueTask<object?> Future => this.ResultSink.Future;
public ValueTask InvokeAsync(CancellationToken cancellation)
{
@@ -48,8 +49,19 @@ internal sealed class MessageEnvelope
ResultSink<object?> resultSink = new ResultSink<object?>();
Func<MessageEnvelope, CancellationToken, ValueTask> boundServicer = async (envelope, cancellation) =>
{
- object? result = await servicer(envelope, cancellation);
- resultSink.SetResult(result);
+ try
+ {
+ object? result = await servicer(envelope, cancellation);
+ resultSink.SetResult(result);
+ }
+ catch (TargetInvocationException ex) when (ex.InnerException is OperationCanceledException innerOCEx)
+ {
+ resultSink.SetCancelled(innerOCEx);
+ }
+ catch (Exception ex)
+ {
+ resultSink.SetException(ex);
+ }
};
return new MessageDelivery(this, boundServicer, resultSink);
@@ -59,6 +71,20 @@ internal sealed class MessageEnvelope
{
this.Topic = topic;
- return new MessageDelivery(this, servicer);
+ ResultSink<object?> waitForPublish = new ResultSink<object?>();
+ Func<MessageEnvelope, CancellationToken, ValueTask> boundServicer = async (envelope, cancellation) =>
+ {
+ try
+ {
+ await servicer(envelope, cancellation);
+ waitForPublish.SetResult(null);
+ }
+ catch (Exception ex)
+ {
+ waitForPublish.SetException(ex);
+ }
+ };
+
+ return new MessageDelivery(this, servicer, waitForPublish);
}
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs b/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
index ef8958366..f5dbaf97d 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
@@ -9,7 +9,7 @@ internal interface IResultSink<TResult> : IValueTaskSource<TResult>
{
public void SetResult(TResult result);
public void SetException(Exception exception);
- public void SetCancelled();
+ public void SetCancelled(OperationCanceledException? ocEx = null);
public ValueTask<TResult> Future { get; }
}
@@ -34,10 +34,10 @@ public sealed class ResultSink<TResult> : IResultSink<TResult>
}
public bool IsCancelled { get; private set; }
- public void SetCancelled()
+ public void SetCancelled(OperationCanceledException? ocEx = null)
{
this.IsCancelled = true;
- this.core.SetException(new OperationCanceledException());
+ this.core.SetException(ocEx ?? new OperationCanceledException());
}
public void SetException(Exception exception)
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs
index 4952c4e7f..c32ed0bdb 100644
--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs
@@ -128,7 +128,7 @@ public class AgentTests()
var topicTypeName = "TestTopic";
await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
- await Task.Delay(100);
+ await runtime.RunUntilIdleAndRestartAsync();
Assert.True(agent.ReceivedItems.Count == 0);
@@ -136,14 +136,14 @@ public class AgentTests()
await runtime.AddSubscriptionAsync(subscription);
await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
- await Task.Delay(100);
+ await runtime.RunUntilIdleAndRestartAsync();
Assert.True(agent.ReceivedItems.Count == 1);
Assert.Equal("info", agent.ReceivedItems[0]);
await runtime.RemoveSubscriptionAsync(subscription.Id);
await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
- await Task.Delay(100);
+ await runtime.RunUntilIdleAsync();
Assert.True(agent.ReceivedItems.Count == 1);
}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/InProcessRuntimeExtensions.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/InProcessRuntimeExtensions.cs
new file mode 100644
index 000000000..b1d659f7e
--- /dev/null
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/InProcessRuntimeExtensions.cs
@@ -0,0 +1,12 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// InProcessRuntimeExtensions.cs
+namespace Microsoft.AutoGen.Core.Tests;
+
+public static class InProcessRuntimeExtensions
+{
+ public static async ValueTask RunUntilIdleAndRestartAsync(this InProcessRuntime this_)
+ {
+ await this_.RunUntilIdleAsync();
+ await this_.StartAsync();
+ }
+}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/SendMessageTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/SendMessageTests.cs
new file mode 100644
index 000000000..cd048e680
--- /dev/null
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/SendMessageTests.cs
@@ -0,0 +1,234 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// SendMessageTests.cs
+
+using System.Diagnostics;
+using System.Reflection;
+using FluentAssertions;
+using Microsoft.AutoGen.Contracts;
+using Microsoft.Extensions.Logging;
+using Xunit;
+
+namespace Microsoft.AutoGen.Core.Tests;
+
+[Trait("Category", "UnitV2")]
+public class SendMessageTests
+{
+ private sealed class BasicMessage
+ {
+ public string Content { get; set; } = string.Empty;
+ }
+
+ private sealed class SendOnAgent : BaseAgent, IHandle<BasicMessage>
+ {
+ private IList<Guid> targetKeys;
+
+ public SendOnAgent(AgentId id, IAgentRuntime runtime, string description, IList<Guid> targetKeys, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ this.targetKeys = targetKeys;
+ }
+
+ public async ValueTask HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ foreach (Guid targetKey in targetKeys)
+ {
+ AgentId targetId = new(nameof(ReceiverAgent), targetKey.ToString());
+ BasicMessage message = new BasicMessage { Content = $"@{targetKey}: item.Content" };
+ await this.Runtime.SendMessageAsync(message, targetId);
+ }
+ }
+ }
+
+ private sealed class ReceiverAgent : BaseAgent, IHandle<BasicMessage>
+ {
+ public List<BasicMessage> Messages { get; } = new();
+
+ public ReceiverAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ }
+
+ public ValueTask HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ this.Messages.Add(item);
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ private sealed class ProcessorAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
+ {
+ private Func<string, string> ProcessFunc { get; }
+
+ public ProcessorAgent(AgentId id, IAgentRuntime runtime, Func<string, string> processFunc, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ this.ProcessFunc = processFunc;
+ }
+
+ public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ BasicMessage result = new() { Content = this.ProcessFunc(item.Content) };
+
+ return ValueTask.FromResult(result);
+ }
+ }
+
+ private sealed class TestException : Exception
+ { }
+
+ private sealed class CancelAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
+ {
+ public CancelAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ }
+
+ public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ CancellationToken cancelledToken = new CancellationToken(canceled: true);
+ cancelledToken.ThrowIfCancellationRequested();
+
+ return ValueTask.FromResult(item);
+ }
+ }
+
+ private sealed class ErrorAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
+ {
+ public ErrorAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ }
+
+ public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ throw new TestException();
+ }
+ }
+
+ private sealed class SendTestFixture
+ {
+ private Dictionary<Type, object> AgentsTypeMap { get; } = new();
+ public InProcessRuntime Runtime { get; private set; } = new();
+
+ public ValueTask<AgentType> RegisterFactoryMapInstances<TAgent>(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<TAgent>> factory)
+ where TAgent : IHostableAgent
+ {
+ Func<AgentId, IAgentRuntime, ValueTask<TAgent>> wrappedFactory = async (id, runtime) =>
+ {
+ TAgent agent = await factory(id, runtime);
+ this.GetAgentInstances<TAgent>()[id] = agent;
+ return agent;
+ };
+
+ return this.Runtime.RegisterAgentFactoryAsync(type, wrappedFactory);
+ }
+
+ public Dictionary<AgentId, TAgent> GetAgentInstances<TAgent>() where TAgent : IHostableAgent
+ {
+ if (!AgentsTypeMap.TryGetValue(typeof(TAgent), out object? maybeAgentMap) ||
+ maybeAgentMap is not Dictionary<AgentId, TAgent> result)
+ {
+ this.AgentsTypeMap[typeof(TAgent)] = result = new Dictionary<AgentId, TAgent>();
+ }
+
+ return result;
+ }
+
+ public async ValueTask<object?> RunTestAsync(AgentId sendTarget, object message, string? messageId = null)
+ {
+ messageId ??= Guid.NewGuid().ToString();
+
+ await this.Runtime.StartAsync();
+
+ object? result = await this.Runtime.SendMessageAsync(message, sendTarget, messageId: messageId);
+
+ await this.Runtime.RunUntilIdleAsync();
+
+ return result;
+ }
+ }
+
+ [Fact]
+ public async Task Test_SendMessage_ReturnsValue()
+ {
+ Func<string, string> ProcessFunc = (s) => $"Processed({s})";
+
+ SendTestFixture fixture = new SendTestFixture();
+
+ await fixture.RegisterFactoryMapInstances(nameof(ProcessorAgent),
+ (id, runtime) => ValueTask.FromResult(new ProcessorAgent(id, runtime, ProcessFunc, string.Empty)));
+
+ AgentId targetAgent = new AgentId(nameof(ProcessorAgent), Guid.NewGuid().ToString());
+ object? maybeResult = await fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "1" });
+
+ maybeResult.Should().NotBeNull()
+ .And.BeOfType<BasicMessage>()
+ .And.Match<BasicMessage>(m => m.Content == "Processed(1)");
+ }
+
+ [Fact]
+ public async Task Test_SendMessage_Cancellation()
+ {
+ SendTestFixture fixture = new SendTestFixture();
+
+ await fixture.RegisterFactoryMapInstances(nameof(CancelAgent),
+ (id, runtime) => ValueTask.FromResult(new CancelAgent(id, runtime, string.Empty)));
+
+ AgentId targetAgent = new AgentId(nameof(CancelAgent), Guid.NewGuid().ToString());
+ Func<Task> testAction = () => fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "1" }).AsTask();
+
+ // TODO: Do we want to do the unwrap in this case?
+ await testAction.Should().ThrowAsync<OperationCanceledException>();
+ }
+
+ [Fact]
+ public async Task Test_SendMessage_Error()
+ {
+ SendTestFixture fixture = new SendTestFixture();
+
+ await fixture.RegisterFactoryMapInstances(nameof(ErrorAgent),
+ (id, runtime) => ValueTask.FromResult(new ErrorAgent(id, runtime, string.Empty)));
+
+ AgentId targetAgent = new AgentId(nameof(ErrorAgent), Guid.NewGuid().ToString());
+ Func<Task> testAction = () => fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "1" }).AsTask();
+
+ (await testAction.Should().ThrowAsync<TargetInvocationException>())
+ .WithInnerException<TestException>();
+ }
+
+ [Fact]
+ public async Task TesT_SendMessage_FromSendMessageHandler()
+ {
+ Guid[] targetGuids = [Guid.NewGuid(), Guid.NewGuid()];
+
+ SendTestFixture fixture = new SendTestFixture();
+
+ Dictionary<AgentId, SendOnAgent> sendAgents = fixture.GetAgentInstances<SendOnAgent>();
+ Dictionary<AgentId, ReceiverAgent> receiverAgents = fixture.GetAgentInstances<ReceiverAgent>();
+
+ await fixture.RegisterFactoryMapInstances(nameof(SendOnAgent),
+ (id, runtime) => ValueTask.FromResult(new SendOnAgent(id, runtime, string.Empty, targetGuids)));
+
+ await fixture.RegisterFactoryMapInstances(nameof(ReceiverAgent),
+ (id, runtime) => ValueTask.FromResult(new ReceiverAgent(id, runtime, string.Empty)));
+
+ AgentId targetAgent = new AgentId(nameof(SendOnAgent), Guid.NewGuid().ToString());
+ Task testTask = fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "Hello" }).AsTask();
+
+ // We do not actually expect to wait the timeout here, but it is still better than waiting the 10 min
+ // timeout that the tests default to. A failure will fail regardless of what timeout value we set.
+ TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromSeconds(120) : TimeSpan.FromSeconds(10);
+ Task timeoutTask = Task.Delay(timeout);
+
+ Task completedTask = await Task.WhenAny([testTask, timeoutTask]);
+ completedTask.Should().Be(testTask, "SendOnAgent should complete before timeout");
+
+ // Check that each of the target agents received the message
+ foreach (var targetKey in targetGuids)
+ {
+ var targetId = new AgentId(nameof(ReceiverAgent), targetKey.ToString());
+ receiverAgents[targetId].Messages.Should().ContainSingle(m => m.Content == $"@{targetKey}: item.Content");
+ }
+ }
+}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs
index 712c7c56b..fff15e312 100644
--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs
@@ -113,9 +113,11 @@ public class SubscribedSelfPublishAgent(AgentId id,
Source = "TestTopic",
Content = item
};
+
// This will publish the new message type which will be handled by the TextMessage handler
await this.PublishMessageAsync(strToText, new TopicId("TestTopic"));
}
+
public ValueTask HandleAsync(TextMessage item, MessageContext messageContext)
{
_text = item;
diff --git a/dotnet/test/Microsoft.AutoGen.Integration.Tests/Microsoft.AutoGen.Integration.Tests.csproj b/dotnet/test/Microsoft.AutoGen.Integration.Tests/Microsoft.AutoGen.Integration.Tests.csproj
index 661c49d3b..9ddc467f4 100644
--- a/dotnet/test/Microsoft.AutoGen.Integration.Tests/Microsoft.AutoGen.Integration.Tests.csproj
+++ b/dotnet/test/Microsoft.AutoGen.Integration.Tests/Microsoft.AutoGen.Integration.Tests.csproj
@@ -56,7 +56,7 @@
</PropertyGroup>
<Message Importance="Normal" Text="Initializing virtual environment for $(PythonVenvRoot)" />
- <Exec Command="$(UvPath) sync --all-extras" WorkingDirectory="$(PythonRoot)" Condition=" '$(CreateVenv)' == 'True' " />
+ <Exec Command="$(UvPath) sync --all-extras --no-install-package llama-cpp-python" WorkingDirectory="$(PythonRoot)" Condition=" '$(CreateVenv)' == 'True' " />
<!--Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
</Exec>
<Message Importance="Normal" Text="$(OutputOfExec)" />-->
@@ -64,3 +64,4 @@
</Project>
+
\ No newline at end of file