From 1b5718afbf236039c17bcd0ce97a983411d0baac Mon Sep 17 00:00:00 2001 From: khanak0509 Date: Tue, 24 Nov 2026 11:20:05 +0530 Subject: [PATCH 1/5] Fall back to the next address when one silently drops connections --- proofline/_sync_http.py | 141 +++++++++++++++++++++++--- tests/test_sync_connect.py | 200 +++++++++++++++++++++++++++++++++++++ 2 files changed, 329 insertions(+), 12 deletions(-) create mode 100644 tests/test_sync_connect.py diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index 0ef0b5b0..a6843992 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -3,6 +3,10 @@ Operating-system name resolution cannot be interrupted, so it runs on a daemon thread and the request stops waiting for it at the deadline. An abandoned lookup finishes on its own thread and its result is discarded. + +A host name with several addresses races its connection attempts (RFC 8305): each starts +250 ms after the previous one, or at once when it fails, and the first connection wins. An +address that silently drops packets then costs one attempt delay instead of the deadline. """ from __future__ import annotations @@ -11,9 +15,10 @@ import socket import ssl import threading -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar +from functools import partial from time import monotonic from typing import Any @@ -100,6 +105,84 @@ def get_extra_info(self, info: str) -> Any: return self._inner.get_extra_info(info) +# RFC 8305 recommends 250 ms between connection attempts, as anyio uses for the async client. +ATTEMPT_DELAY = 0.25 + + +def interleaved(addresses: list[str]) -> list[str]: + """Alternate address families, starting with the resolver's first preference (RFC 8305 ยง4).""" + families: dict[bool, list[str]] = {True: [], False: []} + for address in addresses: + families[":" in address].append(address) + first = ":" in addresses[0] + preferred, other = families[first], families[not first] + ordered: list[str] = [] + for index in range(max(len(preferred), len(other))): + ordered.extend(family[index] for family in (preferred, other) if index < len(family)) + return ordered + + +class Race: + """Concurrent connection attempts. The first stream wins; later streams are closed.""" + + def __init__(self) -> None: + self._changed = threading.Condition() + self._running = 0 + self._settled = False + self.winner: httpcore2.NetworkStream | None = None + self.failure: Exception | None = None + self.failures = 0 + + def start(self, connect: Callable[[], httpcore2.NetworkStream]) -> None: + with self._changed: + self._running += 1 + threading.Thread( + target=self._attempt, args=(connect,), name="proofline-connect", daemon=True + ).start() + + def _attempt(self, connect: Callable[[], httpcore2.NetworkStream]) -> None: + try: + stream = connect() + except Exception as error: + with self._changed: + self._running -= 1 + self.failure = error + self.failures += 1 + self._changed.notify_all() + return + with self._changed: + self._running -= 1 + if not self._settled and self.winner is None: + self.winner = stream + self._changed.notify_all() + return + # The request already has a connection or stopped waiting for one. + stream.close() + + def wait(self, timeout: float | None, *, failures: int | None = None) -> None: + """Wait for a winner or for every attempt to fail; or for more than `failures` failures.""" + with self._changed: + self._changed.wait_for( + lambda: ( + self.winner is not None + or self._running == 0 + or (failures is not None and self.failures > failures) + ), + timeout, + ) + + def settle(self) -> httpcore2.NetworkStream | None: + """Stop accepting streams; a stream that connects later is closed by its attempt.""" + with self._changed: + self._settled = True + return self.winner + + @property + def running(self) -> int: + with self._changed: + return self._running + + class NetworkBackend(httpcore2.SyncBackend): def connect_tcp( self, @@ -109,17 +192,51 @@ def connect_tcp( local_address: str | None = None, socket_options: Iterable[Any] | None = None, ) -> httpcore2.NetworkStream: - failure: httpcore2.ConnectError | httpcore2.ConnectTimeout | None = None - for address in resolve(host, port, bounded_timeout(timeout)): - try: - stream = super().connect_tcp( - address, port, bounded_timeout(timeout), local_address, socket_options - ) - except (httpcore2.ConnectError, httpcore2.ConnectTimeout) as error: - failure = error - else: - return NetworkStream(stream) - raise failure or httpcore2.ConnectError("The host name did not resolve.") + addresses = resolve(host, port, bounded_timeout(timeout)) + if len(addresses) == 1: + stream = super().connect_tcp( + addresses[0], port, bounded_timeout(timeout), local_address, socket_options + ) + return NetworkStream(stream) + # One address that silently drops packets must not spend the whole request deadline + # while the next address would answer, so attempts overlap ATTEMPT_DELAY apart. + budget = bounded_timeout(timeout) + deadline = None if budget is None else monotonic() + budget + options = list(socket_options or ()) + connect = super().connect_tcp + race = Race() + failures = 0 + try: + for index, address in enumerate(interleaved(addresses)): + if index: + # Start the next attempt after the delay, or as soon as any attempt fails. + race.wait( + ATTEMPT_DELAY + if deadline is None + else min(ATTEMPT_DELAY, deadline - monotonic()), + failures=failures, + ) + if race.winner is not None: + break + if deadline is not None and monotonic() >= deadline: + break + failures = race.failures + remaining = None if deadline is None else max(0.0, deadline - monotonic()) + race.start(partial(connect, address, port, remaining, local_address, options)) + while race.winner is None and race.running: + if deadline is None: + race.wait(None) + elif (left := deadline - monotonic()) > 0: + race.wait(left) + else: + break + finally: + winner = race.settle() + if winner is not None: + return NetworkStream(winner) + if race.running: + raise httpcore2.ConnectTimeout("No resolved address connected in time.") + raise race.failure or httpcore2.ConnectError("The host name did not resolve.") @contextmanager diff --git a/tests/test_sync_connect.py b/tests/test_sync_connect.py new file mode 100644 index 00000000..e97eb7b2 --- /dev/null +++ b/tests/test_sync_connect.py @@ -0,0 +1,200 @@ +"""The sync transport races resolved addresses so one silent address cannot spend the deadline.""" + +from __future__ import annotations + +import socket +import threading +import time +from collections.abc import Iterator +from dataclasses import dataclass, field +from typing import Any + +import httpcore2 +import httpx2 +import pytest + +from proofline import ProoflineClient, _sync_http + +from .fixtures import FINDING, ORG, REVIEW, TOKEN, finding +from .http_server import Reply, Server + +# Documentation addresses (RFC 5737, RFC 3849) stand in for hosts that drop every SYN. +SILENT = "192.0.2.1" +SILENT_V6 = "2001:db8::1" +# These answer every SYN with a reset, as a host with nothing listening does. +REFUSED = "198.51.100.1" +REFUSED_V6 = "2001:db8::2" + + +@dataclass +class Network: + hosts: dict[str, list[str]] = field(default_factory=dict) + # Every address the backend tried, in order, with the time the attempt started. + attempts: list[tuple[str, float]] = field(default_factory=list) + silence: threading.Event = field(default_factory=threading.Event) + + @property + def tried(self) -> list[str]: + return [address for address, _ in self.attempts] + + +@pytest.fixture +def network(monkeypatch: pytest.MonkeyPatch) -> Iterator[Network]: + """Resolve test hosts to chosen addresses. A silent address never answers its SYN. + + Like an unanswered SYN, a silent attempt waits out its whole connect timeout and then + raises ConnectTimeout; a refused attempt fails at once. Loopback is real TCP. + """ + state = Network() + resolve = socket.getaddrinfo + connect = httpcore2.SyncBackend.connect_tcp + + def getaddrinfo(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: + if host not in state.hosts: + return resolve(host, port, *args, **kwargs) + return [ + (socket.AF_INET6, socket.SOCK_STREAM, 6, "", (address, port, 0, 0)) + if ":" in address + else (socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, port)) + for address in state.hosts[host] + ] + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + state.attempts.append((host, time.monotonic())) + if host in (SILENT, SILENT_V6): + state.silence.wait(timeout) + raise httpcore2.ConnectTimeout("timed out") + if host in (REFUSED, REFUSED_V6): + raise httpcore2.ConnectError("Connection refused") + return connect(self, host, port, timeout, *args) + + monkeypatch.setattr(socket, "getaddrinfo", getaddrinfo) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + try: + yield state + finally: + # End silent attempts that are still waiting so their threads finish with the test. + state.silence.set() + + +def test_a_silent_first_address_falls_back_to_the_next_one(network: Network) -> None: + network.hosts["dual.proofline.invalid"] = [SILENT_V6, SILENT, "127.0.0.1"] + with Server(lambda request, index: Reply(body=finding())) as server: + port = server.url.rsplit(":", 1)[1] + with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: + started = time.monotonic() + response = client.get(f"http://dual.proofline.invalid:{port}/finding") + elapsed = time.monotonic() - started + assert response.json()["id"] == str(FINDING) + assert server.requests[0].headers["Host"] == f"dual.proofline.invalid:{port}" + assert network.tried == [SILENT_V6, SILENT, "127.0.0.1"] + # Each silent address costs one attempt delay, not the 5 second connect timeout. + assert elapsed < 2 + starts = [at for _, at in network.attempts] + assert all( + later - earlier >= _sync_http.ATTEMPT_DELAY * 0.8 + for earlier, later in zip(starts, starts[1:], strict=False) + ) + + +def test_the_client_reads_through_a_silent_address( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + with Server(lambda request, index: Reply(body=finding())) as server: + # The origin must be a loopback literal, which resolves to itself; give it a silent + # address first, as a dual-stack name with broken IPv6 resolves. + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, "127.0.0.1"]) + with ProoflineClient(TOKEN, base_url=server.url, timeout=5) as client: + started = time.monotonic() + result = client.get_finding(ORG, FINDING) + elapsed = time.monotonic() - started + assert result.id == FINDING + assert len(server.requests) == 1 + assert network.tried == [SILENT, "127.0.0.1"] + # Before the race, this read raised urn:proofline:sdk:timeout after 5 seconds. + assert elapsed < 2 + + +def test_a_refused_address_starts_the_next_attempt_at_once(network: Network) -> None: + network.hosts["refused.proofline.invalid"] = [REFUSED, "127.0.0.1"] + with Server(lambda request, index: Reply(body=finding())) as server: + port = server.url.rsplit(":", 1)[1] + with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: + started = time.monotonic() + response = client.get(f"http://refused.proofline.invalid:{port}/finding") + elapsed = time.monotonic() - started + assert response.json()["id"] == str(FINDING) + assert network.tried == [REFUSED, "127.0.0.1"] + assert elapsed < _sync_http.ATTEMPT_DELAY + + +def test_every_silent_address_ends_at_the_request_deadline(network: Network) -> None: + network.hosts["dark.proofline.invalid"] = [SILENT_V6, SILENT] + with httpx2.Client(transport=_sync_http.Transport(), timeout=0.6) as client: + started = time.monotonic() + with pytest.raises(httpx2.TimeoutException): + client.get("http://dark.proofline.invalid:443/finding") + elapsed = time.monotonic() - started + assert 0.5 < elapsed < 1.5 + assert network.tried == [SILENT_V6, SILENT] + + +def test_the_wait_deadline_still_bounds_the_race( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) + with ProoflineClient(TOKEN, base_url="http://127.0.0.1:9", timeout=30) as client: + started = time.monotonic() + result = client.wait_for_review(ORG, REVIEW, timeout=0.4) + elapsed = time.monotonic() - started + assert result.status == "TIMED_OUT" + assert network.tried == [SILENT, SILENT_V6] + assert elapsed < 1.5 + + +def test_every_refused_address_raises_a_connect_error(network: Network) -> None: + network.hosts["closed.proofline.invalid"] = [REFUSED, REFUSED_V6] + with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: + started = time.monotonic() + with pytest.raises(httpx2.TransportError) as raised: + client.get("http://closed.proofline.invalid:443/finding") + elapsed = time.monotonic() - started + assert not isinstance(raised.value, httpx2.TimeoutException) + assert network.tried == [REFUSED, REFUSED_V6] + assert elapsed < _sync_http.ATTEMPT_DELAY + + +def test_a_stream_that_connects_after_the_race_settles_is_closed() -> None: + release = threading.Event() + closed = threading.Event() + + class Stream(httpcore2.MockStream): + def close(self) -> None: + closed.set() + + def late() -> httpcore2.NetworkStream: + release.wait(5) + return Stream([]) + + race = _sync_http.Race() + race.start(late) + assert race.settle() is None + release.set() + assert closed.wait(5) + assert race.winner is None + + +@pytest.mark.parametrize( + ("resolved", "ordered"), + [ + ( + ["2001:db8::1", "2001:db8::2", "192.0.2.1", "192.0.2.2"], + ["2001:db8::1", "192.0.2.1", "2001:db8::2", "192.0.2.2"], + ), + (["192.0.2.1", "192.0.2.2", "2001:db8::1"], ["192.0.2.1", "2001:db8::1", "192.0.2.2"]), + (["192.0.2.1", "192.0.2.2"], ["192.0.2.1", "192.0.2.2"]), + (["fe80::1%41", "fe80::1%42"], ["fe80::1%41", "fe80::1%42"]), + ], +) +def test_attempts_alternate_address_families(resolved: list[str], ordered: list[str]) -> None: + assert _sync_http.interleaved(resolved) == ordered From a2a6a8600a9ffc0e99e2600989961942913d85e6 Mon Sep 17 00:00:00 2001 From: khanak0509 Date: Tue, 24 Nov 2026 11:38:17 +0530 Subject: [PATCH 2/5] Address Proofline review findings --- proofline/_sync_http.py | 34 +++++++--- tests/test_sync_connect.py | 135 +++++++++++++++++++++++++++++++++---- 2 files changed, 144 insertions(+), 25 deletions(-) diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index a6843992..878e19af 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -159,8 +159,12 @@ def _attempt(self, connect: Callable[[], httpcore2.NetworkStream]) -> None: # The request already has a connection or stopped waiting for one. stream.close() - def wait(self, timeout: float | None, *, failures: int | None = None) -> None: - """Wait for a winner or for every attempt to fail; or for more than `failures` failures.""" + def wait(self, timeout: float | None, *, failures: int | None = None) -> int: + """Wait for a winner or for every attempt to fail; or for more than `failures` failures. + + Returns the failure count observed under the lock, so the caller acts on exactly the + failures this wait saw rather than on ones that arrive after it returns. + """ with self._changed: self._changed.wait_for( lambda: ( @@ -170,6 +174,7 @@ def wait(self, timeout: float | None, *, failures: int | None = None) -> None: ), timeout, ) + return self.failures def settle(self) -> httpcore2.NetworkStream | None: """Stop accepting streams; a stream that connects later is closed by its attempt.""" @@ -205,36 +210,43 @@ def connect_tcp( options = list(socket_options or ()) connect = super().connect_tcp race = Race() - failures = 0 + # Failures that have already started an attempt. Each failure starts at most one, + # so one that arrives while an attempt is being started still starts the next. + answered = 0 + # Set only here, so a worker that fails after the deadline cannot change the outcome. + expired = False try: for index, address in enumerate(interleaved(addresses)): if index: # Start the next attempt after the delay, or as soon as any attempt fails. - race.wait( + seen = race.wait( ATTEMPT_DELAY if deadline is None else min(ATTEMPT_DELAY, deadline - monotonic()), - failures=failures, + failures=answered, ) if race.winner is not None: break if deadline is not None and monotonic() >= deadline: + expired = True break - failures = race.failures + if seen > answered: + answered += 1 remaining = None if deadline is None else max(0.0, deadline - monotonic()) race.start(partial(connect, address, port, remaining, local_address, options)) - while race.winner is None and race.running: + while not expired and race.winner is None and race.running: if deadline is None: race.wait(None) - elif (left := deadline - monotonic()) > 0: + continue + if (left := deadline - monotonic()) > 0: race.wait(left) - else: - break + # Judge the deadline before rereading worker state that may change after it. + expired = monotonic() >= deadline finally: winner = race.settle() if winner is not None: return NetworkStream(winner) - if race.running: + if expired: raise httpcore2.ConnectTimeout("No resolved address connected in time.") raise race.failure or httpcore2.ConnectError("The host name did not resolve.") diff --git a/tests/test_sync_connect.py b/tests/test_sync_connect.py index e97eb7b2..e3a743d1 100644 --- a/tests/test_sync_connect.py +++ b/tests/test_sync_connect.py @@ -29,13 +29,17 @@ @dataclass class Network: hosts: dict[str, list[str]] = field(default_factory=dict) - # Every address the backend tried, in order, with the time the attempt started. - attempts: list[tuple[str, float]] = field(default_factory=list) + # Every address the backend tried, in order, with its start time and connect timeout. + attempts: list[tuple[str, float, float | None]] = field(default_factory=list) silence: threading.Event = field(default_factory=threading.Event) @property def tried(self) -> list[str]: - return [address for address, _ in self.attempts] + return [address for address, _, _ in self.attempts] + + @property + def timeouts(self) -> list[float | None]: + return [timeout for _, _, timeout in self.attempts] @pytest.fixture @@ -60,7 +64,7 @@ def getaddrinfo(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: ] def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: - state.attempts.append((host, time.monotonic())) + state.attempts.append((host, time.monotonic(), timeout)) if host in (SILENT, SILENT_V6): state.silence.wait(timeout) raise httpcore2.ConnectTimeout("timed out") @@ -90,7 +94,7 @@ def test_a_silent_first_address_falls_back_to_the_next_one(network: Network) -> assert network.tried == [SILENT_V6, SILENT, "127.0.0.1"] # Each silent address costs one attempt delay, not the 5 second connect timeout. assert elapsed < 2 - starts = [at for _, at in network.attempts] + starts = [at for _, at, _ in network.attempts] assert all( later - earlier >= _sync_http.ATTEMPT_DELAY * 0.8 for earlier, later in zip(starts, starts[1:], strict=False) @@ -137,6 +141,11 @@ def test_every_silent_address_ends_at_the_request_deadline(network: Network) -> elapsed = time.monotonic() - started assert 0.5 < elapsed < 1.5 assert network.tried == [SILENT_V6, SILENT] + # The second attempt starts one delay later and gets only what is left of the budget. + first, second = network.timeouts + assert first is not None and second is not None + assert first <= 0.6 + assert second <= 0.6 - _sync_http.ATTEMPT_DELAY * 0.8 def test_the_wait_deadline_still_bounds_the_race( @@ -150,6 +159,11 @@ def test_the_wait_deadline_still_bounds_the_race( assert result.status == "TIMED_OUT" assert network.tried == [SILENT, SILENT_V6] assert elapsed < 1.5 + # Each attempt is bounded by the 0.4 second wait, not the 30 second HTTP timeout. + first, second = network.timeouts + assert first is not None and second is not None + assert first <= 0.4 + assert second <= 0.4 - _sync_http.ATTEMPT_DELAY * 0.8 def test_every_refused_address_raises_a_connect_error(network: Network) -> None: @@ -164,26 +178,119 @@ def test_every_refused_address_raises_a_connect_error(network: Network) -> None: assert elapsed < _sync_http.ATTEMPT_DELAY +class Stream(httpcore2.MockStream): + def __init__(self) -> None: + super().__init__([]) + self.closed = threading.Event() + + def close(self) -> None: + self.closed.set() + + def test_a_stream_that_connects_after_the_race_settles_is_closed() -> None: release = threading.Event() - closed = threading.Event() - - class Stream(httpcore2.MockStream): - def close(self) -> None: - closed.set() + late = Stream() - def late() -> httpcore2.NetworkStream: + def connect_late() -> httpcore2.NetworkStream: release.wait(5) - return Stream([]) + return late race = _sync_http.Race() - race.start(late) + race.start(connect_late) assert race.settle() is None release.set() - assert closed.wait(5) + assert late.closed.wait(5) assert race.winner is None +def test_a_losing_stream_is_closed_and_the_winner_kept() -> None: + release = threading.Event() + winner, loser = Stream(), Stream() + + def connect_loser() -> httpcore2.NetworkStream: + release.wait(5) + return loser + + race = _sync_http.Race() + race.start(connect_loser) + race.start(lambda: winner) + race.wait(5) + assert race.settle() is winner + release.set() + assert loser.closed.wait(5) + assert not winner.closed.is_set() + + +def test_a_failure_while_an_attempt_starts_still_starts_the_next( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Four silent addresses. The first fails just after the wait before the third attempt + # times out, so that failure has started nothing yet: the fourth attempt starts at once. + first_fails = threading.Event() + silence = threading.Event() + starts: dict[str, float] = {} + original_wait = _sync_http.Race.wait + calls = 0 + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + starts[host] = time.monotonic() + if host == "192.0.2.1": + first_fails.wait(5) + raise httpcore2.ConnectError("Connection reset") + silence.wait(timeout) + raise httpcore2.ConnectTimeout("timed out") + + def wait(race: _sync_http.Race, timeout: float | None, **kwargs: Any) -> int: + nonlocal calls + seen = original_wait(race, timeout, **kwargs) + calls += 1 + if calls == 2: + failures = race.failures + first_fails.set() + while race.failures == failures: + time.sleep(0.001) + return seen + + addresses = ["192.0.2.1", "192.0.2.2", "192.0.2.3", "192.0.2.4"] + monkeypatch.setattr(_sync_http, "resolve", lambda *_: addresses) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "wait", wait) + try: + with pytest.raises(httpcore2.ConnectTimeout): + _sync_http.NetworkBackend().connect_tcp("dark.proofline.invalid", 443, 1.2) + finally: + silence.set() + assert list(starts) == addresses + assert starts["192.0.2.4"] - starts["192.0.2.3"] < _sync_http.ATTEMPT_DELAY / 2 + + +def test_a_failure_after_the_deadline_still_reports_the_timeout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Both attempts hang until the deadline ends the race; one then fails with a reset. + # The deadline ended the request, so the caller sees a timeout, not the late reset. + reset = threading.Event() + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + reset.wait(10) + raise httpcore2.ConnectError("Connection reset") + + settle = _sync_http.Race.settle + + def settle_then_fail(race: _sync_http.Race) -> httpcore2.NetworkStream | None: + winner = settle(race) + reset.set() + while race.running: + time.sleep(0.001) + return winner + + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "settle", settle_then_fail) + with pytest.raises(httpcore2.ConnectTimeout): + _sync_http.NetworkBackend().connect_tcp("dark.proofline.invalid", 443, 0.4) + + @pytest.mark.parametrize( ("resolved", "ordered"), [ From 22de1a22880c683015b9af6e5c5a6847dcada8ff Mon Sep 17 00:00:00 2001 From: khanak0509 Date: Tue, 24 Nov 2026 11:50:46 +0530 Subject: [PATCH 3/5] Close the winning stream on errors and harden connect tests --- proofline/_sync_http.py | 23 +++++++++--- tests/test_sync_connect.py | 71 +++++++++++++++++++++++++++++++++++--- 2 files changed, 84 insertions(+), 10 deletions(-) diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index 878e19af..b8d22cf8 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -136,9 +136,15 @@ def __init__(self) -> None: def start(self, connect: Callable[[], httpcore2.NetworkStream]) -> None: with self._changed: self._running += 1 - threading.Thread( - target=self._attempt, args=(connect,), name="proofline-connect", daemon=True - ).start() + try: + threading.Thread( + target=self._attempt, args=(connect,), name="proofline-connect", daemon=True + ).start() + except BaseException: + with self._changed: + self._running -= 1 + self._changed.notify_all() + raise def _attempt(self, connect: Callable[[], httpcore2.NetworkStream]) -> None: try: @@ -242,8 +248,15 @@ def connect_tcp( race.wait(left) # Judge the deadline before rereading worker state that may change after it. expired = monotonic() >= deadline - finally: - winner = race.settle() + except BaseException: + # The request is failing anyway; release a connection that won in the meantime. + if (late := race.settle()) is not None: + late.close() + raise + winner = race.settle() + # A stream that won is used even if the deadline passed while it was handed over: each + # attempt's own connect timeout is the remaining budget, so it connected within it, and + # later I/O stays bounded by the request deadline. Only failures defer to the timeout. if winner is not None: return NetworkStream(winner) if expired: diff --git a/tests/test_sync_connect.py b/tests/test_sync_connect.py index e3a743d1..82d440a8 100644 --- a/tests/test_sync_connect.py +++ b/tests/test_sync_connect.py @@ -5,7 +5,7 @@ import socket import threading import time -from collections.abc import Iterator +from collections.abc import Callable, Iterator from dataclasses import dataclass, field from typing import Any @@ -26,6 +26,15 @@ REFUSED_V6 = "2001:db8::2" +def until(condition: Callable[[], bool], what: str) -> None: + """Poll a condition a worker thread sets; fail instead of hanging if it never holds.""" + deadline = time.monotonic() + 5 + while not condition(): + if time.monotonic() > deadline: + pytest.fail(f"Timed out waiting for {what}.") + time.sleep(0.001) + + @dataclass class Network: hosts: dict[str, list[str]] = field(default_factory=dict) @@ -247,8 +256,7 @@ def wait(race: _sync_http.Race, timeout: float | None, **kwargs: Any) -> int: if calls == 2: failures = race.failures first_fails.set() - while race.failures == failures: - time.sleep(0.001) + until(lambda: race.failures > failures, "the first attempt to fail") return seen addresses = ["192.0.2.1", "192.0.2.2", "192.0.2.3", "192.0.2.4"] @@ -280,8 +288,7 @@ def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: A def settle_then_fail(race: _sync_http.Race) -> httpcore2.NetworkStream | None: winner = settle(race) reset.set() - while race.running: - time.sleep(0.001) + until(lambda: not race.running, "the late attempts to fail") return winner monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) @@ -291,6 +298,60 @@ def settle_then_fail(race: _sync_http.Race) -> httpcore2.NetworkStream | None: _sync_http.NetworkBackend().connect_tcp("dark.proofline.invalid", 443, 0.4) +def test_a_winner_is_closed_when_starting_the_next_attempt_fails( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The first attempt connects just after the scheduler checked for a winner, and then + # starting the second attempt's thread fails. The error propagates; the stream is closed. + release = threading.Event() + winner = Stream() + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + release.wait(5) + return winner + + original_start = _sync_http.Race.start + starts = 0 + + def start(race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream]) -> None: + nonlocal starts + starts += 1 + if starts == 2: + release.set() + until(lambda: race.winner is not None, "the first attempt to connect") + raise RuntimeError("can't start new thread") + original_start(race, connect) + + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "start", start) + with pytest.raises(RuntimeError): + _sync_http.NetworkBackend().connect_tcp("dual.proofline.invalid", 443, 5) + assert winner.closed.wait(5) + + +def test_an_attempt_whose_thread_cannot_start_is_not_counted( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def refuse(thread: threading.Thread) -> None: + raise RuntimeError("can't start new thread") + + race = _sync_http.Race() + monkeypatch.setattr(threading.Thread, "start", refuse) + with pytest.raises(RuntimeError): + race.start(Stream) + assert race.running == 0 + + +def test_the_backend_alternates_address_families(network: Network) -> None: + # The resolver groups addresses by family; attempts must still alternate between them. + network.hosts["grouped.proofline.invalid"] = [SILENT_V6, REFUSED_V6, SILENT, REFUSED] + with httpx2.Client(transport=_sync_http.Transport(), timeout=0.8) as client: + with pytest.raises(httpx2.TimeoutException): + client.get("http://grouped.proofline.invalid:443/finding") + assert network.tried == [SILENT_V6, SILENT, REFUSED_V6, REFUSED] + + @pytest.mark.parametrize( ("resolved", "ordered"), [ From 08fb832a47672b209462a08698e1be67e9938799 Mon Sep 17 00:00:00 2001 From: khanak0509 Date: Tue, 24 Nov 2026 12:00:44 +0530 Subject: [PATCH 4/5] Test launch gaps instead of request time; cover losers before settle --- tests/test_sync_connect.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/tests/test_sync_connect.py b/tests/test_sync_connect.py index 82d440a8..f163ec3a 100644 --- a/tests/test_sync_connect.py +++ b/tests/test_sync_connect.py @@ -46,6 +46,12 @@ class Network: def tried(self) -> list[str]: return [address for address, _, _ in self.attempts] + @property + def gaps(self) -> list[float]: + """Seconds between consecutive attempt starts: the scheduler's launch decisions.""" + starts = [at for _, at, _ in self.attempts] + return [later - earlier for earlier, later in zip(starts, starts[1:], strict=False)] + @property def timeouts(self) -> list[float | None]: return [timeout for _, _, timeout in self.attempts] @@ -133,12 +139,11 @@ def test_a_refused_address_starts_the_next_attempt_at_once(network: Network) -> with Server(lambda request, index: Reply(body=finding())) as server: port = server.url.rsplit(":", 1)[1] with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: - started = time.monotonic() response = client.get(f"http://refused.proofline.invalid:{port}/finding") - elapsed = time.monotonic() - started assert response.json()["id"] == str(FINDING) assert network.tried == [REFUSED, "127.0.0.1"] - assert elapsed < _sync_http.ATTEMPT_DELAY + # The refusal started the next attempt without waiting out the stagger. + assert network.gaps[0] < _sync_http.ATTEMPT_DELAY / 2 def test_every_silent_address_ends_at_the_request_deadline(network: Network) -> None: @@ -178,13 +183,11 @@ def test_the_wait_deadline_still_bounds_the_race( def test_every_refused_address_raises_a_connect_error(network: Network) -> None: network.hosts["closed.proofline.invalid"] = [REFUSED, REFUSED_V6] with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: - started = time.monotonic() with pytest.raises(httpx2.TransportError) as raised: client.get("http://closed.proofline.invalid:443/finding") - elapsed = time.monotonic() - started assert not isinstance(raised.value, httpx2.TimeoutException) assert network.tried == [REFUSED, REFUSED_V6] - assert elapsed < _sync_http.ATTEMPT_DELAY + assert network.gaps[0] < _sync_http.ATTEMPT_DELAY / 2 class Stream(httpcore2.MockStream): @@ -212,7 +215,10 @@ def connect_late() -> httpcore2.NetworkStream: assert race.winner is None -def test_a_losing_stream_is_closed_and_the_winner_kept() -> None: +@pytest.mark.parametrize("settled", [False, True], ids=["before-settle", "after-settle"]) +def test_a_losing_stream_is_closed_and_the_winner_kept(settled: bool) -> None: + # The loser connects after the winner is published, either while the caller is still + # handing the winner over or after it has settled the race. release = threading.Event() winner, loser = Stream(), Stream() @@ -224,9 +230,12 @@ def connect_loser() -> httpcore2.NetworkStream: race.start(connect_loser) race.start(lambda: winner) race.wait(5) - assert race.settle() is winner + assert race.winner is winner + if settled: + assert race.settle() is winner release.set() assert loser.closed.wait(5) + assert race.settle() is winner assert not winner.closed.is_set() From 6ee7ce9f36894ea509cf7299413d6b723db97f71 Mon Sep 17 00:00:00 2001 From: khanak0509 Date: Tue, 24 Nov 2026 12:14:01 +0530 Subject: [PATCH 5/5] Measure each attempt's budget when it runs; record launches in order --- proofline/_sync_http.py | 23 +++++--- tests/test_sync_connect.py | 104 +++++++++++++++++++++++++++---------- 2 files changed, 94 insertions(+), 33 deletions(-) diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index b8d22cf8..424e5a7e 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -133,12 +133,15 @@ def __init__(self) -> None: self.failure: Exception | None = None self.failures = 0 - def start(self, connect: Callable[[], httpcore2.NetworkStream]) -> None: + def start(self, connect: Callable[[], httpcore2.NetworkStream], address: str = "") -> None: with self._changed: self._running += 1 try: threading.Thread( - target=self._attempt, args=(connect,), name="proofline-connect", daemon=True + target=self._attempt, + args=(connect,), + name=f"proofline-connect {address}".rstrip(), + daemon=True, ).start() except BaseException: with self._changed: @@ -215,6 +218,15 @@ def connect_tcp( deadline = None if budget is None else monotonic() + budget options = list(socket_options or ()) connect = super().connect_tcp + + def attempt(address: str) -> httpcore2.NetworkStream: + # Measure the budget when the thread runs, not when it was scheduled, so an + # attempt whose thread starts late still cannot connect past the deadline. + left = None if deadline is None else deadline - monotonic() + if left is not None and left <= 0: + raise httpcore2.ConnectTimeout("The request deadline expired.") + return connect(address, port, left, local_address, options) + race = Race() # Failures that have already started an attempt. Each failure starts at most one, # so one that arrives while an attempt is being started still starts the next. @@ -238,8 +250,7 @@ def connect_tcp( break if seen > answered: answered += 1 - remaining = None if deadline is None else max(0.0, deadline - monotonic()) - race.start(partial(connect, address, port, remaining, local_address, options)) + race.start(partial(attempt, address), address) while not expired and race.winner is None and race.running: if deadline is None: race.wait(None) @@ -255,8 +266,8 @@ def connect_tcp( raise winner = race.settle() # A stream that won is used even if the deadline passed while it was handed over: each - # attempt's own connect timeout is the remaining budget, so it connected within it, and - # later I/O stays bounded by the request deadline. Only failures defer to the timeout. + # attempt connects within the budget left when it runs, so it connected before the + # deadline, and later I/O stays bounded by it. Only failures defer to the timeout. if winner is not None: return NetworkStream(winner) if expired: diff --git a/tests/test_sync_connect.py b/tests/test_sync_connect.py index f163ec3a..f3234593 100644 --- a/tests/test_sync_connect.py +++ b/tests/test_sync_connect.py @@ -38,23 +38,25 @@ def until(condition: Callable[[], bool], what: str) -> None: @dataclass class Network: hosts: dict[str, list[str]] = field(default_factory=dict) - # Every address the backend tried, in order, with its start time and connect timeout. - attempts: list[tuple[str, float, float | None]] = field(default_factory=list) + # Attempts in the order the scheduler launched them, recorded on the scheduler thread. + launches: list[tuple[str, float]] = field(default_factory=list) + # Each address's connect call, recorded by its worker: when it ran and its timeout. + runs: dict[str, tuple[float, float | None]] = field(default_factory=dict) silence: threading.Event = field(default_factory=threading.Event) @property def tried(self) -> list[str]: - return [address for address, _, _ in self.attempts] + return [address for address, _ in self.launches] @property def gaps(self) -> list[float]: - """Seconds between consecutive attempt starts: the scheduler's launch decisions.""" - starts = [at for _, at, _ in self.attempts] + """Seconds between consecutive launches: the scheduler's launch decisions.""" + starts = [at for _, at in self.launches] return [later - earlier for earlier, later in zip(starts, starts[1:], strict=False)] @property def timeouts(self) -> list[float | None]: - return [timeout for _, _, timeout in self.attempts] + return [self.runs[address][1] for address in self.tried] @pytest.fixture @@ -78,8 +80,16 @@ def getaddrinfo(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: for address in state.hosts[host] ] + launch = _sync_http.Race.start + + def start( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: + state.launches.append((address, time.monotonic())) + launch(race, connect, address) + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: - state.attempts.append((host, time.monotonic(), timeout)) + state.runs[host] = (time.monotonic(), timeout) if host in (SILENT, SILENT_V6): state.silence.wait(timeout) raise httpcore2.ConnectTimeout("timed out") @@ -89,6 +99,7 @@ def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: A monkeypatch.setattr(socket, "getaddrinfo", getaddrinfo) monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "start", start) try: yield state finally: @@ -109,11 +120,7 @@ def test_a_silent_first_address_falls_back_to_the_next_one(network: Network) -> assert network.tried == [SILENT_V6, SILENT, "127.0.0.1"] # Each silent address costs one attempt delay, not the 5 second connect timeout. assert elapsed < 2 - starts = [at for _, at, _ in network.attempts] - assert all( - later - earlier >= _sync_http.ATTEMPT_DELAY * 0.8 - for earlier, later in zip(starts, starts[1:], strict=False) - ) + assert all(gap >= _sync_http.ATTEMPT_DELAY * 0.8 for gap in network.gaps) def test_the_client_reads_through_a_silent_address( @@ -180,6 +187,35 @@ def test_the_wait_deadline_still_bounds_the_race( assert second <= 0.4 - _sync_http.ATTEMPT_DELAY * 0.8 +def test_an_attempt_whose_thread_starts_late_still_ends_at_the_deadline( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + # Every worker thread starts 0.3 s after it is launched. The second is launched at about + # 0.25 s and runs at about 0.55 s, so only about 0.05 s of the 0.6 s budget is left then. + network.hosts["late.proofline.invalid"] = [SILENT, SILENT_V6] + launch = _sync_http.Race.start + + def start_late( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: + def late() -> httpcore2.NetworkStream: + time.sleep(0.3) + return connect() + + launch(race, late, address) + + monkeypatch.setattr(_sync_http.Race, "start", start_late) + with httpx2.Client(transport=_sync_http.Transport(), timeout=0.6) as client: + started = time.monotonic() + with pytest.raises(httpx2.TimeoutException): + client.get("http://late.proofline.invalid:443/finding") + assert network.runs + for ran, timeout in network.runs.values(): + # No connect call may run past the request deadline, however late its thread started. + assert timeout is not None + assert ran + timeout <= started + 0.6 + 0.05 + + def test_every_refused_address_raises_a_connect_error(network: Network) -> None: network.hosts["closed.proofline.invalid"] = [REFUSED, REFUSED_V6] with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: @@ -246,12 +282,18 @@ def test_a_failure_while_an_attempt_starts_still_starts_the_next( # times out, so that failure has started nothing yet: the fourth attempt starts at once. first_fails = threading.Event() silence = threading.Event() - starts: dict[str, float] = {} + launches: dict[str, float] = {} original_wait = _sync_http.Race.wait + original_start = _sync_http.Race.start calls = 0 + def start( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: + launches[address] = time.monotonic() + original_start(race, connect, address) + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: - starts[host] = time.monotonic() if host == "192.0.2.1": first_fails.wait(5) raise httpcore2.ConnectError("Connection reset") @@ -272,39 +314,45 @@ def wait(race: _sync_http.Race, timeout: float | None, **kwargs: Any) -> int: monkeypatch.setattr(_sync_http, "resolve", lambda *_: addresses) monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) monkeypatch.setattr(_sync_http.Race, "wait", wait) + monkeypatch.setattr(_sync_http.Race, "start", start) try: with pytest.raises(httpcore2.ConnectTimeout): _sync_http.NetworkBackend().connect_tcp("dark.proofline.invalid", 443, 1.2) finally: silence.set() - assert list(starts) == addresses - assert starts["192.0.2.4"] - starts["192.0.2.3"] < _sync_http.ATTEMPT_DELAY / 2 + assert list(launches) == addresses + assert launches["192.0.2.4"] - launches["192.0.2.3"] < _sync_http.ATTEMPT_DELAY / 2 def test_a_failure_after_the_deadline_still_reports_the_timeout( monkeypatch: pytest.MonkeyPatch, ) -> None: - # Both attempts hang until the deadline ends the race; one then fails with a reset. - # The deadline ended the request, so the caller sees a timeout, not the late reset. + # Both attempts hang past the deadline. When the final wait returns at the deadline, both + # fail with a reset before the scheduler looks again. The deadline ended the request, so + # the caller sees a timeout, not the late reset. reset = threading.Event() def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: reset.wait(10) raise httpcore2.ConnectError("Connection reset") - settle = _sync_http.Race.settle + original_wait = _sync_http.Race.wait + deadline = 0.0 - def settle_then_fail(race: _sync_http.Race) -> httpcore2.NetworkStream | None: - winner = settle(race) - reset.set() - until(lambda: not race.running, "the late attempts to fail") - return winner + def wait(race: _sync_http.Race, timeout: float | None, **kwargs: Any) -> int: + seen = original_wait(race, timeout, **kwargs) + if time.monotonic() >= deadline and not reset.is_set(): + reset.set() + until(lambda: not race.running, "the late attempts to fail") + return seen monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) - monkeypatch.setattr(_sync_http.Race, "settle", settle_then_fail) + monkeypatch.setattr(_sync_http.Race, "wait", wait) + deadline = time.monotonic() + 0.4 with pytest.raises(httpcore2.ConnectTimeout): _sync_http.NetworkBackend().connect_tcp("dark.proofline.invalid", 443, 0.4) + assert reset.is_set() def test_a_winner_is_closed_when_starting_the_next_attempt_fails( @@ -322,14 +370,16 @@ def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: A original_start = _sync_http.Race.start starts = 0 - def start(race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream]) -> None: + def start( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: nonlocal starts starts += 1 if starts == 2: release.set() until(lambda: race.winner is not None, "the first attempt to connect") raise RuntimeError("can't start new thread") - original_start(race, connect) + original_start(race, connect, address) monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp)