Skip to content

Leave time for later addresses when the first one does not answer (sync client) - #1

Open
1AbdullahButt wants to merge 8 commits into
mainfrom
fix/sync-connect-address-budget
Open

1AbdullahButt wants to merge 8 commits into
mainfrom
fix/sync-connect-address-budget

Conversation

@1AbdullahButt

@1AbdullahButt 1AbdullahButt commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

ProoflineClient cannot reach the API when the first address a host resolves to never answers, even though a later address is healthy. AsyncProoflineClient and stock httpx2 both connect in that situation. This change gives each address an equal share of the connect time still left, so a silent address no longer uses up the time of the ones after it. One function changes: NetworkBackend.connect_tcp in proofline/_sync_http.py.

Known limit: IPv4 behind two silent IPv6 addresses waits half the budget

proofline.sh publishes two AAAA and two A records, and IPv6 addresses come first. With a broken IPv6 route, the sync client now spends 7.5 s on each IPv6 address and reaches IPv4 after 15 s at the default 30 s timeout. Before this change it never reached IPv4 at all. The async client gets there in about 0.25 s because anyio races addresses ("Happy Eyeballs", RFC 8305).

I did not add a race to the sync client. It would need threads to run connection attempts in parallel, plus cancellation of the losers, inside a transport that is deliberately small and bound to one deadline. That is a larger change than this fix.

Possible follow-up: interleave address families (IPv6, IPv4, IPv6, IPv4), as anyio and RFC 8305 do. With the same sharing rule, IPv4 would be tried second and connect after 7.5 s instead of 15 s, still without threads. I left it out to keep this PR to one behaviour change, and can send it separately if you want it.

Problem

connect_tcp resolves the host, then tries each address in turn. It remembers each error and moves on, and the first success wins. Each attempt's timeout comes from bounded_timeout(timeout), which is all the time left before the request deadline.

So the first address is told it may use all the remaining time. If it never answers (packets dropped rather than refused), it uses all of it. When the loop reaches the second address, bounded_timeout finds no time left and raises before trying it. The loop only helps when an address fails fast, for example a refused connection; the existing test test_sync_transport_connects_to_each_resolved_address_under_the_original_host covers that case.

The other clients do not have this problem:

  • Stock httpx2 uses socket.create_connection. It gives every address the full connect timeout and has no overall deadline.
  • AsyncProoflineClient uses anyio's connect_tcp, which starts the next address 0.25 s after the previous one.

Who it affects: anyone using ProoflineClient on a dual-stack machine whose IPv6 path drops packets. This happens with some VPNs, container networks and home routers. Every sync call times out, with urn:proofline:sdk:timeout, while AsyncProoflineClient and curl work on the same machine.

Change

Each attempt gets (time left) ÷ (addresses not yet tried). Time an attempt does not use carries over to the next one. The budget is taken once, before the name lookup, so the lookup and all attempts share one connect timeout.

Situation Before After
One address, or an IP literal all the time left unchanged
Refused, then healthy healthy address connects unchanged (the refusal costs no time)
Silent, then healthy (30 s) timeout at 30 s; second address never tried connects at 15 s
2 silent IPv6, then 2 healthy IPv4 (30 s) timeout; IPv4 never tried connects at 15 s
All addresses silent timeout at the deadline; only the first tried timeout at the deadline; every address tried
No timeout and no deadline unbounded unchanged

Unchanged: address order, error types and their mapping, the single request deadline, the public API and the README. No threads, retries, options or constants are added.

One stricter case: ProoflineClient always sets a request deadline before connecting; I checked that REST, MCP and export calls all connect with one set. Only when _sync_http.Transport is used directly, with no deadline, did each attempt previously get the full connect timeout. Four silent addresses at 30 s could take 120 s. They now share the 30 s.

Trade-off: an address that is alive but slower to accept than its share is abandoned for the next one. At the default 30 s and four addresses the share is 7.5 s for a TCP handshake, and the last address always gets everything that is left.

Alternatives considered

  • Thread-based Happy Eyeballs race. Closest to the async client, but adds concurrency and cancellation to a small, deadline-bound transport (see the known limit above).
  • A fixed short cap per attempt (for example 250 ms). Needs a magic number and can drop slow but healthy links.
  • Interleaving address families. Useful, but a second behaviour change; offered above as a follow-up.

How to verify

From the repository root:

python -m pytest tests/test_sync_connect.py -v   # 13 tests: 7 fail on main, all pass here
python scripts/check.py                          # the repository gate

The new tests replace the clock, the resolver and the connector, so they open no sockets and never sleep. A silent address uses exactly the time it is given, and a refused address fails at once. They also assert that the attempts never add up to more than the timeout, with or without a request deadline.

End-to-end repro with a real loopback server (pr-repro.py, run from the repository root)
"""A host whose first address never answers: run from the sdk-python repository root.

    python pr-repro.py

The host name resolves to 10.255.255.1 (unroutable, so connection attempts are dropped)
and then to 127.0.0.1, where a local test server answers. Exits 1 if ProoflineClient
cannot reach the server.
"""

import asyncio
import socket
import sys
import time
from uuid import UUID

sys.path.insert(0, ".")

import httpx2  # noqa: E402

from proofline import AsyncProoflineClient, ProoflineClient, ProoflineError, _transport  # noqa: E402
from tests.http_server import Reply, Server  # noqa: E402

ORG = UUID("11111111-1111-4111-8111-111111111111")
real_getaddrinfo = socket.getaddrinfo


def two_addresses(host, port, *args, **kwargs):
    if host in ("dual.test", b"dual.test"):
        return [
            (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.255.255.1", port)),
            (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port)),
        ]
    return real_getaddrinfo(host, port, *args, **kwargs)


socket.getaddrinfo = two_addresses
# Plain HTTP is only accepted for loopback literals; this repro needs a host name.
_transport.base_url = lambda value: value.rstrip("/")

failed = False
with Server(lambda request, index: Reply(200, {"repositories": []})) as server:
    url = server.url.replace("127.0.0.1", "dual.test")

    started = time.monotonic()
    response = httpx2.Client(timeout=httpx2.Timeout(30, connect=3)).get(f"{url}/x")
    print(f"stock httpx2 (sync)  : HTTP {response.status_code} after {time.monotonic() - started:.2f}s")

    async def asynchronous() -> None:
        started = time.monotonic()
        async with AsyncProoflineClient("token", base_url=url, timeout=3) as client:
            await client.list_repositories(ORG)
        print(f"AsyncProoflineClient : OK after {time.monotonic() - started:.2f}s")

    asyncio.run(asynchronous())

    for timeout in (3, 10):
        started = time.monotonic()
        try:
            with ProoflineClient("token", base_url=url, timeout=timeout) as client:
                client.list_repositories(ORG)
            print(f"ProoflineClient t={timeout:<2} : OK after {time.monotonic() - started:.2f}s")
        except ProoflineError as error:
            failed = True
            print(f"ProoflineClient t={timeout:<2} : {error.type} after {time.monotonic() - started:.2f}s")

sys.exit(1 if failed else 0)

Results

New tests. On main, with only the test commit applied, 7 fail and 5 pass. The first three fail with httpcore2.ReadTimeout: The request deadline expired. before the second address is attempted. With the fix all 13 pass.

Review follow-up. A Proofline review of this branch found that the budget and its end came from two clock readings. When the request deadline was the tighter limit, the end could land after it by the time between the two readings (microseconds in practice). connect_tcp now reads the clock once and passes that reading to bounded_timeout, which takes it as a new optional now argument. test_time_between_clock_reads_does_not_move_the_request_deadline advances the fake clock between readings. It failed before that commit and passes on main, which read the clock once per attempt, so the drift was never in a release.

A second review raised two more points:

  • The test resolver ignored its timeout. test_sync_connect.py passed even when connect_tcp gave the lookup no timeout. The full suite did catch that, through test_streaming_and_resolution_keep_deadline_outcomes_explicit[sync]. The fake now records the timeout, and the lookup and single-address tests assert it equals the budget. With resolve(host, port, None), 6 of them fail.
  • The comment claimed one budget covers the lookup. That was slightly too strong. resolve() starts its wait once its worker thread is running, so a lookup that times out can pass the end by the thread's start-up time: a median of 130 µs and at most about 1.2 ms over 2,000 starts here. No address is tried after the end. The comment now says this. I left resolve() alone because Fix: Bound DNS Lookup Workers and Add Regression Test prooflinedev/sdk-python#53 rewrites those exact lines to wait against an absolute deadline, and that fix belongs there.

A third review withdrew the comment finding and raised two more:

  • The no-deadline test missed a dropped lookup timeout. It still passed with resolve(host, port, None). It now asserts that the lookup gets the 30-second budget, and fails without it.
  • An expired request deadline before an address attempt raises httpcore2.ConnectTimeout rather than ReadTimeout. Not changed. mapped_errors() turns every httpcore2 timeout into httpx2.ReadTimeout, so callers see the same error either way.

A fourth review found the last test that didn't check the lookup timeout: test_no_timeout_and_no_deadline_stay_unbounded. It now asserts that the lookup gets no timeout, and fails if it is given 5 s.

Repository gate. I ran python scripts/check.py on Linux in python:3.13.12-bookworm, matching CI, on a clean clone of this branch. Generation check, contracts, ruff check, ruff format, mypy and pytest (232 passed) all pass, the wheel and sdist build, and both install smokes pass. The same Checks workflow also passes on GitHub Actions for this branch's head commit (f35a2f7): run 45253172785.

End-to-end repro on Windows 11 with Python 3.12, using a real loopback server:

Client Before After
Stock httpx2, sync, connect=3 HTTP 200 after 3.03 s HTTP 200 after 3.02 s
AsyncProoflineClient, timeout 3 OK after 0.39 s OK after 0.36 s
ProoflineClient, timeout 3 urn:proofline:sdk:timeout after 3.02 s; no request reached the server OK after 1.52 s
ProoflineClient, timeout 10 urn:proofline:sdk:timeout after 10.01 s; no request reached the server OK after 5.03 s

Open PRs touching _sync_http.py. I trial-merged this branch locally; nothing was pushed.

Not tested: a real network with broken IPv6. The silent address is simulated with an unroutable IPv4 address in the repro and with a fake connector in the tests.

🤖 Generated with Claude Code

1AbdullahButt and others added 2 commits November 23, 2026 03:01
ProoflineClient connects to each address of a host in turn, but hands the
first one all the time left before the request deadline. When that address
never answers, the deadline expires before the next address is tried. These
tests use a fake clock, resolver and connector, so they open no sockets and
never sleep. Seven fail on main; the five that pass guard the single-address,
deadline and no-timeout paths that must not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The synchronous backend tried each resolved address in turn but gave the
first one all the time left before the request deadline. An address that
never answers, such as an IPv6 address on a machine with a broken IPv6
route, therefore used the whole budget, and the deadline expired before a
healthy address was tried. The async client and stock httpx2 both connect
in that situation.

Each attempt now gets an equal share of the time still left, measured from
one budget that also covers the name lookup. Unused time carries over, so a
refused address costs nothing and the last address gets all that remains.
A single address, address order, error mapping and the overall deadline are
unchanged. Without a request deadline the connect timeout now bounds the
lookup and all attempts together instead of each attempt separately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1AbdullahButt and others added 2 commits November 23, 2026 15:53
connect_tcp takes the time left from one clock reading and the end time from a second, so when the request deadline is the tighter limit the end lands after it by the time between the two. The new test advances the fake clock between readings and fails on the current code (the attempt gets 30 s instead of 29 s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bounded_timeout read the clock and connect_tcp read it again to place the end, so the end could land after the request deadline by the time between the two readings. Read the clock once and pass that reading to bounded_timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@prooflinedev prooflinedev Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proofline has 1 new finding to review.

View full review in Proofline

Comment thread proofline/_sync_http.py Resolved

@prooflinedev prooflinedev Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proofline has 1 more finding to review, 2 in this review run.

View full review in Proofline

Comment on lines +41 to +43
def resolve(host: str, port: int, timeout: float | None) -> list[str]:
self.now += lookup_seconds
return resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · DNS budget tests pass even if the lookup timeout is dropped

The fake resolve ignores its timeout, so both DNS budget tests still pass if connect_tcp passes None while keeping the address-attempt deadline.

The tests miss a regression that lets a stalled lookup outlast the connect budget.

Record the resolver timeout and assert that both tests pass the expected 30-second budget.

Details

The six-second lookup still leaves two 12-second shares, and the 30-second lookup still triggers the post-lookup deadline check before any address attempt. Neither outcome depends on the resolver argument.

View finding in Proofline

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still present in this version: Proofline found the issue again. Proofline's finding in this version: The unbounded connection test misses DNS timeouts. View review

1AbdullahButt and others added 2 commits November 23, 2026 22:27
The fake resolver ignored its timeout, so tests/test_sync_connect.py still passed when connect_tcp gave the lookup no timeout at all. It now records the timeout, and the lookup and single-address tests assert it equals the budget; with resolve(host, port, None) six of them fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
resolve() measures its wait from once its worker thread has started, so a lookup that times out can pass the end of the budget by that start-up time. The comment said one budget covers the lookup; it now says exactly what holds. resolve() is left unchanged: open PR prooflinedev#53 rewrites those lines with an absolute deadline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@prooflinedev prooflinedev Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proofline has 1 new finding to review.

View full review in Proofline

Comment thread proofline/_sync_http.py
remaining = deadline - monotonic()
remaining = deadline - (monotonic() if now is None else now)
if remaining <= 0:
raise httpcore2.ReadTimeout("The request deadline expired.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Request deadline expiry is reported as a connect timeout

Before an address attempt, connect_tcp treats expiry of the request deadline as expiry of the connect budget.

The backend raises httpcore2.ConnectTimeout instead of httpcore2.ReadTimeout when the request deadline expires after lookup or between attempts.

Check the request deadline first using the same clock sample, then raise ConnectTimeout only if the connect budget is exhausted.

Details

The public transport maps both exceptions to httpx2.ReadTimeout; the difference is at the backend boundary.

View finding in Proofline

test_without_a_request_deadline_the_connect_timeout_bounds_all_addresses still passed when connect_tcp gave the lookup no timeout. It now asserts the lookup gets the 30-second budget, and fails with resolve(host, port, None).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@prooflinedev prooflinedev Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proofline has 1 new finding to review. 3 open findings need attention in this pull request.

View full review in Proofline

Comment thread tests/test_sync_connect.py Resolved
test_no_timeout_and_no_deadline_stay_unbounded still passed if connect_tcp gave the lookup a finite timeout when there was no budget. It now asserts the lookup gets None, and fails when resolve() is given 5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@prooflinedev prooflinedev Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proofline has 1 new finding to review.

View full review in Proofline

Comment thread proofline/_sync_http.py
Comment on lines +26 to 29
def bounded_timeout(timeout: float | None, now: float | None = None) -> float | None:
deadline = IO_DEADLINE.get()
if deadline is None:
return timeout

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Zero connect timeout skips the nonblocking socket attempt

For an IP literal and a live or unset request deadline, timeout=0 sets the budget end to the initial clock reading, so the pre-attempt check always raises.

The caller gets a synthetic ConnectTimeout instead of the socket attempt’s result.

Forward an explicit zero timeout to the socket backend while still enforcing the request deadline.

View finding in Proofline

@prooflinedev prooflinedev Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proofline has 1 more finding to review, 2 in this review run.

View full review in Proofline

Comment on lines +176 to +179
@pytest.mark.parametrize(
("timeout", "deadline", "expected"),
[(30, 30, 30.0), (30, 12, 12.0), (5, 30, 5.0), (30, None, 30.0)],
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Connect tests miss connections bounded only by the request deadline

The budget matrix never pairs timeout=None with a finite IO_DEADLINE.

The tests would still pass if that combination passed None to both DNS and TCP.

Add (None, 12, 12.0) to the matrix and annotate timeout as float | None so the existing assertions check both calls.

View finding in Proofline

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant