Skip to content

Commit f505ab1

Browse files
fix(tests): make node auto-approve tests deterministic
Replace Task.Delay timing waits with deterministic synchronisation signals: - Add postApproveDelay constructor parameter to GatewayConnectionManager (defaults to 1s for production; tests pass TimeSpan.Zero for instant completion) - Add internal AutoApproveDecisionCompleted event that fires when each auto-approve handler finishes (regardless of whether an approval was made) - Extract OnNodePairingStatusChanged auto-approve body into RunNodeSideAutoApproveAsync so the completion event fires from a single try/finally - Update NodePairListUpdated lambda to fire AutoApproveDecisionCompleted after TryOperatorAutoApproveOwnNodePairAsync returns - Replace all Task.Delay(200) negative-assertion waits and the Task.Delay(1100) post-approve wait with WaitForAutoApproveDecisionAsync helper Eliminates the timing-sensitive 1100ms wait that depended on the production 1s reconnect delay, plus six 200ms waits in negative-assertion tests. Closes #460 Co-authored-by: Copilot <[email protected]>
1 parent ef1afa3 commit f505ab1

2 files changed

Lines changed: 72 additions & 18 deletions

File tree

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,19 @@ public sealed class GatewayConnectionManager : IGatewayConnectionManager
3232
private bool _gatewayNeedsV2Signature; // remembered across reconnects
3333
private string? _lastAutoApprovedRequestId; // prevent auto-approve loops
3434
private string? _autoApproveInFlight; // atomic guard against concurrent approval of same requestId
35+
private readonly TimeSpan _postApproveDelay;
3536

3637
public event EventHandler<GatewayConnectionSnapshot>? StateChanged;
3738
public event EventHandler<ConnectionDiagnosticEvent>? DiagnosticEvent;
3839
public event EventHandler<OperatorClientChangedEventArgs>? OperatorClientChanged;
3940

41+
/// <summary>
42+
/// Fired after each auto-approve decision handler completes (regardless of whether an
43+
/// approval was attempted or granted). Exposed internally for test synchronisation so
44+
/// tests can replace <c>Task.Delay</c> waits with a deterministic signal.
45+
/// </summary>
46+
internal event EventHandler? AutoApproveDecisionCompleted;
47+
4048
public GatewayConnectionManager(
4149
ICredentialResolver credentialResolver,
4250
IGatewayClientFactory clientFactory,
@@ -48,7 +56,8 @@ public GatewayConnectionManager(
4856
Func<bool>? isNodeEnabled = null,
4957
ConnectionDiagnostics? diagnostics = null,
5058
ISshTunnelManager? tunnelManager = null,
51-
Func<GatewayRecord, string, bool>? shouldStartNodeConnection = null)
59+
Func<GatewayRecord, string, bool>? shouldStartNodeConnection = null,
60+
TimeSpan postApproveDelay = default)
5261
{
5362
_credentialResolver = credentialResolver ?? throw new ArgumentNullException(nameof(credentialResolver));
5463
_clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory));
@@ -62,6 +71,7 @@ public GatewayConnectionManager(
6271
_shouldStartNodeConnection = shouldStartNodeConnection;
6372
_diagnostics = diagnostics ?? new ConnectionDiagnostics(clock: clock);
6473
_diagnostics.EventRecorded += (_, e) => DiagnosticEvent?.Invoke(this, e);
74+
_postApproveDelay = postApproveDelay == default ? TimeSpan.FromSeconds(1) : postApproveDelay;
6575

6676
if (_nodeConnector != null)
6777
{
@@ -249,10 +259,17 @@ private async Task ConnectCoreAsync(string? gatewayId = null)
249259
// This complements (not replaces) the node-side flow on line ~810
250260
// which still handles the case where the node knows it's pending
251261
// before any operator event lands.
252-
lifecycle.DataClient.NodePairListUpdated += (s, info) =>
262+
lifecycle.DataClient.NodePairListUpdated += async (s, info) =>
253263
{
254264
if (Interlocked.Read(ref _generation) != gen) return;
255-
_ = TryOperatorAutoApproveOwnNodePairAsync(info, gen);
265+
try
266+
{
267+
await TryOperatorAutoApproveOwnNodePairAsync(info, gen);
268+
}
269+
finally
270+
{
271+
AutoApproveDecisionCompleted?.Invoke(this, EventArgs.Empty);
272+
}
256273
};
257274

258275
// If we already know this gateway needs v2, tell the client upfront
@@ -857,6 +874,18 @@ private async void OnNodePairingStatusChanged(object? sender, PairingStatusEvent
857874
_transitionSemaphore.Release();
858875
}
859876

877+
try
878+
{
879+
await RunNodeSideAutoApproveAsync(e);
880+
}
881+
finally
882+
{
883+
AutoApproveDecisionCompleted?.Invoke(this, EventArgs.Empty);
884+
}
885+
}
886+
887+
private async Task RunNodeSideAutoApproveAsync(PairingStatusEventArgs e)
888+
{
860889
// Auto-approve node pairing if operator has admin/pairing scope.
861890
// _autoApproveInFlight is a CAS guard scoped to JUST the approve RPC —
862891
// we release it before the reconnect delay so unrelated approvals
@@ -916,7 +945,7 @@ private async void OnNodePairingStatusChanged(object? sender, PairingStatusEvent
916945
if (approved)
917946
{
918947
_diagnostics.Record("node", "Node pairing auto-approved — reconnecting node");
919-
await Task.Delay(1000); // brief delay for gateway to process
948+
await Task.Delay(_postApproveDelay); // brief delay for gateway to process
920949
if (Interlocked.Read(ref _generation) == approvalGeneration)
921950
await StartNodeConnectionAsync();
922951
}
@@ -1010,7 +1039,7 @@ private async Task TryOperatorAutoApproveOwnNodePairAsync(PairingListInfo? info,
10101039
if (lastApprovedRequestId is not null)
10111040
{
10121041
_diagnostics.Record("node", $"Operator-side approved {lastApprovedRequestId} — reconnecting node so caps propagate");
1013-
await Task.Delay(1000);
1042+
await Task.Delay(_postApproveDelay);
10141043
if (Interlocked.Read(ref _generation) == gen)
10151044
await StartNodeConnectionAsync();
10161045
}

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

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ await FireAndWait(manager, () =>
7272
_nodeConnector.FireStatusChanged(ConnectionStatus.Connecting));
7373

7474
// Pending WITHOUT a requestId — auto-approval should not trigger.
75-
// Brief delay is acceptable here: we're asserting nothing happened.
75+
var decisionDone = WaitForAutoApproveDecisionAsync(manager);
7676
_nodeConnector.FirePairingStatusChanged(PairingStatus.Pending, requestId: null);
77-
await Task.Delay(200);
77+
await decisionDone;
7878

7979
Assert.Empty(lifecycle.TrackingClient.ApprovalMethodsCalled);
8080
}
@@ -92,8 +92,9 @@ await FireAndWait(manager, () =>
9292
_nodeConnector.FireStatusChanged(ConnectionStatus.Connecting));
9393

9494
// Insufficient scope — auto-approval should not trigger.
95+
var decisionDone = WaitForAutoApproveDecisionAsync(manager);
9596
_nodeConnector.FirePairingStatusChanged(PairingStatus.Pending, requestId: "req-123");
96-
await Task.Delay(200);
97+
await decisionDone;
9798

9899
Assert.Empty(lifecycle.TrackingClient.ApprovalMethodsCalled);
99100
}
@@ -119,12 +120,13 @@ await FireAndWait(manager, () =>
119120
await firstEntered; // First call has entered NodePairApproveAsync but is blocked
120121

121122
// Fire second event while first is still in-flight — CAS guard should reject
123+
var secondDecision = WaitForAutoApproveDecisionAsync(manager);
122124
_nodeConnector.FirePairingStatusChanged(PairingStatus.Pending, requestId: "req-same");
123-
await Task.Delay(200); // brief wait for the second handler to run and be rejected
125+
await secondDecision; // second handler has been rejected by CAS guard
124126

125127
// Release the blocked first approval
126128
lifecycle.TrackingClient.ReleaseApproveGate();
127-
await Task.Delay(200); // let it complete
129+
await Task.Delay(50); // let it complete
128130

129131
// Only one approval call should have been made
130132
Assert.Equal(1, lifecycle.TrackingClient.ApprovalMethodsCalled
@@ -182,14 +184,15 @@ public async Task OperatorSideAutoApprove_IgnoresPendingForOtherNodeId()
182184
lifecycle.TrackingClient.SetIsConnected(true);
183185
_nodeConnector.NodeDeviceId = "f52d5187...own";
184186

187+
var decisionDone = WaitForAutoApproveDecisionAsync(manager);
185188
lifecycle.TrackingClient.FireNodePairListUpdated(new PairingListInfo
186189
{
187190
Pending =
188191
[
189192
new PairingRequest { RequestId = "req-someone-else", NodeId = "different-node-id" }
190193
]
191194
});
192-
await Task.Delay(200);
195+
await decisionDone;
193196

194197
Assert.Empty(lifecycle.TrackingClient.ApprovalMethodsCalled);
195198
}
@@ -204,14 +207,15 @@ public async Task OperatorSideAutoApprove_WithoutScope_DoesNotApprove()
204207
lifecycle.TrackingClient.SetIsConnected(true);
205208
_nodeConnector.NodeDeviceId = "own-id";
206209

210+
var decisionDone = WaitForAutoApproveDecisionAsync(manager);
207211
lifecycle.TrackingClient.FireNodePairListUpdated(new PairingListInfo
208212
{
209213
Pending =
210214
[
211215
new PairingRequest { RequestId = "req-no-scope", NodeId = "own-id" }
212216
]
213217
});
214-
await Task.Delay(200);
218+
await decisionDone;
215219

216220
Assert.Empty(lifecycle.TrackingClient.ApprovalMethodsCalled);
217221
}
@@ -229,8 +233,9 @@ public async Task OperatorSideAutoApprove_NodeSideSkippedWithoutScope_CanStillAp
229233
await FireAndWait(manager, () =>
230234
_nodeConnector.FireStatusChanged(ConnectionStatus.Connecting));
231235

236+
var firstDecision = WaitForAutoApproveDecisionAsync(manager);
232237
_nodeConnector.FirePairingStatusChanged(PairingStatus.Pending, requestId: "req-same-later-scope");
233-
await Task.Delay(200);
238+
await firstDecision;
234239
Assert.Empty(lifecycle.TrackingClient.ApprovalMethodsCalled);
235240

236241
lifecycle.TrackingClient.SetGrantedScopes(["operator.admin"]);
@@ -255,21 +260,23 @@ public async Task OperatorSideAutoApprove_SameRequestId_DoesNotApproveTwice()
255260
_nodeConnector.NodeDeviceId = "own-id";
256261

257262
var firstDone = lifecycle.TrackingClient.WaitForApprovalCallAsync();
263+
var firstDecision = WaitForAutoApproveDecisionAsync(manager);
258264
lifecycle.TrackingClient.FireNodePairListUpdated(new PairingListInfo
259265
{
260266
Pending = [new PairingRequest { RequestId = "dedupe-1", NodeId = "own-id" }]
261267
});
262268
await firstDone;
263-
// Wait for the post-approve sequence to complete before firing the
264-
// second event; _lastAutoApprovedRequestId must be set first.
265-
await Task.Delay(1100);
269+
// Wait for the full post-approve sequence (including _lastAutoApprovedRequestId being set)
270+
// before firing the second event. With postApproveDelay:Zero this completes immediately.
271+
await firstDecision;
266272

267273
// Re-broadcast (same id) — must be skipped via _lastAutoApprovedRequestId.
274+
var secondDecision = WaitForAutoApproveDecisionAsync(manager);
268275
lifecycle.TrackingClient.FireNodePairListUpdated(new PairingListInfo
269276
{
270277
Pending = [new PairingRequest { RequestId = "dedupe-1", NodeId = "own-id" }]
271278
});
272-
await Task.Delay(200);
279+
await secondDecision;
273280

274281
Assert.Equal(1, lifecycle.TrackingClient.ApprovalMethodsCalled
275282
.Count(m => m == "node.pair.approve"));
@@ -289,12 +296,30 @@ private GatewayConnectionManager CreateConnectedManager()
289296
var manager = new GatewayConnectionManager(
290297
_resolver, _factory, _registry, NullLogger.Instance,
291298
nodeConnector: _nodeConnector,
292-
isNodeEnabled: () => true);
299+
isNodeEnabled: () => true,
300+
postApproveDelay: TimeSpan.Zero);
293301

294302
manager.ConnectAsync("gw1").GetAwaiter().GetResult();
295303
return manager;
296304
}
297305

306+
/// <summary>
307+
/// Returns a task that completes when the manager's next auto-approve decision handler
308+
/// fires <see cref="GatewayConnectionManager.AutoApproveDecisionCompleted"/>.
309+
/// Use instead of <c>Task.Delay</c> for deterministic negative-assertion synchronisation.
310+
/// </summary>
311+
private static Task WaitForAutoApproveDecisionAsync(GatewayConnectionManager manager, int timeoutMs = 5000)
312+
{
313+
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
314+
void Handler(object? _, EventArgs __)
315+
{
316+
manager.AutoApproveDecisionCompleted -= Handler;
317+
tcs.TrySetResult();
318+
}
319+
manager.AutoApproveDecisionCompleted += Handler;
320+
return tcs.Task.WaitAsync(TimeSpan.FromMilliseconds(timeoutMs));
321+
}
322+
298323
private static async Task<GatewayConnectionSnapshot> FireAndWait(
299324
GatewayConnectionManager manager, Action action, int timeoutMs = 5000)
300325
{

0 commit comments

Comments
 (0)