Skip to content

Commit 55f93df

Browse files
fix(setup): cancel node pairing cleanly instead of a spurious timeout warning + wasted retry
On a user cancel during node pairing, the step logged a misleading "Node connection failed: Timeout" and burned a retry (PairNodeStep has MaxAttempts=3) before the pipeline reported Cancelled — the final outcome is Cancelled either way, but via a spurious failure narrative and a wasted retry delay. WaitForNodeConnection caught every OperationCanceledException as Timeout, and PairNodeStep's catch-all re-swallowed it into StepResult.Fail. Guard the Timeout mapping with when (!ct.IsCancellationRequested) and add the file's existing cancel-rethrow idiom (SetupSteps.cs:1725, :2044) to PairNodeStep, so a caller cancel propagates and the pipeline maps it to Cancelled immediately — no failure warning, no retry. Tests (SetupEngine.Tests), all red on base / green on HEAD except the timeout guard: - SetupPipeline_CallerCancel_CancelsCleanlyWithoutFailureNarrative: drives the REAL pipeline and asserts the full contract — Cancelled/exit 3, no 'connection failed'/retry warning, pipeline_cancelled journal (not a failed-step narrative). - PairNodeStep_CallerCancellation + WaitForNodeConnection_CallerCancellation: the two catch boundaries, cancelled from a deterministic WS-upgrade barrier (no timing guess). - WaitForNodeConnection_GenuineInternalTimeout: a real internal timeout still maps to Timeout.
1 parent 9fb1960 commit 55f93df

5 files changed

Lines changed: 322 additions & 2 deletions

File tree

‎src/OpenClaw.SetupEngine/SetupSteps.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2257,6 +2257,13 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
22572257

22582258
return StepResult.Fail($"Node connection failed: {outcome.Outcome}");
22592259
}
2260+
catch (OperationCanceledException) when (ct.IsCancellationRequested)
2261+
{
2262+
// Let a caller-driven cancel propagate so the pipeline reports Cancelled,
2263+
// not a Failed step — the catch-all below would otherwise convert it back
2264+
// into StepResult.Fail (same idiom as the other steps' cancel rethrow).
2265+
throw;
2266+
}
22602267
catch (Exception ex)
22612268
{
22622269
return StepResult.Fail($"Node pairing failed: {ex.Message}", ex);
@@ -2387,8 +2394,11 @@ void OnPairingStatusChanged(object? sender, PairingStatusEventArgs args)
23872394
cts.CancelAfter(timeout);
23882395
return await tcs.Task.WaitAsync(cts.Token);
23892396
}
2390-
catch (OperationCanceledException)
2397+
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
23912398
{
2399+
// Only the internal CancelAfter(timeout) firing is a Timeout; a caller
2400+
// (user aborting setup) cancelling `ct` must propagate so the pipeline
2401+
// reports Cancelled, rather than being misreported as a node timeout.
23922402
return new NodeConnectionResult(NodeConnectionOutcome.Timeout);
23932403
}
23942404
finally

‎tests/OpenClaw.SetupEngine.Tests/OpenClaw.SetupEngine.Tests.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
<ItemGroup>
44
<ProjectReference Include="..\..\src\OpenClaw.SetupEngine\OpenClaw.SetupEngine.csproj" />
5+
<ProjectReference Include="..\OpenClaw.TestSupport\OpenClaw.TestSupport.csproj" />
56
</ItemGroup>
67

78
</Project>
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
using System;
2+
using System.Linq;
3+
using System.Reflection;
4+
using System.Threading;
5+
using System.Threading.Tasks;
6+
using OpenClaw.Shared;
7+
using OpenClaw.TestSupport;
8+
using Xunit;
9+
using Xunit.Abstractions;
10+
11+
namespace OpenClaw.SetupEngine.Tests;
12+
13+
/// <summary>
14+
/// Helper-level coverage for the node-pairing cancellation fix. The durable end-to-end
15+
/// contract (Cancelled outcome + no retry warning + cancellation journal) is asserted at the
16+
/// pipeline level in <c>SetupStepsTests.SetupPipeline_CallerCancel_*</c>; these tests pin the
17+
/// two catch-filter boundaries directly: a caller cancel must propagate as an
18+
/// <see cref="OperationCanceledException"/>, while a genuine internal timeout must still map to
19+
/// <see cref="NodeConnectionOutcome.Timeout"/>.
20+
/// </summary>
21+
public sealed class SetupNodeConnectCancellationTests : IDisposable
22+
{
23+
private readonly ITestOutputHelper _output;
24+
private readonly string _dataDir;
25+
26+
public SetupNodeConnectCancellationTests(ITestOutputHelper output)
27+
{
28+
_output = output;
29+
_dataDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "setup-cancel-" + Guid.NewGuid().ToString("N"));
30+
System.IO.Directory.CreateDirectory(_dataDir);
31+
}
32+
33+
public void Dispose()
34+
{
35+
try { System.IO.Directory.Delete(_dataDir, recursive: true); } catch { /* best effort */ }
36+
}
37+
38+
// Bind by full signature (not just name) so a signature change fails loudly here rather than
39+
// silently matching the wrong overload — per reviewer feedback on brittle reflection.
40+
private static MethodInfo ResolveWaitForNodeConnection()
41+
{
42+
var candidates = typeof(SetupStep).Assembly.GetTypes()
43+
.SelectMany(t => t.GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
44+
.Where(m => m.Name == "WaitForNodeConnection")
45+
.Where(m =>
46+
{
47+
var p = m.GetParameters();
48+
return p.Length == 4
49+
&& p[0].ParameterType == typeof(WindowsNodeClient)
50+
&& p[1].ParameterType == typeof(SetupContext)
51+
&& p[2].ParameterType == typeof(TimeSpan)
52+
&& p[3].ParameterType == typeof(CancellationToken);
53+
})
54+
.ToList();
55+
Assert.True(candidates.Count == 1,
56+
$"Expected exactly one private static WaitForNodeConnection(WindowsNodeClient, SetupContext, TimeSpan, " +
57+
$"CancellationToken); found {candidates.Count}. If the signature moved, update this test.");
58+
return candidates[0];
59+
}
60+
61+
private SetupContext MakeContext()
62+
{
63+
var logger = new SetupLogger(filePath: null, LogLevel.Trace);
64+
return new SetupContext(
65+
new SetupConfig(), logger, new TransactionJournal(filePath: null),
66+
new CommandRunner(logger), CancellationToken.None,
67+
dataDir: _dataDir, localDataDir: _dataDir);
68+
}
69+
70+
[Fact]
71+
public async Task WaitForNodeConnection_CallerCancellation_PropagatesInsteadOfTimeout()
72+
{
73+
using var server = new SilentWebSocketServer();
74+
var ctx = MakeContext();
75+
using var client = new WindowsNodeClient($"ws://127.0.0.1:{server.Port}", "test-token-placeholder", _dataDir);
76+
77+
using var callerCts = new CancellationTokenSource();
78+
// 15s internal timeout window; the caller cancels only AFTER the WS upgrade barrier, so
79+
// the method is provably in its wait — not a 300ms guess about handshake timing.
80+
var task = (Task)ResolveWaitForNodeConnection().Invoke(null,
81+
new object[] { client, ctx, TimeSpan.FromSeconds(15), callerCts.Token })!;
82+
await server.UpgradeCompleted;
83+
callerCts.Cancel();
84+
85+
try
86+
{
87+
await task.WaitAsync(TimeSpan.FromSeconds(30));
88+
var result = task.GetType().GetProperty("Result")!.GetValue(task)!;
89+
var outcome = result.GetType().GetProperty("Outcome")!.GetValue(result)!.ToString();
90+
Assert.Fail($"Caller cancellation was misclassified: returned Outcome={outcome} " +
91+
"(the 15s internal timeout never elapsed). Expected OperationCanceledException.");
92+
}
93+
catch (OperationCanceledException)
94+
{
95+
_output.WriteLine("caller cancellation propagated as OperationCanceledException");
96+
}
97+
}
98+
99+
[Fact]
100+
public async Task WaitForNodeConnection_GenuineInternalTimeout_StillMapsToTimeout()
101+
{
102+
using var server = new SilentWebSocketServer();
103+
var ctx = MakeContext();
104+
using var client = new WindowsNodeClient($"ws://127.0.0.1:{server.Port}", "test-token-placeholder", _dataDir);
105+
106+
// No caller cancellation — the internal CancelAfter(timeout) is the only thing that fires.
107+
// This must still be classified as Timeout (the fix only diverts caller-driven cancels).
108+
var task = (Task)ResolveWaitForNodeConnection().Invoke(null,
109+
new object[] { client, ctx, TimeSpan.FromMilliseconds(200), CancellationToken.None })!;
110+
111+
await task.WaitAsync(TimeSpan.FromSeconds(30));
112+
var result = task.GetType().GetProperty("Result")!.GetValue(task)!;
113+
var outcome = result.GetType().GetProperty("Outcome")!.GetValue(result)!.ToString();
114+
_output.WriteLine($"genuine internal timeout → Outcome={outcome}");
115+
Assert.Equal("Timeout", outcome);
116+
}
117+
}

‎tests/OpenClaw.SetupEngine.Tests/SetupStepsTests.cs‎

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using OpenClaw.Connection;
2+
using OpenClaw.TestSupport;
23
using System.Net;
34
using System.Net.Sockets;
45
using System.Runtime.InteropServices;
56
using System.Text.Json;
7+
using Xunit.Abstractions;
68

79
namespace OpenClaw.SetupEngine.Tests;
810

@@ -13,11 +15,13 @@ public class SetupStepsTests : IDisposable
1315
private readonly string _localTempDir;
1416
private readonly string? _prevDataDir;
1517
private readonly string? _prevLocalDataDir;
18+
private readonly ITestOutputHelper _output;
1619
private const string DevicePairPluginNotFoundOutput = "plugins.entries.device-pair: plugin not found: device-pair";
1720
private const string OtherPluginNotFoundOutput = "plugins.entries.other-plugin: plugin not found: other-plugin";
1821

19-
public SetupStepsTests()
22+
public SetupStepsTests(ITestOutputHelper output)
2023
{
24+
_output = output;
2125
_tempDir = Path.Combine(Path.GetTempPath(), $"steps-test-{Guid.NewGuid():N}");
2226
_localTempDir = Path.Combine(Path.GetTempPath(), $"steps-local-test-{Guid.NewGuid():N}");
2327
Directory.CreateDirectory(_tempDir);
@@ -2195,6 +2199,112 @@ private SetupContext CreatePairingContext(string failureStdout)
21952199
return ctx;
21962200
}
21972201

2202+
// Shared scenario for the node-pairing cancellation tests: a reachable gateway HTTP endpoint (so
2203+
// WindowsGatewayReachability.VerifyAsync passes), a silent WebSocket the node client parks against,
2204+
// a fake WSL runner whose approval drain is empty, and a seeded gateway registry record — enough to
2205+
// drive the REAL PairNodeStep to its node-connection wait. `ctxToken` becomes the SetupContext's
2206+
// CancellationToken (used by the pipeline); pass CancellationToken.None when cancelling the step call
2207+
// directly. The caller disposes the returned `ws`/`http`.
2208+
private (SetupContext ctx, SilentWebSocketServer ws, HttpListener http, SetupLogger logger)
2209+
BuildNodePairingScenario(CancellationToken ctxToken)
2210+
{
2211+
var httpPort = GetFreeTcpPort();
2212+
var http = new HttpListener();
2213+
http.Prefixes.Add($"http://localhost:{httpPort}/");
2214+
http.Start();
2215+
_ = Task.Run(async () =>
2216+
{
2217+
while (http.IsListening)
2218+
{
2219+
HttpListenerContext c;
2220+
try { c = await http.GetContextAsync(); }
2221+
catch { return; }
2222+
c.Response.StatusCode = 200;
2223+
c.Response.Close();
2224+
}
2225+
});
2226+
2227+
var ws = new SilentWebSocketServer();
2228+
var commands = new FakeCommandRunner(_ => Ok(), (_, _, _) => Ok(stdout: "No pending device approvals"));
2229+
var logger = new SetupLogger(filePath: null, LogLevel.Trace);
2230+
var ctx = new SetupContext(
2231+
new SetupConfig { GatewayPort = httpPort }, logger,
2232+
new TransactionJournal(filePath: null), commands, ctxToken);
2233+
ctx.DistroName = "test-distro";
2234+
ctx.SharedGatewayToken = "test-token-placeholder";
2235+
ctx.GatewayUrl = $"ws://127.0.0.1:{ws.Port}";
2236+
ctx.GatewayRecordId = "test-gw";
2237+
2238+
var registry = new GatewayRegistry(_tempDir);
2239+
registry.Load();
2240+
registry.AddOrUpdate(new GatewayRecord
2241+
{
2242+
Id = "test-gw",
2243+
Url = ctx.GatewayUrl,
2244+
IsLocal = true,
2245+
SetupManagedDistroName = ctx.DistroName,
2246+
SshTunnel = null,
2247+
});
2248+
registry.Save();
2249+
return (ctx, ws, http, logger);
2250+
}
2251+
2252+
// The step itself must rethrow a caller cancel rather than swallow it into StepResult.Fail.
2253+
[Fact]
2254+
public async Task PairNodeStep_CallerCancellation_PropagatesInsteadOfFailing()
2255+
{
2256+
var (ctx, ws, http, _) = BuildNodePairingScenario(CancellationToken.None);
2257+
using (ws)
2258+
using (http)
2259+
{
2260+
using var callerCts = new CancellationTokenSource();
2261+
var task = new PairNodeStep().ExecuteAsync(ctx, callerCts.Token);
2262+
await ws.UpgradeCompleted; // deterministic barrier: the client is in its node-connection wait
2263+
callerCts.Cancel();
2264+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
2265+
}
2266+
}
2267+
2268+
// Durable end-to-end contract (the user-visible behavior the PR promises): driving the REAL
2269+
// SetupPipeline with the real PairNodeStep and a caller cancel, the pipeline reports Cancelled/exit 3,
2270+
// emits NO "connection failed"/retry warning, and journals the abort as a cancellation — not a
2271+
// failed-step narrative. On base the step's retry masks the *outcome* to Cancelled too, so the
2272+
// log/journal assertions are what actually pin this fix.
2273+
[Fact]
2274+
public async Task SetupPipeline_CallerCancel_CancelsCleanlyWithoutFailureNarrative()
2275+
{
2276+
using var callerCts = new CancellationTokenSource();
2277+
var (ctx, ws, http, logger) = BuildNodePairingScenario(callerCts.Token);
2278+
using (ws)
2279+
using (http)
2280+
{
2281+
var logs = new List<LogEntry>();
2282+
logger.LogEmitted += (_, e) => { lock (logs) { logs.Add(e); } };
2283+
2284+
var pipeline = new SetupPipeline(new SetupStep[] { new PairNodeStep() }, rollbackOnFailureOverride: false);
2285+
var run = pipeline.RunAsync(ctx);
2286+
await ws.UpgradeCompleted;
2287+
callerCts.Cancel();
2288+
var result = await run;
2289+
2290+
_output.WriteLine($"SetupPipeline on caller-cancel → Outcome={result.Outcome}, ExitCode={result.ExitCode}");
2291+
2292+
// 1. user-observable outcome
2293+
Assert.Equal(PipelineOutcome.Cancelled, result.Outcome);
2294+
Assert.Equal(3, result.ExitCode);
2295+
2296+
// 2. no misleading connection-failure / retry warning for a user abort
2297+
List<LogEntry> snapshot;
2298+
lock (logs) { snapshot = logs.ToList(); }
2299+
Assert.DoesNotContain(snapshot, e => e.Message.Contains("Node connection failed", StringComparison.OrdinalIgnoreCase));
2300+
Assert.DoesNotContain(snapshot, e => e.Level == LogLevel.Warn && e.Message.Contains("retrying", StringComparison.OrdinalIgnoreCase));
2301+
2302+
// 3. journal records the cancellation, not a failed-step narrative
2303+
Assert.Contains(ctx.Journal.Entries, en => en.Event == "pipeline_cancelled");
2304+
Assert.DoesNotContain(ctx.Journal.Entries, en => en.Event == "pipeline_failed");
2305+
}
2306+
}
2307+
21982308
private sealed class FakeCommandRunner(
21992309
Func<string[], CommandResult> run,
22002310
Func<string, string, TimeSpan, CommandResult>? runInWsl = null) : ICommandRunner
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
using System.Net;
2+
using System.Net.Sockets;
3+
using System.Security.Cryptography;
4+
using System.Text;
5+
6+
namespace OpenClaw.TestSupport;
7+
8+
/// <summary>
9+
/// Loopback WebSocket server that completes the upgrade handshake and then stays
10+
/// silent — the client connects successfully but never receives a message, so code
11+
/// that waits for a gateway challenge/response parks in its wait. Lets a test drive
12+
/// the real <c>ClientWebSocket</c> connect path and then exercise cancellation while
13+
/// the wait is in flight, without any running gateway. Shared single source so the
14+
/// helper can't drift across test projects.
15+
/// </summary>
16+
public sealed class SilentWebSocketServer : IDisposable
17+
{
18+
private readonly TcpListener _listener;
19+
private readonly CancellationTokenSource _cts = new();
20+
private readonly TaskCompletionSource _upgraded =
21+
new(TaskCreationOptions.RunContinuationsAsynchronously);
22+
23+
/// <summary>The loopback port the server is listening on (use as <c>ws://127.0.0.1:{Port}</c>).</summary>
24+
public int Port { get; }
25+
26+
/// <summary>Completes once the server has sent the WebSocket 101 upgrade to a client — a
27+
/// deterministic barrier a test can await before cancelling, instead of guessing a delay.</summary>
28+
public Task UpgradeCompleted => _upgraded.Task;
29+
30+
public SilentWebSocketServer()
31+
{
32+
_listener = new TcpListener(IPAddress.Loopback, 0);
33+
_listener.Start();
34+
Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
35+
_ = AcceptLoopAsync();
36+
}
37+
38+
private async Task AcceptLoopAsync()
39+
{
40+
while (!_cts.IsCancellationRequested)
41+
{
42+
TcpClient tcp;
43+
try { tcp = await _listener.AcceptTcpClientAsync(_cts.Token); }
44+
catch { return; }
45+
_ = HandleAsync(tcp);
46+
}
47+
}
48+
49+
private async Task HandleAsync(TcpClient tcp)
50+
{
51+
try
52+
{
53+
var stream = tcp.GetStream();
54+
var buf = new byte[16384];
55+
var sb = new StringBuilder();
56+
while (!sb.ToString().Contains("\r\n\r\n"))
57+
{
58+
var n = await stream.ReadAsync(buf, _cts.Token);
59+
if (n <= 0) return;
60+
sb.Append(Encoding.ASCII.GetString(buf, 0, n));
61+
}
62+
var key = sb.ToString().Split("\r\n")
63+
.FirstOrDefault(l => l.StartsWith("Sec-WebSocket-Key:", StringComparison.OrdinalIgnoreCase))
64+
?.Split(':', 2)[1].Trim();
65+
var accept = Convert.ToBase64String(SHA1.HashData(
66+
Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")));
67+
var resp = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n" +
68+
"Connection: Upgrade\r\nSec-WebSocket-Accept: " + accept + "\r\n\r\n";
69+
await stream.WriteAsync(Encoding.ASCII.GetBytes(resp), _cts.Token);
70+
_upgraded.TrySetResult();
71+
await Task.Delay(Timeout.Infinite, _cts.Token);
72+
}
73+
catch { /* torn down with the test */ }
74+
finally { try { tcp.Dispose(); } catch { } }
75+
}
76+
77+
public void Dispose()
78+
{
79+
_cts.Cancel();
80+
_listener.Stop();
81+
}
82+
}

0 commit comments

Comments
 (0)