Skip to content

Commit bd6c4bf

Browse files
fix: report gateway shutdown as a cancellation instead of chat/approval timeouts (#1026)
* fix: report gateway shutdown as cancellation instead of chat/approval timeouts A chat.send or exec.approval.resolve response wait races its timeout delay against the client-lifetime token. A cancelled delay completes Task.WhenAny exactly like an elapsed one, so client shutdown mid-request surfaced as 'Timed out waiting for ... response from gateway' instead of a cancellation. Classify the cancelled-token case before throwing TimeoutException at both sites, mirroring the wizard-request fix in #1018. Fixes the two sibling sites of #1021. * fix: report gateway shutdown as cancellation instead of chat/approval timeouts A chat.send or exec.approval.resolve response wait races its timeout delay against the client-lifetime token. A cancelled delay completes Task.WhenAny exactly like an elapsed one, so client shutdown mid-request surfaced as 'Timed out waiting for ... response from gateway' instead of a cancellation. Classify the cancelled-token case before throwing TimeoutException at both sites, mirroring the wizard-request fix in #1018. Fixes the two sibling sites of #1021. --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 93174b2 commit bd6c4bf

2 files changed

Lines changed: 250 additions & 19 deletions

File tree

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 59 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -364,16 +364,20 @@ public async Task<ChatSendResult> SendChatMessageForRunAsync(
364364

365365
await SendRawAsync(JsonSerializer.Serialize(req));
366366

367-
var completedTask = await Task.WhenAny(completion.Task, Task.Delay(5000, CancellationToken));
368-
if (completedTask != completion.Task)
367+
try
368+
{
369+
var result = await WaitForGatewayResponseAsync(
370+
completion.Task,
371+
TimeSpan.FromSeconds(5),
372+
CancellationToken,
373+
"Timed out waiting for chat.send response from gateway");
374+
_logger.Info($"Sent chat message ({message.Length} chars{(hasAttachments ? $", {attachments!.Count} attachment(s)" : "")})");
375+
return result;
376+
}
377+
finally
369378
{
370379
RemovePendingChatSend(requestId);
371-
throw new TimeoutException("Timed out waiting for chat.send response from gateway");
372380
}
373-
374-
var result = await completion.Task.ConfigureAwait(false);
375-
_logger.Info($"Sent chat message ({message.Length} chars{(hasAttachments ? $", {attachments!.Count} attachment(s)" : "")})");
376-
return result;
377381
}
378382

379383
Task IOperatorGatewayClient.SendChatMessageAsync(string message, string? sessionKey) =>
@@ -491,23 +495,59 @@ public async Task ResolveExecApprovalAsync(string approvalId, string decision)
491495
// traverse gateway → operator → optional UI confirm → ack, so we give
492496
// it a larger budget than the chat.send sibling's 5s. A timeout keeps
493497
// the banner visible for the user to retry rather than hanging the UI.
494-
var delayTask = Task.Delay(15000, CancellationToken);
495-
await Task.WhenAny(completion.Task, delayTask);
496-
497-
// Use IsCompleted directly rather than Task.WhenAny's return identity:
498-
// when both tasks complete in the same scheduling tick, WhenAny may
499-
// return the delay task even though the TCS is already complete, which
500-
// would otherwise surface as a spurious TimeoutException and discard a
501-
// real ok:true / ok:false response.
502-
if (!completion.Task.IsCompleted)
498+
try
499+
{
500+
await WaitForGatewayResponseAsync(
501+
completion.Task,
502+
TimeSpan.FromSeconds(15),
503+
CancellationToken,
504+
"Timed out waiting for exec.approval.resolve response from gateway");
505+
}
506+
finally
503507
{
504508
_pendingApprovalResolves.TryRemove(requestId, out _);
505509
RemovePendingRequest(requestId);
506-
throw new TimeoutException("Timed out waiting for exec.approval.resolve response from gateway");
510+
}
511+
}
512+
513+
private static async Task<T> WaitForGatewayResponseAsync<T>(
514+
Task<T> responseTask,
515+
TimeSpan timeout,
516+
CancellationToken cancellationToken,
517+
string timeoutMessage)
518+
{
519+
var cancellationSignal = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
520+
using var cancellationRegistration = cancellationToken.Register(
521+
() => cancellationSignal.TrySetCanceled(cancellationToken));
522+
var timeoutTask = Task.Delay(timeout);
523+
var completedTask = await Task.WhenAny(responseTask, timeoutTask, cancellationSignal.Task);
524+
return await ResolveGatewayResponseAsync(
525+
responseTask,
526+
completedTask,
527+
cancellationSignal.Task,
528+
timeoutMessage);
529+
}
530+
531+
internal static async Task<T> ResolveGatewayResponseAsync<T>(
532+
Task<T> responseTask,
533+
Task completedTask,
534+
Task cancellationTask,
535+
string timeoutMessage)
536+
{
537+
// A response that arrived before this continuation resumed wins over
538+
// either terminal signal, preserving the existing same-tick contract.
539+
if (responseTask.IsCompleted)
540+
return await responseTask.ConfigureAwait(false);
541+
542+
// Classify from the task that actually won WhenAny. Sampling the token
543+
// here would let later shutdown reclassify an already-elapsed deadline.
544+
if (ReferenceEquals(completedTask, cancellationTask))
545+
{
546+
await cancellationTask.ConfigureAwait(false);
547+
throw new OperationCanceledException("Gateway request canceled");
507548
}
508549

509-
// Propagate any exception (ok:false, disconnect) stored on the TCS.
510-
await completion.Task.ConfigureAwait(false);
550+
throw new TimeoutException(timeoutMessage);
511551
}
512552

513553
private static bool IsValidApprovalDecision(string decision)
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Diagnostics;
4+
using System.Net.WebSockets;
5+
using System.Reflection;
6+
using System.Text;
7+
using System.Threading;
8+
using System.Threading.Tasks;
9+
using OpenClaw.TestSupport;
10+
using Xunit;
11+
12+
namespace OpenClaw.Shared.Tests;
13+
14+
/// <summary>
15+
/// Regression tests for the #1021 sibling sites: when the client-lifetime token is
16+
/// cancelled while a chat.send or exec.approval.resolve response is pending, the
17+
/// failure must surface as a cancellation, not as a gateway timeout. The
18+
/// wizard-request site has its own fix and tests (#1018).
19+
/// </summary>
20+
[Collection("WebSocketClientBase")]
21+
public sealed class GatewayRequestShutdownClassificationTests
22+
{
23+
[Fact]
24+
public async Task SendChatMessage_ShutdownDuringWait_SurfacesCancellationNotTimeout()
25+
{
26+
using var server = new LoopbackWebSocketServer();
27+
using var identity = new TempDirectory("gateway-shutdown-");
28+
await server.StartAsync();
29+
using var client = CreateClient(server, identity.Path);
30+
await ConnectAsync(client, server);
31+
32+
// Start the request, then cancel the lifetime token only after the server has
33+
// observed the request frame — by then the request has passed its connectivity
34+
// guards and is parked on the response wait, so the cancelled timeout delay is
35+
// the only thing that can complete it.
36+
var requestTask = client.SendChatMessageAsync("hello", sessionKey: "agent:main:test");
37+
await WaitForFrameContainingAsync(server, "chat.send", TimeSpan.FromSeconds(2));
38+
CancelLifetime(client);
39+
40+
var elapsed = Stopwatch.StartNew();
41+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => requestTask);
42+
Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(4),
43+
"shutdown must classify immediately instead of waiting out the 5s chat.send budget");
44+
}
45+
46+
[Fact]
47+
public async Task ResolveExecApproval_ShutdownDuringWait_SurfacesCancellationNotTimeout()
48+
{
49+
using var server = new LoopbackWebSocketServer();
50+
using var identity = new TempDirectory("gateway-shutdown-");
51+
await server.StartAsync();
52+
using var client = CreateClient(server, identity.Path);
53+
await ConnectAsync(client, server);
54+
55+
var requestTask = client.ResolveExecApprovalAsync("approval-1", "allow-once");
56+
await WaitForFrameContainingAsync(server, "exec.approval.resolve", TimeSpan.FromSeconds(2));
57+
CancelLifetime(client);
58+
59+
var elapsed = Stopwatch.StartNew();
60+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => requestTask);
61+
Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(10),
62+
"shutdown must classify immediately instead of waiting out the 15s approval budget");
63+
}
64+
65+
// Guards the actual shutdown entry point: Dispose faults the pending completion
66+
// via ClearPendingRequests before cancelling the lifetime token, and that path
67+
// must never fabricate a gateway timeout either. The two tests above pin the
68+
// residual register-after-clear window, which a real Dispose cannot reach
69+
// deterministically precisely because of that ordering.
70+
[Fact]
71+
public async Task ResolveExecApproval_RealDisposeDuringWait_SurfacesCancellationNotTimeout()
72+
{
73+
using var server = new LoopbackWebSocketServer();
74+
using var identity = new TempDirectory("gateway-shutdown-");
75+
await server.StartAsync();
76+
using var client = CreateClient(server, identity.Path);
77+
await ConnectAsync(client, server);
78+
79+
var requestTask = client.ResolveExecApprovalAsync("approval-1", "allow-once");
80+
await WaitForFrameContainingAsync(server, "exec.approval.resolve", TimeSpan.FromSeconds(2));
81+
client.Dispose();
82+
83+
var elapsed = Stopwatch.StartNew();
84+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => requestTask);
85+
Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(10),
86+
"disposal must surface as cancellation instead of waiting out the 15s approval budget");
87+
}
88+
89+
[Fact]
90+
public async Task ResolveGatewayResponse_ResponseWinsWhenTerminalSignalCompletedFirst()
91+
{
92+
using var cancellation = new CancellationTokenSource();
93+
var cancellationTask = Task.Delay(Timeout.InfiniteTimeSpan, cancellation.Token);
94+
cancellation.Cancel();
95+
var responseTask = Task.FromResult(42);
96+
97+
var result = await OpenClawGatewayClient.ResolveGatewayResponseAsync(
98+
responseTask,
99+
cancellationTask,
100+
cancellationTask,
101+
"must not time out");
102+
103+
Assert.Equal(42, result);
104+
}
105+
106+
[Fact]
107+
public async Task ResolveGatewayResponse_TimeoutWinnerStaysTimeoutAfterLaterCancellation()
108+
{
109+
var response = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
110+
var timeoutTask = Task.CompletedTask;
111+
using var cancellation = new CancellationTokenSource();
112+
var cancellationTask = Task.Delay(Timeout.InfiniteTimeSpan, cancellation.Token);
113+
cancellation.Cancel();
114+
115+
var exception = await Assert.ThrowsAsync<TimeoutException>(() =>
116+
OpenClawGatewayClient.ResolveGatewayResponseAsync(
117+
response.Task,
118+
timeoutTask,
119+
cancellationTask,
120+
"expected timeout"));
121+
122+
Assert.Equal("expected timeout", exception.Message);
123+
}
124+
125+
private static OpenClawGatewayClient CreateClient(LoopbackWebSocketServer server, string identityPath)
126+
=> new(server.WebSocketUrl, "test-token", new TestLogger(), identityPath: identityPath);
127+
128+
private static async Task ConnectAsync(OpenClawGatewayClient client, LoopbackWebSocketServer server)
129+
{
130+
await client.ConnectAsync();
131+
var start = DateTime.UtcNow;
132+
while (server.AcceptedCount < 1)
133+
{
134+
if (DateTime.UtcNow - start > TimeSpan.FromSeconds(2))
135+
throw new TimeoutException("Loopback server did not accept the connection.");
136+
137+
// slopwatch-ignore: SW004 Test delay is an intentional bounded async wait; replacing it would change the scenario under test.
138+
await Task.Delay(25);
139+
}
140+
}
141+
142+
/// <summary>Reads server-side frames (skipping the connect handshake traffic) until
143+
/// one contains the marker, proving the request frame reached the wire.</summary>
144+
private static async Task WaitForFrameContainingAsync(
145+
LoopbackWebSocketServer server, string marker, TimeSpan timeout)
146+
{
147+
var socket = GetAcceptedSocket(server);
148+
var buffer = new byte[64 * 1024];
149+
using var cts = new CancellationTokenSource(timeout);
150+
while (true)
151+
{
152+
var message = new StringBuilder();
153+
WebSocketReceiveResult result;
154+
do
155+
{
156+
result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token);
157+
if (result.MessageType != WebSocketMessageType.Text)
158+
throw new InvalidOperationException($"Unexpected {result.MessageType} frame before '{marker}'.");
159+
160+
message.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
161+
} while (!result.EndOfMessage);
162+
163+
if (message.ToString().Contains(marker, StringComparison.Ordinal))
164+
return;
165+
}
166+
}
167+
168+
// Models the shutdown race from #1021: the lifetime token is cancelled while this
169+
// request's pending completion has not been faulted — the state a request reaches
170+
// when it registers after ClearPendingRequests has already swept the pending maps.
171+
private static void CancelLifetime(OpenClawGatewayClient client)
172+
{
173+
var field = typeof(WebSocketClientBase).GetField(
174+
"_cts", BindingFlags.Instance | BindingFlags.NonPublic);
175+
Assert.NotNull(field);
176+
((CancellationTokenSource)field!.GetValue(client)!).Cancel();
177+
}
178+
179+
private static WebSocket GetAcceptedSocket(LoopbackWebSocketServer server)
180+
{
181+
var field = typeof(LoopbackWebSocketServer).GetField(
182+
"_acceptedSockets", BindingFlags.Instance | BindingFlags.NonPublic);
183+
Assert.NotNull(field);
184+
var sockets = (List<WebSocket>)field!.GetValue(server)!;
185+
lock (sockets)
186+
{
187+
Assert.NotEmpty(sockets);
188+
return sockets[0];
189+
}
190+
}
191+
}

0 commit comments

Comments
 (0)