From 661046b80aace150f4ae21c96522a52759df6305 Mon Sep 17 00:00:00 2001 From: Jacob Alber Date: Thu, 16 Apr 2026 09:19:20 -0400 Subject: [PATCH] fix: Thread safety issue in `MultiPartyConversation.AllMessages` --- .../Specialized/MultiPartyConversation.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/MultiPartyConversation.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/MultiPartyConversation.cs index b587db2197..4d59184f0d 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/MultiPartyConversation.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/Specialized/MultiPartyConversation.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. +using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.AI; @@ -11,19 +12,25 @@ internal sealed class MultiPartyConversation private readonly List _history = []; private readonly object _mutex = new(); - public List CloneAllMessages() => this._history.ToList(); + public List CloneAllMessages() + { + lock (this._mutex) + { + return this._history.ToList(); + } + } public (ChatMessage[], int) CollectNewMessages(int bookmark) { lock (this._mutex) { int count = this._history.Count - bookmark; - if (count > 0) + if (count < 0) { - return (this._history.Skip(bookmark).ToArray(), this.CurrentBookmark); + throw new InvalidOperationException($"Bookmark value too large: {bookmark} vs count={count}"); } - return ([], this.CurrentBookmark); + return (this._history.Skip(bookmark).ToArray(), this.CurrentBookmark); } }