The Python crate (eggfetch-python) uses PyO3/maturin to expose eggfetch-core to Python. It provides both sync and async APIs over the async Rust engine.
See also: overview.md.
The supported native Python import surface is the pure-Python eggfetch
package. Its explicit eggfetch.__all__ list is the single public export
contract and is checked against
crates/eggfetch-python/tests/native_api_manifest.json. The _native PyO3
extension is private implementation machinery: it intentionally has no
__all__, so registering an implementation symbol cannot silently create a
second supported API.
The top-level surface exports the complete native exception hierarchy,
including DecompressionError, UnsupportedContentEncoding, H3Error,
H3ConnectError, and H3ProtocolError. NetworkStream and
AsyncNetworkStream are public concrete wrappers for writable 101 upgrade
streams; ordinary pooled responses and internal CONNECT tunnels do not expose
one. Their methods and the important client/helper constructors are covered by
the native API oracle. Release validation also checks that the native runtime
version, coordinated Cargo/pyproject.toml version, and installed wheel
metadata agree.
eggfetch/py.typed marks the package as typed. The reviewed native stubs are
eggfetch/__init__.pyi (the explicit package re-export surface) and
eggfetch/_native.pyi (the extension declarations). The native API manifest
also carries a reviewed member inventory and semantic contract table.
check_python_typing_surface.py verifies every tracked property and method,
sync/async declaration shape, reliable parameter structure, and selected
return/property annotations; the native runtime oracle checks the same
inventory against live PyO3 members and signatures. This keeps runtime
signatures as evidence without attempting to synthesize Python unions from
Rust types. mypy consumer fixtures cover native and compatibility entry
points, including negative sync-client/async-body, unsupported verify-sequence,
and stale start_tls() -> None cases. Built-wheel validation repeats both the
surface and consumer checks from the installed artifact. Private
underscore-prefixed implementation modules are not part of the typing promise.
The checker also enforces relational contracts: Client and AsyncClient
constructors and request/verb methods keep their reviewed parameter inventory,
top-level helpers retain the deliberate limits versus client-only
extensions distinction, and body-capable versus body-less convenience
helpers cannot drift independently. The concrete PyO3 declarations remain
explicit and readable; the guardrails are checker metadata, not generated
public code.
The native stream contract types sync NetworkStream.start_tls() as returning
a new NetworkStream, and async AsyncNetworkStream.start_tls() as an
awaitable resolving to a new AsyncNetworkStream. Both expose
is_upgraded: bool. Client and AsyncClient expose typed is_closed and
cookies; AsyncClient.close() is synchronous while aclose() is awaitable.
The reviewed Verify alias accepts only bool, a CA path str, an
ssl.SSLContext, or a concrete list[bytes] of DER certificates.
The native aliases distinguish SyncBody from AsyncBody: synchronous
clients and helpers accept buffered bytes-like/text values or synchronous
iterables, while AsyncClient additionally accepts lazy async iterables.
Compatibility-facade types remain versioned and should not be substituted for
native eggfetch types.
| Module | Purpose |
|---|---|
lib.rs |
Module registration + top-level functions (get, post, put, patch, delete, head, options, request) |
client.rs |
Client — sync adapter with persistent runtime |
async_client.rs |
AsyncClient — async adapter targeting asyncio |
response.rs |
PyResponse — buffered response surface and private lazy buffered iterators |
headers.rs |
PyHeaders — header wrapper |
errors.rs |
Exception hierarchy |
auth.rs |
BasicAuth, BearerAuth, NoAuth |
cookies.rs |
Cookie handling |
proxy.rs |
Internal proxy-override parsing (ProxyOverride, env_proxy_urls()); the public Proxy class lives in the compat facade, not here |
retry.rs |
Retry configuration class |
timeout.rs |
Timeout configuration |
tls.rs |
TLS configuration (verify, cert kwargs) |
multipart.rs |
File wrapper for multipart uploads |
streaming.rs |
StreamingResponse public PyO3 wiring |
streaming/state.rs |
Private response consumption state and runtime lease |
streaming/sync_bridge.rs |
Private bounded sync backpressure bridge |
streaming/decoding.rs |
Private incremental text and line decoding |
streaming/sync_iterators.rs |
Private sync iterator implementations |
streaming/async_iterators.rs |
Private async iterator implementations |
conversion.rs |
Python↔Rust type conversion (shared by sync/async) |
request_preparation.rs |
Shared client configuration and method/URL/header/body/auth/proxy/retry normalization |
limits.rs |
PyLimits — pool concurrency limits |
extensions.rs |
Request extension extraction (target, sni_hostname, trace only; core resolved_target has no Python extensions= path and is never resolved via DNS fallback, and unknown keys are ignored) |
network_stream.rs |
PyNetworkStream / PyAsyncNetworkStream upgrade wrappers |
trace_bridge.rs |
PyTraceObserver — sync trace-callback bridge |
Each PyClient owns a tokio runtime and an eggfetch_core::Client.
- Normalize Python arguments through
request_preparation.rs(including lazy sync-body handling and sync rejection of async-only bodies). - Release the GIL via
py.detach. - Block on the async Rust engine via
runtime.block_on(future). - Buffer the response body via
response.bytes().await. - Re-acquire the GIL and return a
PyResponsewith buffered data.
client.stream("GET", url) returns a StreamingResponse context manager. Iterating advances the stream one chunk at a time, releasing the GIL during each read.
Streaming responses retain the Tokio handle that created them; synchronous
iterators and buffered reads run on that same client runtime so transport body
state and connection-pool leases are never moved to an unrelated runtime.
The response also retains a runtime lease, so an open stream remains readable
after its Client is closed; the runtime shuts down once the last lease is
released.
Sync streaming producers use a bounded runtime-neutral bridge: producer-side
backpressure awaits capacity without blocking a Tokio worker, while the sync
iterator waits with the GIL detached. Rust-side byte payloads remain Bytes
through queueing and chunk splitting; conversion to Python-owned bytes happens
only at the iterator boundary. Buffered PyResponse objects retain raw
content and initialize their private decoded-text cache only when .text,
.json(), or text iteration first needs it.
Core response construction extracts status, wire metadata, charset, and
Set-Cookie values before moving the ordinary core HeaderMap into
PyHeaders; it does not clone the complete map. Buffered iter_bytes(),
iter_text(), and iter_lines() keep a reference to the response plus a
private cursor and create one Python value per __next__. Text chunks count
Unicode scalars and lines retain str.lines() CRLF/trailing-line semantics,
including preserving a final standalone carriage return rather than treating
it as a CRLF delimiter.
Async StreamingResponse.aread() accumulates chunks in a Rust BytesMut
outside the GIL, then freezes and creates the final Python bytes inside the
GIL bridge (single copy into Python; the full body is still buffered in Rust,
and a Bytes clone is retained for the response cache).
eggfetch.get(...), eggfetch.post(...), etc. create a short-lived runtime and client per call. The Client class owns a persistent runtime for connection reuse.
AsyncClient targets asyncio via pyo3-async-runtimes. It accepts both lazy
synchronous iterables and lazy AsyncIterable[bytes | str] request bodies;
the latter are advanced only when the Rust body is polled, so transport
backpressure is preserved and iterator errors/cancellation propagate through
the request future.
Each request method uses future_into_py to convert the Rust future into a Python awaitable. The async block buffers the response body before returning.
request_preparation.rs is the single GIL-held normalization boundary for
both adapters. prepare_client_config() owns constructor policy conversion
(TLS, protocol flags, limits, defaults, timeout, redirects, cookies, auth,
proxies and NO_PROXY, retries, and transport options); the adapter then
chooses its runtime ownership and calls apply_client_config(). The sync
adapter creates and owns a Tokio runtime, while AsyncClient uses the
pyo3-async-runtimes asyncio bridge. Runtime ownership is not hidden in the
shared type.
prepare_request() performs the corresponding request-local normalization
once for sync and async dispatch. It classifies content= as buffered,
synchronous iterable, or asynchronous iterable and stores the iterator it
obtained, avoiding a second probe of one-shot objects. Async-only bodies are
rejected before dispatch by sync APIs and are supported lazily by
AsyncClient; each __anext__() is awaited only when core polls the request
body. Producer exceptions become BodyError, StopAsyncIteration is EOF,
and cancelling the request drops the in-flight producer future.
- Unified response construction: both sync and async use
PyResponse::from_core_response_with_body(). - Pre-resolved futures:
__aenter__/__aexit__return pre-resolvedasyncio.Futureobjects. - Cancellation safety: cancelling an in-flight request drops the Rust future cleanly; pool permits are released via RAII.
The native module declares Py_MOD_GIL_NOT_USED. PyO3 0.29 emits that by
default, so no gil_used opt-in is needed, and importing eggfetch into a
free-threaded CPython build (Py_GIL_DISABLED == 1) leaves the GIL
disabled instead of letting the interpreter silently re-enable it.
The binding is written in the GIL-optional API shape throughout: blocking
waits run under py.detach, Python values are constructed under
Python::attach, and no Python<'py> token is stored beyond a call.
Shared mutable state is held behind Rust synchronization (Mutex,
Condvar, AtomicBool, OnceLock), not behind the GIL.
Two consequences are visible to user code and are part of the supported contract:
- User callbacks are not serialized. A trace callback
(
extensions={"trace": ...}) and a request-body iterator supplied by the caller are invoked from transport threads. Under a GIL-enabled build those calls were implicitly serialized against all other Python execution; underPy_GIL_DISABLEDtwo in-flight requests on oneClientcan enter the same callable concurrently. State shared between those entries must carry its own synchronization. The contract is pinned bycrates/eggfetch-python/tests/test_free_threading.py. - Sub-interpreters are not supported. The process-global
NOOP_ACLOSEcache inresponse.rsis not interpreter-keyed, so a sub-interpreter that callsResponse.aclose()could observe an object owned by another interpreter. The binding makes no sub-interpreter claim.
Free-threaded coverage is qualified on CPython 3.14t and 3.15t. The
release matrix includes cp314-cp314t and cp315-cp315t wheels for Linux
x86_64, Linux aarch64, macOS arm64, and Windows x86_64, and
scripts/validate_wheel_coverage.py keys coverage on the Python tag and
the ABI tag so a free-threaded wheel never stands in for its GIL-enabled
twin.
The distribution declares the trove classifier
Programming Language :: Python :: Free Threading :: 3 - Stable: free-threaded
use is supported, multithreaded use is tested, and the thread-safety
constraints above are documented. It does not claim the highest level — the
binding is not fully thread-safe, because it does not serialize user
callbacks.
The engine already releases the GIL for the network wait, so the binding's I/O path parallelizes on a GIL-enabled build too. What free-threading adds is parallelism for the Python work that surrounds a request. On a GIL-enabled build two threads cannot execute Python bytecode at the same time, so per-response Python work serializes and throughput can fall as threads are added; on a free-threaded build that work runs concurrently.
The repository measures this with the --concurrency group of
scripts/performance_benchmark.py. The method and the recorded result are in
free-threading-performance.md.
PyResponse presents a requests/httpx-compatible surface:
| Property/Method | Description |
|---|---|
status_code |
HTTP status code |
reason_phrase |
Status reason phrase |
headers |
PyHeaders wrapper |
url |
Final URL (after redirects) |
content |
Raw bytes |
text |
Decoded text |
encoding |
Detected or explicit encoding |
http_version |
"HTTP/1.1", "HTTP/2", etc. |
history |
Redirect history |
json(**kwargs) |
JSON deserialization |
iter_bytes() |
Byte chunk iterator |
iter_text() |
Text chunk iterator |
iter_lines() |
Line iterator |
raise_for_status() |
Raise HTTPStatusError for 4xx/5xx |
cookies |
Response cookies |
Priority: explicit encoding kwarg > Content-Type charset > UTF-8 fallback. Uses encoding_rs for non-UTF-8 charsets.
Source of truth: crates/eggfetch-python/src/errors.rs.
EggfetchError
├── RequestError
│ ├── InvalidUrl
│ ├── TimeoutException
│ │ ├── ConnectTimeout
│ │ ├── ReadTimeout
│ │ ├── WriteTimeout
│ │ └── PoolTimeout
│ ├── NetworkError
│ ├── ProtocolError
│ ├── BodyError
│ ├── TooManyRedirects
│ ├── DecompressionError
│ ├── UnsupportedContentEncoding
│ ├── ProxyError
│ │ ├── ProxyConnectError
│ │ └── ProxyAuthError
│ ├── BodyNotReplayableForRetry
│ ├── RetryBudgetExhausted
│ ├── RetryNotConfigured
│ ├── Http2Error
│ │ ├── Http2GoAway
│ │ ├── Http2StreamReset
│ │ └── Http2FlowControlError
│ └── H3Error
│ ├── H3ConnectError
│ └── H3ProtocolError
├── HTTPStatusError
├── UnsupportedKwarg
├── StreamConsumed
├── StreamClosed
└── ResponseNotRead
| Kwargs | Type | Description |
|---|---|---|
headers |
dict/sequence | Request headers |
params |
dict/sequence | Query parameters |
content |
bytes/str/bytearray | Raw body |
data |
dict/sequence | Form data (urlencoded) |
json |
any | JSON-serializable object |
files |
dict | Multipart file uploads |
timeout |
float/Timeout | Request timeout (seconds) |
cookies |
dict | Request-local cookies |
auth |
Auth/NOAUTH | Authentication override |
follow_redirects |
bool | Redirect following |
max_redirects |
int | Maximum redirects |
verify |
bool/str/SSLContext/list[bytes] |
TLS verification (bool, CA path, ssl.SSLContext, or DER list) |
cert |
str/tuple | Client certificate |
http2 |
bool | HTTP/2 negotiation |
http3 |
bool | HTTP/3 (experimental) |
decompress |
bool | Automatic decompression |
Body kwargs (content, data, json) are mutually exclusive. files may combine with data but conflicts with content and json.
Two versioned, independent facades share the single Rust engine:
eggfetch.compat.httpx— HTTPX 0.28.1, Stage C qualified on the exact executable SHA recorded inplans/httpx-parity-correction-status.md(mirrored incompat/httpx/0.28.1/profile.toml); prior bindings are historical after qualification-sensitive changes.eggfetch.compat.httpx2— httpx2 2.12.0 sibling (independently Stage C qualified on the same ledger-bound SHA; profile incompat/httpx2/2.12.0/profile.toml). The httpx2 facade addsFunctionAuth,Origin+URL.origin,QUERY,Headersmerge operators, truststore OS-trust default, IPv6 CIDRNO_PROXYfix, decoder/multipart/WSGI hardening, and status aliases; SSE (EventSourceover streamed responses) and optional WebSocket (wsproto framing over the core 101network_stream; handshake via the normal pipeline) are implemented in the same facade. Shared helpers are reused where semantics are identical; profile-specific behavior stays behind explicit boundaries. Importing one facade never mutates the other.compat/httpx/1.0-preview/— original HTTPX 1.0 reconnaissance only; no implementation promise until an RC/stable trigger.
The 0.28.1 facade is Stage C qualified for the documented Python 3.10+ asyncio-supported surface on the ledger-bound SHA above. HTTP/3 remains separately experimental; its retained label and blockers do not weaken or extend either compatibility profile.
Client and AsyncClient accept a keyword-only proxy_env option that
selects the rule set used to interpret proxy configuration:
proxy_env=None(default) orproxy_env="native"uses eggfetch's own rules: environmentNO_PROXYis parsed withNoProxy::parse(alocalhostentry covers the loopback IP literals), and an explicitsocks5://proxy URL keeps its local-DNS meaning.proxy_env="httpx"uses HTTPX 0.28.1's rules: environmentNO_PROXYis parsed withNoProxy::parse_httpx(alocalhostentry matches the hostnamelocalhostonly), andsocks5://is normalized tosocks5h://so the SOCKS proxy resolves the destination hostname.
Any other value raises ValueError. The default is the native rule set, so
native callers never inherit compatibility-only semantics. The HTTPX
compatibility facades (eggfetch.compat.httpx and eggfetch.compat.httpx2,
including HTTPTransport/AsyncHTTPTransport) opt into proxy_env="httpx"
explicitly; eggfetch.compat.httpx2 inherits that opt-in through the shared
base facade and needs no separate configuration.
The facade sits between the user and the native PyO3 bindings:
User code
↓
eggfetch.compat.httpx (pure Python facade)
↓
eggfetch (native PyO3 bindings)
↓
eggfetch-core (Rust async engine)
The facade owns all HTTPX-shaped API surfaces (URL, Headers, QueryParams, exceptions, client constructors, merge rules) as pure-Python value objects. Network execution still flows through the native eggfetch module into eggfetch-core. The facade never duplicates networking logic.
| Module | Purpose |
|---|---|
eggfetch/compat/httpx/__init__.py |
Public facade — exports all HTTPX symbols |
eggfetch/compat/httpx/_urls.py |
URL and QueryParams value objects |
eggfetch/compat/httpx/_headers.py |
Headers — case-insensitive, duplicate-preserving |
eggfetch/compat/httpx/_cookies.py |
Cookies — mapping, domain/path, conflict handling |
eggfetch/compat/httpx/_timeout.py |
Timeout — per-phase configuration |
eggfetch/compat/httpx/_limits.py |
Limits — pool concurrency control |
eggfetch/compat/httpx/_proxy.py |
Proxy — proxy configuration |
eggfetch/compat/httpx/_status_codes.py |
codes — status code constants |
eggfetch/compat/httpx/_exceptions.py |
Exception hierarchy matching HTTPX MRO |
eggfetch/compat/httpx/_request.py |
Request — construction and auto-headers |
eggfetch/compat/httpx/_response.py |
Response — metadata, status helpers, raise_for_status |
eggfetch/compat/httpx/_client.py |
Client and AsyncClient — constructors, merge, build_request, send |
eggfetch/_ssl_context.py |
Neutral SSLContext snapshot, classification, construction fingerprint |
eggfetch/compat/httpx/_ssl_context.py |
Backward-compatible shim to the neutral SSL interop module |
eggfetch/compat/httpx/_diagnostics.py |
diagnostics_summary — redacted client diagnostics |
Plus transport/test doubles shipped with the facade (_auth, _asgi, _mock, _stream, _transports, _wsgi) — pure-Python HTTPX-shaped surfaces over the same native engine, no networking logic of their own.
eggfetch/compat/httpx2/ subclasses/re-exports the 0.28.1 facade — no
~97 KB client fork. Shared semantics are re-exported unchanged
(_asgi/_cookies/_mock/_stream/_transports/_wsgi from httpx);
profile-specific modules subclass or wrap:
| Module | Purpose |
|---|---|
httpx2/__init__.py |
Public 2.12.0 surface + truststore create_ssl_context |
httpx2/_auth.py |
Re-exports shared auth + FunctionAuth callable adapter |
httpx2/_urls.py |
URL.origin + frozen Origin (scheme/IDNA/ports/IPv6) |
httpx2/_request.py |
Subclassed Request; its url is always an httpx2 URL |
httpx2/_response.py |
Subclassed Response; its url is always an httpx2 URL |
httpx2/_client.py |
Subclasses base clients + query()/sse()/websocket() |
httpx2/_api.py |
Top-level helpers incl. query + websocket |
httpx2/_headers.py |
Subclassed Headers with |/|= merge operators |
httpx2/_config.py |
Timeout (message names httpx2) + SSE/WS defaults; re-exports Limits from the 0.28.1 facade |
httpx2/_exceptions.py |
Re-exported hierarchy + HTTPXDeprecationWarning |
httpx2/_status_codes.py |
RFC 9110 canonical codes + DeprecationWarning aliases |
httpx2/_alias.py |
Explicit opt-in alias_httpx() only |
httpx2/_sse.py |
EventSource/ServerSentEvent framing over streamed responses |
httpx2/websockets/ |
Optional WebSocket (wsproto framing over 101 network_stream) |
The httpx2 URL delta is reachable from every URL a user observes: the
httpx2 Request/Response are 0.28.1 subclasses whose url is an httpx2
URL, and the httpx2 clients return httpx2 responses (redirect hops
included). Type identity with the 0.28.1 classes is intentionally gone
(httpx2.Request is httpx.Request is now False); the isinstance
relationships still hold. The 0.28.1 facade gains no origin/Origin.
Behavior hardening owned by core/facade boundaries: IPv6 CIDR NO_PROXY
(versioned parser), chained-decoder cap (native 4 vs reference 5,
intentionally stricter), multipart try_header validation, WSGI framing.
Parity cases H2X-API/META/AUTH/TLS/PROXY/COMP/MP/WSGI (core) plus
H2X-SSE-001/002, H2X-WS-001..003 (streaming) in
compat/httpx2/2.12.0/parity-cases.toml; differential tests
test_httpx2_api_parity.py + test_httpx2_behavior.py (core),
test_httpx2_origin_reachability.py (observable origin paths),
test_httpx2_sse.py + test_httpx2_websocket.py (streaming).
Packaging: SSE needs no extra dependency; WS needs wsproto (+ anyio
for async sessions) only when used — Client.websocket/connect_ws
raise a clear ImportError otherwise, so base installs stay lean
(see docs/architecture/dependency-policy.md).
The Python ssl.SSLContext API exposes a large surface (custom ciphers,
ALPN, session tickets, custom verify flags, etc.) that rustls cannot
represent directly. The compat layer classifies every context before
dispatch through three deterministic gates:
- Construction fingerprint: a SHA-256 over the extractable public
state (
verify_mode,check_hostname,min_version,max_version, per-cert DER hashes, cipher list, options flags, and a class-name sentinel). A helper-created context whose live state matches the stored fingerprint reuses the helper-recorded metadata. - Mutation detection: a context whose live state diverges from
the stored fingerprint (e.g. after
load_verify_locations,set_minimum_version,set_ciphers,set_alpn_protocols) loses its stored metadata and is reclassified from the live snapshot. This means the user's post-construction edits always win, never the helper's original intent. - Representability gate: external (caller-created) contexts are
classified into
EXACTLY_REPRESENTABLE,REPRESENTABLE_WITH_DEFAULTS, orUNREPRESENTABLE. Custom cipher lists, custom ALPN, client certificates without path provenance, and explicit version bounds outside TLS 1.2/1.3 causeUNREPRESENTABLE→TypeErrorbefore dispatch. Two CA stores with identical cardinalities but different contents produce differentverifykwargs (no CA-count heuristic).
The registry distinguishes passthrough contexts (caller-supplied
via verify=<SSLContext>) from helper-created contexts
(create_ssl_context()). Passthrough contexts are not assigned a
cert path or verify kwarg; helper contexts are. This prevents a
caller-supplied mTLS context from being silently downgraded to no
client auth, and prevents a caller-supplied verify=False from
inheriting the helper's default trust.
Rust consumes this state through exactly one private helper,
eggfetch._ssl_context._export_ssl_context_state. Its bounded mapping carries
schema version 1, classification, observable verification/version/CA state,
and validated helper provenance. Unknown versions, missing or wrongly typed
fields, and unrepresentable classifications fail before I/O. The mapping is
internal architecture only and is not included in eggfetch.__all__ or the
typing surface.
The facade converts between HTTPX-compatible objects and native types at the boundary:
- URL → core URL: Pure-Python
URLnormalizes to a string; passed to nativeClient.request(). - Headers → native headers:
Headersexposes duplicate-preserving iteration; flattened to a list of(name, value)pairs for native calls. - QueryParams → URL: Request construction materializes merged query pairs into the URL; native dispatch does not forward them a second time.
- Timeout → native timeout:
Timeoutuses an HTTPX-compatible privateUNSETsentinel so omitted and explicitNonephase values remain distinct; its four operational fields map to native phase-aware timeout config and never synthesize nativetotal. - Limits → native limits:
Limitsfields map toPoolConfig. - Proxy → native proxy:
Proxy.urland supported URL credentials map to the native proxy string/authentication path.Proxy(headers=...)is forwarded through the native proxy-leg header channel.Proxy(auth=...)is sent asProxy-Authorizationon the proxy leg. - Proxy header redaction:
Proxy.__repr__redacts the values ofauthorization,proxy-authorization,cookie, andset-cookieto<redacted>so credentials do not appear in diagnostic dumps. The raw values remain available to protocol code throughProxy.headersand to engine code through the native API. TheHeaderstype'sDebug/__str__redacts the same values; the raw values remain available to protocol code. - Request → native body: Body kwargs dispatched by mutual-exclusion rules; auto-headers computed by the facade.
- Response ← native response: Status, headers, URL, body, and version extracted from native
PyResponse. - Errors ← native errors: Exception mapping preserves the most specific HTTPX class with redacted context.
- Pure-Python value objects with exact HTTPX semantics for URL, QueryParams, Headers, Cookies, Timeout, Limits, Proxy.
- Request and Response objects with HTTPX-compatible construction, properties, and state machines.
- Request URL params:
paramsargument merges intorequest.urlmatching HTTPX replacement semantics. - Body source exclusion:
content,json,data,files,streamfollow HTTPX mutual-exclusion rules;data+filesis valid (multipart). - JSON serialization: Compact format with
separators=(",", ":"), UTF-8 encoding, correct headers. - Multipart:
data+filescombined in one body; 4-tuple file spec(filename, fileobj, content_type, headers)supported. - Auto-headers: No auto
Transfer-Encoding: chunkedfor explicitstream=; Content-Length for encoded bodies. - Response extensions:
http_versionandreason_phraseread from response extensions (bytes or strings). - Response.request: Attaches request; URL derives from attached request.
- Response.elapsed: Raises before read/close for streaming; available for buffered responses.
- Status predicates:
is_informational,is_success,is_redirect,is_client_error,is_server_error,is_error,has_redirect_locationmatch HTTPX. - raise_for_status(): Raises for all non-success statuses (informational, redirect, client-error, server-error) with request attachment.
- next_request: Exposed and defaults to
Nonefor Phase 4 redirect support. - History: Copied at construction; setter replaces the list.
- Stream exceptions:
ResponseNotRead,StreamClosed,StreamConsumedraised at correct state boundaries. - Stream state:
is_closed,is_stream_consumed, andnum_bytes_downloadedupdate during sync/async chunked iteration, read, close, and failure paths. - Corrective boundaries: Redirect body replay uses one source, timeout mappings cross as native timeout objects, cookies are merged per hop, and query pairs are serialized once.
- Encoding: Callable
default_encoding;encodingsetter raises aftertextaccess. - Repr: Response includes status and reason phrase; URL redacts passwords.
- Exports:
main()andcreate_ssl_context()stubs added for API compatibility. - Full exception hierarchy (HTTPError → RequestError/TransportError → specific subclasses) with MRO matching the pinned manifest.
- Client and AsyncClient constructors with all HTTPX parameters (auth, params, headers, cookies, verify, cert, trust_env, proxy, timeout, limits, follow_redirects, max_redirects, base_url, default_encoding, event_hooks).
- Configuration merge semantics: client-level defaults merge with per-request overrides for params, headers, cookies, auth, timeout, extensions, and redirect policy.
build_request()producing a fully merged Request without sending.send()preserving object identity, body, and extensions.- Top-level helpers (
get,post, etc.) using short-lived facade clients.
Streaming and body:
- Stream base classes (
SyncByteStream,AsyncByteStream,ByteStream) for custom body producers. - Response streaming delegation: compat
Responseiterates over nativeStreamingResponsechunks. iter_raw()/aiter_raw()for undecoded transport-level bytes.- Chunk size parameter on all streaming iterators; compatibility
iter_raw()/aiter_raw()default toNone, while decoded iterator defaults remain 8192. IncrementalDecoderfor multibyte character safety in text iterators.- Request streaming: iterable content, file-like objects, and custom
ByteStreamsubclasses passed through to the native streaming engine. - Multipart passthrough: compat
Requestdelegates multipart encoding to the native encoder. StreamingRawBytesIteratorandAsyncStreamingRawBytesIteratortypes exposed to Python.
Transport, mount, hook, and dispatch (Phase 3 correction):
- One-hop dispatch contract:
_dispatch_one_hop()sends exactly one prepared Request through exactly one selected transport. Native dispatch always usesfollow_redirects=False. The higher-level client owns auth/redirect orchestration. - Timeout extension: Effective timeout is placed into
request.extensions["timeout"]unless the caller provided one, matching HTTPX's transport contract. - Per-hop event hooks (Track 4): Request and response hooks run around every dispatch hop. For auth challenges, hooks see each intermediate request/response, not just the final pair. Ordering: auth yields Request → request hook → transport → response hook → auth/redirect decision.
- Faithful mount matching (Track 3):
_parse_mount_pattern()returns a 5-tuple(scheme, host, port, path, is_wildcard). Wildcard domain patterns (all://*.example.com) are supported. Priority follows HTTPX 0.28.1: exact host+port+path > wildcard > host+port > host+path > host > scheme > catch-all. ExplicitNonemounts bypass to default transport. Malformed patterns are rejected at construction. - Extension preservation (Track 5): Client and request extensions merge losslessly. Request extensions live on
response.request.extensions, never onresponse.extensions. Response extensions from the transport handler are preserved without overwriting. - Typed extensions plumbing (corrective 02, refined 06):
request.extensions={"target": ..., "sni_hostname": ..., "trace": <callable>}is extracted byextract_native_extensionsintoTransportHintsbefore dispatch. Python callables are wrapped byPyTraceObserver(aTraceObserverimplementation incrates/eggfetch-python/src/trace_bridge.rs) so callables never entereggfetch-core. Both syncClientandAsyncClientdetect coroutine callbacks viainspect.iscoroutinefunction(callback); the observer records aNotAwaitederror eagerly in itsCallbackErrorSlotand short-circuitson_eventwithAbortso the transport stops issuing events and never produces a discarded coroutine. The slot is checked after dispatch on every path (success or failure) and the original callback error propagates as aTypeErrorfor not-awaited coroutines or as the original exception for raised ones.resolved_targetis core-only and cannot be set from Pythonextensions=(same-origin redirects preserve it alongsideproxied_target, cross-origin hops fail closed; proxy/UDS/H3 combinations are rejected); unknown extension keys are ignored at this layer. Once installed, hints ride the core retry pipeline at full fidelity; on redirect hopstarget/sni_hostname/traceattach to the first hop only and are cleared thereafter (only a same-originresolved_targetsurvives). Corrective 06 unifies the extension parser across all four sync/async buffered/streaming paths soAsyncClient.stream()no longer uses a hand-rolledtarget/sni_hostnameparser andAsyncClient.request()(buffered) forwards the full extension dict includingtrace. - Wire metadata on response (corrective 02): Native
Response.extensionsandStreamingResponse.extensionsexpose{http_version, reason_phrase, network_stream}snapshots that mirror the coreResponsewire state.Response.reason_phrasepreferswire_reason_phrase()over the canonical lookup table so unusual status codes do not silently collapse to empty strings. HTTP/2stream_idis intentionally absent (hyper-util does not expose it; seedocs/residual-differences.md). - 101 Switching Protocols and
network_stream(corrective 03, refined 06): When the core captures a Hyper upgrade future,Response.extensions["network_stream"]exposes a livePyNetworkStream(sync, GIL-released) orPyAsyncNetworkStream(async, awaits on the asyncio loop) wrapper. Wrapper selection in Corrective 06 follows the caller's API mode (sync vs async), not the buffered-vs-streaming response path: syncClient.stream()101 responses expose the sync wrapper, and asyncAsyncClient.request()buffered 101 responses expose the async wrapper. The two are stored behind anEitherNetworkStreamenum so the Python-facing attribute delivers the correct wrapper type. Ordinary buffered responses setextensions["network_stream"] = Nonebecause the connection has been returned to the pool; internal HTTPS CONNECT tunnels are also classified asNonebecause the canonical access path is the body iterator.start_tls(ssl_context=..., server_hostname=..., timeout=...)is rejected for Hyper-opaqueAdaptervariants and for streams that are already TLS-wrapped; onlyTcp-variant streams use the Corrective 01 safe TLS translation (and Corrective 06 makes that translation genuinely fail-closed for unrepresentable SSLContext state). The sync wrapper carries an explicittokio::runtime::Handleplus optionalRuntimeLeaseso it can drive IO without relying on an ambient runtime; cloning aPyNetworkStreamshares the same underlyingArc<Mutex<>>. Sync read/write hold the lock across the blocking IO, so concurrent clones serialize and a slow peer stalls all clones; for independent concurrent IO, do not clone — open separate streams. Leading data after 101 headers is preserved inside Hyper's rewind buffer and returned by the first reads from the upgraded stream. - Transport ownership and close (Track 6): Duplicate mounted transport instances close exactly once. Close errors propagate (last error raised). Client close is idempotent.
- Transport body preservation (Track 2): Buffered custom transport responses retain their body under
stream=True. Streaming responses remain lazy.HTTPTransport/AsyncHTTPTransportalways return stream-backed responses.
Redirect, authentication, cookie, and history state machine:
- Python-level redirect loop (Track 1, 2):
_send_handling_redirects()replaces the native redirect-following. Each hop runs request/response hooks, dispatches through_send_single_request(), and builds the next request via_build_redirect_request().follow_redirects=Truefollows automatically;Falsesetsresponse.next_request. - Method rewriting (Track 2.1): 303 → GET (non-HEAD), 302 → GET (non-HEAD), 301 POST → GET. 307/308 retain method and body.
- URL resolution (Track 2.2): Absolute, relative, scheme-relative, and malformed Location headers resolved. Fragment inheritance per RFC 7231 7.1.2.
- Header stripping (Track 2.3):
Authorizationstripped on cross-origin redirects (except HTTP→HTTPS same-host).Hostupdated.Cookieheader stripped on all redirects (same-origin and cross-origin) and regenerated from the client jar for the destination URL. Content headers stripped when method changes to GET. - History management (Track 1.2): Single authoritative history list. Redirect responses appended when followed. Auth challenge responses appended when auth yields a follow-up. Final response gets
response.history = list(history). - Manual redirects (Track 2.5):
response.next_requestpopulated for unfollowed redirects. - max_redirects (Track 2.6):
TooManyRedirectsraised with request attached. - Scoped cookie jar (Track 4):
Cookieswrapshttp.cookiejar.CookieJar(Preferred A architecture). Domain/path/secure/expiry scoping. Multiple Set-Cookie headers parsed.CookieConflicton ambiguous.get(name). Cookies extracted from each response, set on each request hop. - Auth flow integration (Track 3): Auth generators drive the outer loop. Auth-produced requests go through the full redirect handler. Cross-origin auth stripping matches HTTPX. Intermediate auth challenge responses added to history.
- Hook ordering (Track 5): Per-hop order: auth yields → Cookie header set → request hook → transport → response hook → cookie extraction → redirect/auth decision. Each actual transport hop produces exactly one request-hook and one response-hook call.
- Resource cleanup (Track 6): Auth generators closed on all exits. Intermediate redirect responses read and closed when followed.
TooManyRedirectspreserves the request reference.
The facade has one authoritative Python cookie jar, request-relative timeout mapping, explicit buffered/live response state, body replay classification (buffered, reusable-stream, multipart-reconstructable, one-shot), explicit Cookie header stripping on redirects, and raw stream lifecycle management (consumed state, source-byte accounting, bounded chunk adaptation, normal-exhaustion close). For the documented HTTPX 0.28.1 asyncio-supported surface, retained bodies replay or fail before redispatch and redirects regenerate cookies for each destination. Compatibility raw bytes remain distinct from decoded response data: the core response retains compressed encoded bytes until first selection, and the Python binding selects raw or decoded mode exactly once. The existing core decoded-header policy removes Content-Encoding and Content-Length from automatically decompressed response metadata; the facade overlays only the original wire values for those headers using the native binding's narrow metadata accessors. Native cancellation coverage uses the built-in async client and proves lease release with a constrained follow-up request. scripts/check.sh Tier 1 runs tests/compat/test_corrective_kernel.py; tests/compat/test_raw_stream_httpx_differential.py, the complete pinned HTTPX suite, and the API oracle remain extended validation. Keep plans/httpx-parity-raw-stream-final-corrective-closure.md and plans/httpx-parity-correction-status.md exact-SHA-bound when changing compatibility claims.
The compatibility facade discovers proxy environment state through
urllib.request.getproxies(), matching HTTPX 0.28.1's lowercase precedence,
scheme-less HTTP proxy normalization, and NO_PROXY URL-pattern behavior.
Ordinary bare domains match the bare host and subdomains only at a domain-label
boundary; leading-dot domains exclude the bare host; localhost and IP literals
are exact; and an explicit host port matches only an explicit normalized target
port. Scheme-qualified entries retain their scheme and optional URL-pattern
port, while CIDR-looking values remain exact host text rather than native
subnet matching. Bare unbracketed IPv6 literals follow the pinned HTTPX
environment form; bracketed IPv6 and IPv6 prefix-looking values are rejected
before dispatch. Native Rust parsing retains its richer bracketed-IPv6 and
CIDR behavior. UDS uses the
shared Hyper HTTP/TLS path and has executable fixed-length, chunked, TLS, and
keep-alive coverage. local_address remains HTTPX's host-only bind form and
is tested against the server-observed source address. SOCKS clients are
persistent per effective route, advertise exactly the reference-selected
authentication method, send HTTPX-compatible destination address types, and
preserve origin-form requests after CONNECT. The facade intentionally bounds
socket_options to safe three-element tuples; integer, bytes, and
bytearray values are converted losslessly. HTTPX's valid four-element
(level, option, None, optlen) form is accepted by its constructor and
forwarded to the platform socket API, but EggFetch does not expose arbitrary
null-pointer socket operations in its safe Rust boundary. HTTP and HTTPS proxy
endpoint schemes are both supported; HTTPS proxy TLS uses the proxy hostname,
while origin TLS after CONNECT uses the origin hostname. Proxy and origin
TLS configurations are kept independent: the proxy endpoint is verified
using Proxy(ssl_context=...) (or rustls' default trust when not supplied),
never reusing the origin's verify= setting. Proxy(headers=...) is
forwarded through the native proxy-leg header channel; sensitive header
values are redacted in diagnostic surfaces (__repr__, __str__) but
remain observable to protocol code through Proxy.headers.