From 9a2c7457594e2de3afa8be2a3138bce92d4d89f8 Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 21:02:20 +0000 Subject: [PATCH 01/16] feat: qualify eggfetch 0.3.0 for AInews pilot --- .github/workflows/pypi.yml | 47 ++++- .skills/release-process.md | 2 +- CHANGELOG.md | 38 +++- Cargo.lock | 12 +- crates/eggfetch-bench/src/bench_proxy.rs | 53 ++++- crates/eggfetch-cli/Cargo.toml | 4 +- crates/eggfetch-core/Cargo.toml | 4 +- .../eggfetch-core/src/pipeline/h3_dispatch.rs | 6 +- .../src/pipeline/hyper_dispatch.rs | 24 ++- crates/eggfetch-core/src/pipeline/mod.rs | 90 ++++++-- crates/eggfetch-core/src/timeout.rs | 27 ++- crates/eggfetch-core/src/transport/connect.rs | 10 +- crates/eggfetch-core/src/transport/direct.rs | 121 +++++++++-- crates/eggfetch-core/src/transport/http3.rs | 6 +- crates/eggfetch-core/src/transport/mod.rs | 105 +++++++++- crates/eggfetch-core/src/transport/proxy.rs | 42 ++-- crates/eggfetch-core/src/transport/uds.rs | 22 +- .../tests/native_http_body_tests.rs | 44 +++- crates/eggfetch-core/tests/timeout_tests.rs | 122 ++++++++++- crates/eggfetch-ffi/Cargo.toml | 4 +- crates/eggfetch-http-connect/Cargo.toml | 2 +- crates/eggfetch-node/Cargo.toml | 4 +- crates/eggfetch-node/package-lock.json | 4 +- crates/eggfetch-node/package.json | 2 +- crates/eggfetch-python/Cargo.toml | 4 +- crates/eggfetch-python/pyproject.toml | 5 +- .../python/eggfetch/compat/httpx/_urls.py | 86 ++++++-- .../python/eggfetch/integrations/__init__.py | 2 + .../python/eggfetch/integrations/httpx.py | 197 ++++++++++++++++++ .../compat/test_httpx_transport_bridge.py | 84 ++++++++ .../test_httpx_transport_sdk_construction.py | 128 ++++++++++++ .../tests/compat/test_url_query.py | 11 + crates/eggfetch-python/tests/test_sync.py | 2 +- docs/README.md | 1 + docs/architecture/benchmarks.md | 16 +- docs/architecture/build-ci.md | 6 +- docs/architecture/core-timeout-pool.md | 25 ++- docs/architecture/core-tls-proxy-protocols.md | 6 +- docs/architecture/dependency-policy.md | 11 + docs/concepts/lifecycle.md | 2 +- docs/concepts/pooling.md | 5 +- docs/python/guide.md | 3 + docs/python/httpx-transport.md | 48 +++++ docs/reference/versioning.md | 4 +- docs/releases/compatibility-policy.md | 8 +- docs/releases/process.md | 5 +- docs/verification-policy.md | 3 +- fuzz/Cargo.lock | 4 +- scripts/validate_wheel_coverage.py | 10 +- 49 files changed, 1306 insertions(+), 165 deletions(-) create mode 100644 crates/eggfetch-python/python/eggfetch/integrations/__init__.py create mode 100644 crates/eggfetch-python/python/eggfetch/integrations/httpx.py create mode 100644 crates/eggfetch-python/tests/compat/test_httpx_transport_bridge.py create mode 100644 crates/eggfetch-python/tests/compat/test_httpx_transport_sdk_construction.py create mode 100644 docs/python/httpx-transport.md diff --git a/.github/workflows/pypi.yml b/.github/workflows/pypi.yml index 9b9493a5..18c3d563 100644 --- a/.github/workflows/pypi.yml +++ b/.github/workflows/pypi.yml @@ -142,6 +142,43 @@ jobs: maturin-args: --target x86_64-unknown-linux-gnu manylinux: "2014" python: "3.15" + # Linux aarch64 uses a native runner for build and import smoke. + - os: linux + arch: aarch64 + runner: ubuntu-24.04-arm + maturin-args: --target aarch64-unknown-linux-gnu + manylinux: "2014" + python: "3.10" + - os: linux + arch: aarch64 + runner: ubuntu-24.04-arm + maturin-args: --target aarch64-unknown-linux-gnu + manylinux: "2014" + python: "3.11" + - os: linux + arch: aarch64 + runner: ubuntu-24.04-arm + maturin-args: --target aarch64-unknown-linux-gnu + manylinux: "2014" + python: "3.12" + - os: linux + arch: aarch64 + runner: ubuntu-24.04-arm + maturin-args: --target aarch64-unknown-linux-gnu + manylinux: "2014" + python: "3.13" + - os: linux + arch: aarch64 + runner: ubuntu-24.04-arm + maturin-args: --target aarch64-unknown-linux-gnu + manylinux: "2014" + python: "3.14" + - os: linux + arch: aarch64 + runner: ubuntu-24.04-arm + maturin-args: --target aarch64-unknown-linux-gnu + manylinux: "2014" + python: "3.15" # macOS arm64 - os: macos arch: arm64 @@ -221,12 +258,6 @@ jobs: # once 3.15.0 final ships, with no further change. allow-prereleases: ${{ matrix.python == '3.15' }} - - name: Set up QEMU - if: matrix.arch == 'aarch64' - uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0 - with: - platforms: arm64 - - name: Build wheel uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: @@ -419,8 +450,8 @@ jobs: echo "Sdists: $sdist_count" echo "Total: $total" - if [[ $wheel_count -ne 18 ]]; then - echo "FAIL: expected 18 wheels, found $wheel_count" >&2; exit 1 + if [[ $wheel_count -ne 24 ]]; then + echo "FAIL: expected 24 wheels, found $wheel_count" >&2; exit 1 fi if [[ $sdist_count -ne 1 ]]; then echo "FAIL: expected 1 sdist, found $sdist_count" >&2; exit 1 diff --git a/.skills/release-process.md b/.skills/release-process.md index 44f8bb22..a75e1c0c 100644 --- a/.skills/release-process.md +++ b/.skills/release-process.md @@ -67,7 +67,7 @@ crates.io versions are immutable. If publication is partial, bump and republish. ## CI - Routine CI (`.github/workflows/ci.yml`): runs `./scripts/check.sh` on pushes and pull requests. One Ubuntu job, no matrix; this includes the reviewed native/facade typing fixtures and stub drift check. Python tooling is pinned in `scripts/ci-requirements.txt` (maturin aligned with `scripts/release-requirements.txt`); tool bumps are reviewed diffs, never automated. -- PyPI CI (`.github/workflows/pypi.yml`): manually dispatched, builds 18 wheels + 1 sdist (linux-x86_64, macos-arm64, windows-x86_64 × Python 3.10–3.15). +- PyPI CI (`.github/workflows/pypi.yml`): manually dispatched, builds 24 wheels + 1 sdist (linux-x86_64, linux-aarch64, macos-arm64, windows-x86_64 × Python 3.10–3.15). ## Architecture References diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a0c701c..02bba711 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,41 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/). +## [0.3.0] - 2026-10-30 + +### Added + +- Python: add the optional `eggfetch[httpx-transport]` extra with the + synchronous `EggFetchTransport` for HTTPX 0.28.x. The adapter preserves + HTTPX request/response semantics and maps EggFetch failures to HTTPX's + exception hierarchy. Async HTTPX transports and HTTP/3 are not supported by + this integration. +- PyPI: build and smoke-test Linux aarch64 wheels on native ARM runners for + Python 3.10–3.15. The release matrix now produces 24 wheels plus one source + distribution. + +### Fixed + +- Core: on HTTP/1.1 and HTTP/2 routes, apply the configured read timeout while + waiting for response headers, beginning after request-body production + completes. Connect and upload time remain owned by their respective timeout + phases; the total deadline keeps precedence. Experimental HTTP/3 retains its + documented body-read-only timeout behavior. This brings the synchronous + HTTPX transport bridge in line with HTTPX read-timeout behavior. +- Benchmarks: restore blocking mode on accepted proxy sockets. The listener + remains nonblocking for shutdown, but accepted sockets are explicitly made + blocking before the handler uses blocking reads. This prevents intermittent + `WouldBlock`/`IncompleteMessage` failures on platforms that preserve + nonblocking mode on accepted sockets. +- Security: update Tokio, zstd, and Brotli to versions that clear the live + RustSec advisories recorded during the release qualification pass. + +### Changed + +- The coordinated pre-1.0 version is now `0.3.0` across all six published + crates and the PyPI package. The new Python integration is opt-in and does + not change AInews or other consumers' HTTP client behavior. + ## [0.2.2] - 2026-10-02 ### Added @@ -291,7 +326,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/). - Multipart boundary validation - Proxy authentication boundary enforcement -[Unreleased]: https://github.com/eggstack/eggfetch/compare/v0.2.2...HEAD +[Unreleased]: https://github.com/eggstack/eggfetch/compare/v0.3.0...HEAD +[0.3.0]: https://github.com/eggstack/eggfetch/compare/v0.2.2...v0.3.0 [0.2.2]: https://github.com/eggstack/eggfetch/releases/tag/v0.2.2 [0.2.1]: https://github.com/eggstack/eggfetch/releases/tag/v0.2.1 [0.2.0]: https://github.com/eggstack/eggfetch/releases/tag/v0.2.0 diff --git a/Cargo.lock b/Cargo.lock index 77dbb366..c581d9d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -505,7 +505,7 @@ dependencies = [ [[package]] name = "eggfetch-cli" -version = "0.2.2" +version = "0.3.0" dependencies = [ "anyhow", "bytes", @@ -527,7 +527,7 @@ dependencies = [ [[package]] name = "eggfetch-core" -version = "0.2.2" +version = "0.3.0" dependencies = [ "async-compression", "base64 0.23.1", @@ -573,7 +573,7 @@ dependencies = [ [[package]] name = "eggfetch-ffi" -version = "0.2.2" +version = "0.3.0" dependencies = [ "bytes", "eggfetch-core", @@ -585,7 +585,7 @@ dependencies = [ [[package]] name = "eggfetch-http-connect" -version = "0.2.2" +version = "0.3.0" dependencies = [ "base64 0.23.1", "thiserror", @@ -594,7 +594,7 @@ dependencies = [ [[package]] name = "eggfetch-node" -version = "0.2.2" +version = "0.3.0" dependencies = [ "eggfetch-ffi", "napi", @@ -606,7 +606,7 @@ dependencies = [ [[package]] name = "eggfetch-python" -version = "0.2.2" +version = "0.3.0" dependencies = [ "bytes", "eggfetch-core", diff --git a/crates/eggfetch-bench/src/bench_proxy.rs b/crates/eggfetch-bench/src/bench_proxy.rs index f3806478..08bfb219 100644 --- a/crates/eggfetch-bench/src/bench_proxy.rs +++ b/crates/eggfetch-bench/src/bench_proxy.rs @@ -37,6 +37,14 @@ impl BenchProxy { while !thread_stop.load(Ordering::Acquire) { match listener.accept() { Ok((stream, _)) => { + // The listener is nonblocking so shutdown can wake + // its accept loop. Accepted sockets must be blocking: + // the connection handler uses blocking line/body I/O, + // and some platforms preserve nonblocking mode on + // accepted sockets. + if stream.set_nonblocking(false).is_err() { + continue; + } thread_count.fetch_add(1, Ordering::Relaxed); if let Ok(handler) = thread::Builder::new() .name("eggfetch-bench-proxy-client".into()) @@ -225,16 +233,17 @@ mod tests { use std::net::TcpListener; use std::sync::{Arc, Mutex}; use std::thread; + use std::time::{Duration, Instant}; type RequestRecords = Arc>>>; - fn origin() -> (String, RequestRecords, thread::JoinHandle<()>) { + fn origin(expected_requests: usize) -> (String, RequestRecords, thread::JoinHandle<()>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let seen = Arc::new(Mutex::new(Vec::new())); let records = Arc::clone(&seen); let handle = thread::spawn(move || { - for _ in 0..3 { + for _ in 0..expected_requests { let Ok((mut stream, _)) = listener.accept() else { break; }; @@ -259,7 +268,7 @@ mod tests { #[tokio::test] async fn forwards_complete_origin_form_requests_and_repeated_gets() { - let (origin_url, records, origin_thread) = origin(); + let (origin_url, records, origin_thread) = origin(3); let mut proxy = BenchProxy::start(); let client = Client::builder() .proxy(Proxy::http(&proxy.url()).unwrap()) @@ -296,4 +305,42 @@ mod tests { assert_eq!(proxy.connections_served(), 3); proxy.shutdown(); } + + #[test] + fn accepted_socket_waits_for_a_later_request_head() { + let (origin_url, records, origin_thread) = origin(1); + let mut proxy = BenchProxy::start(); + let proxy_address = proxy.url().trim_start_matches("http://").to_owned(); + let mut client = std::net::TcpStream::connect(proxy_address).unwrap(); + client + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + + let accept_deadline = Instant::now() + Duration::from_secs(1); + while proxy.connections_served() == 0 && Instant::now() < accept_deadline { + thread::sleep(Duration::from_millis(1)); + } + assert_eq!(proxy.connections_served(), 1, "proxy did not accept client"); + + // Give the handler time to call read_line before the request arrives. + // If an accepted socket inherited O_NONBLOCK from the listener, that + // read returns WouldBlock and the proxy closes the connection here. + thread::sleep(Duration::from_millis(50)); + let host = origin_url.trim_start_matches("http://"); + write!( + client, + "GET {origin_url}/delayed HTTP/1.1\r\nHost: {host}\r\n\r\n" + ) + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).unwrap(); + let response = String::from_utf8_lossy(&response); + assert!(response.starts_with("HTTP/1.1 200 OK\r\n"), "{response}"); + assert!(response.ends_with("\r\n\r\nok"), "{response}"); + + origin_thread.join().unwrap(); + assert!(String::from_utf8_lossy(&records.lock().unwrap()[0]) + .starts_with("GET /delayed HTTP/1.1\r\n")); + proxy.shutdown(); + } } diff --git a/crates/eggfetch-cli/Cargo.toml b/crates/eggfetch-cli/Cargo.toml index deff7f9b..bde17f73 100644 --- a/crates/eggfetch-cli/Cargo.toml +++ b/crates/eggfetch-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggfetch-cli" -version = "0.2.2" +version = "0.3.0" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -29,7 +29,7 @@ name = "eggfetch" path = "src/main.rs" [dependencies] -eggfetch-core = { version = "0.2.2", path = "../eggfetch-core", features = ["cookies", "multipart", "proxy"] } +eggfetch-core = { version = "0.3.0", path = "../eggfetch-core", features = ["cookies", "multipart", "proxy"] } clap = { version = "4", features = ["derive", "wrap_help", "env"] } clap_complete = "4" serde_json = "1" diff --git a/crates/eggfetch-core/Cargo.toml b/crates/eggfetch-core/Cargo.toml index a9a00896..5ae90dd1 100644 --- a/crates/eggfetch-core/Cargo.toml +++ b/crates/eggfetch-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggfetch-core" -version = "0.2.2" +version = "0.3.0" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -82,7 +82,7 @@ test-util = ["tokio/test-util"] [dependencies] bytes = "1" -eggfetch-http-connect = { version = "0.2.2", path = "../eggfetch-http-connect", optional = true } +eggfetch-http-connect = { version = "0.3.0", path = "../eggfetch-http-connect", optional = true } futures-core = "0.3" futures-util = { version = "0.3", default-features = false, features = ["alloc"] } http = "1" diff --git a/crates/eggfetch-core/src/pipeline/h3_dispatch.rs b/crates/eggfetch-core/src/pipeline/h3_dispatch.rs index 8112de27..b901a197 100644 --- a/crates/eggfetch-core/src/pipeline/h3_dispatch.rs +++ b/crates/eggfetch-core/src/pipeline/h3_dispatch.rs @@ -237,8 +237,9 @@ pub(super) async fn send_h3_route( // inside the connector as one budget shared across address // fallback attempts. `remaining_total` stays the outer // deadline enforced here and is never restarted per address. - // Read/write phases are enforced by the body wrappers at the - // documented boundaries. Boxed so the QUIC handshake state + // H3 currently enforces read on response-body progress only; unlike + // Hyper/UDS routes, its response-header wait remains total-bounded. + // Write is enforced by the request-body wrapper. Boxed so the QUIC handshake state // does not bloat the shared dispatch future. let h3_alt_clone = h3_alt.clone(); let connect_budget = hop_timeout.connect; @@ -340,6 +341,7 @@ pub(super) async fn send_h3_route( remaining_total, transport_hints, failure_context, + hop_timeout.read, ) .await } else { diff --git a/crates/eggfetch-core/src/pipeline/hyper_dispatch.rs b/crates/eggfetch-core/src/pipeline/hyper_dispatch.rs index a640cf5c..3292d129 100644 --- a/crates/eggfetch-core/src/pipeline/hyper_dispatch.rs +++ b/crates/eggfetch-core/src/pipeline/hyper_dispatch.rs @@ -33,7 +33,13 @@ pub(super) fn build_hyper_request( headers: Headers, body: RequestBody, ) -> Result> { - build_http_request_owned(method, uri, version, headers, body.into_http_body()) + build_http_request_owned( + method, + uri, + version, + headers, + crate::transport::HyperRequestBody::new(body.into_http_body()), + ) } /// Build a request by moving an already-owned header map into the request. @@ -70,6 +76,7 @@ pub(super) async fn send_uds_route( url: url::Url, transport_hints: &TransportHints, remaining_total: Option, + read_timeout: Option, ) -> Result { #[cfg(all(unix, feature = "advanced-routing"))] { @@ -83,6 +90,8 @@ pub(super) async fn send_uds_route( hyper_request, url, transport_hints.trace.as_deref(), + read_timeout, + remaining_total, ); super::send_with_total_timeout(send_future, remaining_total).await } @@ -98,6 +107,7 @@ pub(super) async fn send_uds_route( url, transport_hints, remaining_total, + read_timeout, ); Err(Error::Unsupported( "Unix domain sockets are not supported on this platform".into(), @@ -123,6 +133,7 @@ pub(super) async fn send_custom_route( transport_hints: &TransportHints, failure_context: Option<&crate::error::RequestFailureContext>, remaining_total: Option, + read_timeout: Option, ) -> Result { let custom_client = if let Some(sni_hostname) = transport_hints.sni_hostname.as_deref() { inner.sni_custom_client(sni_hostname).await? @@ -140,6 +151,8 @@ pub(super) async fn send_custom_route( url, transport_hints.trace.as_deref(), failure_context, + read_timeout, + remaining_total, ); super::send_with_total_timeout(send_future, remaining_total).await } @@ -162,6 +175,7 @@ pub(super) async fn send_direct_route( transport_hints: &TransportHints, failure_context: Option<&crate::error::RequestFailureContext>, remaining_total: Option, + read_timeout: Option, ) -> Result { let resolved_client; let direct_client = if let Some(target) = transport_hints.resolved_target.as_ref() { @@ -189,6 +203,8 @@ pub(super) async fn send_direct_route( url, transport_hints.trace.as_deref(), failure_context, + read_timeout, + remaining_total, ); super::send_with_total_timeout(send_future, remaining_total).await } @@ -210,6 +226,7 @@ pub(super) async fn send_sni_route( transport_hints: &TransportHints, failure_context: Option<&crate::error::RequestFailureContext>, remaining_total: Option, + read_timeout: Option, ) -> Result { // SNI override separates DNS/TCP (to the original host) from TLS // (with the override hostname). @@ -225,6 +242,8 @@ pub(super) async fn send_sni_route( url, transport_hints.trace.as_deref(), failure_context, + read_timeout, + remaining_total, ); super::send_with_total_timeout(send_future, remaining_total).await } @@ -250,6 +269,7 @@ pub(super) async fn send_hyper_request( remaining_total: Option, transport_hints: &TransportHints, failure_context: Option<&crate::error::RequestFailureContext>, + read_timeout: Option, ) -> Result { let hyper_client = inner.hyper_client.as_ref().ok_or_else(|| { crate::http_version::missing_client_error(inner.config.http_version_policy) @@ -264,6 +284,8 @@ pub(super) async fn send_hyper_request( url, transport_hints.trace.as_deref(), failure_context, + read_timeout, + remaining_total, ); super::send_with_total_timeout(send_future, remaining_total).await diff --git a/crates/eggfetch-core/src/pipeline/mod.rs b/crates/eggfetch-core/src/pipeline/mod.rs index dd6d8b60..eecabfc1 100644 --- a/crates/eggfetch-core/src/pipeline/mod.rs +++ b/crates/eggfetch-core/src/pipeline/mod.rs @@ -323,6 +323,7 @@ pub(crate) async fn send_single_request( url, &transport_hints, remaining_total, + hop_timeout.read, ) .await? } @@ -339,6 +340,7 @@ pub(crate) async fn send_single_request( &transport_hints, failure_context.as_deref(), remaining_total, + hop_timeout.read, ) .await? } @@ -355,6 +357,7 @@ pub(crate) async fn send_single_request( &transport_hints, failure_context.as_deref(), remaining_total, + hop_timeout.read, ) .await? } @@ -397,6 +400,7 @@ pub(crate) async fn send_single_request( &transport_hints, failure_context.as_deref(), remaining_total, + hop_timeout.read, ) .await? } @@ -436,6 +440,7 @@ pub(crate) async fn send_single_request( remaining_total, &transport_hints, failure_context.as_deref(), + hop_timeout.read, ) .await? } @@ -664,10 +669,21 @@ where .uds_client .as_ref() .ok_or_else(|| Error::Unsupported("UDS client not available".into()))?; - let hyper_request = - hyper_dispatch::build_http_request_owned(method, uri, version, headers, body)?; + let hyper_request = hyper_dispatch::build_http_request_owned( + method, + uri, + version, + headers, + crate::transport::HyperRequestBody::new(body), + )?; send_with_total_timeout( - crate::transport::direct::send_raw_request(uds_client, hyper_request, trace), + crate::transport::direct::send_raw_request( + uds_client, + hyper_request, + trace, + timeout.read, + remaining_total, + ), remaining_total, ) .await? @@ -692,10 +708,21 @@ where .ok_or_else(|| Error::Unsupported("custom dialer client not available".into()))? .clone() }; - let hyper_request = - hyper_dispatch::build_http_request_owned(method, uri, version, headers, body)?; + let hyper_request = hyper_dispatch::build_http_request_owned( + method, + uri, + version, + headers, + crate::transport::HyperRequestBody::new(body), + )?; send_with_total_timeout( - crate::transport::direct::send_raw_request(&custom_client, hyper_request, trace), + crate::transport::direct::send_raw_request( + &custom_client, + hyper_request, + trace, + timeout.read, + remaining_total, + ), remaining_total, ) .await? @@ -718,10 +745,21 @@ where .as_ref() .ok_or_else(|| Error::Unsupported("direct client not available".into()))? }; - let hyper_request = - hyper_dispatch::build_http_request_owned(method, uri, version, headers, body)?; + let hyper_request = hyper_dispatch::build_http_request_owned( + method, + uri, + version, + headers, + crate::transport::HyperRequestBody::new(body), + )?; send_with_total_timeout( - crate::transport::direct::send_raw_request(direct_client, hyper_request, trace), + crate::transport::direct::send_raw_request( + direct_client, + hyper_request, + trace, + timeout.read, + remaining_total, + ), remaining_total, ) .await? @@ -732,10 +770,21 @@ where Error::RequestBuild("SNI route selected without sni_hostname".into()) })?; let sni_client = inner.sni_client(sni_hostname).await?; - let hyper_request = - hyper_dispatch::build_http_request_owned(method, uri, version, headers, body)?; + let hyper_request = hyper_dispatch::build_http_request_owned( + method, + uri, + version, + headers, + crate::transport::HyperRequestBody::new(body), + )?; send_with_total_timeout( - crate::transport::direct::send_raw_request(&sni_client, hyper_request, trace), + crate::transport::direct::send_raw_request( + &sni_client, + hyper_request, + trace, + timeout.read, + remaining_total, + ), remaining_total, ) .await? @@ -744,10 +793,21 @@ where let hyper_client = inner.hyper_client.as_ref().ok_or_else(|| { crate::http_version::missing_client_error(inner.config.http_version_policy) })?; - let hyper_request = - hyper_dispatch::build_http_request_owned(method, uri, version, headers, body)?; + let hyper_request = hyper_dispatch::build_http_request_owned( + method, + uri, + version, + headers, + crate::transport::HyperRequestBody::new(body), + )?; send_with_total_timeout( - crate::transport::direct::send_raw_request(hyper_client, hyper_request, trace), + crate::transport::direct::send_raw_request( + hyper_client, + hyper_request, + trace, + timeout.read, + remaining_total, + ), remaining_total, ) .await? diff --git a/crates/eggfetch-core/src/timeout.rs b/crates/eggfetch-core/src/timeout.rs index 2c044be7..1fbf03d1 100644 --- a/crates/eggfetch-core/src/timeout.rs +++ b/crates/eggfetch-core/src/timeout.rs @@ -13,9 +13,9 @@ //! - **Write**: time for the request body producer to yield each chunk. //! Only applies to streamed request bodies; buffered bodies complete //! synchronously. -//! - **Read**: time to wait for response headers and each response body -//! chunk. The deadline resets on every chunk arrival. The timer starts -//! when body consumption begins, not when response headers arrive. +//! - **Read**: after the request body producer completes, time to wait for +//! response headers, then each response body chunk. The deadline resets on +//! each chunk. Early responses do not charge upload time to the read budget. //! - **Total**: absolute wall-clock deadline across the entire request //! lifecycle, from logical request start through response-body EOF (or //! terminal body error), including pool acquisition, transport setup, @@ -39,10 +39,11 @@ //! # Enforcement //! //! - **Pool** and **Total** are enforced with `tokio::time::timeout`. -//! - **Read** is enforced by a per-chunk wrapper stream that fires -//! `Error::Timeout { phase: Read }` if no chunk arrives within the -//! configured duration. The deadline starts on first body poll and resets -//! on every chunk. +//! - **Read** is enforced while waiting for response headers after request +//! body completion on Hyper and UDS routes, then by a per-chunk wrapper +//! stream. The body deadline starts on first body poll and resets on every +//! chunk. Experimental HTTP/3 currently applies this field to response-body +//! progress only; its header wait remains total-bounded. //! - **Total** is enforced in two stages: `tokio::time::timeout` bounds the //! transport future up to response headers, and a crate-private absolute //! response-body deadline (`ResponseDeadline`) bounds body streaming @@ -112,9 +113,10 @@ impl std::fmt::Display for TimeoutPhase { /// # Enforcement /// /// - `pool`: enforced via `tokio::time::timeout` around the pool acquire. -/// - `read`: enforced per chunk by a wrapper stream that fires -/// `Error::Timeout { phase: Read }` when no data arrives within the -/// configured duration. Resets on every chunk arrival. +/// - `read`: on Hyper/UDS routes, response-header waiting is bounded after +/// request-body completion; response-body progress is enforced per chunk by +/// a wrapper stream and resets on each arrival. Experimental HTTP/3 currently +/// applies this field to response-body chunks only. /// - `write`: enforced per chunk by a wrapper stream that fires /// `Error::Timeout { phase: Write }` when the request body producer /// does not yield a chunk within the configured duration. Resets on @@ -161,7 +163,10 @@ pub struct Timeout { /// Applies to high-level streamed request bodies and the native /// `http_body::Body` execution surface. pub write: Option, - /// Time allowed between response body chunks. Resets on every chunk. + /// Time allowed for response headers after request-body completion and + /// between response-body chunks. The body timer starts on first body poll + /// and resets on every chunk. Experimental HTTP/3 currently applies this + /// field to response-body progress only. pub read: Option, /// Optional wall-clock cap across the entire request lifecycle. pub total: Option, diff --git a/crates/eggfetch-core/src/transport/connect.rs b/crates/eggfetch-core/src/transport/connect.rs index 47ab0904..edb7097a 100644 --- a/crates/eggfetch-core/src/transport/connect.rs +++ b/crates/eggfetch-core/src/transport/connect.rs @@ -280,6 +280,8 @@ pub(crate) async fn send_https_connect_request( transport_hints, client, ctx.failure_context, + ctx.read_timeout, + ctx.remaining_total, ) .await; } @@ -344,6 +346,8 @@ async fn send_https_connect_request_hyper( transport_hints: &crate::transport_hints::TransportHints, client: &crate::transport::TimeoutConnectClient, failure_context: Option<&crate::error::RequestFailureContext>, + read_timeout: Option, + remaining_total: Option, ) -> Result { let target = if let Some(target) = transport_hints.target.as_deref() { crate::pipeline::validate_target(target)?; @@ -380,7 +384,9 @@ async fn send_https_connect_request_hyper( request = request.header(name, value); } let request = request - .body(body.into_http_body()) + .body(crate::transport::HyperRequestBody::new( + body.into_http_body(), + )) .map_err(|error| Error::RequestBuild(error.to_string()))?; crate::transport::direct::send_request( client, @@ -388,6 +394,8 @@ async fn send_https_connect_request_hyper( dest_url.clone(), transport_hints.trace.as_deref(), failure_context, + read_timeout, + remaining_total, ) .await } diff --git a/crates/eggfetch-core/src/transport/direct.rs b/crates/eggfetch-core/src/transport/direct.rs index dba58384..354bc8f9 100644 --- a/crates/eggfetch-core/src/transport/direct.rs +++ b/crates/eggfetch-core/src/transport/direct.rs @@ -3,6 +3,7 @@ #[cfg(feature = "transport-http2")] use std::error::Error as StdError; use std::sync::Arc; +use std::time::Duration; use bytes::Bytes; @@ -144,20 +145,26 @@ async fn finish_hyper_response( #[cfg(feature = "high-level-url")] pub(crate) async fn send_request( hyper_client: &hyper_util::client::legacy::Client, - request: http::Request, + mut request: http::Request, url: url::Url, trace: Option<&dyn TraceObserver>, failure_context: Option<&crate::error::RequestFailureContext>, + read_timeout: Option, + remaining_total: Option, ) -> Result where C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static, { emit_send_start(trace, request.method().as_str(), request.uri())?; - let result = hyper_client - .request(request) - .await - .map_err(|error| map_send_error_with_context(error, failure_context)); + let completion = request.body_mut().take_completion_receiver(); + let send = async { + hyper_client + .request(request) + .await + .map_err(|error| map_send_error_with_context(error, failure_context)) + }; + let result = send_with_read_timeout(send, completion, read_timeout, remaining_total).await; match result { Ok(hyper_response) => Ok(finish_hyper_response(hyper_response, url, trace).await), @@ -174,19 +181,25 @@ where #[cfg(feature = "proxy")] pub(crate) async fn send_proxy_request( hyper_client: &hyper_util::client::legacy::Client, - request: http::Request, + mut request: http::Request, url: url::Url, trace: Option<&dyn TraceObserver>, failure_context: Option<&crate::error::RequestFailureContext>, + read_timeout: Option, + remaining_total: Option, ) -> Result where C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static, { emit_send_start(trace, request.method().as_str(), request.uri())?; - let result = hyper_client - .request(request) - .await - .map_err(|error| map_send_error_for_proxy(error, failure_context)); + let completion = request.body_mut().take_completion_receiver(); + let send = async { + hyper_client + .request(request) + .await + .map_err(|error| map_send_error_for_proxy(error, failure_context)) + }; + let result = send_with_read_timeout(send, completion, read_timeout, remaining_total).await; match result { Ok(hyper_response) => Ok(finish_hyper_response(hyper_response, url, trace).await), Err(error) => { @@ -202,21 +215,25 @@ where /// pipeline. pub(crate) async fn send_raw_request( hyper_client: &hyper_util::client::legacy::Client, - request: http::Request, + mut request: http::Request, trace: Option<&dyn TraceObserver>, + read_timeout: Option, + remaining_total: Option, ) -> Result> where C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static, { emit_send_start(trace, request.method().as_str(), request.uri())?; - match hyper_client.request(request).await { + let completion = request.body_mut().take_completion_receiver(); + let send = async { hyper_client.request(request).await.map_err(map_send_error) }; + match send_with_read_timeout(send, completion, read_timeout, remaining_total).await { Ok(response) => { emit_receive_complete(trace, response.status().as_u16()); Ok(response) } Err(error) => { emit_send_failed(trace); - Err(map_send_error(error)) + Err(error) } } } @@ -233,20 +250,26 @@ where #[cfg(feature = "high-level-url")] pub(crate) async fn send_direct_request( hyper_client: &hyper_util::client::legacy::Client, - request: http::Request, + mut request: http::Request, url: url::Url, trace: Option<&dyn TraceObserver>, failure_context: Option<&crate::error::RequestFailureContext>, + read_timeout: Option, + remaining_total: Option, ) -> Result where C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static, { emit_send_start(trace, request.method().as_str(), request.uri())?; - let result = hyper_client - .request(request) - .await - .map_err(|error| map_send_error_with_context(error, failure_context)); + let completion = request.body_mut().take_completion_receiver(); + let send = async { + hyper_client + .request(request) + .await + .map_err(|error| map_send_error_with_context(error, failure_context)) + }; + let result = send_with_read_timeout(send, completion, read_timeout, remaining_total).await; match result { Ok(hyper_response) => Ok(finish_hyper_response(hyper_response, url, trace).await), @@ -257,6 +280,68 @@ where } } +/// Bound response-header wait after Hyper consumes the request body. +/// +/// Connection setup and request-body production keep their existing connect +/// and write budgets. When the total deadline is earlier than or tied with +/// the read deadline, the outer total wrapper remains authoritative. +pub(crate) async fn send_with_read_timeout( + send_future: F, + completion: Option>, + read_timeout: Option, + remaining_total: Option, +) -> Result +where + F: std::future::Future>, +{ + use crate::timeout::TimeoutPhase; + + let (Some(completion), Some(read_timeout)) = (completion, read_timeout) else { + return send_future.await; + }; + let started = tokio::time::Instant::now(); + tokio::pin!(send_future); + tokio::pin!(completion); + + let sent_at = tokio::select! { + biased; + result = &mut send_future => return result, + completed = &mut completion => match completed { + Ok(at) => at, + Err(_) => return send_future.await, + }, + }; + let read_deadline = sent_at + read_timeout; + let total_deadline = remaining_total.map(|remaining| started + remaining); + if total_deadline.is_some_and(|deadline| deadline <= read_deadline) { + return send_future.await; + } + + if tokio::time::Instant::now() >= read_deadline { + return Err(Error::Timeout { + phase: TimeoutPhase::Read, + elapsed: tokio::time::Instant::now().saturating_duration_since(sent_at), + }); + } + tokio::select! { + biased; + () = tokio::time::sleep_until(read_deadline) => Err(Error::Timeout { + phase: TimeoutPhase::Read, + elapsed: tokio::time::Instant::now().saturating_duration_since(sent_at), + }), + result = &mut send_future => { + if tokio::time::Instant::now() >= read_deadline { + Err(Error::Timeout { + phase: TimeoutPhase::Read, + elapsed: tokio::time::Instant::now().saturating_duration_since(sent_at), + }) + } else { + result + } + }, + } +} + /// Returns `true` for HTTP status codes that indicate a protocol upgrade /// on the direct (non-proxy) send path. /// diff --git a/crates/eggfetch-core/src/transport/http3.rs b/crates/eggfetch-core/src/transport/http3.rs index a0badcaa..f0fecca4 100644 --- a/crates/eggfetch-core/src/transport/http3.rs +++ b/crates/eggfetch-core/src/transport/http3.rs @@ -35,8 +35,10 @@ //! connect budget shared across address fallback attempts. `Timeout.total` //! remains the outer logical deadline enforced by the pipeline and is never //! restarted per address or reconnect. -//! - `Timeout.read` applies to response-body progress at the documented -//! response boundary (post-transport wrapper). `Timeout.write` applies to +//! - `Timeout.read` currently applies to response-body progress at the +//! documented response boundary (post-transport wrapper); response-header +//! waiting remains total-bounded on this experimental transport. +//! `Timeout.write` applies to //! streamed request-body progress via the pre-transport wrapper installed //! before dispatch. //! - QUIC idle lifetime derives from `PoolConfig::idle_timeout` diff --git a/crates/eggfetch-core/src/transport/mod.rs b/crates/eggfetch-core/src/transport/mod.rs index 22755d6d..cd6609f5 100644 --- a/crates/eggfetch-core/src/transport/mod.rs +++ b/crates/eggfetch-core/src/transport/mod.rs @@ -5,6 +5,10 @@ //! HTTP/3 transport over QUIC is available when the `http3` feature is enabled. use bytes::Bytes; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::task::{Context, Poll}; /// Private connection-establishment evidence shared by transport seams. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -25,9 +29,104 @@ pub(crate) type Connector = hyper_rustls::HttpsConnector< pub(crate) type Connector = hyper_util::client::legacy::connect::HttpConnector; -/// HTTP request body type expected by the hyper client. -pub(crate) type HyperRequestBody = - http_body_util::combinators::UnsyncBoxBody>; +/// HTTP request body type expected by Hyper. +/// +/// The completion channel marks when Hyper has consumed the request body +/// producer. The high-level response-header read timeout starts at this +/// boundary, so connection setup and a stalled upload remain owned by their +/// connect/write budgets. +pub(crate) struct HyperRequestBody { + inner: Pin< + Box< + http_body_util::combinators::UnsyncBoxBody< + Bytes, + Box, + >, + >, + >, + completion_tx: Mutex>>, + completion_rx: Option>, + complete: AtomicBool, +} + +impl HyperRequestBody { + pub(crate) fn new( + inner: http_body_util::combinators::UnsyncBoxBody< + Bytes, + Box, + >, + ) -> Self { + let (completion_tx, completion_rx) = tokio::sync::oneshot::channel(); + Self { + inner: Box::pin(inner), + completion_tx: Mutex::new(Some(completion_tx)), + completion_rx: Some(completion_rx), + complete: AtomicBool::new(false), + } + } + + pub(crate) fn take_completion_receiver( + &mut self, + ) -> Option> { + self.completion_rx.take() + } + + fn mark_complete(&self) { + if !self.complete.swap(true, Ordering::AcqRel) { + if let Ok(mut sender) = self.completion_tx.lock() { + if let Some(sender) = sender.take() { + let _ = sender.send(tokio::time::Instant::now()); + } + } + } + } +} + +impl http_body::Body for HyperRequestBody { + type Data = Bytes; + type Error = Box; + + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + let this = self.as_mut().get_mut(); + match this.inner.as_mut().poll_frame(cx) { + Poll::Ready(Some(Ok(frame))) => { + if this.inner.as_ref().get_ref().is_end_stream() { + this.mark_complete(); + } + Poll::Ready(Some(Ok(frame))) + } + Poll::Ready(None) => { + this.mark_complete(); + Poll::Ready(None) + } + Poll::Ready(Some(Err(error))) => { + if let Ok(mut sender) = this.completion_tx.lock() { + sender.take(); + } + Poll::Ready(Some(Err(error))) + } + other => other, + } + } + + fn is_end_stream(&self) -> bool { + // Preserve the wrapped body's framing signal exactly. Hyper may + // inspect an empty body without polling it, so publish completion + // when that signal is observed as well. + let is_end_stream = self.inner.as_ref().get_ref().is_end_stream(); + if is_end_stream { + self.mark_complete(); + } + is_end_stream + } + + fn size_hint(&self) -> http_body::SizeHint { + self.inner.as_ref().get_ref().size_hint() + } +} #[cfg(feature = "advanced-routing")] pub(crate) type CustomConnector = custom_connector::CustomConnector; diff --git a/crates/eggfetch-core/src/transport/proxy.rs b/crates/eggfetch-core/src/transport/proxy.rs index 4096b5e5..a48f8e2f 100644 --- a/crates/eggfetch-core/src/transport/proxy.rs +++ b/crates/eggfetch-core/src/transport/proxy.rs @@ -613,6 +613,8 @@ async fn send_http_proxy_request( transport_hints, forward_client, ctx.failure_context, + ctx.read_timeout, + ctx.remaining_total, ) .await; } @@ -715,6 +717,8 @@ async fn send_http_proxy_request_hyper( transport_hints: &crate::transport_hints::TransportHints, client: &crate::transport::TimeoutForwardClient, failure_context: Option<&crate::error::RequestFailureContext>, + read_timeout: Option, + remaining_total: Option, ) -> Result { let absolute_uri = transport_hints .target @@ -745,7 +749,9 @@ async fn send_http_proxy_request_hyper( request = request.header(name, value); } let request = request - .body(body.into_http_body()) + .body(crate::transport::HyperRequestBody::new( + body.into_http_body(), + )) .map_err(|error| Error::RequestBuild(error.to_string()))?; crate::transport::direct::send_proxy_request( client, @@ -753,6 +759,8 @@ async fn send_http_proxy_request_hyper( dest_url.clone(), transport_hints.trace.as_deref(), failure_context, + read_timeout, + remaining_total, ) .await } @@ -1156,22 +1164,30 @@ async fn send_socks_request( .uri(uri) .version(version); let request = request - .body(body.into_http_body()) + .body(crate::transport::HyperRequestBody::new( + body.into_http_body(), + )) .map_err(|e| Error::RequestBuild(e.to_string()))?; let mut request = request; *request.headers_mut() = headers.into_inner(); + let completion = request.body_mut().take_completion_receiver(); + let send = async { client.request(request).await.map_err(map_socks_send_error) }; + let send = super::direct::send_with_read_timeout( + send, + completion, + ctx.read_timeout, + ctx.remaining_total, + ); let response = match ctx.remaining_total { - Some(duration) => tokio::time::timeout(duration, client.request(request)) - .await - .map_err(|_| Error::Timeout { - phase: TimeoutPhase::Total, - elapsed: duration, - })? - .map_err(map_socks_send_error)?, - None => client - .request(request) - .await - .map_err(map_socks_send_error)?, + Some(duration) => { + tokio::time::timeout(duration, send) + .await + .map_err(|_| Error::Timeout { + phase: TimeoutPhase::Total, + elapsed: duration, + })?? + } + None => send.await?, }; let (response_parts, incoming) = response.into_parts(); let trailers = crate::body::SharedTrailers::new(); diff --git a/crates/eggfetch-core/src/transport/uds.rs b/crates/eggfetch-core/src/transport/uds.rs index 0c7706a1..23e3eb48 100644 --- a/crates/eggfetch-core/src/transport/uds.rs +++ b/crates/eggfetch-core/src/transport/uds.rs @@ -229,16 +229,28 @@ impl Service for UdsConnector { #[cfg(feature = "high-level-url")] pub(crate) async fn send_request( client: &crate::transport::TimeoutUdsClient, - request: http::Request, + mut request: http::Request, url: url::Url, trace: Option<&dyn crate::trace::TraceObserver>, + read_timeout: Option, + remaining_total: Option, ) -> Result { crate::transport::direct::emit_send_start(trace, request.method().as_str(), request.uri())?; - let result = client - .request(request) - .await - .map_err(crate::transport::direct::map_send_error); + let completion = request.body_mut().take_completion_receiver(); + let send = async { + client + .request(request) + .await + .map_err(crate::transport::direct::map_send_error) + }; + let result = crate::transport::direct::send_with_read_timeout( + send, + completion, + read_timeout, + remaining_total, + ) + .await; match result { Ok(mut response) => { diff --git a/crates/eggfetch-core/tests/native_http_body_tests.rs b/crates/eggfetch-core/tests/native_http_body_tests.rs index 91921b3e..1da5c3e0 100644 --- a/crates/eggfetch-core/tests/native_http_body_tests.rs +++ b/crates/eggfetch-core/tests/native_http_body_tests.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use std::time::Duration; use bytes::Bytes; -use eggfetch_core::{Client, NativeRequestOptions, Timeout}; +use eggfetch_core::{Client, Error, NativeRequestOptions, Timeout, TimeoutPhase}; use http_body::{Body, Frame}; use http_body_util::{BodyExt, StreamBody}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -381,6 +381,48 @@ async fn native_response_read_timeout_starts_on_first_body_poll() { task.await.unwrap(); } +#[tokio::test] +async fn native_response_header_wait_obeys_read_timeout() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let task = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0_u8; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + let read = socket.read(&mut buffer).await.unwrap(); + if read == 0 { + return; + } + request.extend_from_slice(&buffer[..read]); + } + tokio::time::sleep(Duration::from_millis(300)).await; + let _ = socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + .await; + }); + let request = http::Request::get(format!("http://{address}/")) + .body(http_body_util::Empty::::new()) + .unwrap(); + let options = NativeRequestOptions::default().timeout(Timeout { + connect: Some(Duration::from_secs(1)), + read: Some(Duration::from_millis(50)), + ..Timeout::default() + }); + let error = Client::new() + .execute_http_body(request, options) + .await + .unwrap_err(); + assert!(matches!( + error, + Error::Timeout { + phase: TimeoutPhase::Read, + .. + } + )); + task.abort(); +} + #[tokio::test] async fn native_response_error_releases_logical_pool_lease() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/crates/eggfetch-core/tests/timeout_tests.rs b/crates/eggfetch-core/tests/timeout_tests.rs index 693ebbf4..3037731a 100644 --- a/crates/eggfetch-core/tests/timeout_tests.rs +++ b/crates/eggfetch-core/tests/timeout_tests.rs @@ -88,6 +88,7 @@ async fn test_connect_timeout() { let client = Client::builder() .timeout(Timeout { connect: Some(Duration::from_millis(100)), + read: Some(Duration::from_millis(10)), ..Timeout::default() }) .build(); @@ -102,7 +103,10 @@ async fn test_connect_timeout() { // on OS behavior with TEST-NET addresses. match &result { Err( - Error::Timeout { .. } + Error::Timeout { + phase: TimeoutPhase::Connect, + .. + } | Error::Connect(_) | Error::HyperClient(_) | Error::Hyper(_) @@ -427,6 +431,119 @@ async fn test_read_timeout_on_chunked_response_stall() { server.shutdown(); } +/// Read timeout also bounds the wait for response headers after the request +/// body has been sent; it does not consume the connect or upload budget. +#[tokio::test] +async fn test_read_timeout_on_delayed_response_headers() { + let mut server = TestServer::start(&TestServerConfig { + response_delay_ms: 350, + ..Default::default() + }); + let url = server.url(); + + let client = Client::builder() + .timeout(Timeout { + connect: Some(Duration::from_secs(1)), + write: Some(Duration::from_secs(1)), + read: Some(Duration::from_millis(80)), + ..Timeout::default() + }) + .build(); + + let started = tokio::time::Instant::now(); + let result = client.post(&url).unwrap().body("request").send().await; + assert!( + matches!( + result, + Err(Error::Timeout { + phase: TimeoutPhase::Read, + .. + }) + ), + "expected a response-header read timeout, got: {result:?}" + ); + assert!(started.elapsed() < Duration::from_millis(250)); + + server.shutdown(); +} + +#[tokio::test] +async fn test_early_response_during_request_body_is_not_a_read_timeout() { + // This fixture responds as soon as it receives request headers instead of + // waiting for the streamed upload. The response must win while the body + // producer is still pending; upload time is not response-read time. + let mut server = TestServer::start(&TestServerConfig { + consume_body: false, + ..Default::default() + }); + let url = server.url(); + let client = Client::builder() + .timeout(Timeout { + write: Some(Duration::from_secs(1)), + read: Some(Duration::from_millis(50)), + ..Timeout::default() + }) + .build(); + let producer = futures_util::stream::unfold(0_u8, |state| async move { + match state { + 0 => Some((Ok(Bytes::from_static(b"first")), 1)), + 1 => { + tokio::time::sleep(Duration::from_millis(300)).await; + Some((Ok(Bytes::from_static(b"second")), 2)) + } + _ => None, + } + }); + + let response = tokio::time::timeout( + Duration::from_millis(250), + client + .post(&url) + .unwrap() + .body(RequestBody::Stream { + stream: Box::pin(producer), + length: None, + }) + .send(), + ) + .await + .expect("an early response should not wait for the stalled upload") + .expect("early response should succeed"); + assert_eq!(response.status(), 200); + server.shutdown(); +} + +#[tokio::test] +async fn test_total_timeout_wins_over_response_header_read_timeout() { + let mut server = TestServer::start(&TestServerConfig { + response_delay_ms: 350, + ..Default::default() + }); + let url = server.url(); + let client = Client::builder() + .timeout(Timeout { + connect: Some(Duration::from_secs(1)), + write: Some(Duration::from_secs(1)), + read: Some(Duration::from_millis(80)), + total: Some(Duration::from_millis(80)), + ..Timeout::default() + }) + .build(); + + let result = client.post(&url).unwrap().body("request").send().await; + assert!( + matches!( + result, + Err(Error::Timeout { + phase: TimeoutPhase::Total, + .. + }) + ), + "expected total timeout to win, got: {result:?}" + ); + server.shutdown(); +} + /// Write timeout fires when a streaming request body's producer stalls /// between chunks. #[tokio::test] @@ -440,6 +557,9 @@ async fn test_write_timeout_on_request_body_stall() { let client = Client::builder() .timeout(Timeout { write: Some(Duration::from_millis(100)), + // The first body producer delay is longer than this read budget. + // It must stay classified as request-body Write inactivity. + read: Some(Duration::from_millis(20)), ..Timeout::default() }) .build(); diff --git a/crates/eggfetch-ffi/Cargo.toml b/crates/eggfetch-ffi/Cargo.toml index 04f927d4..fdc0a995 100644 --- a/crates/eggfetch-ffi/Cargo.toml +++ b/crates/eggfetch-ffi/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggfetch-ffi" -version = "0.2.2" +version = "0.3.0" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -40,7 +40,7 @@ compression-deflate = ["eggfetch-core/compression-deflate"] multipart = ["eggfetch-core/multipart"] [dependencies] -eggfetch-core = { version = "0.2.2", path = "../eggfetch-core", default-features = false } +eggfetch-core = { version = "0.3.0", path = "../eggfetch-core", default-features = false } tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net", "sync"] } bytes = "1" http = "1" diff --git a/crates/eggfetch-http-connect/Cargo.toml b/crates/eggfetch-http-connect/Cargo.toml index 0a6e6599..f4ee9876 100644 --- a/crates/eggfetch-http-connect/Cargo.toml +++ b/crates/eggfetch-http-connect/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggfetch-http-connect" -version = "0.2.2" +version = "0.3.0" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/crates/eggfetch-node/Cargo.toml b/crates/eggfetch-node/Cargo.toml index 7e8da62d..5faad741 100644 --- a/crates/eggfetch-node/Cargo.toml +++ b/crates/eggfetch-node/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggfetch-node" -version = "0.2.2" +version = "0.3.0" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -19,7 +19,7 @@ crate-type = ["cdylib"] napi-build = "2" [dependencies] -eggfetch-ffi = { version = "0.2.2", path = "../eggfetch-ffi", default-features = false, features = ["http1", "tls-rustls", "tls-native-roots"] } +eggfetch-ffi = { version = "0.3.0", path = "../eggfetch-ffi", default-features = false, features = ["http1", "tls-rustls", "tls-native-roots"] } napi = { version = "2", features = ["async", "napi8", "serde-json"] } napi-derive = "2" serde = { version = "1", features = ["derive"] } diff --git a/crates/eggfetch-node/package-lock.json b/crates/eggfetch-node/package-lock.json index e17f5295..a84f9a29 100644 --- a/crates/eggfetch-node/package-lock.json +++ b/crates/eggfetch-node/package-lock.json @@ -1,12 +1,12 @@ { "name": "eggfetch-node", - "version": "0.1.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "eggfetch-node", - "version": "0.1.0", + "version": "0.3.0", "license": "MIT OR Apache-2.0", "devDependencies": { "@napi-rs/cli": "^3.0.0" diff --git a/crates/eggfetch-node/package.json b/crates/eggfetch-node/package.json index b466bf57..f77881ec 100644 --- a/crates/eggfetch-node/package.json +++ b/crates/eggfetch-node/package.json @@ -1,6 +1,6 @@ { "name": "eggfetch-node", - "version": "0.2.2", + "version": "0.3.0", "description": "Experimental Node.js prototype bindings for eggfetch (unsupported API surface)", "main": "index.js", "types": "index.d.ts", diff --git a/crates/eggfetch-python/Cargo.toml b/crates/eggfetch-python/Cargo.toml index 59e267c2..eb924233 100644 --- a/crates/eggfetch-python/Cargo.toml +++ b/crates/eggfetch-python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggfetch-python" -version = "0.2.2" +version = "0.3.0" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -23,7 +23,7 @@ proxy = ["eggfetch-core/proxy"] crate-type = ["cdylib", "rlib"] [dependencies] -eggfetch-core = { version = "0.2.2", path = "../eggfetch-core", features = ["cookies", "multipart", "proxy", "compression-gzip", "compression-brotli", "compression-zstd", "compression-deflate", "http2", "http3"] } +eggfetch-core = { version = "0.3.0", path = "../eggfetch-core", features = ["cookies", "multipart", "proxy", "compression-gzip", "compression-brotli", "compression-zstd", "compression-deflate", "http2", "http3"] } pyo3 = { version = "0.29", features = ["extension-module"] } pyo3-async-runtimes = { version = "0.29", features = ["tokio-runtime"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net", "fs"] } diff --git a/crates/eggfetch-python/pyproject.toml b/crates/eggfetch-python/pyproject.toml index 05d84969..7fa885f2 100644 --- a/crates/eggfetch-python/pyproject.toml +++ b/crates/eggfetch-python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "eggfetch" -version = "0.2.2" +version = "0.3.0" description = "Python bindings for eggfetch" readme = "../../README.md" requires-python = ">=3.10" @@ -35,6 +35,9 @@ test = [ "pytest>=8.4", "pytest-asyncio>=1.0", ] +httpx-transport = [ + "httpx>=0.28,<0.29", +] [tool.maturin] features = ["pyo3/extension-module"] diff --git a/crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py b/crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py index 689535c1..0250f09a 100644 --- a/crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py +++ b/crates/eggfetch-python/python/eggfetch/compat/httpx/_urls.py @@ -276,6 +276,8 @@ def raw_path(self) -> bytes: path = self._parts.path if not path: path = "/" + if self._parts.query: + path = f"{path}?{self._parts.query}" return path.encode("utf-8") @property @@ -317,27 +319,73 @@ def params(self) -> QueryParams: return QueryParams(self._parts.query) return QueryParams() - def copy_with(self, url=None, params=None): - if url is not None: - new = URL(url) - else: - new = URL(self) + def copy_with(self, url=None, params=None, **kwargs): + """Return a copy of this URL with selected components replaced. + ``raw_path`` follows HTTPX's public convention and includes the query + component when present. The legacy ``url`` and ``params`` arguments + remain supported for callers of the earlier facade implementation. + """ + new = URL(url) if url is not None else URL(self) if params is not None: - if isinstance(params, QueryParams): - query_str = str(params) - elif isinstance(params, dict): - query_str = urllib.parse.urlencode(params) - else: - query_str = urllib.parse.urlencode(params) - parts = _urlsplit(str(new)) - new_parts = urllib.parse.SplitResult( - parts.scheme, parts.netloc, parts.path, query_str, parts.fragment - ) - new = object.__new__(URL) - new._parts = new_parts - new._raw = urllib.parse.urlunsplit(new_parts) - return new + kwargs["params"] = params + + if "params" in kwargs: + query_params = QueryParams(kwargs.pop("params")) + query = str(query_params) + kwargs["query"] = query.encode("ascii") if query else None + + if "raw_path" in kwargs: + raw_path = kwargs.pop("raw_path") + if not isinstance(raw_path, bytes): + raise TypeError("Argument 'raw_path' must be bytes") + raw_value = raw_path.decode("utf-8") + path, separator, query = raw_value.partition("?") + kwargs["path"] = path + kwargs["query"] = query.encode("ascii") if separator else None + + allowed_types = { + "scheme": str, + "netloc": bytes, + "path": str, + "query": bytes, + "fragment": str, + } + unknown = set(kwargs) - set(allowed_types) + if unknown: + name = sorted(unknown)[0] + raise TypeError(f"{name!r} is an invalid keyword argument for URL()") + + values = { + "scheme": new._parts.scheme, + "netloc": new._parts.netloc, + "path": new._parts.path, + "query": new._parts.query, + "fragment": new._parts.fragment, + } + for name, value in kwargs.items(): + expected_type = allowed_types[name] + if value is not None and not isinstance(value, expected_type): + raise TypeError( + f"Argument {name!r} must be {expected_type.__name__} " + f"but got {type(value).__name__}" + ) + if isinstance(value, bytes): + value = value.decode("ascii") + if value is not None: + values[name] = value + + parts = urllib.parse.SplitResult( + values["scheme"], + values["netloc"], + values["path"], + values["query"], + values["fragment"], + ) + result = object.__new__(URL) + result._parts = parts + result._raw = urllib.parse.urlunsplit(parts) + return result def copy_set_param(self, key: str, value) -> "URL": params = self.params diff --git a/crates/eggfetch-python/python/eggfetch/integrations/__init__.py b/crates/eggfetch-python/python/eggfetch/integrations/__init__.py new file mode 100644 index 00000000..80e9b805 --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/integrations/__init__.py @@ -0,0 +1,2 @@ +"""Optional integrations with third-party client libraries.""" + diff --git a/crates/eggfetch-python/python/eggfetch/integrations/httpx.py b/crates/eggfetch-python/python/eggfetch/integrations/httpx.py new file mode 100644 index 00000000..973e8f9d --- /dev/null +++ b/crates/eggfetch-python/python/eggfetch/integrations/httpx.py @@ -0,0 +1,197 @@ +"""HTTPX transport integration backed by EggFetch's Rust engine. + +Install ``eggfetch[httpx-transport]`` to use this module. Pass the transport +to a real :class:`httpx.Client`; the SDK-facing client remains an HTTPX +instance while request I/O is delegated to EggFetch. + +The integration currently supports synchronous HTTPX clients. Configure +network options on ``EggFetchTransport`` because HTTPX does not forward +``Client`` TLS, limits, or proxy settings to a custom transport. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from typing import Any + +import httpx + +from eggfetch.compat.httpx import ( + ConnectError as EggConnectError, + ConnectTimeout as EggConnectTimeout, + HTTPTransport as _EggHTTPTransport, + Limits as _EggLimits, + NetworkError as EggNetworkError, + PoolTimeout as EggPoolTimeout, + ProtocolError as EggProtocolError, + ProxyError as EggProxyError, + ReadTimeout as EggReadTimeout, + Request as _EggRequest, + RequestError as EggRequestError, + Response as _EggResponse, + TimeoutException as EggTimeoutException, + TransportError as EggTransportError, + UnsupportedProtocol as EggUnsupportedProtocol, + WriteTimeout as EggWriteTimeout, +) + + +def _translate_error(error: Exception, request: httpx.Request) -> Exception: + """Convert an EggFetch compatibility exception to HTTPX's exception type.""" + message = str(error) + pairs: tuple[tuple[type[BaseException], type[BaseException]], ...] = ( + (EggConnectTimeout, httpx.ConnectTimeout), + (EggReadTimeout, httpx.ReadTimeout), + (EggWriteTimeout, httpx.WriteTimeout), + (EggPoolTimeout, httpx.PoolTimeout), + (EggTimeoutException, httpx.TimeoutException), + (EggProxyError, httpx.ProxyError), + (EggUnsupportedProtocol, httpx.UnsupportedProtocol), + (EggProtocolError, httpx.ProtocolError), + (EggConnectError, httpx.ConnectError), + (EggNetworkError, httpx.NetworkError), + (EggTransportError, httpx.TransportError), + (EggRequestError, httpx.RequestError), + ) + for egg_type, httpx_type in pairs: + if isinstance(error, egg_type): + return httpx_type(message, request=request) + return httpx.TransportError(message or "EggFetch transport failure", request=request) + + +class _EggFetchResponseStream(httpx.SyncByteStream): + """Expose EggFetch's raw response stream as HTTPX's public stream type.""" + + def __init__(self, response: _EggResponse, request: httpx.Request) -> None: + self._response = response + self._request = request + self._closed = False + + def __iter__(self) -> Iterator[bytes]: + try: + yield from self._response.iter_raw() + except Exception as error: + translated = _translate_error(error, self._request) + if translated is error: + raise + raise translated from error + finally: + self.close() + + def close(self) -> None: + if not self._closed: + self._closed = True + self._response.close() + + +class EggFetchTransport(httpx.BaseTransport): + """An HTTPX sync transport that delegates HTTP requests to EggFetch. + + Args mirror the network-relevant subset of ``httpx.HTTPTransport``. + The HTTPX client remains responsible for SDK-facing URL construction, + authentication, hooks, redirects, and retry policy. EggFetch transport + retries default to zero so retry ownership remains with the SDK/application. + """ + + def __init__( + self, + *, + verify: bool | str | Any = True, + cert: str | tuple[str, str] | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: httpx.Limits | None = None, + proxy: str | httpx.Proxy | None = None, + uds: str | None = None, + local_address: str | None = None, + socket_options: Iterable[tuple[int, ...]] | None = None, + ) -> None: + limits = limits or httpx.Limits( + max_connections=100, + max_keepalive_connections=20, + keepalive_expiry=5.0, + ) + egg_limits = _EggLimits( + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + ) + if isinstance(proxy, httpx.Proxy): + proxy = str(proxy.url) + self._transport = _EggHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=egg_limits, + proxy=proxy, + uds=uds, + local_address=local_address, + retries=0, + socket_options=socket_options, + ) + self._closed = False + + def handle_request(self, request: httpx.Request) -> httpx.Response: + if self._closed: + raise RuntimeError("EggFetchTransport is closed") + + timeout = request.extensions.get("timeout") + extensions = {"timeout": timeout} if isinstance(timeout, dict) else {} + try: + content: bytes | None = request.content + except httpx.RequestNotRead: + content = None + stream = None + if content is None: + if "content-length" in request.headers: + # EggFetch deliberately rejects an unknown-length iterator + # paired with Content-Length. Buffer this uncommon + # HTTPX-stream shape so the declared framing stays truthful. + content = request.read() + else: + stream = iter(request.stream) + egg_request = _EggRequest( + request.method, + str(request.url), + headers=request.headers.multi_items(), + content=content, + stream=stream, + extensions=extensions, + ) + + try: + egg_response = self._transport.handle_request(egg_request) + except Exception as error: + translated = _translate_error(error, request) + if translated is error: + raise + raise translated from error + + stream = _EggFetchResponseStream(egg_response, request) + response_extensions: dict[str, Any] = {} + for key in ("http_version", "reason_phrase"): + value = egg_response.extensions.get(key) + if value is not None: + response_extensions[key] = ( + value.encode("ascii", errors="replace") + if isinstance(value, str) + else value + ) + return httpx.Response( + egg_response.status_code, + headers=egg_response.headers.multi_items(), + stream=stream, + request=request, + extensions=response_extensions, + ) + + def close(self) -> None: + if not self._closed: + self._closed = True + self._transport.close() + + +__all__ = ["EggFetchTransport"] diff --git a/crates/eggfetch-python/tests/compat/test_httpx_transport_bridge.py b/crates/eggfetch-python/tests/compat/test_httpx_transport_bridge.py new file mode 100644 index 00000000..17600db4 --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_httpx_transport_bridge.py @@ -0,0 +1,84 @@ +"""Downstream checks for the optional real-HTTPX transport bridge.""" + +from __future__ import annotations + +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import httpx +import pytest + +from eggfetch.compat.httpx import ReadTimeout as EggReadTimeout +from eggfetch.integrations.httpx import EggFetchTransport + + +class _Handler(BaseHTTPRequestHandler): + response_delay = 0.0 + + def do_POST(self) -> None: # noqa: N802 - stdlib protocol callback + content_length = int(self.headers.get("Content-Length", "0")) + self.rfile.read(content_length) + if self.response_delay: + time.sleep(self.response_delay) + body = b'{"ok":true}' + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + +@pytest.fixture +def server(): + httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{httpd.server_port}/completion" + finally: + httpd.shutdown() + thread.join(timeout=2) + httpd.server_close() + + +def test_real_httpx_client_uses_eggfetch_and_returns_streamed_body(server: str) -> None: + transport = EggFetchTransport(trust_env=False) + client = httpx.Client(transport=transport, timeout=1.0) + try: + response = client.post(server, content=b"prompt") + assert isinstance(client, httpx.Client) + assert response.json() == {"ok": True} + assert response.request.content == b"prompt" + finally: + client.close() + + +def test_delayed_response_headers_obey_httpx_read_timeout(server: str) -> None: + _Handler.response_delay = 0.3 + try: + with httpx.Client( + transport=EggFetchTransport(trust_env=False), + timeout=httpx.Timeout(connect=1.0, read=0.05, write=1.0, pool=1.0), + ) as client: + with pytest.raises(httpx.ReadTimeout): + client.post(server, content=b"prompt") + finally: + _Handler.response_delay = 0.0 + + +def test_eggfetch_timeout_maps_to_httpx_with_original_request(monkeypatch) -> None: + transport = EggFetchTransport(trust_env=False) + + def fail_request(*args, **kwargs): + raise EggReadTimeout("response headers timed out") + + monkeypatch.setattr(transport._transport, "handle_request", fail_request) + request = httpx.Request("GET", "http://example.test/") + with pytest.raises(httpx.ReadTimeout) as caught: + transport.handle_request(request) + assert caught.value.request is request + diff --git a/crates/eggfetch-python/tests/compat/test_httpx_transport_sdk_construction.py b/crates/eggfetch-python/tests/compat/test_httpx_transport_sdk_construction.py new file mode 100644 index 00000000..962e44ba --- /dev/null +++ b/crates/eggfetch-python/tests/compat/test_httpx_transport_sdk_construction.py @@ -0,0 +1,128 @@ +"""Construction checks for downstream SDKs that require real HTTPX clients. + +Run with AInews's pinned SDK versions installed. Each test is independently +optional so EggFetch's ordinary compat environment does not acquire SDK deps. +""" + +from __future__ import annotations + +import httpx +import pytest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread + +from eggfetch.integrations.httpx import EggFetchTransport + + +def _transport() -> EggFetchTransport: + return EggFetchTransport(trust_env=False) + + +@pytest.fixture +def openai_stub_url(): + class Handler(BaseHTTPRequestHandler): + def do_POST(self) -> None: # noqa: N802 - stdlib protocol callback + length = int(self.headers.get("Content-Length", "0")) + self.rfile.read(length) + body = ( + b'{"id":"chatcmpl-test","object":"chat.completion",' + b'"created":1,"model":"stub-model","choices":[{"index":0,' + b'"message":{"role":"assistant","content":"ok"},' + b'"finish_reason":"stop"}],"usage":{"prompt_tokens":1,' + b'"completion_tokens":1,"total_tokens":2}}' + ) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}/v1" + finally: + server.shutdown() + thread.join(timeout=2) + server.server_close() + + +def test_openai_accepts_real_httpx_client_with_eggfetch_transport() -> None: + openai = pytest.importorskip("openai") + transport = _transport() + client = openai.OpenAI( + api_key="test-key", + http_client=httpx.Client(transport=transport), + max_retries=0, + ) + try: + assert isinstance(client._client, httpx.Client) + assert client._client._transport is transport + finally: + client.close() + + +def test_openai_chat_completion_uses_eggfetch_transport(openai_stub_url: str) -> None: + openai = pytest.importorskip("openai") + transport = _transport() + client = openai.OpenAI( + api_key="test-key", + base_url=openai_stub_url, + http_client=httpx.Client(transport=transport), + max_retries=0, + ) + try: + result = client.chat.completions.create( + model="stub-model", + messages=[{"role": "user", "content": "hello"}], + ) + assert result.choices[0].message.content == "ok" + assert result.usage.total_tokens == 2 + finally: + client.close() + + +def test_anthropic_accepts_real_httpx_client_with_eggfetch_transport() -> None: + anthropic = pytest.importorskip("anthropic") + transport = _transport() + client = anthropic.Anthropic( + api_key="test-key", + http_client=httpx.Client(transport=transport), + max_retries=0, + ) + try: + assert isinstance(client._client, httpx.Client) + assert client._client._transport is transport + finally: + client.close() + + +def test_ollama_passes_transport_to_its_sdk_created_httpx_client() -> None: + ollama = pytest.importorskip("ollama") + transport = _transport() + client = ollama.Client(host="http://127.0.0.1:1", transport=transport) + try: + assert isinstance(client._client, httpx.Client) + assert client._client._transport is transport + finally: + client._client.close() + + +def test_google_genai_sync_client_args_accept_eggfetch_transport() -> None: + genai = pytest.importorskip("google.genai") + types = pytest.importorskip("google.genai.types") + transport = _transport() + client = genai.Client( + api_key="test-key", + http_options=types.HttpOptions(client_args={"transport": transport}), + ) + try: + sdk_httpx = client._api_client._httpx_client + assert isinstance(sdk_httpx, httpx.Client) + assert sdk_httpx._transport is transport + finally: + client.close() diff --git a/crates/eggfetch-python/tests/compat/test_url_query.py b/crates/eggfetch-python/tests/compat/test_url_query.py index 60df3cc4..9ba3617d 100644 --- a/crates/eggfetch-python/tests/compat/test_url_query.py +++ b/crates/eggfetch-python/tests/compat/test_url_query.py @@ -138,6 +138,17 @@ def test_relative_not_absolute(self): # ── copy_with / param helpers ────────────────────────────────────────── class TestURLCopyWith: + def test_copy_with_raw_path(self): + url = URL("https://api.example.com/v1") + new = url.copy_with(raw_path=url.raw_path + b"/") + assert str(new) == "https://api.example.com/v1/" + + def test_raw_path_includes_query(self): + url = URL("https://api.example.com/v1?version=2") + assert url.raw_path == b"/v1?version=2" + new = url.copy_with(raw_path=b"/v1/?version=2") + assert str(new) == "https://api.example.com/v1/?version=2" + def test_copy_with_params(self): url = URL("https://example.com/path") new = url.copy_with(params={"q": "1"}) diff --git a/crates/eggfetch-python/tests/test_sync.py b/crates/eggfetch-python/tests/test_sync.py index b220602a..03dd88c8 100644 --- a/crates/eggfetch-python/tests/test_sync.py +++ b/crates/eggfetch-python/tests/test_sync.py @@ -93,7 +93,7 @@ def server(): class TestPackageImports: def test_import_version(self): assert isinstance(eggfetch.__version__, str) - assert eggfetch.__version__ == "0.2.2" + assert eggfetch.__version__ == "0.3.0" def test_native_ssl_interop_does_not_import_compat_facade(self): before = {name for name in sys.modules if name.startswith("eggfetch.compat")} diff --git a/docs/README.md b/docs/README.md index 06978bb4..86941a59 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,6 +28,7 @@ policy) and `residual-differences.md` (known intentional compatibility deltas). - **New to eggfetch?** Start with `getting-started/quickstart.md` - **Rust users?** See `rust/guide.md` - **Python users?** See `python/guide.md` +- **HTTPX SDK transport integration?** See `python/httpx-transport.md` - **CLI users?** See `cli/guide.md` - **Migrating?** Check `migration/from-requests.md` or `migration/from-httpx.md` - **Releasing?** See `releases/process.md` for the release workflow and `releases/compatibility-policy.md` for versioning diff --git a/docs/architecture/benchmarks.md b/docs/architecture/benchmarks.md index 84849f01..f9a7aae6 100644 --- a/docs/architecture/benchmarks.md +++ b/docs/architecture/benchmarks.md @@ -54,12 +54,16 @@ Whole-request-path measurements over loopback TCP with `HttpVersionPolicy::Http1 The fixture lives in `eggfetch-bench/src/bench_proxy.rs`. It parses each request head once, forwards absolute-form targets as origin-form path/query, strips proxy-only and hop-specific connection headers, and closes the upstream -request explicitly. CONNECT and chunked request bodies receive deterministic -`501 Not Implemented` responses — unsupported framing is reported explicitly -rather than relying on read timeouts; fixed-length bodies are forwarded. Focused -loopback correctness tests run with `cargo test -p eggfetch-bench --lib` and -verify repeated requests, complete origin headers, and response bodies. This -test fixture does not implement or qualify production proxy behavior. +request explicitly. Its accept loop stays nonblocking for shutdown, then +explicitly makes each accepted socket blocking before the handler's blocking +I/O; this avoids platform-dependent inheritance of nonblocking mode. CONNECT +and chunked request bodies receive deterministic `501 Not Implemented` +responses — unsupported framing is reported explicitly rather than relying on +read timeouts; fixed-length bodies are forwarded. Focused loopback correctness +tests run with `cargo test -p eggfetch-bench --lib` and verify delayed +request-head arrival, repeated requests, complete origin headers, and response +bodies. This test fixture does not implement or qualify production proxy +behavior. ### `resources` — allocation/throughput shape diff --git a/docs/architecture/build-ci.md b/docs/architecture/build-ci.md index 5894f327..dcf7f27a 100644 --- a/docs/architecture/build-ci.md +++ b/docs/architecture/build-ci.md @@ -43,7 +43,7 @@ coverage rationale and the tool-bump update rule. Two GitHub Actions workflows: - **`ci.yml`** — routine push/PR validation. One Ubuntu job, no matrix, no artifact exchange. Calls `./scripts/check.sh`. This is the only automatic workflow. -- **`pypi.yml`** — manual-dispatch PyPI release pipeline. Builds 18 wheels across 3 platforms (linux-x86_64, macos-arm64, windows-x86_64) and Python 3.10–3.15, builds and validates an sdist, assembles the release set, and optionally publishes via Trusted Publishing (OIDC). +- **`pypi.yml`** — manual-dispatch PyPI release pipeline. Builds 24 wheels across 4 targets (linux-x86_64, linux-aarch64, macos-arm64, windows-x86_64) and Python 3.10–3.15, builds and validates an sdist, assembles the release set, and optionally publishes via Trusted Publishing (OIDC). See [verification-policy.md](../verification-policy.md) for the normative policy. @@ -178,9 +178,9 @@ Run `./scripts/check.sh package` for: leaf publish dry-run (`cargo publish --dry Run manually via `workflow_dispatch` from `.github/workflows/pypi.yml`. The pipeline: 1. **validate-release** — version coherence, internal dependency topology, routine + package validation -2. **build-wheel** — 18 wheel jobs across 3 platforms × 6 Python versions +2. **build-wheel** — 24 wheel jobs across 4 platform targets × 6 Python versions 3. **build-sdist** — source distribution with isolated build test -4. **assemble** — downloads all artifacts, validates coverage matrix (18 wheels + 1 sdist), runs twine check +4. **assemble** — downloads all artifacts, validates coverage matrix (24 wheels + 1 sdist), runs twine check 5. **publish** — optional OIDC upload to PyPI (requires `publish=true` input plus `pypi` environment approval) ## Environment diff --git a/docs/architecture/core-timeout-pool.md b/docs/architecture/core-timeout-pool.md index 88cdaddc..fa981a77 100644 --- a/docs/architecture/core-timeout-pool.md +++ b/docs/architecture/core-timeout-pool.md @@ -17,7 +17,7 @@ eggfetch implements phase-aware timeouts that map to specific segments of the re | `ProxyConnect` | Error-taxonomy classification for proxy TCP setup; budget aliases `Timeout.connect` (no separate field) | | `ProxyTls` | Error-taxonomy classification for TLS to an HTTPS proxy endpoint; budget aliases `Timeout.connect` (no separate field) | | `Write` | Sending streamed request-body chunks only (buffered bodies complete synchronously) | -| `Read` | Inactivity between response body chunks from first body poll; proxy CONNECT-head reads also use the read budget; ordinary response headers are `Total`-bounded | +| `Read` | Response-header wait after request-body completion on Hyper/UDS routes, then inactivity between response body chunks from first body poll; proxy CONNECT-head reads also use the read budget; experimental HTTP/3 currently applies it to response-body chunks only | | `Total` | Wall-clock cap across the entire request lifecycle | Physical admission (optional wait for a live Hyper-connection permit) is not a `TimeoutPhase`; it reports `Error::Pool`, not `Error::Timeout`, and is distinct from logical pool acquisition. @@ -45,12 +45,16 @@ computation and the pool deadline. |-------|-------------| | Pool | `tokio::time::timeout` around pool acquisition using `min(pool, total)`; reports `Total` when the total budget is the smaller bound | | Total | `tokio::time::timeout` around the transport future up to response headers, plus a crate-private absolute response-body deadline (`ResponseDeadline`) through body EOF/trailers | -| Read | Per-chunk wrapper (`BodyTimeoutStream` for `ResponseBody` streaming; `NativeResponseBody` implements the same contract for `execute_http_body`) — starts on first body poll, deadline resets on each body chunk/frame; direct Hyper/UDS/H3 header acquisition remains owned by the transport future | +| Read | Hyper/UDS response-header wait races request-body completion against `Timeout.read`; response-body wrappers (`BodyTimeoutStream` / `NativeResponseBody`) start on first body poll and reset per chunk/frame. Experimental H3 currently applies read only to response-body progress; its header wait remains total-bounded | | Write | Per-chunk wrapper stream (`WriteTimeoutStream`) — deadline resets on each chunk delivery; H3 propagates `Write` without masking or evicting | | Connect | Enforced by the direct connector, by proxy TCP/TLS/origin-TLS setup, and by the H3 connector (DNS + QUIC + h3 init as one budget shared across address fallback with fair per-address shares) | -Read timeout: inactivity timeout, starts when body consumption begins, -resets after each successful chunk/frame. +Read timeout: the Hyper/UDS response-header wait starts after request-body +completion, while response-body inactivity starts when body consumption +begins and resets after each successful chunk/frame. Early responses during +upload are returned without charging upload time to the read budget. The +experimental H3 path currently has body-read timeout only; response headers +remain bounded by `Timeout.total` there. Total timeout: absolute request-lifecycle deadline, starts with the logical request, includes pool/transport/headers/body/trailers, never resets, and @@ -63,13 +67,14 @@ both read and total are observably expired at the same poll boundary, `Total` is preferred as the outer cap. A ready chunk/frame at or after the absolute deadline never extends the request. -The native `execute_http_body()` response wrapper uses the same contract: -its read timer starts when the caller first polls the body and resets -after each returned frame, while its total deadline starts with the request +The native `execute_http_body()` response wrapper uses the same body contract: +its read timer starts when the caller first polls the body and resets after +each returned frame, while its total deadline starts with the request lifecycle and never resets on DATA/trailer frames. A delay between response -headers and the first body poll therefore does not consume `Timeout.read` -but can already exhaust `Timeout.total`; `TransportIoTimeout` remains -the separate established-connection inactivity control. +headers and the first body poll therefore does not consume the response-body +portion of `Timeout.read` but can already exhaust `Timeout.total`; +`TransportIoTimeout` remains the separate established-connection inactivity +control. Native embedded consumers may additionally set `PhysicalConnectionPolicy` and `TransportIoTimeout`. The physical policy is applied by the common Hyper diff --git a/docs/architecture/core-tls-proxy-protocols.md b/docs/architecture/core-tls-proxy-protocols.md index 40330a91..9ecd4db5 100644 --- a/docs/architecture/core-tls-proxy-protocols.md +++ b/docs/architecture/core-tls-proxy-protocols.md @@ -830,8 +830,10 @@ All-address failure preserves the `Connect` (DNS) / `H3Connect` - `Timeout.write` applies to streamed request-body progress via the pre-transport wrapper; stalls surface as `Write`, never as H3 protocol errors, and never evict the shared connection. -- `Timeout.read` applies to response-body progress at the documented - post-transport boundary (phase `Read`). +- `Timeout.read` applies to response-header waiting after request-body + completion on Hyper/UDS routes, then response-body progress at the + documented post-transport boundary (phase `Read`). Experimental H3 + currently applies it to response-body progress only. ### Idle Lifetime diff --git a/docs/architecture/dependency-policy.md b/docs/architecture/dependency-policy.md index 9dc74f5f..f87586ee 100644 --- a/docs/architecture/dependency-policy.md +++ b/docs/architecture/dependency-policy.md @@ -194,6 +194,17 @@ session but arriving transitively, unpinned): SSE itself has no extra dependency: `EventSource`/`ServerSentEvent` are pure-Python framing over normal streamed responses. +## Optional HTTPX Transport Integration + +The `httpx-transport` Python extra requires `httpx>=0.28,<0.29` and provides +`EggFetchTransport`, a synchronous `httpx.BaseTransport` adapter over the +EggFetch engine. HTTPX remains an optional dependency; the base `eggfetch` +installation and native Rust core do not depend on it. The bridge disables +EggFetch retries so SDK/application retry policy remains authoritative. Async +HTTPX transport support and HTTP/3 are outside this integration's contract. +See [httpx-transport.md](../python/httpx-transport.md) for installation, +configuration, lifecycle, and limitations. + ## Selection Criteria When evaluating a new dependency: diff --git a/docs/concepts/lifecycle.md b/docs/concepts/lifecycle.md index e37576d6..7af39afa 100644 --- a/docs/concepts/lifecycle.md +++ b/docs/concepts/lifecycle.md @@ -53,7 +53,7 @@ The request line, headers, and body are written to the transport. For streaming ### 10. Response Reading -Response status, headers, and body are read. The body starts as a live stream. Calling `bytes()` or `text()` buffers the entire body; calling `bytes_stream()` returns an iterator over chunks. The read timeout applies per-chunk, resetting on every arrival. +Response status, headers, and body are read. The body starts as a live stream. Calling `bytes()` or `text()` buffers the entire body; calling `bytes_stream()` returns an iterator over chunks. On Hyper and UDS routes, the read timeout covers response headers after request-body completion and then applies per body chunk, resetting on every arrival. Experimental HTTP/3 currently applies it to body chunks only. ### 11. Decompression (if enabled) diff --git a/docs/concepts/pooling.md b/docs/concepts/pooling.md index 6671e1b8..f9d5ff68 100644 --- a/docs/concepts/pooling.md +++ b/docs/concepts/pooling.md @@ -74,8 +74,9 @@ Native Rust callers can additionally set `PhysicalConnectionPolicy` to cap live established Hyper connections. That cap is independent of logical in-flight limits and includes idle pooled connections; HTTP/2 streams sharing one connection consume one physical permit. Use `TransportIoTimeout` for -established read/write inactivity guardrails, not `Timeout.write` or -`Timeout.read` request-body/response-body timing. +established read/write inactivity guardrails, not `Timeout.write` request-body +production or `Timeout.read` response-header/response-body timing (H3 applies +read to response-body progress only). ## Pool Metrics diff --git a/docs/python/guide.md b/docs/python/guide.md index 2e214079..af34f3fc 100644 --- a/docs/python/guide.md +++ b/docs/python/guide.md @@ -511,6 +511,9 @@ evidence live in `compat/httpx/0.28.1/profile.toml`, `compat/httpx2/2.12.0/profile.toml`, and `plans/httpx-parity-correction-status.md`. +For SDKs that require a genuine `httpx.Client` while using EggFetch for +network I/O, see the optional [HTTPX transport integration](httpx-transport.md). + ## Error Handling eggfetch provides a rich exception hierarchy: diff --git a/docs/python/httpx-transport.md b/docs/python/httpx-transport.md new file mode 100644 index 00000000..1f03a2c6 --- /dev/null +++ b/docs/python/httpx-transport.md @@ -0,0 +1,48 @@ +# Using EggFetch behind a real HTTPX client + +The optional `eggfetch.integrations.httpx` module lets a third-party SDK keep +using a genuine `httpx.Client` while EggFetch handles synchronous network +requests. Install the integration extra with `pip install +"eggfetch[httpx-transport]"`. It supports HTTPX 0.28.x and requires the +matching EggFetch package installation. + +```python +import httpx +from eggfetch.integrations.httpx import EggFetchTransport + +transport = EggFetchTransport( + trust_env=True, + http1=True, + http2=False, + limits=httpx.Limits(max_connections=8, max_keepalive_connections=4), +) +client = httpx.Client(transport=transport, timeout=60.0) +try: + response = client.get("https://example.com/") + response.raise_for_status() +finally: + client.close() +``` + +The HTTPX client remains responsible for SDK-visible request construction, +authentication, hooks, redirects, and exception handling. EggFetch receives +HTTPX's timeout extension and has internal retries disabled so the SDK or +application owns retries. Closing the HTTPX client closes the EggFetch +transport; closing or exhausting a response closes its EggFetch response +stream. + +Pass connection options to `EggFetchTransport`, because HTTPX does not pass +client TLS, proxy, UDS, local-address, socket-option, or limit settings into a +custom transport. The integration is synchronous. It does not provide +`httpx.AsyncBaseTransport`; async SDK clients must continue using their +existing transport. Async request streams are unsupported. Request/response +streaming is synchronous and follows HTTPX stream lifecycle rules. + +The current bridge is intended for HTTP/1.1 and HTTP/2. EggFetch's experimental +HTTP/3 route is not selected through this HTTPX integration. Its header-read +timeout behavior is separately documented in the core timeout contract. + +The supported HTTPX range is intentionally limited to 0.28.x. Do not install +the `eggfetch.compat.httpx` facade as a replacement for the public `httpx` +package: this integration composes the public HTTPX transport interface and +keeps both distributions intact. diff --git a/docs/reference/versioning.md b/docs/reference/versioning.md index e259a0e3..e3e508f9 100644 --- a/docs/reference/versioning.md +++ b/docs/reference/versioning.md @@ -7,8 +7,8 @@ change, and what stability expectations users can rely on. ## Coordinated versioning All publishable crates in the workspace share a single version number. When -eggfetch-core is at `0.2.2`, the CONNECT wire primitive, CLI, Python -bindings, FFI bindings, and Node bindings are also at `0.2.2`. This +eggfetch-core is at `0.3.0`, the CONNECT wire primitive, CLI, Python +bindings, FFI bindings, and Node bindings are also at `0.3.0`. This eliminates version-matrix confusion for consumers who depend on multiple crates from the project. diff --git a/docs/releases/compatibility-policy.md b/docs/releases/compatibility-policy.md index ec8349ca..9bf63ede 100644 --- a/docs/releases/compatibility-policy.md +++ b/docs/releases/compatibility-policy.md @@ -28,11 +28,13 @@ release is available, so the published wheel matrix does not change. | Tier | Platforms | CI Coverage | PyPI Wheels | |------|-----------|-------------|-------------| -| Tier 1 | Linux x86_64, macOS arm64, Windows x86_64 | Wheel build + smoke test in the PyPI release workflow | Native wheels, smoke-tested | -| Tier 2 | macOS x86_64, Linux aarch64 | Not built or tested in CI | None (build from source) | +| Tier 1 | Linux x86_64, Linux aarch64, macOS arm64, Windows x86_64 | Native wheel build + smoke test in the PyPI release workflow | Native wheels, smoke-tested | +| Tier 2 | macOS x86_64 | Not built or tested in CI | None (build from source) | | Tier 3 | FreeBSD, other Unix variants | Community-supported, not tested | No wheels | -Routine CI runs on a single Ubuntu runner; platform breadth comes from the PyPI wheel matrix, not from routine CI. +Routine CI runs on a single Ubuntu x86_64 runner; platform breadth comes from +the PyPI release wheel matrix, including native Linux aarch64 builds, not from +routine CI. ## CLI Machine-Output Schema Versioning diff --git a/docs/releases/process.md b/docs/releases/process.md index e1f241cd..7ccb0a3b 100644 --- a/docs/releases/process.md +++ b/docs/releases/process.md @@ -78,10 +78,11 @@ PyPI publication is performed via the manually dispatched `.github/workflows/pyp | Operating system | Architecture | Python versions | |---|---|---| | Linux manylinux2014 | x86_64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | +| Linux manylinux2014 | aarch64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | | macOS | arm64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | | Windows | x86_64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | -18 wheels + 1 source distribution = 19 distributions per release. +24 wheels + 1 source distribution = 25 distributions per release. Linux aarch64 wheels are built and smoke-tested on native `ubuntu-24.04-arm` runners. ### Dispatch Procedure @@ -130,7 +131,7 @@ A coordinated public release requires a manual GitHub Release after PyPI publica 3. Run `./scripts/check.sh`, `./scripts/check.sh extended`, and `./scripts/check.sh package`, plus the live `./scripts/check_security.sh` preflight. 4. Manually publish crates.io packages in dependency order. 5. Verify crates.io propagation between publishes. -6. Dispatch PyPI Wheels from the frozen candidate SHA with `publish=false`; inspect all 18 wheels and the sdist. +6. Dispatch PyPI Wheels from the frozen candidate SHA with `publish=false`; inspect all 24 wheels and the sdist. 7. Create and push the signed tag on that exact candidate after crates.io publication. 8. Dispatch from the same tag with `publish=true`. 9. Approve the `pypi` environment deployment after assembled-set validation. diff --git a/docs/verification-policy.md b/docs/verification-policy.md index d785585a..2f456f24 100644 --- a/docs/verification-policy.md +++ b/docs/verification-policy.md @@ -172,10 +172,11 @@ The PyPI wheel workflow (`.github/workflows/pypi.yml`) is a manually dispatched, | Operating system | Architecture | Python versions | Build method | |---|---|---|---| | Linux manylinux2014 | x86_64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | maturin-action native | +| Linux manylinux2014 | aarch64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | maturin-action on native `ubuntu-24.04-arm` | | macOS | arm64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | maturin-action native | | Windows | x86_64 | 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 | maturin-action native | -18 wheels + 1 sdist = 19 distributions per release. +24 wheels + 1 sdist = 25 distributions per release. ### Workflow Modes diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index fac1219c..7d397fd7 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -185,7 +185,7 @@ dependencies = [ [[package]] name = "eggfetch-core" -version = "0.2.2" +version = "0.3.0" dependencies = [ "async-compression", "base64", @@ -234,7 +234,7 @@ dependencies = [ [[package]] name = "eggfetch-http-connect" -version = "0.2.2" +version = "0.3.0" dependencies = [ "base64", "thiserror", diff --git a/scripts/validate_wheel_coverage.py b/scripts/validate_wheel_coverage.py index 340cd77d..25b602fd 100644 --- a/scripts/validate_wheel_coverage.py +++ b/scripts/validate_wheel_coverage.py @@ -2,9 +2,9 @@ """Validate that the assembled wheel set covers the expected matrix. Expected coverage: - - 3 platforms: linux x86_64, macOS arm64, Windows x86_64 + - 4 platforms: Linux x86_64 + aarch64, macOS arm64, Windows x86_64 - 6 Python versions: 3.10, 3.11, 3.12, 3.13, 3.14, 3.15 - - 18 total wheels + - 24 total wheels Parses wheel filenames (PEP 427) to extract tags. No third-party dependencies. """ @@ -15,6 +15,7 @@ EXPECTED_PLATFORMS = { "linux_x86_64", + "linux_aarch64", "macosx_arm64", "win_amd64", } @@ -141,8 +142,9 @@ def main() -> int: errors.append(f"Unexpected wheel: {platform} py{py}") # Check total count - if len(observed) != 18: - errors.append(f"Expected 18 wheels, observed {len(observed)}") + expected_count = len(EXPECTED_PLATFORMS) * len(EXPECTED_PYTHON_VERSIONS) + if len(observed) != expected_count: + errors.append(f"Expected {expected_count} wheels, observed {len(observed)}") if errors: for e in errors: From 22a616cb224fd27057c38aea40895b9acacbe3b0 Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 21:32:11 +0000 Subject: [PATCH 02/16] test: make routed H3 failure deterministic --- .../eggfetch-core/tests/h3_datagram_route.rs | 64 ++++++++++++++----- 1 file changed, 49 insertions(+), 15 deletions(-) diff --git a/crates/eggfetch-core/tests/h3_datagram_route.rs b/crates/eggfetch-core/tests/h3_datagram_route.rs index 1bd716c2..a350e20f 100644 --- a/crates/eggfetch-core/tests/h3_datagram_route.rs +++ b/crates/eggfetch-core/tests/h3_datagram_route.rs @@ -264,13 +264,24 @@ impl Drop for AltSvcH1Server { // --------------------------------------------------------------------------- /// Observable state shared between the harness and its routes. -#[derive(Default)] struct CarrierProbe { dials: AtomicUsize, live_routes: AtomicUsize, observed_targets: Mutex>, - /// Route id whose receive side should terminate, or 0 for none. - kill_route: AtomicUsize, + /// Broadcasts the route id whose receive side should terminate, or 0 for none. + kill_route: watch::Sender, +} + +impl Default for CarrierProbe { + fn default() -> Self { + let (kill_route, _) = watch::channel(0); + Self { + dials: AtomicUsize::default(), + live_routes: AtomicUsize::default(), + observed_targets: Mutex::default(), + kill_route, + } + } } impl CarrierProbe { @@ -288,6 +299,10 @@ impl CarrierProbe { .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() } + + fn terminate_route(&self, route_id: usize) { + self.kill_route.send_replace(route_id); + } } /// How a carrier route should misbehave, if at all. @@ -327,6 +342,7 @@ struct CarrierRoute { fault: CarrierFault, /// Distinguishes this route from later replacements of the same origin. route_id: usize, + kill_route: watch::Receiver, probe: Arc, } @@ -339,6 +355,7 @@ impl CarrierRoute { peer: plan.peer, fault: plan.fault, route_id, + kill_route: probe.kill_route.subscribe(), probe, }) } @@ -386,18 +403,35 @@ impl DatagramRoute for CarrierRoute { if let CarrierFault::SlowRecv = self.fault { tokio::time::sleep(Duration::from_millis(1)).await; } - // Scoped to this exact route id so a replacement route for the same - // origin is unaffected. - if self.route_id == self.probe.kill_route.load(Ordering::Relaxed) { - return Err(DialError::new( - DialErrorKind::Connection, - "carrier receive terminated", - )); + // Watch the socket and route-specific shutdown together. Checking + // an atomic before `recv_from` alone is racy: a blocked receive + // would never observe a later kill signal until another packet + // happened to arrive. + let mut kill_route = self.kill_route.clone(); + loop { + if *kill_route.borrow_and_update() == self.route_id { + return Err(DialError::new( + DialErrorKind::Connection, + "carrier receive terminated", + )); + } + tokio::select! { + result = self.socket.recv_from(buffer) => { + let (len, _source) = result.map_err(|e| { + DialError::new(DialErrorKind::Connection, format!("carrier recv: {e}")) + })?; + return Ok(len); + } + changed = kill_route.changed() => { + if changed.is_err() || *kill_route.borrow_and_update() == self.route_id { + return Err(DialError::new( + DialErrorKind::Connection, + "carrier receive terminated", + )); + } + } + } } - let (len, _source) = self.socket.recv_from(buffer).await.map_err(|e| { - DialError::new(DialErrorKind::Connection, format!("carrier recv: {e}")) - })?; - Ok(len) }) } @@ -808,7 +842,7 @@ async fn terminal_route_io_evicts_only_the_current_generation() { let first_route_id = 1; // Terminate the receive side of the *first* origin's live route only. - probe.kill_route.store(first_route_id, Ordering::Relaxed); + probe.terminate_route(first_route_id); // A terminal route I/O error is discovered lazily: the request riding the // doomed generation is the one that observes the failure, and that From 20a47abfa48032bdc4ebf648953d13a3f63c9000 Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 21:36:23 +0000 Subject: [PATCH 03/16] test: read complete UDS request before replying --- .../eggfetch-core/tests/direct_transport_tests.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/eggfetch-core/tests/direct_transport_tests.rs b/crates/eggfetch-core/tests/direct_transport_tests.rs index a594c03f..d9897463 100644 --- a/crates/eggfetch-core/tests/direct_transport_tests.rs +++ b/crates/eggfetch-core/tests/direct_transport_tests.rs @@ -279,7 +279,19 @@ async fn test_pool_isolation_uds_vs_tcp() { match listener.accept() { Ok((mut stream, _)) => { let mut buf = [0u8; 4096]; - let _ = stream.read(&mut buf).unwrap_or(0); + let mut request = Vec::new(); + while !request.windows(4).any(|window| window == b"\r\n\r\n") + && request.len() < 16 * 1024 + { + let read = stream.read(&mut buf).unwrap_or(0); + if read == 0 { + break; + } + request.extend_from_slice(&buf[..read]); + } + if !request.windows(4).any(|window| window == b"\r\n\r\n") { + continue; + } let response = b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nUDS-OK!"; let _ = stream.write_all(response); let _ = stream.flush(); From a3e24d47352ef30377617aaa2da6b11c2eef831d Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 22:06:35 +0000 Subject: [PATCH 04/16] test: fix compatibility fixtures on macOS OpenSSL --- compat/httpx/0.28.1/requirements.txt | 4 +++- .../eggfetch-python/tests/compat/native_fixtures.py | 11 ++++++++++- .../tests/compat/test_h2_differential.py | 6 +++++- .../tests/compat/test_resource_assertions.py | 4 ++++ .../tests/compat/test_ssl_context_network_proof.py | 1 + 5 files changed, 23 insertions(+), 3 deletions(-) diff --git a/compat/httpx/0.28.1/requirements.txt b/compat/httpx/0.28.1/requirements.txt index ec98da55..edd17be5 100644 --- a/compat/httpx/0.28.1/requirements.txt +++ b/compat/httpx/0.28.1/requirements.txt @@ -6,7 +6,9 @@ pytest-asyncio>=0.21.0 pytest-timeout>=2.0.0 # Downstream behavioral fixtures -anthropic>=0.25.0 +# Keep the SDK integration check aligned with AInews's pinned dependency. Newer +# Anthropic SDK major versions use the separately versioned httpx2 client. +anthropic==0.87.0 httpx-sse>=0.4.0 respx>=0.21.0 starlette>=0.27.0 diff --git a/crates/eggfetch-python/tests/compat/native_fixtures.py b/crates/eggfetch-python/tests/compat/native_fixtures.py index f60c985e..ea76b936 100644 --- a/crates/eggfetch-python/tests/compat/native_fixtures.py +++ b/crates/eggfetch-python/tests/compat/native_fixtures.py @@ -564,6 +564,8 @@ def _generate_self_signed_ca_cert(cert_dir: str) -> tuple[str, str]: "-days", "1", "-nodes", "-subj", "/CN=127.0.0.1", "-addext", "basicConstraints=critical,CA:TRUE", + "-addext", "keyUsage=critical,digitalSignature,keyEncipherment,keyCertSign,cRLSign", + "-addext", "extendedKeyUsage=serverAuth", "-addext", "subjectAltName=IP:127.0.0.1", ], check=True, capture_output=True, @@ -602,6 +604,7 @@ def _generate_ca_signed_server_cert( "-days", "1", "-nodes", "-subj", "/CN=Test CA", "-addext", "basicConstraints=critical,CA:TRUE", + "-addext", "keyUsage=critical,keyCertSign,cRLSign", ], check=True, capture_output=True, @@ -613,7 +616,13 @@ def _generate_ca_signed_server_cert( f.write("req_extensions = v3_req\n") f.write("prompt = no\n\n") f.write("[req_dn]\nCN = 127.0.0.1\n\n") - f.write("[v3_req]\nsubjectAltName = IP:127.0.0.1\n") + f.write( + "[v3_req]\n" + "basicConstraints = critical,CA:FALSE\n" + "keyUsage = critical,digitalSignature,keyEncipherment\n" + "extendedKeyUsage = serverAuth\n" + "subjectAltName = IP:127.0.0.1\n" + ) subprocess.run( [ diff --git a/crates/eggfetch-python/tests/compat/test_h2_differential.py b/crates/eggfetch-python/tests/compat/test_h2_differential.py index e1537a83..5f4482e3 100644 --- a/crates/eggfetch-python/tests/compat/test_h2_differential.py +++ b/crates/eggfetch-python/tests/compat/test_h2_differential.py @@ -150,7 +150,11 @@ def test_reference_httpx_fails_h2_only_vs_h1_only(self): http1=False, http2=True, verify=cert_path, trust_env=False, timeout=5, ) as client: - with pytest.raises(httpx.RemoteProtocolError): + # HTTPX/httpcore can classify the abrupt H1-only close as + # either a protocol error or a read error across supported + # Python/OpenSSL socket stacks. Both are transport failures; + # silent HTTP/1 downgrade is the behavior under test. + with pytest.raises(httpx.TransportError): client.get(f"https://{host}:{port}/health") finally: httpd.shutdown() diff --git a/crates/eggfetch-python/tests/compat/test_resource_assertions.py b/crates/eggfetch-python/tests/compat/test_resource_assertions.py index 3c5cfd82..56a3de09 100644 --- a/crates/eggfetch-python/tests/compat/test_resource_assertions.py +++ b/crates/eggfetch-python/tests/compat/test_resource_assertions.py @@ -40,6 +40,10 @@ def _load_resource_thresholds(): data = tomllib.load(f) system = platform.system().lower() + # The policy names the Apple platform by OS family, while Python reports + # its system string as "Darwin" on both Intel and Apple Silicon Macs. + if system == "darwin": + system = "macos" if system not in data.get("platform", {}): pytest.fail(f"No resource thresholds for platform: {system}") return data["platform"][system] diff --git a/crates/eggfetch-python/tests/compat/test_ssl_context_network_proof.py b/crates/eggfetch-python/tests/compat/test_ssl_context_network_proof.py index 9237be03..9c4df209 100644 --- a/crates/eggfetch-python/tests/compat/test_ssl_context_network_proof.py +++ b/crates/eggfetch-python/tests/compat/test_ssl_context_network_proof.py @@ -118,6 +118,7 @@ def _generate_self_signed_ca(cert_dir: str) -> tuple[str, str]: "-days", "1", "-nodes", "-subj", "/CN=Test CA", "-addext", "basicConstraints=critical,CA:TRUE", + "-addext", "keyUsage=critical,keyCertSign,cRLSign", ], check=True, capture_output=True, ) From 502031aa3e3b8d94e5b88dcc383df7669091f3f5 Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 22:06:52 +0000 Subject: [PATCH 05/16] ci: qualify both Python compatibility profiles --- docs/architecture/testing-fuzzing.md | 6 +++++- scripts/check.sh | 19 ++++++++++++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/docs/architecture/testing-fuzzing.md b/docs/architecture/testing-fuzzing.md index 464d5bb1..88f7a060 100644 --- a/docs/architecture/testing-fuzzing.md +++ b/docs/architecture/testing-fuzzing.md @@ -37,6 +37,9 @@ python -m pytest crates/eggfetch-python/tests/ -q --ignore=crates/eggfetch-pytho pip install -r compat/httpx/0.28.1/requirements.txt pip install -r compat/httpx2/2.12.0/requirements.txt EGGFETCH_COMPAT_REQUIRED=1 python -m pytest crates/eggfetch-python/tests/compat/ -v --strict-markers +# Run the same suite against the independent HTTPX2 facade as well. +EGGFETCH_COMPAT_PROFILE=httpx2/2.12.0 EGGFETCH_COMPAT_REQUIRED=1 \ + python -m pytest crates/eggfetch-python/tests/compat/ -v --strict-markers ``` ## Native Python interop coverage @@ -141,7 +144,8 @@ retry, typing-surface, downstream-portfolio, and upstream-derived cases alongside the rows above); the table names the load-bearing suites rather than enumerating every file. Tier 1 runs only the smoke kernel (`test_imports.py`, `test_client.py`, `test_exceptions.py`, -`test_corrective_kernel.py`); Tier 2 runs the full suite. +`test_corrective_kernel.py`); Tier 2 runs the full suite separately for both +versioned profiles: `httpx/0.28.1` and `httpx2/2.12.0`. Run with `EGGFETCH_COMPAT_REQUIRED=1` for fail-closed behavior. Tier 2 (`tier2_full_compat`) enforces this. diff --git a/scripts/check.sh b/scripts/check.sh index 82cfa084..ad9e3bee 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -269,7 +269,7 @@ run_tier1() { # ── Tier 2: Extended validation ────────────────────────────────────────── tier2_full_compat() { - info "Full HTTPX compatibility suite" + info "Full versioned HTTPX compatibility suites" # Verify compatibility dependencies are installed if ! "$PYTHON_BIN" -c "import httpx; assert httpx.__version__ == '0.28.1'" 2>/dev/null; then cat >&2 <<'SETUP_GUIDE' @@ -293,12 +293,17 @@ SETUP_GUIDE fail "Required Python module not found: $mod. Install into the active venv: python -m pip install -r compat/httpx/0.28.1/requirements.txt" fi done - ( - cd "$REPO_ROOT" - EGGFETCH_COMPAT_REQUIRED=1 "$PYTHON_BIN" -m pytest \ - "$REPO_ROOT/crates/eggfetch-python/tests/compat/" \ - -v --strict-markers - ) + local profile + for profile in "httpx/0.28.1" "httpx2/2.12.0"; do + info "Full compatibility profile: ${profile}" + ( + cd "$REPO_ROOT" + EGGFETCH_COMPAT_PROFILE="$profile" EGGFETCH_COMPAT_REQUIRED=1 \ + "$PYTHON_BIN" -m pytest \ + "$REPO_ROOT/crates/eggfetch-python/tests/compat/" \ + -v --strict-markers + ) + done } tier2_api_manifest() { From 96be34e63c497fd8f7fc2e3a9b0d3398b9b3ff6a Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 22:28:00 +0000 Subject: [PATCH 06/16] docs: reconcile status-code compatibility ledgers --- compat/httpx/0.28.1/allowed-differences.toml | 41 ------------------ compat/httpx/0.28.1/resolved-differences.toml | 32 ++++++++++++++ compat/httpx2/2.12.0/allowed-differences.toml | 42 +++++++++++++++++++ 3 files changed, 74 insertions(+), 41 deletions(-) diff --git a/compat/httpx/0.28.1/allowed-differences.toml b/compat/httpx/0.28.1/allowed-differences.toml index b779924c..ea2b78be 100644 --- a/compat/httpx/0.28.1/allowed-differences.toml +++ b/compat/httpx/0.28.1/allowed-differences.toml @@ -1453,45 +1453,4 @@ review-milestone = "stage-d" tests = ["test_url_query.py"] non_expiring = true -[[difference]] -id = "CODES-CTOR-001" -category = "stage-bounded" -classification = "intentional" -symbol = "codes" -difference-type = "parameter-name" -member = "codes" -reference = "['self', 'args', 'kwargs']" -candidate = "['self', 'args', 'kwds']" -behavior-case = "codes-constructor-differences" -reference-behavior = "HTTPX codes constructor uses kwargs" -eggfetch-behavior = "eggfetch codes constructor uses kwds" -rationale = "eggfetch codes uses kwds instead of kwargs due to IntEnum metaclass." -compatibility-stage-impact = "stage-c" -security-improvement = "false" -migration-impact = "None; internal implementation detail" -owner = "eggfetch-team" -review-milestone = "stage-d" -tests = ["test_config_objects.py"] -non_expiring = true - -[[difference]] -id = "CODES-CTOR-001-2" -category = "stage-bounded" -classification = "intentional" -symbol = "codes" -difference-type = "parameter-kind" -member = "self" -reference = "POSITIONAL_ONLY" -candidate = "POSITIONAL_OR_KEYWORD" -behavior-case = "codes-constructor-differences" -reference-behavior = "HTTPX codes self is POSITIONAL_ONLY" -eggfetch-behavior = "eggfetch codes IntEnum self is POSITIONAL_OR_KEYWORD" -rationale = "eggfetch codes IntEnum uses positional-or-keyword self." -compatibility-stage-impact = "stage-c" -security-improvement = "false" -migration-impact = "None; internal implementation detail" -owner = "eggfetch-team" -review-milestone = "stage-d" -tests = ["test_config_objects.py"] -non_expiring = true diff --git a/compat/httpx/0.28.1/resolved-differences.toml b/compat/httpx/0.28.1/resolved-differences.toml index 423006db..c4a36168 100644 --- a/compat/httpx/0.28.1/resolved-differences.toml +++ b/compat/httpx/0.28.1/resolved-differences.toml @@ -2292,3 +2292,35 @@ tests = [ "test_native_proxy_tls.py::TestProxyForwarding::test_proxy_headers_candidate_for_async_client", ] non_expiring = true + +[[difference]] +id = "CODES-CTOR-001" +category = "resolved" +symbol = "codes" +behavior-case = "codes-constructor-differences" +reference-behavior = "HTTPX 0.28.1 codes exposes **kwargs." +eggfetch-behavior = "eggfetch codes exposes **kwargs, matching HTTPX 0.28.1." +rationale = "The HTTPX 0.28.1 API manifest now matches this constructor exactly; the former allowance is stale." +compatibility-stage-impact = "resolved" +security-improvement = "false" +migration-impact = "None; internal implementation detail" +owner = "eggfetch-team" +review-milestone = "release-0.3.0" +tests = ["test_config_objects.py"] +non_expiring = true + +[[difference]] +id = "CODES-CTOR-001-2" +category = "resolved" +symbol = "codes" +behavior-case = "codes-constructor-differences" +reference-behavior = "HTTPX 0.28.1 codes self is POSITIONAL_ONLY." +eggfetch-behavior = "eggfetch codes self is POSITIONAL_ONLY, matching HTTPX 0.28.1." +rationale = "The HTTPX 0.28.1 API manifest now matches this parameter kind exactly; the former allowance is stale." +compatibility-stage-impact = "resolved" +security-improvement = "false" +migration-impact = "None; internal implementation detail" +owner = "eggfetch-team" +review-milestone = "release-0.3.0" +tests = ["test_config_objects.py"] +non_expiring = true diff --git a/compat/httpx2/2.12.0/allowed-differences.toml b/compat/httpx2/2.12.0/allowed-differences.toml index 2d70633b..c404fc68 100644 --- a/compat/httpx2/2.12.0/allowed-differences.toml +++ b/compat/httpx2/2.12.0/allowed-differences.toml @@ -1725,6 +1725,48 @@ review-milestone = "httpx2-baseline" tests = ["test_httpx2_origin_reachability.py"] non_expiring = true +[[difference]] +id = "H2X-CODES-001" +category = "intentional-difference" +classification = "intentional" +symbol = "codes" +difference-type = "parameter-name" +member = "codes" +reference = "['self', 'args', 'kwds']" +candidate = "['self', 'args', 'kwargs']" +behavior-case = "codes-constructor-differences" +reference-behavior = "httpx2 2.12.0 codes exposes **kwds." +eggfetch-behavior = "eggfetch codes exposes **kwargs." +rationale = "The IntEnum metaclass exposes a version-specific variadic keyword name; constructor behavior is unchanged and the HTTPX 0.28.1 facade matches its own reference." +compatibility-stage-impact = "baseline" +security-improvement = "false" +migration-impact = "None; internal introspection difference" +owner = "eggfetch-team" +review-milestone = "httpx2-baseline" +tests = ["test_config_objects.py"] +non_expiring = true + +[[difference]] +id = "H2X-CODES-002" +category = "intentional-difference" +classification = "intentional" +symbol = "codes" +difference-type = "parameter-kind" +member = "self" +reference = "POSITIONAL_OR_KEYWORD" +candidate = "POSITIONAL_ONLY" +behavior-case = "codes-constructor-differences" +reference-behavior = "httpx2 2.12.0 codes self is POSITIONAL_OR_KEYWORD." +eggfetch-behavior = "eggfetch codes self is POSITIONAL_ONLY." +rationale = "The IntEnum metaclass exposes a version-specific self parameter kind; constructor behavior is unchanged and the HTTPX 0.28.1 facade matches its own reference." +compatibility-stage-impact = "baseline" +security-improvement = "false" +migration-impact = "None; internal introspection difference" +owner = "eggfetch-team" +review-milestone = "httpx2-baseline" +tests = ["test_config_objects.py"] +non_expiring = true + [[difference]] id = "H2X-NEW-017" category = "intentional-difference" From 6978b27e14d1fbac99f8fc91c13c5e0f94e592a5 Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 22:32:33 +0000 Subject: [PATCH 07/16] test: stabilize Unix socket upgrade fixture --- .../eggfetch-core/tests/network_stream_tests.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/eggfetch-core/tests/network_stream_tests.rs b/crates/eggfetch-core/tests/network_stream_tests.rs index efc15e3e..4d3a86a2 100644 --- a/crates/eggfetch-core/tests/network_stream_tests.rs +++ b/crates/eggfetch-core/tests/network_stream_tests.rs @@ -572,20 +572,26 @@ async fn uds_upgrade_reports_uds_without_ips() { use std::io::{Read, Write}; use std::os::unix::net::UnixListener; - let path = "/tmp/eggfetch_metadata_uds.sock"; - let _ = std::fs::remove_file(path); + let path = + std::env::temp_dir().join(format!("eggfetch_metadata_uds_{}.sock", std::process::id())); + let _ = std::fs::remove_file(&path); let shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false)); let sd = shutdown.clone(); // Bind synchronously on the test thread so the socket exists before the // client connects. Binding inside the spawned thread raced the client's // first connect under parallel-test load (fixed 50 ms sleep was not a // readiness signal). No behavior change: same listener, same accept loop. - let listener = UnixListener::bind(path).unwrap(); + let listener = UnixListener::bind(&path).unwrap(); listener.set_nonblocking(true).unwrap(); let handle = std::thread::spawn(move || { while !sd.load(std::sync::atomic::Ordering::Relaxed) { match listener.accept() { Ok((mut stream, _)) => { + // On macOS an accepted Unix socket can inherit the + // nonblocking state of its listener. The fixture reads + // the complete request before writing the 101 response, + // so make that contract explicit. + stream.set_nonblocking(false).unwrap(); let mut buf = [0u8; 4096]; let mut acc = Vec::new(); stream.set_read_timeout(Some(Duration::from_secs(1))).ok(); @@ -616,7 +622,7 @@ async fn uds_upgrade_reports_uds_without_ips() { } }); let client = eggfetch_core::Client::builder() - .uds_path(path.to_owned()) + .uds_path(path.to_string_lossy().into_owned()) .build(); let mut response = client .get("http://localhost/") @@ -635,7 +641,7 @@ async fn uds_upgrade_reports_uds_without_ips() { assert!(meta.tls_info.is_none()); shutdown.store(true, std::sync::atomic::Ordering::SeqCst); let _ = handle.join(); - let _ = std::fs::remove_file(path); + let _ = std::fs::remove_file(&path); } #[tokio::test] From 9d642b8a82081542fa85f389dfe00b78f845ab0a Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 22:56:03 +0000 Subject: [PATCH 08/16] ci: select pinned Rust toolchain for API checks --- scripts/check.sh | 1 + scripts/check_rust_public_api.py | 26 ++++++++--- scripts/test_rust_public_api_oracle.py | 65 ++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 6 deletions(-) create mode 100644 scripts/test_rust_public_api_oracle.py diff --git a/scripts/check.sh b/scripts/check.sh index ad9e3bee..bccf0ff3 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -351,6 +351,7 @@ tier2_rust_public_api() { info "Rust public API oracle" require_command cargo-public-api require_command cargo-semver-checks + "$PYTHON_BIN" "$SCRIPT_DIR/test_rust_public_api_oracle.py" "$PYTHON_BIN" "$SCRIPT_DIR/check_rust_public_api.py" } diff --git a/scripts/check_rust_public_api.py b/scripts/check_rust_public_api.py index 29016c85..4b8f427f 100644 --- a/scripts/check_rust_public_api.py +++ b/scripts/check_rust_public_api.py @@ -52,12 +52,26 @@ def _toolchain_env() -> dict[str, str]: fail the gate for a reason unrelated to the change under test. The pin must cover the semver half too, not just the snapshot half. """ - return { - **os.environ, - "RUSTUP_TOOLCHAIN": os.environ.get( - "RUST_API_RUSTUP_TOOLCHAIN", "nightly-2026-05-07" - ), - } + toolchain = os.environ.get("RUST_API_RUSTUP_TOOLCHAIN", "nightly-2026-05-07") + env = {**os.environ, "RUSTUP_TOOLCHAIN": toolchain} + # Some hosts put standalone Homebrew/system Rust binaries before the + # rustup proxies on PATH. RUSTUP_TOOLCHAIN cannot select a compiler when + # those binaries are invoked directly, so resolve the pinned toolchain's + # executables and pass them explicitly to Cargo and the API tools. + for variable, binary in (("CARGO", "cargo"), ("RUSTC", "rustc"), ("RUSTDOC", "rustdoc")): + result = subprocess.run( + ["rustup", "which", "--toolchain", toolchain, binary], + check=False, + capture_output=True, + text=True, + ) + if result.returncode: + raise SystemExit( + f"cannot resolve {binary} from required Rust toolchain {toolchain}: " + f"{result.stderr.strip()}" + ) + env[variable] = result.stdout.strip() + return env def _run_public_api(tool: list[str], feature_args: tuple[str, ...]) -> str: diff --git a/scripts/test_rust_public_api_oracle.py b/scripts/test_rust_public_api_oracle.py new file mode 100644 index 00000000..e9c29fed --- /dev/null +++ b/scripts/test_rust_public_api_oracle.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Self-test pinned Rust toolchain resolution for the public API oracle.""" + +from __future__ import annotations + +import importlib.util +import os +import subprocess +from pathlib import Path +from unittest.mock import patch + + +SCRIPT = Path(__file__).with_name("check_rust_public_api.py") +SPEC = importlib.util.spec_from_file_location("check_rust_public_api", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +def test_toolchain_binaries_are_explicitly_resolved() -> None: + with patch.dict(os.environ, {"RUST_API_RUSTUP_TOOLCHAIN": "nightly-test"}): + with patch.object( + MODULE.subprocess, + "run", + side_effect=[ + subprocess.CompletedProcess([], 0, "/rust/bin/cargo\n", ""), + subprocess.CompletedProcess([], 0, "/rust/bin/rustc\n", ""), + subprocess.CompletedProcess([], 0, "/rust/bin/rustdoc\n", ""), + ], + ) as run: + env = MODULE._toolchain_env() + + assert env["RUSTUP_TOOLCHAIN"] == "nightly-test" + assert env["CARGO"] == "/rust/bin/cargo" + assert env["RUSTC"] == "/rust/bin/rustc" + assert env["RUSTDOC"] == "/rust/bin/rustdoc" + assert [call.args[0][-1] for call in run.call_args_list] == ["cargo", "rustc", "rustdoc"] + + +def test_missing_pinned_toolchain_fails_closed() -> None: + with patch.dict(os.environ, {"RUST_API_RUSTUP_TOOLCHAIN": "nightly-missing"}): + with patch.object( + MODULE.subprocess, + "run", + return_value=subprocess.CompletedProcess( + [], 1, "", "toolchain is not installed" + ), + ): + try: + MODULE._toolchain_env() + except SystemExit as exc: + assert "nightly-missing" in str(exc) + else: + raise AssertionError("missing Rust toolchain must fail closed") + + +def main() -> int: + test_toolchain_binaries_are_explicitly_resolved() + test_missing_pinned_toolchain_fails_closed() + print("Rust public API toolchain self-test passed (2 cases)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From b0a827565d496bc99ca42362ee9264c2735f720a Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 23:01:07 +0000 Subject: [PATCH 09/16] test: serialize proxy tunnel close before reconnect --- crates/eggfetch-core/tests/proxy_tests.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/eggfetch-core/tests/proxy_tests.rs b/crates/eggfetch-core/tests/proxy_tests.rs index b4ac2997..735fc656 100644 --- a/crates/eggfetch-core/tests/proxy_tests.rs +++ b/crates/eggfetch-core/tests/proxy_tests.rs @@ -617,12 +617,18 @@ async fn handle_connect_tunnel( let _ = client_write.shutdown().await; }; - tokio::select! { - () = c2d => {} - () = d2c => {} - Ok(()) = close_rx.recv() => { - closed_tunnel_count.fetch_add(1, Ordering::SeqCst); - } + let closed_by_fixture = tokio::select! { + () = c2d => false, + () = d2c => false, + Ok(()) = close_rx.recv() => true, + }; + if closed_by_fixture { + // Close the proxy-side TCP connection before waking tests that + // issue the reconnect. Otherwise the next request can race the + // server's read loop and observe a half-closed TLS tunnel instead + // of deterministically exercising a fresh CONNECT handshake. + let _ = client_stream.shutdown().await; + closed_tunnel_count.fetch_add(1, Ordering::SeqCst); } } else { let resp = b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n"; From 25ed17e43dee85aada631986f50e3fe39d8c6735 Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 30 Oct 2026 23:01:45 +0000 Subject: [PATCH 10/16] test: reborrow proxy stream for deterministic close --- crates/eggfetch-core/tests/proxy_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/eggfetch-core/tests/proxy_tests.rs b/crates/eggfetch-core/tests/proxy_tests.rs index 735fc656..ffdfc27c 100644 --- a/crates/eggfetch-core/tests/proxy_tests.rs +++ b/crates/eggfetch-core/tests/proxy_tests.rs @@ -604,7 +604,7 @@ async fn handle_connect_tunnel( let resp = b"HTTP/1.1 200 Connection Established\r\n\r\n"; client_stream.write_all(resp).await?; - let (mut client_read, mut client_write) = tokio::io::split(client_stream); + let (mut client_read, mut client_write) = tokio::io::split(&mut *client_stream); let (mut dest_read, mut dest_write) = dest_stream.into_split(); let c2d = async { From 0fed44747f74a0dad45f617219fc1173aa7c72ba Mon Sep 17 00:00:00 2001 From: CI Test Date: Sat, 31 Oct 2026 02:14:12 +0000 Subject: [PATCH 11/16] test: isolate proxy reconnect timeout budget --- crates/eggfetch-core/tests/proxy_tests.rs | 33 +++++++++++++++++------ 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/crates/eggfetch-core/tests/proxy_tests.rs b/crates/eggfetch-core/tests/proxy_tests.rs index ffdfc27c..06e48f24 100644 --- a/crates/eggfetch-core/tests/proxy_tests.rs +++ b/crates/eggfetch-core/tests/proxy_tests.rs @@ -1833,7 +1833,7 @@ async fn hyper_connect_proxy_does_not_reuse_short_total_on_reconnect() { } #[tokio::test] -async fn hyper_connect_proxy_reconnect_honors_short_current_total() { +async fn hyper_connect_proxy_fresh_client_honors_short_total() { let ca = CertAuthority::new(); let origin = TlsTestServer::start(&ca, &["origin.invalid"]).await; let proxy_server = HttpProxyServer::start(HttpProxyConfig { @@ -1870,6 +1870,20 @@ async fn hyper_connect_proxy_reconnect_honors_short_current_total() { proxy_server.close_tunnels(); proxy_server.wait_for_closed_tunnels(1).await; + // The preceding test covers recovery through the same pooled client. Use + // a fresh client here so the short budget is measured against a known new + // CONNECT, rather than racing a stale TLS EOF from the closed tunnel. + drop(client); + let client = Client::builder() + .proxy(Proxy::all(&proxy_server.url()).unwrap()) + .tls_config( + TlsConfig::builder() + .ca_certificate_pem(&ca.cert_pem()) + .unwrap() + .build(), + ) + .build(); + let error = client .get(&origin_url) .unwrap() @@ -1882,13 +1896,16 @@ async fn hyper_connect_proxy_reconnect_honors_short_current_total() { .send() .await .expect_err("the current short total budget must cancel reconnect setup"); - assert!(matches!( - error, - Error::Timeout { - phase: TimeoutPhase::Total, - .. - } - )); + assert!( + matches!( + &error, + Error::Timeout { + phase: TimeoutPhase::Total, + .. + } + ), + "expected the current request's total timeout, got: {error:?}" + ); assert_eq!(proxy_server.connection_count(), 2); assert_eq!(proxy_server.connect_targets().len(), 2); From 6f81ce54180dbe9921015ac4a010c82fcdfbcbbf Mon Sep 17 00:00:00 2001 From: CI Test Date: Sat, 31 Oct 2026 03:31:32 +0000 Subject: [PATCH 12/16] test: serialize feature profile suites --- scripts/check.sh | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/scripts/check.sh b/scripts/check.sh index bccf0ff3..97b607b0 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -357,11 +357,13 @@ tier2_rust_public_api() { tier2_feature_tests() { info "Feature-gated tests" - cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-gzip - cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-brotli - cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-zstd - cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-deflate - cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,proxy + # Pool and resource fixtures depend on loopback scheduling. Keep the + # feature profiles serialized just like the all-features workspace suite. + cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-gzip -- --test-threads=1 + cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-brotli -- --test-threads=1 + cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-zstd -- --test-threads=1 + cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,compression-deflate -- --test-threads=1 + cargo test -p eggfetch-core --no-default-features --features http1,tls-rustls,proxy -- --test-threads=1 } tier2_msrv() { From e22dcf57def5e791fe7e51e866663ead693be417 Mon Sep 17 00:00:00 2001 From: CI Test Date: Sat, 31 Oct 2026 03:56:48 +0000 Subject: [PATCH 13/16] test: read complete UDS metrics request --- .../tests/transport_metrics_tests.rs | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/crates/eggfetch-core/tests/transport_metrics_tests.rs b/crates/eggfetch-core/tests/transport_metrics_tests.rs index 5dc6c844..f36cf209 100644 --- a/crates/eggfetch-core/tests/transport_metrics_tests.rs +++ b/crates/eggfetch-core/tests/transport_metrics_tests.rs @@ -233,25 +233,35 @@ async fn direct_connector_failure_counts_exactly() { #[cfg(unix)] #[tokio::test] async fn uds_success_counts_exactly() { - use std::io::{Read, Write}; + use std::io::{BufRead, BufReader, Write}; use std::os::unix::net::UnixListener; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; - let path = "/tmp/eggfetch_metrics_uds.sock"; - let _ = std::fs::remove_file(path); + let path = format!("/tmp/eggfetch_metrics_uds_{}.sock", std::process::id()); + let _ = std::fs::remove_file(&path); let shutdown = Arc::new(AtomicBool::new(false)); let sd = shutdown.clone(); // Bind on the test thread so the socket exists before the client // connects (see network_stream_tests.rs UDS upgrade fixture). - let listener = UnixListener::bind(path).unwrap(); + let listener = UnixListener::bind(&path).unwrap(); listener.set_nonblocking(true).unwrap(); let handle = std::thread::spawn(move || { while !sd.load(Ordering::Relaxed) { match listener.accept() { - Ok((mut stream, _)) => { - let mut buf = [0u8; 4096]; - let _ = stream.read(&mut buf).unwrap_or(0); + Ok((stream, _)) => { + stream.set_nonblocking(false).unwrap(); + let mut reader = BufReader::new(stream); + let mut line = Vec::new(); + loop { + line.clear(); + match reader.read_until(b'\n', &mut line) { + Ok(0) | Err(_) => break, + Ok(_) if line == b"\r\n" || line == b"\n" => break, + Ok(_) => {} + } + } + let stream = reader.get_mut(); let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); let _ = stream.flush(); } @@ -262,7 +272,7 @@ async fn uds_success_counts_exactly() { } } }); - let client = Client::builder().uds_path(path.to_owned()).build(); + let client = Client::builder().uds_path(path.clone()).build(); let before = client.transport_metrics().snapshot(); let mut resp = client .get("http://localhost/") From 4a008bdf051bb7b779864814f0a9c25550ab6d57 Mon Sep 17 00:00:00 2001 From: CI Test Date: Sat, 31 Oct 2026 04:46:35 +0000 Subject: [PATCH 14/16] docs: record 0.3.0 qualification candidate status --- plans/httpx-parity-correction-status.md | 35 +++++++++++++------------ 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/plans/httpx-parity-correction-status.md b/plans/httpx-parity-correction-status.md index 24eea1ec..c2ebd040 100644 --- a/plans/httpx-parity-correction-status.md +++ b/plans/httpx-parity-correction-status.md @@ -4,16 +4,16 @@ This record is the exact-SHA-bound status for the HTTPX 0.28.1 compatibility facade. Historical phase and corrective-pass records remain in the git history and referenced plans; counts below are only from the runs named here. -## Recorded state — Stage C renewed at the advisory-patch freeze (2026-10-28) +## Release candidate qualification — 0.3.0 (2026-10-31) -Recorded designation: **Stage C qualified (renewal)** for both documented -facades, bound to executable freeze -`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f`. +The release candidate executable tree is frozen at +`e22dcf57def5e791fe7e51e866663ead693be417`. PR #26 CI passed on this exact +SHA. Final Tier 2, package, live security, registry publication and release +checks are in progress; the profiles continue to point at the last completed +Stage C binding until those gates finish. -The advisory-patch pass has now been qualified in its own right, so the live -Stage C binding names that freeze. This is a compatibility binding only: it -authorizes no release. H3 stays experimental, HTTPX 1.0 stays gated on the -upstream trigger, and Node maturation stays a separately registered future. +H3 stays experimental, HTTPX 1.0 stays gated on the upstream trigger, and +Node maturation stays a separately registered future. ### What was qualified @@ -44,19 +44,20 @@ tree. Those two tests are the regression net. The pin, its rationale and that net are recorded in `docs/architecture/dependency-policy.md`, so a later `cargo update` does not silently reintroduce 1.54.x. -The qualification ran on `b74cf891…`, which is the executable freeze itself. -The renewal commit that rebinds the two compat profiles and this ledger lands -on top of it and changes no executable input, so it does not invalidate the -binding. +The last completed Stage C qualification remains bound to +`b74cf891…` until the candidate gates below finish. This ledger update changes +documentation only; candidate executable inputs remain frozen at `e22dcf57…`. -### Qualification evidence +### Candidate evidence collected so far | Gate | Result | |---|---| -| Tier 1 | exit 0 — the H3 runner self-test, formatting, the lint-suppression guard self-test and its policy scan, adapter feature ownership, release version validation, clippy, **1772 Rust workspace tests** across 74 binaries, the stable public contract fixtures, the feature-isolated profile whole-suite compile, the native Python API manifest, the Python typing surface and typing fixture, **581 Python behaviour tests** and **134 HTTPX compatibility smoke tests**, and the downstream-artifact producer self-test. The Node JS surface skipped, which the policy defines as optional | -| Tier 2 | exit 0 — the full pinned HTTPX compatibility suite **2073 passed / 0 failed**; the API manifest comparison at **74 symbols** for httpx 0.28.1 and **76 symbols** for httpx2 2.12.0, with 0 unexplained and 0 stale allowed differences; the Rust public-API oracle **passed in 8 profiles**; `cargo-semver-checks` 0.49.0 reported **"no semver update required"** against the planning baseline `03ecba973010e2858bf16a2b5f84d51ce70adae4`; the feature matrix and the 5 feature-gated combinations green; **5 MSRV checks** on the exact Rust 1.89.0 toolchain, all `--locked`; documentation and doctests; FFI; the resource regression check; the lifecycle and soak tests; the downstream behavioral-fixture portfolio **4/4 required packages** with `overall_pass: true`; lossless merge; Criterion micro-benchmarks. One optional check skipped: the Node JS surface | -| Tier 3 | exit 0 — crate packaging, the release wheel build, the wheel smoke test, package content validation and the installed-wheel typing smoke | -| Live security preflight | exit 0 — `advisories ok, bans ok, licenses ok, sources ok` | +| CI | exit 0 — PR #26 on the exact candidate SHA | +| Rust, Python, API, feature, MSRV, docs, FFI checks | passed in the extended run; Python behavior suite **581 passed**, compatibility profiles and API oracle passed, 5 feature-gated suites and 5 MSRV checks passed | +| Lifecycle, soak, downstream, merge | lifecycle tests passed; soak **11 passed**; downstream behavioral fixtures **4/4 required packages**, `overall_pass: true`; lossless merge **12 passed** | +| Resource monitor | The full extended run once exceeded its 64 MiB delta limit (**81.22 MiB delta**, 84.58 MiB peak). A standalone rerun passed at **59.72 MiB delta**, 63.08 MiB peak. The full combined gate must be rerun before qualification is complete. | +| Criterion benchmarks | Complete; timings were reported without a failing threshold. | +| Package and live security gates | Pending. | ### Host accommodations From 6093cc7aa0961194f096cbf2f92c3fc057671a34 Mon Sep 17 00:00:00 2001 From: CI Test Date: Sat, 31 Oct 2026 04:53:41 +0000 Subject: [PATCH 15/16] test: make proxy reconnect budget fixture deterministic --- crates/eggfetch-core/tests/proxy_tests.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/eggfetch-core/tests/proxy_tests.rs b/crates/eggfetch-core/tests/proxy_tests.rs index 06e48f24..a20eb60c 100644 --- a/crates/eggfetch-core/tests/proxy_tests.rs +++ b/crates/eggfetch-core/tests/proxy_tests.rs @@ -1777,7 +1777,7 @@ async fn hyper_connect_proxy_reuses_keep_alive_tunnel() { #[tokio::test] async fn hyper_connect_proxy_does_not_reuse_short_total_on_reconnect() { let ca = CertAuthority::new(); - let origin = TlsTestServer::start(&ca, &["origin.invalid"]).await; + let origin = TlsTestServer::start(&ca, &["origin.invalid", "second-origin.invalid"]).await; let proxy_server = HttpProxyServer::start(HttpProxyConfig { connect_delay: Some((2, Duration::from_millis(700))), ..Default::default() @@ -1793,6 +1793,7 @@ async fn hyper_connect_proxy_does_not_reuse_short_total_on_reconnect() { ) .build(); let origin_url = format!("https://origin.invalid:{}/", origin.port()); + let second_origin_url = format!("https://second-origin.invalid:{}/", origin.port()); let target = format!("127.0.0.1:{}", origin.port()).parse().unwrap(); let mut first = client @@ -1809,11 +1810,12 @@ async fn hyper_connect_proxy_does_not_reuse_short_total_on_reconnect() { .unwrap(); assert_eq!(first.text().await.unwrap(), "OK"); - proxy_server.close_tunnels(); - proxy_server.wait_for_closed_tunnels(1).await; - let mut second = client - .get(&origin_url) + // A different origin forces a fresh CONNECT through the same client + // without relying on a request racing a TLS tunnel that the fixture + // has just torn down. The proxy delays this second connection, so a + // deadline accidentally retained from the first request would fail. + .get(&second_origin_url) .unwrap() .proxy_target_addresses([target]) .timeout(Timeout { From 64dc9c02e9142a08e49e9a8edd46978c60f1e026 Mon Sep 17 00:00:00 2001 From: CI Test Date: Sat, 31 Oct 2026 06:13:25 +0000 Subject: [PATCH 16/16] docs: qualify eggfetch 0.3.0 candidate --- compat/httpx/0.28.1/profile.toml | 8 ++--- compat/httpx2/2.12.0/profile.toml | 8 ++--- .../reference/compatibility-stage-decision.md | 21 ++++--------- docs/reference/compatibility.md | 31 +++++-------------- docs/residual-differences.md | 19 ++++-------- plans/httpx-parity-correction-status.md | 27 ++++++++-------- 6 files changed, 41 insertions(+), 73 deletions(-) diff --git a/compat/httpx/0.28.1/profile.toml b/compat/httpx/0.28.1/profile.toml index d7a5f151..da57e7d4 100644 --- a/compat/httpx/0.28.1/profile.toml +++ b/compat/httpx/0.28.1/profile.toml @@ -12,11 +12,11 @@ rebaseline-sha = "f9eb1a455907d43210886b7b047d18bde8716652" # log is not duplicated here. stage = "stage-c-qualified" status = "qualified" -qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" -qualification-date = "2026-10-28" -previous-qualification-sha = "822b7246bab79cca7c54c32aaf403c1366472c57" +qualification-sha = "6093cc7aa0961194f096cbf2f92c3fc057671a34" +qualification-date = "2026-10-31" +previous-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" historical-current-qualification-sha = "42a9c96db5b25354843bd83bd458c71757e95651" -historical-qualification-sha = "26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e, cc90f5ed561bbe10d4c26accc54ed3b916518f98, d034a1005857a7f403222dda4bda5f2f204a44fe, d24101be6ed7be64463813750da5b4043d9905ec, 5c7899fefb6df087dfa1b3578fbef9ba64f87742, 9ffa6cd85848fd16a424b65f73254351911777c4, c44d4f25ffebc1a792335163ae4bc106076b3963" +historical-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f, 26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e, cc90f5ed561bbe10d4c26accc54ed3b916518f98, d034a1005857a7f403222dda4bda5f2f204a44fe, d24101be6ed7be64463813750da5b4043d9905ec, 5c7899fefb6df087dfa1b3578fbef9ba64f87742, 9ffa6cd85848fd16a424b65f73254351911777c4, c44d4f25ffebc1a792335163ae4bc106076b3963" reference = "httpx==0.28.1" [reference] diff --git a/compat/httpx2/2.12.0/profile.toml b/compat/httpx2/2.12.0/profile.toml index d0b8a8c7..616f00b9 100644 --- a/compat/httpx2/2.12.0/profile.toml +++ b/compat/httpx2/2.12.0/profile.toml @@ -10,11 +10,11 @@ created = "2026-09-10" # log is not duplicated here. stage = "stage-c-qualified" status = "qualified" -qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" -qualification-date = "2026-10-28" -previous-qualification-sha = "822b7246bab79cca7c54c32aaf403c1366472c57" +qualification-sha = "6093cc7aa0961194f096cbf2f92c3fc057671a34" +qualification-date = "2026-10-31" +previous-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" historical-current-qualification-sha = "42a9c96db5b25354843bd83bd458c71757e95651" -historical-qualification-sha = "26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e" +historical-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f, 26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e" reference = "httpx2==2.12.0" [reference] diff --git a/docs/reference/compatibility-stage-decision.md b/docs/reference/compatibility-stage-decision.md index 7b573f0d..8cf9685d 100644 --- a/docs/reference/compatibility-stage-decision.md +++ b/docs/reference/compatibility-stage-decision.md @@ -1,23 +1,14 @@ # Compatibility Stage Decision **Current decision — Stage C qualified on frozen executable SHA -`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f`** +`6093cc7aa0961194f096cbf2f92c3fc057671a34` (2026-10-31)** The documented Python 3.10+ asyncio-supported HTTPX 0.28.1 surface and the -documented httpx2 2.12.0 sibling surface are qualified on executable SHA -`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` (2026-10-28, renewal after the -advisory-patch pass — two newly published RustSec advisories were cleared from -the dependency tree, RUSTSEC-2026-0386 in `tokio` and RUSTSEC-2026-0391 in -`zstd`. `tokio` is pinned to 1.53.3 rather than the newer 1.54.x because -1.54.0 regresses the HTTP/1 client path, `zstd` was raised to 0.14.3 and -`brotli` to 9.1.1, and both `Cargo.lock` and `fuzz/Cargo.lock` carry the same -pins). -The prior `822b7246bab79cca7c54c32aaf403c1366472c57` binding is historical, -and the binding before it, `26fa619299fb8d447f25cbcb5eb713a1f537a30c`, is -historical too. The anchor binding `42a9c96db5b25354843bd83bd458c71757e95651` -and every binding before it are historical as well. The full history of every -binding, renewal and supersession is in -`plans/httpx-parity-correction-status.md`. +documented httpx2 2.12.0 sibling surface passed the full compatibility, +extended, package, and live security gates on that frozen executable tree. +The previous binding `b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` and all +earlier bindings are historical. The full binding history and qualification +evidence are in `plans/httpx-parity-correction-status.md`. The `015a56d7...` binding (the coordinated 0.2.2 candidate) is historical. The `3fc58fbd99ecb496749b833ee7b27436fe3b412d` (M007) and `bb6e07320f61736702e37f335fd1d48c7c3dfbaf` bindings are historical; earlier diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md index f3c65ce5..b0c45b3d 100644 --- a/docs/reference/compatibility.md +++ b/docs/reference/compatibility.md @@ -5,18 +5,9 @@ claims refer specifically to the pinned 0.28.1 asyncio-supported facade (`eggfetch.compat.httpx`), not all HTTPX transports or concurrency backends. HTTPX2 claims refer specifically to the sibling 2.12.0 facade (`eggfetch.compat.httpx2`, Stage C qualified on frozen executable SHA -`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` (2026-10-28, renewal after the -advisory-patch pass — two newly published RustSec advisories were cleared from -the dependency tree, RUSTSEC-2026-0386 in `tokio` and RUSTSEC-2026-0391 in -`zstd`. `tokio` is pinned to 1.53.3 rather than the newer 1.54.x because -1.54.0 regresses the HTTP/1 client path, `zstd` was raised to 0.14.3 and -`brotli` to 9.1.1, and both `Cargo.lock` and `fuzz/Cargo.lock` carry the same -pins). -The prior `822b7246bab79cca7c54c32aaf403c1366472c57` binding is historical, -and the binding before it, `26fa619299fb8d447f25cbcb5eb713a1f537a30c`, is -historical too. The anchor binding `42a9c96db5b25354843bd83bd458c71757e95651` -and every binding before it are historical as well. The full history of every -binding, renewal and supersession is in +`6093cc7aa0961194f096cbf2f92c3fc057671a34`, 2026-10-31). The previous +`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` binding and all earlier bindings +are historical. Full qualification evidence and binding history are in `plans/httpx-parity-correction-status.md`. The `015a56d7ec3edf186eec8ebccff01cbf5584274e` binding (the coordinated 0.2.2 candidate) is historical. Profiles live in @@ -143,18 +134,10 @@ eggfetch targets HTTPX 0.28.1 compatibility in phases. The current status: lifecycle hardening, observability cleanup. Historical evidence only. - **Current qualification**: HTTPX 0.28.1 and HTTPX2 2.12.0 **are** Stage C qualified on executable SHA - `b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` (2026-10-28, renewal after the - advisory-patch pass — two newly published RustSec advisories were cleared from - the dependency tree, RUSTSEC-2026-0386 in `tokio` and RUSTSEC-2026-0391 in - `zstd`. `tokio` is pinned to 1.53.3 rather than the newer 1.54.x because - 1.54.0 regresses the HTTP/1 client path, `zstd` was raised to 0.14.3 and - `brotli` to 9.1.1, and both `Cargo.lock` and `fuzz/Cargo.lock` carry the same - pins). - The prior `822b7246bab79cca7c54c32aaf403c1366472c57` binding is historical, - and the binding before it, `26fa619299fb8d447f25cbcb5eb713a1f537a30c`, is - historical too. The anchor binding - `42a9c96db5b25354843bd83bd458c71757e95651` and every binding before it are - historical as well. The full history of every binding, renewal and supersession + `6093cc7aa0961194f096cbf2f92c3fc057671a34` (2026-10-31). Both full + compatibility profiles, extended and package validation, and the live + security preflight passed. The previous `b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` + binding and every earlier binding are historical. Full qualification evidence is in `plans/httpx-parity-correction-status.md`. The `3fc58fbd99ecb496749b833ee7b27436fe3b412d` (M007) and `bb6e07320f61736702e37f335fd1d48c7c3dfbaf` bindings are historical; earlier diff --git a/docs/residual-differences.md b/docs/residual-differences.md index e701bb41..15ef5bbb 100644 --- a/docs/residual-differences.md +++ b/docs/residual-differences.md @@ -1,19 +1,12 @@ # Residual Differences from HTTPX 0.28.1 The HTTPX 0.28.1 and httpx2 2.12.0 facades are Stage C qualified on frozen -executable SHA -`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` (2026-10-28, renewal after the -advisory-patch pass — two newly published RustSec advisories were cleared from -the dependency tree, RUSTSEC-2026-0386 in `tokio` and RUSTSEC-2026-0391 in -`zstd`. `tokio` is pinned to 1.53.3 rather than the newer 1.54.x because -1.54.0 regresses the HTTP/1 client path, `zstd` was raised to 0.14.3 and -`brotli` to 9.1.1, and both `Cargo.lock` and `fuzz/Cargo.lock` carry the same -pins). -The prior `822b7246bab79cca7c54c32aaf403c1366472c57` binding is historical, -and the binding before it, `26fa619299fb8d447f25cbcb5eb713a1f537a30c`, is -historical too. The anchor binding `42a9c96db5b25354843bd83bd458c71757e95651` -and every binding before it are historical as well. The full history of every -binding, renewal and supersession is in +executable SHA `6093cc7aa0961194f096cbf2f92c3fc057671a34` (2026-10-31). The +0.3.0 candidate passed CI, extended validation, package validation, and the +live security preflight. Its dependency policy retains the audited Tokio, +zstd and brotli pins; see `docs/architecture/dependency-policy.md`. The prior +`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` binding is historical. The full +history of every binding, renewal and supersession is in `plans/httpx-parity-correction-status.md`. The `015a56d7ec3edf186eec8ebccff01cbf5584274e` binding (the coordinated 0.2.2 candidate) is historical. diff --git a/plans/httpx-parity-correction-status.md b/plans/httpx-parity-correction-status.md index c2ebd040..1eea584e 100644 --- a/plans/httpx-parity-correction-status.md +++ b/plans/httpx-parity-correction-status.md @@ -7,10 +7,10 @@ and referenced plans; counts below are only from the runs named here. ## Release candidate qualification — 0.3.0 (2026-10-31) The release candidate executable tree is frozen at -`e22dcf57def5e791fe7e51e866663ead693be417`. PR #26 CI passed on this exact -SHA. Final Tier 2, package, live security, registry publication and release -checks are in progress; the profiles continue to point at the last completed -Stage C binding until those gates finish. +`6093cc7aa0961194f096cbf2f92c3fc057671a34`. Both documented facades are +**Stage C qualified (renewal)** on this exact executable SHA. PR #26 CI, the +extended gate, package gate, and live security preflight all passed. Registry +publication and tagged release workflow remain in progress. H3 stays experimental, HTTPX 1.0 stays gated on the upstream trigger, and Node maturation stays a separately registered future. @@ -44,20 +44,21 @@ tree. Those two tests are the regression net. The pin, its rationale and that net are recorded in `docs/architecture/dependency-policy.md`, so a later `cargo update` does not silently reintroduce 1.54.x. -The last completed Stage C qualification remains bound to -`b74cf891…` until the candidate gates below finish. This ledger update changes -documentation only; candidate executable inputs remain frozen at `e22dcf57…`. +The previous Stage C binding was `b74cf891…`; this renewal is bound to the +candidate executable freeze `6093cc7a…`. The profile and ledger edits after +that freeze are documentation only and do not change executable inputs. -### Candidate evidence collected so far +### Qualification evidence | Gate | Result | |---|---| | CI | exit 0 — PR #26 on the exact candidate SHA | -| Rust, Python, API, feature, MSRV, docs, FFI checks | passed in the extended run; Python behavior suite **581 passed**, compatibility profiles and API oracle passed, 5 feature-gated suites and 5 MSRV checks passed | -| Lifecycle, soak, downstream, merge | lifecycle tests passed; soak **11 passed**; downstream behavioral fixtures **4/4 required packages**, `overall_pass: true`; lossless merge **12 passed** | -| Resource monitor | The full extended run once exceeded its 64 MiB delta limit (**81.22 MiB delta**, 84.58 MiB peak). A standalone rerun passed at **59.72 MiB delta**, 63.08 MiB peak. The full combined gate must be rerun before qualification is complete. | -| Criterion benchmarks | Complete; timings were reported without a failing threshold. | -| Package and live security gates | Pending. | +| Tier 1 and Tier 2 | `./scripts/check.sh extended` exit 0. Python behavior suite **581 passed**; both full compatibility profiles, API oracle, five feature profiles, five MSRV checks, docs/doctests/link checks, and FFI checks passed. Lifecycle **49 passed**; soak **11 passed**; downstream behavioral fixtures **4/4 required packages** with `overall_pass: true`; lossless merge and all required gates passed. | +| Resource monitor | Passed in the full extended run: **52.37 MB peak / 49.01 MB delta** against 100 MB peak / 64 MB delta limits. | +| Tier 3 package gate | `./scripts/check.sh package` exit 0. Release wheel built; wheel smoke, content validation, and installed-wheel typing smoke passed. Local wheel follows the shell's x86_64/Rosetta architecture; the release workflow's macOS matrix targets Apple Silicon arm64 only. | +| Live security preflight | `./scripts/check_security.sh` exit 0 — `advisories ok, bans ok, licenses ok, sources ok`. The duplicate `getrandom` notice is informational and permitted by policy. | +| Criterion | Completed. Timings span unrelated groups and include large architecture-sensitive shifts; this host ran the x86_64/Rosetta toolchain on Apple Silicon. Since microbenchmarks have no failure threshold and the executable change is test-fixture-only, these numbers are not a comparable performance qualification. | +| Optional Node JS surface | Skipped by policy because the native Node artifact was not built. | ### Host accommodations