Repository navigation
.NET: add AsyncRequestBroker #9167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Mark Licata (marklicata)
wants to merge
5
commits into
microsoft:main
Choose a base branch
from
marklicata:agent-async-request-broker-dotnet
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9fcfbf9
.NET: add AsyncRequestBroker
marklicata 0b3a20a
Address review feedback: atomic broker state transitions, timeout val…
marklicata ffed286
Return true from Resolve/Reject for recently settled IDs to match Python
marklicata ff5f4cc
Merge remote-tracking branch 'origin/main' into agent-async-request-b…
marklicata c4428f5
Merge remote-tracking branch 'origin/main' into agent-async-request-b…
marklicata File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
209 changes: 209 additions & 0 deletions
209
dotnet/src/Microsoft.Agents.AI/Harness/AsyncRequestBroker.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Shared.DiagnosticIds; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Agents.AI; | ||
|
|
||
| /// <summary> | ||
| /// A generic async pause-and-wait broker for request/response patterns. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Allows server-side code to suspend on a request ID and await a client response | ||
| /// delivered via <see cref="Resolve"/> or <see cref="Reject"/>, without polling or | ||
| /// blocking a thread. | ||
| /// </remarks> | ||
| /// <typeparam name="TResult">The type of the result delivered to the waiter.</typeparam> | ||
| [Experimental(DiagnosticIds.Experiments.AgentsAIExperiments)] | ||
| public sealed class AsyncRequestBroker<TResult> | ||
| { | ||
| private const int DefaultSettledQueueSize = 256; | ||
|
|
||
| private readonly Dictionary<string, TaskCompletionSource<TResult>> _pending = new(StringComparer.Ordinal); | ||
| private readonly Queue<string> _settledQueue = new(); | ||
| private readonly HashSet<string> _settledSet = new(StringComparer.Ordinal); | ||
| private readonly int _settledQueueSize; | ||
|
|
||
| // Guards _pending, _settledQueue, and _settledSet so that registration, removal, and | ||
| // settled-tracking are a single atomic transition. | ||
| private readonly object _lock = new(); | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="AsyncRequestBroker{TResult}"/> class. | ||
| /// </summary> | ||
| /// <param name="settledQueueSize">Maximum number of recently settled request IDs to track for late-response handling.</param> | ||
| public AsyncRequestBroker(int settledQueueSize = DefaultSettledQueueSize) | ||
| { | ||
| if (settledQueueSize < 1) | ||
| { | ||
| throw new ArgumentOutOfRangeException(nameof(settledQueueSize), "Settled queue size must be at least 1."); | ||
| } | ||
|
|
||
| this._settledQueueSize = settledQueueSize; | ||
| } | ||
|
|
||
| /// <summary>Gets the number of requests currently awaiting a response.</summary> | ||
| public int PendingCount | ||
| { | ||
| get | ||
| { | ||
| lock (this._lock) | ||
| { | ||
| return this._pending.Count; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary>Suspend until the request is resolved, rejected, or cancelled.</summary> | ||
| /// <param name="requestId">Unique identifier for this request.</param> | ||
| /// <param name="timeout"> | ||
| /// Optional timeout. <see langword="null"/> or <see cref="Timeout.InfiniteTimeSpan"/> waits indefinitely. | ||
| /// Otherwise must be non-negative and no greater than <see cref="int.MaxValue"/> milliseconds. | ||
| /// </param> | ||
| /// <param name="cancellationToken">Token to cancel the wait.</param> | ||
| /// <returns>The result passed to <see cref="Resolve"/>.</returns> | ||
| /// <exception cref="ArgumentNullException"><paramref name="requestId"/> is <see langword="null"/>.</exception> | ||
| /// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> is outside the supported range.</exception> | ||
| /// <exception cref="InvalidOperationException">The request ID is already pending or was recently settled.</exception> | ||
| /// <exception cref="OperationCanceledException">The timeout elapsed or <paramref name="cancellationToken"/> was cancelled.</exception> | ||
| public async Task<TResult> RequestAsync(string requestId, TimeSpan? timeout = null, CancellationToken cancellationToken = default) | ||
| { | ||
| _ = Throw.IfNull(requestId); | ||
|
|
||
| bool hasTimeout = timeout.HasValue && timeout.Value != Timeout.InfiniteTimeSpan; | ||
| if (hasTimeout && (timeout!.Value < TimeSpan.Zero || timeout.Value.TotalMilliseconds > int.MaxValue)) | ||
| { | ||
| throw new ArgumentOutOfRangeException(nameof(timeout), timeout, "Timeout must be non-negative and no greater than Int32.MaxValue milliseconds, or Timeout.InfiniteTimeSpan."); | ||
| } | ||
|
|
||
| var tcs = new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously); | ||
|
|
||
| lock (this._lock) | ||
| { | ||
| if (this._settledSet.Contains(requestId)) | ||
| { | ||
| throw new InvalidOperationException($"Request '{requestId}' was already settled."); | ||
| } | ||
|
|
||
| if (this._pending.ContainsKey(requestId)) | ||
| { | ||
| throw new InvalidOperationException($"Request '{requestId}' is already pending."); | ||
| } | ||
|
|
||
| this._pending.Add(requestId, tcs); | ||
| } | ||
|
|
||
| using var cts = hasTimeout | ||
| ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken) | ||
| : null; | ||
|
|
||
| // The timeout was validated above, so CancelAfter cannot throw here. | ||
| cts?.CancelAfter(timeout!.Value); | ||
|
|
||
| var effectiveToken = cts?.Token ?? cancellationToken; | ||
| using var registration = effectiveToken.Register(() => | ||
| { | ||
| bool removed; | ||
| lock (this._lock) | ||
| { | ||
| // Only cancel our own TCS, never a replacement registered under the same ID. | ||
| removed = this._pending.TryGetValue(requestId, out var current) && ReferenceEquals(current, tcs); | ||
| if (removed) | ||
| { | ||
| this._pending.Remove(requestId); | ||
| this.TrackSettledLocked(requestId); | ||
| } | ||
| } | ||
|
|
||
| if (removed) | ||
| { | ||
| tcs.TrySetCanceled(effectiveToken); | ||
| } | ||
| }); | ||
|
|
||
| return await tcs.Task.ConfigureAwait(false); | ||
| } | ||
|
|
||
| /// <summary>Deliver a successful result to a waiting <see cref="RequestAsync"/> call.</summary> | ||
| /// <param name="requestId">The request identifier.</param> | ||
| /// <param name="result">The result to deliver.</param> | ||
| /// <returns> | ||
| /// <see langword="true"/> if a waiter was notified, or if the request was recently settled (resolved, rejected, | ||
| /// timed out, or cancelled), in which case the late <paramref name="result"/> is ignored; | ||
| /// <see langword="false"/> if the request ID is unknown or has been evicted from the settled-ID history. | ||
| /// </returns> | ||
| public bool Resolve(string requestId, TResult result) | ||
| { | ||
| if (!this.TrySettle(requestId, out var tcs)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| tcs?.TrySetResult(result); | ||
| return true; | ||
| } | ||
|
|
||
| /// <summary>Deliver an exception to a waiting <see cref="RequestAsync"/> call.</summary> | ||
| /// <param name="requestId">The request identifier.</param> | ||
| /// <param name="exception">The exception to deliver.</param> | ||
| /// <returns> | ||
| /// <see langword="true"/> if a waiter was notified, or if the request was recently settled (resolved, rejected, | ||
| /// timed out, or cancelled), in which case the late <paramref name="exception"/> is ignored; | ||
| /// <see langword="false"/> if the request ID is unknown or has been evicted from the settled-ID history. | ||
| /// </returns> | ||
| public bool Reject(string requestId, Exception exception) | ||
| { | ||
| _ = Throw.IfNull(exception); | ||
|
|
||
| if (!this.TrySettle(requestId, out var tcs)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| tcs?.TrySetException(exception); | ||
| return true; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Removes a pending request and records it as settled, or detects a late response for a recently settled request. | ||
| /// </summary> | ||
| /// <returns> | ||
| /// <see langword="true"/> if the ID was pending (<paramref name="tcs"/> is the waiter to complete) or recently | ||
| /// settled (<paramref name="tcs"/> is <see langword="null"/>); <see langword="false"/> if the ID is unknown. | ||
| /// </returns> | ||
| private bool TrySettle(string requestId, out TaskCompletionSource<TResult>? tcs) | ||
| { | ||
| _ = Throw.IfNull(requestId); | ||
|
|
||
| lock (this._lock) | ||
| { | ||
| if (this._pending.TryGetValue(requestId, out tcs)) | ||
| { | ||
| this._pending.Remove(requestId); | ||
| this.TrackSettledLocked(requestId); | ||
| return true; | ||
| } | ||
|
|
||
| tcs = null; | ||
| return this._settledSet.Contains(requestId); | ||
| } | ||
| } | ||
|
|
||
| // Caller must hold _lock. | ||
| private void TrackSettledLocked(string requestId) | ||
| { | ||
| if (this._settledQueue.Count >= this._settledQueueSize) | ||
| { | ||
| string oldest = this._settledQueue.Dequeue(); | ||
| this._settledSet.Remove(oldest); | ||
| } | ||
|
|
||
| this._settledQueue.Enqueue(requestId); | ||
| this._settledSet.Add(requestId); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.