Skip to content

Commit 15ed439

Browse files
shanselmanCopilot
andauthored
test+doc: harden ForwardIfCurrent dispatch-under-lock invariant (#1010) (#1022)
Exercises the real ForwardIfCurrent event path by invoking WebSocketClientBase.RaiseStatusChanged via reflection on captured WindowsNodeClient instances. This proves: - Reconnect: StatusChanged on retired client A is suppressed by the generation check; events on current client B are forwarded. - Disconnect: StatusChanged on a retired client is suppressed after disconnect (generation mismatch + null _client). - Reentrancy safety: a StatusChanged subscriber can read IsConnected/PairingStatus/Mode/Client without blocking, observing consistent values from inside the _clientLifecycleLock scope. Documents the lock ordering invariant at ForwardIfCurrent: this lock is outermost; subscriber-owned locks must not re-enter connector lifecycle operations. Ref: #1010 (hazard 2) Copilot-Session: 102b1f54-0707-4f84-9f7f-dc254b38de70 Co-authored-by: Copilot App <[email protected]>
1 parent 9b5ce4b commit 15ed439

2 files changed

Lines changed: 113 additions & 0 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,

‎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
}

0 commit comments

Comments
 (0)