From 20cc6bbe1ab63c13d62fe5b1fd693e9d1ac8856c Mon Sep 17 00:00:00 2001 From: Satheesh Valluru Date: Mon, 16 Nov 2026 14:19:08 +0530 Subject: [PATCH 1/2] Claude quota: connect over IPv4 first so it works on broken IPv6 networks On networks that advertise IPv6 but don't route it, .NET resolves the IPv6 address of api.anthropic.com first and fails with "Socket is not connected" instead of falling back to IPv4. The Claude quota check then never succeeds and the AI quotas widget stays empty. The quota HttpClient now uses a ConnectCallback that tries IPv4 addresses first, then the rest, with a 5 s timeout per address. Proxy settings and TLS handling are unchanged. Co-Authored-By: Claude Sonnet 5.5 --- .../PhoneBox.Agent.Tests/QuotaConnectTests.cs | 54 +++++++++++++++++++ agent/PhoneBox.Agent/QuotaMonitor.cs | 36 ++++++++++++- 2 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs diff --git a/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs b/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs new file mode 100644 index 0000000..0bf5d57 --- /dev/null +++ b/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs @@ -0,0 +1,54 @@ +using System.Net; +using System.Net.Sockets; +using PhoneBox.Agent; +using Xunit; + +public sealed class QuotaConnectTests +{ + [Fact] + public void Ipv4AddressesAreTriedBeforeIpv6ButKeepTheirOrder() + { + // api.anthropic.com resolves to an IPv6 address first; on networks where IPv6 is advertised but not + // routable, .NET failed with "Socket is not connected" instead of using the IPv4 address after it. + var addresses = new[] + { + IPAddress.Parse("2607:6bc0::10"), IPAddress.Parse("160.79.104.10"), + IPAddress.Parse("fe80::1"), IPAddress.Parse("10.0.0.2"), + }; + + var ordered = QuotaMonitor.Ipv4First(addresses).Select(a => a.ToString()).ToArray(); + + Assert.Equal(["160.79.104.10", "10.0.0.2", "2607:6bc0::10", "fe80::1"], ordered); + } + + [Fact] + public async Task ConnectsToAnIpv4Listener() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var accept = listener.AcceptTcpClientAsync(); + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await using var stream = await QuotaMonitor.ConnectIpv4First(new DnsEndPoint("127.0.0.1", port), cts.Token); + using var server = await accept; + + await stream.WriteAsync(new byte[] { 42 }, cts.Token); + var buffer = new byte[1]; + Assert.Equal(1, await server.GetStream().ReadAsync(buffer, cts.Token)); + Assert.Equal(42, buffer[0]); + } + + [Fact] + public async Task FailsWithAnHttpErrorWhenNothingListens() + { + var free = new TcpListener(IPAddress.Loopback, 0); + free.Start(); + var port = ((IPEndPoint)free.LocalEndpoint).Port; + free.Stop(); + + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await Assert.ThrowsAsync(async () => + await QuotaMonitor.ConnectIpv4First(new DnsEndPoint("127.0.0.1", port), cts.Token)); + } +} diff --git a/agent/PhoneBox.Agent/QuotaMonitor.cs b/agent/PhoneBox.Agent/QuotaMonitor.cs index 2276ae0..2ad94fa 100644 --- a/agent/PhoneBox.Agent/QuotaMonitor.cs +++ b/agent/PhoneBox.Agent/QuotaMonitor.cs @@ -1,5 +1,7 @@ using System.Globalization; +using System.Net; using System.Net.Http.Headers; +using System.Net.Sockets; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; @@ -33,7 +35,39 @@ public sealed partial class QuotaMonitor(ConfigStore config, ILogger log) : this(null!, log) { } private static readonly string Home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(15) }; + // IPv4 first: on networks where IPv6 is advertised but not routable, the default connect fails with + // "Socket is not connected" instead of falling back, which breaks the quota checks. + private readonly HttpClient _http = new(new SocketsHttpHandler { ConnectCallback = (ctx, ct) => ConnectIpv4First(ctx.DnsEndPoint, ct) }) + { + Timeout = TimeSpan.FromSeconds(15), + }; + + /// The addresses in the order to try them: IPv4 first, each family keeping its resolver order. + internal static IEnumerable Ipv4First(IEnumerable addresses) => + addresses.OrderBy(a => a.AddressFamily == AddressFamily.InterNetwork ? 0 : 1); + + internal static async ValueTask ConnectIpv4First(DnsEndPoint endpoint, CancellationToken ct) + { + var addresses = await Dns.GetHostAddressesAsync(endpoint.Host, ct); + Exception? last = null; + foreach (var ip in Ipv4First(addresses)) + { + var socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(5)); + await socket.ConnectAsync(new IPEndPoint(ip, endpoint.Port), timeout.Token); + return new NetworkStream(socket, ownsSocket: true); + } + catch (Exception ex) when (ex is SocketException or OperationCanceledException && !ct.IsCancellationRequested) + { + socket.Dispose(); + last = ex; + } + } + throw new HttpRequestException("Could not connect to " + endpoint.Host, last); + } private volatile QuotaProvider? _claude; private volatile QuotaProvider? _codex; From 271e617b01f64d39989af766256270a6b6558ca3 Mon Sep 17 00:00:00 2001 From: Satheesh Valluru Date: Mon, 16 Nov 2026 14:39:01 +0530 Subject: [PATCH 2/2] Quota connect: share the time budget across addresses and always dispose sockets Review feedback on the IPv4-first connect: - Every attempt now gets an equal share of the time that is left in a 10 s budget, so unreachable addresses of one family can't use up the request timeout before the other family is tried. - The socket of an attempt is disposed on every exit that doesn't hand it to the returned stream, including when the caller cancels mid-connect. ConnectInOrder takes the connect step as a parameter so tests can cover both cases without depending on the network. Co-Authored-By: Claude Sonnet 5.5 --- .../PhoneBox.Agent.Tests/QuotaConnectTests.cs | 47 +++++++++++++++++++ agent/PhoneBox.Agent/QuotaMonitor.cs | 40 +++++++++++++--- 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs b/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs index 0bf5d57..27488c3 100644 --- a/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs +++ b/agent/PhoneBox.Agent.Tests/QuotaConnectTests.cs @@ -51,4 +51,51 @@ public async Task FailsWithAnHttpErrorWhenNothingListens() await Assert.ThrowsAsync(async () => await QuotaMonitor.ConnectIpv4First(new DnsEndPoint("127.0.0.1", port), cts.Token)); } + + [Fact] + public async Task DeadAddressesLeaveTimeForTheLastOne() + { + // three addresses that never answer, then one that does: before, each took a fixed share of the request + // timeout, so the working one was never reached. Every address is IPv4 so the order stays as given. + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var addresses = new[] + { + IPAddress.Parse("10.255.255.1"), IPAddress.Parse("10.255.255.2"), IPAddress.Parse("10.255.255.3"), IPAddress.Loopback, + }; + var tried = new List(); + + var budget = TimeSpan.FromSeconds(4); + var clock = System.Diagnostics.Stopwatch.StartNew(); + await using var stream = await QuotaMonitor.ConnectInOrder(addresses, port, budget, async (socket, endpoint, token) => + { + tried.Add(endpoint.Address); + if (IPAddress.IsLoopback(endpoint.Address)) await socket.ConnectAsync(endpoint, token); + else await Task.Delay(Timeout.Infinite, token); // pending until this attempt's share of the budget ends + }, CancellationToken.None); + + Assert.Equal(addresses, tried); + Assert.InRange(clock.Elapsed, TimeSpan.Zero, budget); + } + + [Fact] + public async Task TheSocketIsDisposedWhenTheCallerCancels() + { + Socket? attempted = null; + var started = new TaskCompletionSource(); + using var cts = new CancellationTokenSource(); + + var connecting = QuotaMonitor.ConnectInOrder([IPAddress.Loopback], 9, TimeSpan.FromSeconds(30), async (socket, _, token) => + { + attempted = socket; + started.SetResult(); + await Task.Delay(Timeout.Infinite, token); + }, cts.Token).AsTask(); + await started.Task; + cts.Cancel(); + + await Assert.ThrowsAnyAsync(() => connecting); + Assert.Throws(() => attempted!.Available); + } } diff --git a/agent/PhoneBox.Agent/QuotaMonitor.cs b/agent/PhoneBox.Agent/QuotaMonitor.cs index 2ad94fa..720afc9 100644 --- a/agent/PhoneBox.Agent/QuotaMonitor.cs +++ b/agent/PhoneBox.Agent/QuotaMonitor.cs @@ -46,27 +46,53 @@ internal QuotaMonitor(ILogger log) : this(null!, log) { } internal static IEnumerable Ipv4First(IEnumerable addresses) => addresses.OrderBy(a => a.AddressFamily == AddressFamily.InterNetwork ? 0 : 1); + /// Time all connect attempts of one request may use together; the request itself times out after 15 s. + internal static readonly TimeSpan ConnectBudget = TimeSpan.FromSeconds(10); + internal static async ValueTask ConnectIpv4First(DnsEndPoint endpoint, CancellationToken ct) { var addresses = await Dns.GetHostAddressesAsync(endpoint.Host, ct); + return await ConnectInOrder(addresses, endpoint.Port, ConnectBudget, static (s, ep, t) => s.ConnectAsync(ep, t), ct); + } + + /// + /// Tries the addresses one after another, IPv4 first. Each attempt gets an equal share of the time that is left, + /// so dead addresses of one family can't use up the budget before the other family is tried. The socket of an + /// attempt is disposed on every exit that doesn't hand it to the returned stream. + /// + internal static async ValueTask ConnectInOrder(IReadOnlyCollection addresses, int port, TimeSpan budget, + Func connect, CancellationToken ct) + { + var ordered = Ipv4First(addresses).ToList(); + var clock = System.Diagnostics.Stopwatch.StartNew(); Exception? last = null; - foreach (var ip in Ipv4First(addresses)) + for (var i = 0; i < ordered.Count; i++) { + var left = budget - clock.Elapsed; + if (left <= TimeSpan.Zero) break; + var ip = ordered[i]; var socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + var handedOver = false; try { - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); - timeout.CancelAfter(TimeSpan.FromSeconds(5)); - await socket.ConnectAsync(new IPEndPoint(ip, endpoint.Port), timeout.Token); - return new NetworkStream(socket, ownsSocket: true); + using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct); + attempt.CancelAfter(left / (ordered.Count - i)); + await connect(socket, new IPEndPoint(ip, port), attempt.Token); + var stream = new NetworkStream(socket, ownsSocket: true); + handedOver = true; + return stream; } catch (Exception ex) when (ex is SocketException or OperationCanceledException && !ct.IsCancellationRequested) { - socket.Dispose(); last = ex; } + finally + { + if (!handedOver) socket.Dispose(); + } } - throw new HttpRequestException("Could not connect to " + endpoint.Host, last); + ct.ThrowIfCancellationRequested(); + throw new HttpRequestException("Could not connect", last); } private volatile QuotaProvider? _claude;