Skip to content

Commit 34c1f90

Browse files
fix: classify gateway response wait outcomes
Co-authored-by: Cameron Beeley <[email protected]>
2 parents dff33f7 + 93174b2 commit 34c1f90

8 files changed

Lines changed: 463 additions & 42 deletions

File tree

‎src/OpenClaw.Connection/NodeConnector.cs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,17 @@ private bool IsCurrentClient(object? sender, long generation)
221221
// Validation and dispatch stay atomic so a retired client cannot publish after its
222222
// replacement. Subscribers must remain synchronous and must not block on connector
223223
// lifecycle work while this lock is held.
224+
//
225+
// Lock ordering: _connectSemaphore (async, serialises connect/disconnect) may be
226+
// held when _clientLifecycleLock is acquired, but subscribers never acquire
227+
// _connectSemaphore. Among monitor locks, _clientLifecycleLock is the outermost
228+
// in the connector's acquisition graph. Subscribers may acquire their own locks
229+
// (GatewayConnectionManager._telemetryLock, GatewayRegistry._lock,
230+
// ConnectionDiagnostics._lock) but code holding those locks must not
231+
// synchronously enter connector lifecycle operations, preserving a consistent
232+
// acquisition order that prevents deadlock. Subscriber handlers must return
233+
// promptly; current subscribers use fire-and-forget async dispatch for heavy
234+
// work and perform only lightweight synchronous preambles.
224235
private void ForwardIfCurrent<T>(
225236
object? sender,
226237
long generation,

‎src/OpenClaw.Shared/Markdown/Md4c/Md4cParser.Block.cs‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,11 @@ private int ConsumeLinkReferenceDefinitions()
631631
Debug.Assert(currentBlockIndex >= 0);
632632

633633
int nLines = CurrentBlock.NLines;
634-
int lineStart = GetCurrentBlockLineStart();
634+
// O(1) line-start: the current block's lines are the tail of blockLines — the same computation
635+
// the reference-def removal below (blockLines.Count - nLines) already relies on. Replaces the
636+
// former GetCurrentBlockLineStart() per-block-close O(n) scan over all prior blocks, which made
637+
// list parsing O(n^2) (one close per list item).
638+
int lineStart = blockLines.Count - nLines;
635639
int n = 0;
636640

637641
while (n < nLines)
@@ -675,7 +679,7 @@ private int EndCurrentBlock()
675679
if (CurrentBlock.Type == MarkdownBlockType.P ||
676680
(CurrentBlock.Type == MarkdownBlockType.H && (CurrentBlock.Flags & BLOCK_SETEXT_HEADER) != 0))
677681
{
678-
int lineStart = GetCurrentBlockLineStart();
682+
int lineStart = blockLines.Count - CurrentBlock.NLines;
679683
if (lineStart < blockLines.Count)
680684
{
681685
var span = CollectionsMarshal.AsSpan(blockLines);
@@ -761,21 +765,6 @@ private ref Block CurrentBlock
761765
get => ref CollectionsMarshal.AsSpan(blocks)[currentBlockIndex];
762766
}
763767

764-
private int GetCurrentBlockLineStart()
765-
{
766-
int lineIdx = 0;
767-
var span = CollectionsMarshal.AsSpan(blocks);
768-
for (int i = 0; i < currentBlockIndex; i++)
769-
{
770-
ref Block b = ref span[i];
771-
if ((b.Flags & BLOCK_CONTAINER) != 0)
772-
continue;
773-
if (b.Type != MarkdownBlockType.Code && b.Type != MarkdownBlockType.Html)
774-
lineIdx += b.NLines;
775-
}
776-
return lineIdx;
777-
}
778-
779768
// ── Line Analysis ────────────────────────────────────────────────────
780769

781770
private bool IsHrLine(int beg, out int pEnd, out int pKiller)

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 59 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -364,18 +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-
// A cancelled delay is client shutdown, not an elapsed gateway timeout.
372-
CancellationToken.ThrowIfCancellationRequested();
373-
throw new TimeoutException("Timed out waiting for chat.send response from gateway");
374380
}
375-
376-
var result = await completion.Task.ConfigureAwait(false);
377-
_logger.Info($"Sent chat message ({message.Length} chars{(hasAttachments ? $", {attachments!.Count} attachment(s)" : "")})");
378-
return result;
379381
}
380382

381383
Task IOperatorGatewayClient.SendChatMessageAsync(string message, string? sessionKey) =>
@@ -493,25 +495,59 @@ public async Task ResolveExecApprovalAsync(string approvalId, string decision)
493495
// traverse gateway → operator → optional UI confirm → ack, so we give
494496
// it a larger budget than the chat.send sibling's 5s. A timeout keeps
495497
// the banner visible for the user to retry rather than hanging the UI.
496-
var delayTask = Task.Delay(15000, CancellationToken);
497-
await Task.WhenAny(completion.Task, delayTask);
498-
499-
// Use IsCompleted directly rather than Task.WhenAny's return identity:
500-
// when both tasks complete in the same scheduling tick, WhenAny may
501-
// return the delay task even though the TCS is already complete, which
502-
// would otherwise surface as a spurious TimeoutException and discard a
503-
// real ok:true / ok:false response.
504-
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
505507
{
506508
_pendingApprovalResolves.TryRemove(requestId, out _);
507509
RemovePendingRequest(requestId);
508-
// A cancelled delay is client shutdown, not an elapsed gateway timeout.
509-
CancellationToken.ThrowIfCancellationRequested();
510-
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");
511548
}
512549

513-
// Propagate any exception (ok:false, disconnect) stored on the TCS.
514-
await completion.Task.ConfigureAwait(false);
550+
throw new TimeoutException(timeoutMessage);
515551
}
516552

517553
private static bool IsValidApprovalDecision(string decision)

‎src/OpenClaw.Shared/WebSocketClientBase.cs‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -471,9 +471,38 @@ await ws.SendAsync(buffer.AsMemory(0, written),
471471
protected async Task CloseWebSocketAsync()
472472
{
473473
var ws = _webSocket;
474-
if (ws?.State == WebSocketState.Open)
474+
if (ws?.State != WebSocketState.Open)
475+
return;
476+
477+
try
478+
{
479+
await _sendLock.WaitAsync(_cts.Token);
480+
}
481+
catch (OperationCanceledException)
482+
{
483+
// Shutdown canceled the wait; no close ownership was acquired.
484+
return;
485+
}
486+
catch (ObjectDisposedException)
475487
{
476-
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Disconnecting", System.Threading.CancellationToken.None);
488+
// Send lock or lifetime token was disposed during shutdown.
489+
return;
490+
}
491+
492+
try
493+
{
494+
if (ws.State == WebSocketState.Open)
495+
{
496+
// Preserve normal graceful close; concurrent Dispose aborts the socket and callers contain that failure.
497+
await ws.CloseAsync(
498+
WebSocketCloseStatus.NormalClosure,
499+
"Disconnecting",
500+
CancellationToken.None);
501+
}
502+
}
503+
finally
504+
{
505+
_sendLock.Release();
477506
}
478507
}
479508

‎tests/OpenClaw.Connection.Tests/NodeConnectorTests.cs‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Reflection;
12
using OpenClaw.Shared;
23
using OpenClaw.Connection;
34

@@ -136,4 +137,105 @@ public void Dispose_IsIdempotent()
136137
connector.Dispose();
137138
connector.Dispose(); // second call should not throw
138139
}
140+
141+
[Fact]
142+
public async Task Reconnect_SuppressesStatusFromRetiredClient()
143+
{
144+
using var connector = new NodeConnector(new StubLogger());
145+
var statuses = new List<ConnectionStatus>();
146+
connector.StatusChanged += (_, status) => statuses.Add(status);
147+
148+
await connector.ConnectAsync(
149+
"ws://127.0.0.1:1",
150+
new GatewayCredential("tok", false, "test"),
151+
"id-path");
152+
var clientA = connector.Client;
153+
Assert.NotNull(clientA);
154+
155+
await connector.ConnectAsync(
156+
"ws://127.0.0.1:2",
157+
new GatewayCredential("tok2", false, "test"),
158+
"id-path");
159+
var clientB = connector.Client;
160+
Assert.NotNull(clientB);
161+
Assert.NotSame(clientA, clientB);
162+
statuses.Clear();
163+
164+
// Retired client A — generation mismatch, must be suppressed.
165+
RaiseClientStatus(clientA, ConnectionStatus.Connected);
166+
Assert.Empty(statuses);
167+
168+
// Current client B — generation matches, must be forwarded.
169+
RaiseClientStatus(clientB, ConnectionStatus.Connected);
170+
Assert.Single(statuses);
171+
Assert.Equal(ConnectionStatus.Connected, statuses[0]);
172+
}
173+
174+
[Fact]
175+
public async Task Disconnect_RetiresClient_SuppressesForwarding()
176+
{
177+
using var connector = new NodeConnector(new StubLogger());
178+
179+
await connector.ConnectAsync(
180+
"ws://127.0.0.1:1",
181+
new GatewayCredential("tok", false, "test"),
182+
"id-path");
183+
var retiredClient = connector.Client;
184+
Assert.NotNull(retiredClient);
185+
186+
await connector.DisconnectAsync();
187+
188+
var forwardedConnected = false;
189+
connector.StatusChanged += (_, status) =>
190+
forwardedConnected |= status == ConnectionStatus.Connected;
191+
RaiseClientStatus(retiredClient, ConnectionStatus.Connected);
192+
193+
Assert.Null(connector.Client);
194+
Assert.Equal(NodeConnectionMode.Disabled, connector.Mode);
195+
Assert.False(forwardedConnected);
196+
}
197+
198+
[Fact]
199+
public async Task CurrentClientStatusHandler_CanReadConnectorProperties_WithoutBlocking()
200+
{
201+
using var connector = new NodeConnector(new StubLogger());
202+
bool? wasConnected = null;
203+
PairingStatus? pairingStatus = null;
204+
NodeConnectionMode? mode = null;
205+
WindowsNodeClient? clientRef = null;
206+
207+
await connector.ConnectAsync(
208+
"ws://127.0.0.1:1",
209+
new GatewayCredential("tok", false, "test"),
210+
"id-path");
211+
var currentClient = connector.Client;
212+
Assert.NotNull(currentClient);
213+
214+
connector.StatusChanged += (_, status) =>
215+
{
216+
if (status != ConnectionStatus.Connecting)
217+
return;
218+
219+
wasConnected = connector.IsConnected;
220+
pairingStatus = connector.PairingStatus;
221+
mode = connector.Mode;
222+
clientRef = connector.Client;
223+
};
224+
225+
RaiseClientStatus(currentClient, ConnectionStatus.Connecting);
226+
227+
Assert.False(wasConnected);
228+
Assert.Equal(PairingStatus.Unknown, pairingStatus);
229+
Assert.Equal(NodeConnectionMode.Gateway, mode);
230+
Assert.Same(currentClient, clientRef);
231+
}
232+
233+
private static void RaiseClientStatus(WindowsNodeClient client, ConnectionStatus status)
234+
{
235+
var method = typeof(WebSocketClientBase).GetMethod(
236+
"RaiseStatusChanged",
237+
BindingFlags.Instance | BindingFlags.NonPublic);
238+
Assert.NotNull(method);
239+
method.Invoke(client, [status]);
240+
}
139241
}

‎tests/OpenClaw.Shared.Tests/GatewayRequestShutdownClassificationTests.cs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,42 @@ public async Task ResolveExecApproval_RealDisposeDuringWait_SurfacesCancellation
8686
"disposal must surface as cancellation instead of waiting out the 15s approval budget");
8787
}
8888

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+
89125
private static OpenClawGatewayClient CreateClient(LoopbackWebSocketServer server, string identityPath)
90126
=> new(server.WebSocketUrl, "test-token", new TestLogger(), identityPath: identityPath);
91127

0 commit comments

Comments
 (0)