From fdd37650d5455258f9f34379968fb88d1a6ffaa9 Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:11:11 -0400 Subject: [PATCH 1/8] plans: add HTTPX drop-in compatibility roadmap --- plans/httpx-drop-in-roadmap.md | 400 +++++++++++++++++++++++++++++++++ 1 file changed, 400 insertions(+) create mode 100644 plans/httpx-drop-in-roadmap.md diff --git a/plans/httpx-drop-in-roadmap.md b/plans/httpx-drop-in-roadmap.md new file mode 100644 index 00000000..8b7dea17 --- /dev/null +++ b/plans/httpx-drop-in-roadmap.md @@ -0,0 +1,400 @@ +# HTTPX Drop-In Compatibility and Production Readiness Roadmap + +Status: ready for implementation handoff + +## Purpose + +This roadmap defines the work required to move eggfetch from a capable Rust-native HTTP client with an HTTPX-like Python surface to a production-grade, explicitly validated HTTPX drop-in replacement. + +The current repository has broad HTTP functionality, a single Rust networking engine, sync and asyncio bindings, streaming responses, TLS, proxies, redirects, cookies, retries, HTTP/2, experimental HTTP/3, packaging automation, and substantial tests. Those capabilities are the foundation. They are not, by themselves, evidence that an existing HTTPX consumer can substitute eggfetch without semantic changes. + +This roadmap therefore treats two outcomes as separate gates: + +1. **Production-grade eggfetch client**: deterministic timeouts, bounded resources, correct shutdown, cancellation safety, fault tolerance, and release evidence. +2. **HTTPX drop-in compatibility**: matching public symbols, signatures, object semantics, configuration merging, exceptions, transports, streaming contracts, async backends, and integration behavior against a pinned HTTPX reference. + +Neither gate may be inferred from feature-count parity. Both require executable evidence. + +## Reference target + +The initial compatibility target is **HTTPX 0.28.1**. + +Implementation must pin the reference package and its direct compatibility fixtures in CI. Upstream HTTPX changes after the pinned target do not silently change acceptance criteria. Re-baselining requires: + +- an explicit compatibility-profile update; +- a generated API and behavior delta report; +- review of changed defaults and exception contracts; +- updated differential fixtures; +- a compatibility-policy decision for every new or removed surface; +- a new immutable compatibility manifest committed to the repository. + +The project must never describe itself as compatible with an unpinned moving HTTPX branch. + +## Product-position stages + +Compatibility claims must progress through the following stages. Documentation and package metadata must use the highest stage whose acceptance gate is currently satisfied. + +### Stage A — Production-grade eggfetch + +Eggfetch is safe for long-lived production clients written specifically against the eggfetch API. + +Required characteristics: + +- independently enforced pool, connect, read, and write deadlines; +- safe nonzero defaults or an explicitly versioned alternative policy; +- bounded connection and request concurrency defaults; +- deterministic close and interpreter-shutdown behavior; +- resource-leak and cancellation evidence; +- supported-platform release artifacts and immutable dry-run proof; +- no claim of HTTPX substitution compatibility. + +### Stage B — HTTPX-compatible network-client subset + +Ordinary network requests written against documented HTTPX client APIs work after changing the import, subject to a short, machine-readable list of unsupported extension surfaces. + +Required characteristics: + +- core public data model and exception compatibility; +- client/request/response semantics and signatures; +- client configuration merging; +- sync and asyncio behavior; +- mandatory differential tests with zero comparison skips; +- explicit unsupported-surface errors rather than silent behavior changes. + +### Stage C — HTTPX-compatible asyncio drop-in + +Existing asyncio applications and libraries using supported public HTTPX APIs run without source changes other than selecting the compatibility distribution or module. + +Required characteristics: + +- transport interfaces, mounts, event hooks, extensions, mock transport, and ASGI/WSGI test transports; +- complete request and response streaming contracts; +- custom auth flows; +- representative third-party compatibility suites; +- import and package-shim strategy validated in clean environments. + +### Stage D — Full supported HTTPX drop-in + +The supported public HTTPX 0.28.1 contract, including asyncio and Trio/AnyIO behavior, is implemented or every remaining deviation has been removed from the drop-in claim. + +Required characteristics: + +- supported async backend parity; +- no unexplained public API manifest deltas; +- no unexplained differential behavior deltas; +- unmodified representative consumers pass; +- compatibility release qualification and long-running canary evidence. + +## Architectural invariants + +The following remain non-negotiable: + +- All real network I/O remains owned by `eggfetch-core`. +- The Rust engine remains async-first. +- Python adapters must not grow a second independent network implementation. +- Python-only in-process transports such as ASGI, WSGI, and mock transports may bypass the network engine because they do not perform network I/O. +- Rust APIs remain idiomatic and are not forced to mirror HTTPX's Python object model. +- HTTPX compatibility objects belong in the Python adapter or a dedicated compatibility layer unless the concept is independently useful to the Rust core. +- Compatibility behavior must be derived from tests and reference observation, not recollection or feature tables. +- Secure behavior may intentionally exceed HTTPX only when the difference is explicit, opt-in compatibility behavior is impossible or unsafe, and the claim is adjusted accordingly. +- Experimental HTTP/3 must not complicate or weaken the HTTPX 0.28.1 compatibility path, because HTTPX 0.28.1 does not expose HTTP/3. + +## Scope + +The line of work includes: + +- compatibility contract and executable oracle; +- production timeout, resource-limit, lifecycle, and concurrency corrections; +- HTTPX public object model and exception hierarchy; +- `Client` and `AsyncClient` signature and merge semantics; +- request construction, `build_request()`, `send()`, and response metadata; +- true Python upload and download streaming; +- transport, mount, hook, auth, extension, mock, WSGI, and ASGI boundaries; +- environment proxy and certificate behavior; +- supported async backend strategy; +- real-world downstream package compatibility; +- compatibility packaging and import strategy; +- production and compatibility release qualification. + +## Non-goals + +This roadmap does not require: + +- making Rust APIs look like Python HTTPX; +- replacing the Rust engine with httpcore or Python networking; +- matching undocumented HTTPX internals solely for libraries that import private modules; +- enabling HTTP/3 by default; +- adding browser behavior or browser-grade cookie policy; +- implementing application serving in eggfetch; +- preserving an eggfetch behavior that conflicts with a tested HTTPX contract merely because it shipped in an alpha release; +- claiming parity with future HTTPX versions without an explicit re-baseline. + +Private-module compatibility may be considered only for a specifically approved downstream package and must not distort the public architecture. + +## Workstream sequence + +### Phase 0 — Compatibility contract and mandatory oracle + +Create the versioned compatibility profile and make compatibility evidence fail closed. + +Primary outcomes: + +- pin HTTPX 0.28.1 and Requests where comparison is useful; +- correct known compatibility-document errors; +- make reference dependencies mandatory in compatibility CI; +- fail on skipped differential tests; +- generate public API, signature, inheritance, default, and attribute manifests; +- define allowed-difference records with owners and expiry/review policy; +- establish a local deterministic behavior server and malformed-peer fixtures; +- split native eggfetch tests from compatibility tests while requiring both. + +Detailed plan: `plans/httpx-drop-in-phase-0-compatibility-contract.md` + +Exit gate: + +> The repository has a reproducible, pinned, fail-closed definition of what HTTPX compatibility means, and current gaps are measured rather than described informally. + +### Phase 1 — Production semantics and lifecycle + +Correct production blockers before expanding the compatibility facade. + +Primary outcomes: + +- independently enforced DNS/TCP/TLS/proxy connect deadlines; +- HTTPX-compatible default timeout profile for the compatibility layer; +- Python `Limits` surface and bounded defaults; +- deterministic client, pool, runtime, and socket shutdown; +- shared-client thread-safety contract; +- cancellation and timeout cleanup across every request phase; +- descriptor, thread, task, memory, and pool stabilization tests; +- explicit `trust_env` behavior and environment isolation tests. + +Detailed plan: `plans/httpx-drop-in-phase-1-production-semantics.md` + +Exit gate: + +> Long-lived sync and async clients remain bounded, cancellable, and deterministic under normal use, failures, shutdown, and concurrency. + +### Phase 2 — HTTPX object model and core API parity + +Build the public compatibility model without duplicating network behavior. + +Primary outcomes: + +- `URL`, `QueryParams`, `Headers`, `Cookies`, `Request`, `Response`, `Timeout`, `Limits`, `Proxy`, status-code helpers, and stream base types; +- HTTPX-compatible exception hierarchy with attached request/response context; +- `Client` and `AsyncClient` constructor signatures and defaults; +- client-level `base_url`, params, headers, cookies, auth, timeout, limits, proxy, mounts, hooks, transport, environment, and encoding state; +- `build_request()`, `send()`, request methods, top-level helpers, and top-level stream behavior; +- deterministic client/request configuration merging; +- response request attachment, elapsed time, next request, extensions, encoding control, and chainable `raise_for_status()`. + +Detailed plan: `plans/httpx-drop-in-phase-2-object-model-and-api.md` + +Exit gate: + +> The supported public HTTPX data model imports correctly, exposes compatible signatures, and passes construction and merge semantics before network behavior is considered. + +### Phase 3 — Streaming and body architecture + +Replace Python-side buffering and per-stream runtime/thread patterns with scalable, backpressured streaming. + +Primary outcomes: + +- request content from sync iterables, async iterables, file-like objects, and stream base classes; +- lazy multipart file and field encoding without whole-body buffering; +- raw and decoded response iteration; +- exact single-consumption, read, close, and context-manager state behavior; +- bounded channel bridges driven by shared runtimes; +- cancellation-safe producer and consumer shutdown; +- replayability classification integrated with redirects and retries; +- chunk-boundary, text-decoder, decompression, and backpressure differential tests. + +Detailed plan: `plans/httpx-drop-in-phase-3-streaming-and-bodies.md` + +Exit gate: + +> Python uploads and downloads are genuinely streaming, bounded, cancellation-safe, and behaviorally compatible with the reference API. + +### Phase 4 — Transports, extensions, auth, and async backends + +Implement the extension surfaces required by real HTTPX consumers. + +Primary outcomes: + +- sync and async base transport protocols; +- Rust-backed HTTP transports; +- custom transport dispatch and mount routing; +- mock, WSGI, and ASGI transports; +- event hooks and request/response extension propagation; +- custom auth flow interfaces plus HTTPX built-ins required by the target profile; +- environment proxy, certificate, and netrc behavior; +- UDS, local-address, and transport-level options where present in the target profile; +- SOCKS support behind an optional dependency when required for parity; +- an explicit asyncio/Trio/AnyIO backend architecture and implementation path. + +Detailed plan: `plans/httpx-drop-in-phase-4-transports-extensions-and-backends.md` + +Exit gate: + +> Public transport, hook, auth, environment, and supported async-backend contracts can be used by downstream libraries without special eggfetch branches. + +### Phase 5 — Downstream compatibility and substitution validation + +Prove compatibility against real consumers and a substantially complete behavior corpus. + +Primary outcomes: + +- generated API-manifest comparison with no unexplained differences; +- broad local differential corpus covering success, malformed peers, timeouts, redirects, proxies, TLS, HTTP/2, streaming, and cancellation; +- selected upstream HTTPX tests run against the compatibility layer where licensing and architecture permit; +- pinned representative downstream applications and libraries run unmodified; +- test-client, mocking, SDK, proxy, streaming, and custom-auth consumer categories; +- clean-environment package substitution tests; +- compatibility performance and resource budgets. + +Detailed plan: `plans/httpx-drop-in-phase-5-downstream-validation.md` + +Exit gate: + +> Representative unmodified HTTPX consumers pass, and all remaining differences are explicit, narrow, reviewed, and reflected in the product claim. + +### Phase 6 — Compatibility release qualification + +Turn passing implementation work into defensible release evidence. + +Primary outcomes: + +- compatibility package/import strategy; +- immutable versioned compatibility manifest; +- full supported wheel matrix; +- package-content and symbol smoke tests; +- security, fuzzing, soak, fault-injection, and concurrency evidence; +- signed or attested artifacts where supported; +- canary deployments and rollback criteria; +- documentation and metadata aligned to the achieved compatibility stage; +- a fully green immutable release dry run. + +Detailed plan: `plans/httpx-drop-in-phase-6-release-qualification.md` + +Exit gate: + +> A release candidate has immutable evidence for production safety and the exact compatibility stage claimed in package metadata and documentation. + +## Dependency graph + +The default execution order is strict: + +1. Phase 0 must complete before compatibility implementation is judged. +2. Phase 1 must complete before a production-grade claim or broad downstream testing. +3. Phase 2 may begin after Phase 0 and may overlap late Phase 1 work that does not alter public semantics. +4. Phase 3 depends on the Phase 2 request, response, stream, and exception model. +5. Phase 4 depends on the Phase 2 object model and should use Phase 3 streaming primitives. +6. Phase 5 begins incrementally after Phase 2, but its exit gate depends on Phases 1 through 4. +7. Phase 6 depends on every acceptance gate required by the intended release stage. + +No phase may declare success by weakening or deleting a reference test. Allowed differences require an explicit compatibility-policy record. + +## Compatibility evidence model + +The repository must maintain machine-readable evidence with at least these dimensions: + +- reference package and version; +- eggfetch commit SHA; +- public symbol presence; +- callable signatures and defaults; +- class inheritance and exception relationships; +- object attributes and return types; +- behavior case identifier; +- sync, asyncio, and other supported backend result; +- platform and Python version; +- expected reference result; +- eggfetch result; +- allowed-difference identifier, if any; +- evidence timestamp and generator version. + +A human-authored feature table is documentation, not the compatibility oracle. + +## Allowed-difference policy + +Every allowed difference must include: + +- stable identifier; +- affected symbol or behavior case; +- reference behavior; +- eggfetch behavior; +- rationale; +- security and migration impact; +- affected compatibility stage; +- owner; +- review date or removal milestone; +- tests proving the difference is deliberate and bounded. + +An allowed difference that prevents ordinary downstream substitution blocks the relevant drop-in stage. + +## Package and import strategy + +The normal `eggfetch` distribution remains the native product package. + +During development, compatibility users should import an explicit module such as `eggfetch.compat.httpx` or use `import eggfetch as httpx` only where the manifest confirms the required surface. + +A separate opt-in compatibility distribution that provides the top-level `httpx` module may be created only after Phase 5. Such a distribution must: + +- conflict explicitly with upstream `httpx` rather than silently co-installing two providers; +- identify the emulated HTTPX version in metadata and at runtime; +- expose eggfetch's own implementation version separately; +- install and uninstall cleanly in isolated environments; +- not shadow upstream HTTPX accidentally in the normal `eggfetch` package; +- pass package-manager resolution and import-origin tests. + +## Testing strata + +The final validation stack must include: + +1. Rust unit and integration tests for transport and state machinery. +2. Python native API tests for eggfetch-specific behavior. +3. Public-surface manifest tests against pinned HTTPX. +4. Differential behavior tests against pinned HTTPX. +5. Fault-injection tests with deterministic local peers. +6. Resource and cancellation stress tests. +7. Representative downstream package tests. +8. Built-wheel and source-distribution smoke tests. +9. Long-running canary and soak evidence. + +A green native test suite cannot substitute for a skipped compatibility stratum. + +## Security posture + +Compatibility must not introduce silent security regression. Specific review is required for: + +- environment proxy trust and credential leakage; +- netrc credential discovery; +- redirect auth stripping; +- custom CA and client-certificate loading; +- TLS verification disable paths; +- proxy CONNECT and proxy authentication; +- decompression and unbounded streaming; +- custom transports and in-process application transports; +- event-hook exception behavior; +- URL user-info and display redaction; +- request/response exception serialization and logging. + +Where HTTPX behavior and project security policy conflict, the implementation must either provide an explicit compatibility mode or lower the compatibility claim. + +## Completion definition + +This line of work is complete only when: + +- every detailed phase acceptance gate required for Stage D is satisfied; +- HTTPX 0.28.1 is installed and exercised in required compatibility CI; +- no required compatibility test is skipped; +- the public API manifest has no unexplained differences; +- the behavior corpus has no unexplained differences; +- production timeout, limit, lifecycle, and cancellation evidence is green; +- representative downstream consumers run unmodified; +- the compatibility distribution and ordinary eggfetch distribution coexist according to documented policy; +- the supported platform matrix passes from built artifacts; +- a full immutable release dry run is green; +- documentation, classifiers, versioning, and compatibility claims match the evidence exactly. + +Until those conditions hold, documentation should use a narrower phrase such as "HTTPX-like API" or "HTTPX-compatible subset" rather than "drop-in replacement." From ba7d18ff237c3034ca188c66b74be05f28f4c40e Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:12:34 -0400 Subject: [PATCH 2/8] plans: add HTTPX compatibility contract phase --- ...-drop-in-phase-0-compatibility-contract.md | 395 ++++++++++++++++++ 1 file changed, 395 insertions(+) create mode 100644 plans/httpx-drop-in-phase-0-compatibility-contract.md diff --git a/plans/httpx-drop-in-phase-0-compatibility-contract.md b/plans/httpx-drop-in-phase-0-compatibility-contract.md new file mode 100644 index 00000000..5cc5ce1e --- /dev/null +++ b/plans/httpx-drop-in-phase-0-compatibility-contract.md @@ -0,0 +1,395 @@ +# HTTPX Drop-In Phase 0: Compatibility Contract and Mandatory Oracle + +Status: ready for implementation handoff + +## Purpose + +Create a pinned, executable, fail-closed definition of HTTPX compatibility before adding more compatibility code. + +The repository currently has useful native and differential tests, but the comparison dependencies are optional, reference tests may be skipped, and the existing compatibility matrix contains at least some incorrect statements about HTTPX defaults. This phase replaces informal compatibility claims with a versioned compatibility profile and machine-readable evidence. + +The target reference for this phase is `httpx==0.28.1`. + +## Baseline + +Relevant existing areas include: + +- `crates/eggfetch-python/tests/test_differential.py` +- `crates/eggfetch-python/tests/` +- `scripts/check_api_surface.py` +- `docs/reference/compatibility.md` +- `docs/migration/from-httpx.md` +- `.github/workflows/ci.yml` +- `plans/ROADMAP.md` +- the Python package exports under `crates/eggfetch-python/python/eggfetch/` + +Before implementation, record the exact baseline SHA and current test counts in a phase status file. + +## Non-goals + +- Implementing missing HTTPX API objects. +- Correcting timeout, pooling, or lifecycle behavior beyond what is needed to construct the oracle. +- Adding transports, hooks, Trio support, or downstream package fixtures. +- Declaring any new compatibility stage. +- Treating private HTTPX modules as required public compatibility surface. +- Updating the reference target beyond HTTPX 0.28.1. + +## Deliverables + +1. A compatibility profile file pinning HTTPX 0.28.1 and defining the supported public surface. +2. Required CI installation of the pinned reference package. +3. A dedicated compatibility test job that fails on skips, missing dependencies, malformed manifests, or unexplained differences. +4. Generated reference and eggfetch public API manifests. +5. A machine-readable allowed-differences registry. +6. Corrected compatibility and migration documentation. +7. A deterministic local behavior fixture framework. +8. An implementation status file mapping every acceptance criterion to evidence. + +## Track A — Define the compatibility profile + +### A1. Add a machine-readable profile + +Create a versioned profile, for example: + +- `compat/httpx/0.28.1/profile.toml` +- `compat/httpx/0.28.1/allowed-differences.toml` +- `compat/httpx/0.28.1/README.md` + +The profile must record: + +- reference distribution name and exact version; +- supported Python versions; +- expected sync backends; +- expected async backends for the current phase; +- public modules included in the compatibility contract; +- public symbols excluded because they are private or deprecated; +- feature extras needed for optional HTTPX capabilities; +- manifest schema version; +- generator version; +- date and commit that established the profile. + +The initial contract should include the public top-level `httpx` module and documented public APIs. Private modules beginning with `_` are excluded unless a later downstream compatibility decision explicitly includes one. + +### A2. Define compatibility categories + +Every measured item must be classified as one of: + +- `required-now`: must match for the current stage; +- `required-later`: accepted gap assigned to a later roadmap phase; +- `intentional-difference`: reviewed and explicitly allowed; +- `not-public`: excluded from the contract; +- `not-applicable`: reference feature cannot apply to the selected product stage. + +`required-later` is not a pass. It is a measured open gap that blocks the relevant stage. + +### A3. Add allowed-difference schema validation + +Each allowed difference must include: + +- stable ID; +- category; +- affected symbol or behavior case; +- reference behavior; +- eggfetch behavior; +- rationale; +- compatibility-stage impact; +- security impact; +- migration impact; +- owner; +- review milestone or review date; +- tests that bound the difference. + +Add a schema validator that fails on: + +- duplicate IDs; +- missing fields; +- unknown categories; +- references to nonexistent symbols or behavior cases; +- expired review dates; +- an allowed difference with no associated test; +- an item marked `intentional-difference` that blocks the claimed stage. + +## Track B — Generate public API manifests + +### B1. Reference manifest generator + +Create a Python script that imports the pinned HTTPX package in an isolated environment and records, at minimum: + +- public top-level names; +- object kind: module, class, function, constant, enum, exception; +- `inspect.signature()` output where available; +- parameter kind, name, default representation, and annotation representation; +- class bases and MRO names; +- public methods and properties; +- documented instance attributes that can be observed from safe fixture construction; +- return-object type for approved constructor fixtures; +- module of origin; +- deprecation markers where detectable; +- reference package version. + +The manifest must be stable across runs. Normalize memory addresses, object reprs, platform-dependent paths, and ordering. + +### B2. Eggfetch manifest generator + +Generate the same schema from the eggfetch compatibility surface. Do not maintain a second hand-written expected-name list as the primary oracle. + +The generator must work against: + +- an editable development install; +- a built wheel installed into a clean environment. + +### B3. Manifest comparator + +Create a comparator that reports: + +- missing symbols; +- extra symbols; +- kind mismatches; +- signature mismatches; +- default mismatches; +- inheritance mismatches; +- property/method mismatches; +- return-type mismatches; +- allowed-difference matches; +- unexplained differences. + +The comparator must exit nonzero on every unexplained difference and on stale allowed-difference entries that no longer correspond to a real delta. + +Produce both JSON and concise human-readable reports. + +### B4. Golden-manifest policy + +Commit the normalized HTTPX 0.28.1 reference manifest. Do not regenerate it automatically on every ordinary CI run from an unpinned environment. + +CI should: + +1. verify the installed reference version; +2. optionally regenerate the reference manifest and compare it byte-for-byte with the committed golden file; +3. generate the eggfetch manifest; +4. compare eggfetch against the golden reference and allowed-difference registry. + +A reference-manifest update requires an explicit compatibility-profile commit. + +## Track C — Make differential tests mandatory + +### C1. Pin reference dependencies + +Add a dedicated compatibility dependency group or requirements lock containing at least: + +- `httpx==0.28.1`; +- `requests` at an explicitly pinned version where requests comparison remains useful; +- pytest and required plugins; +- optional HTTPX extras only in dedicated jobs that exercise those extras. + +The required compatibility job must install these dependencies directly. It must not rely on a developer's environment. + +### C2. Remove optional comparison behavior + +Refactor `test_differential.py` so required compatibility tests do not use `HAS_HTTPX` or skip when HTTPX is absent. + +The required job must fail immediately if: + +- HTTPX cannot be imported; +- the imported version is not exactly 0.28.1; +- Requests cannot be imported for a required Requests comparison; +- a required test is skipped; +- pytest reports deselected cases that should belong to the required profile. + +Optional extra-specific tests may skip only in jobs whose profile explicitly excludes that extra. + +### C3. Add skip auditing + +Add a pytest plugin or post-run evaluator that records: + +- skipped tests; +- xfailed tests; +- deselected tests; +- collection errors; +- reference version; +- profile name. + +The required profile must fail on any skip or xfail not listed in a dedicated, machine-readable conditional-test policy. + +### C4. Separate native and compatibility suites + +Keep native eggfetch tests independently useful. Define explicit commands such as: + +- native Python tests; +- HTTPX surface manifest tests; +- HTTPX behavioral differential tests; +- Requests migration comparisons; +- package-artifact compatibility smoke tests. + +The required CI gate must depend on both native and compatibility jobs. A compatibility failure cannot be hidden by a green native matrix. + +## Track D — Correct compatibility documentation + +### D1. Audit defaults and documented claims + +Compare every existing row in `docs/reference/compatibility.md` and every migration statement against the pinned reference. + +At minimum, verify and correct: + +- redirect defaults; +- pool timeout support; +- default timeout behavior; +- resource-limit defaults; +- proxy environment behavior; +- constructor signatures; +- response URL type; +- `raise_for_status()` return behavior; +- client thread-sharing guarantees; +- transport, hook, mount, and auth surfaces. + +### D2. Generate documentation inputs + +Where practical, generate compatibility tables from the machine-readable profile and current comparator result. Hand-written narrative may remain, but status labels must come from executable evidence. + +### D3. Add claim linting + +Add a lightweight documentation check that rejects unqualified phrases such as: + +- `drop-in replacement`; +- `fully compatible`; +- `identical to HTTPX`; + +unless the current profile status file records the required achieved stage. + +## Track E — Build deterministic behavior fixtures + +### E1. Local protocol server + +Refactor the differential test server into reusable fixtures capable of deterministic cases for: + +- all common methods; +- duplicate and unusual headers; +- query encoding and repeated parameters; +- redirects and redirect chains; +- auth challenge and credential echo; +- cookies and multiple `Set-Cookie` fields; +- JSON, form, raw, and multipart bodies; +- fixed and chunked responses; +- compression formats; +- delayed headers and delayed chunks; +- abrupt close and truncated bodies; +- invalid content length; +- malformed status line and headers; +- connection reuse observation; +- proxy forwarding and CONNECT; +- TLS and client certificate scenarios; +- HTTP/2 cases where the existing test harness supports them. + +### E2. Behavior case schema + +Represent cases with stable IDs and structured expected observations. Each case should identify: + +- setup fixture; +- reference invocation; +- eggfetch invocation; +- normalized result fields; +- exception expectations; +- sync/async applicability; +- platform applicability; +- allowed-difference ID if any. + +Do not compare only status codes. Normalize and compare request construction, response metadata, body state, exception type, exception attributes, and cleanup outcome where applicable. + +### E3. Malformed-peer fixtures + +Add a small raw TCP fixture layer for behavior that a compliant `http.server` cannot produce. It must be deterministic, bounded by test timeouts, and shut down cleanly after failures. + +## Track F — CI and evidence + +### F1. Dedicated compatibility jobs + +Add stable CI jobs for: + +- manifest generation and comparison; +- sync behavioral differential tests; +- asyncio behavioral differential tests; +- documentation truth checks; +- wheel-installed compatibility smoke tests when built artifacts are available. + +The aggregate `Required CI Gate` must treat these jobs as required once this phase lands. + +### F2. Artifact reports + +Upload, even on failure: + +- reference manifest; +- eggfetch manifest; +- comparator JSON; +- human-readable delta report; +- pytest skip audit; +- compatibility profile metadata. + +### F3. Implementation status + +Create `plans/httpx-drop-in-phase-0-status.md` during implementation. It must map every acceptance criterion below to: + +- pass, fail, blocked, or not applicable; +- exact file or test evidence; +- CI run URL and commit SHA; +- remaining allowed differences. + +## Expected files + +Likely additions or changes include: + +- `compat/httpx/0.28.1/profile.toml` +- `compat/httpx/0.28.1/reference-api.json` +- `compat/httpx/0.28.1/allowed-differences.toml` +- `compat/httpx/0.28.1/README.md` +- `scripts/generate_httpx_api_manifest.py` +- `scripts/compare_httpx_api_manifest.py` +- `scripts/validate_httpx_compat_profile.py` +- `scripts/check_compatibility_claims.py` +- `crates/eggfetch-python/tests/compat/` +- `.github/workflows/ci.yml` +- `docs/reference/compatibility.md` +- `docs/migration/from-httpx.md` +- `plans/httpx-drop-in-phase-0-status.md` + +The implementation may choose different paths, but the separation between profile, generators, behavior fixtures, tests, and evidence must remain clear. + +## Validation commands + +The implementation status file must record exact working commands. Expected command shapes include: + +```bash +python scripts/validate_httpx_compat_profile.py compat/httpx/0.28.1 +python scripts/generate_httpx_api_manifest.py --package httpx --output /tmp/httpx.json +python scripts/generate_httpx_api_manifest.py --package eggfetch.compat.httpx --output /tmp/eggfetch.json +python scripts/compare_httpx_api_manifest.py \ + --reference compat/httpx/0.28.1/reference-api.json \ + --candidate /tmp/eggfetch.json \ + --allowed compat/httpx/0.28.1/allowed-differences.toml +pytest crates/eggfetch-python/tests/compat -q --strict-markers +``` + +## Acceptance criteria + +This phase is complete only when all of the following are true: + +- [ ] HTTPX 0.28.1 is pinned in a dedicated compatibility dependency definition. +- [ ] Required compatibility CI verifies the imported HTTPX version exactly. +- [ ] Required comparison tests cannot silently skip because HTTPX or Requests is absent. +- [ ] The required profile fails on unapproved skip, xfail, deselection, or collection error. +- [ ] A normalized HTTPX public API golden manifest is committed. +- [ ] An eggfetch manifest using the same schema is generated in CI. +- [ ] The comparator reports symbol, signature, default, inheritance, attribute, and kind differences. +- [ ] Every unexplained manifest difference fails CI. +- [ ] Allowed-difference records are schema validated and linked to tests. +- [ ] Stale allowed-difference records fail CI. +- [ ] Current compatibility documentation has been audited against the pinned reference. +- [ ] Incorrect redirect-default and pool-timeout statements are corrected. +- [ ] Unqualified drop-in claims are rejected until the required stage is achieved. +- [ ] Deterministic local behavior fixtures cover compliant and malformed peer cases. +- [ ] Sync and asyncio differential suites have stable case identifiers. +- [ ] Compatibility reports are retained as CI artifacts. +- [ ] The aggregate required gate includes the compatibility jobs. +- [ ] The implementation status file links a green CI run and exact candidate SHA. + +## Handoff notes + +Implementation should prioritize truth and measurement over closing gaps in this phase. A large red comparator report is an acceptable Phase 0 outcome if every delta is correctly classified and the oracle fails closed. Converting open gaps into false passes is not acceptable. From 010ba74c2319a4438a0a665c01a73cccdaaddd18 Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:14:16 -0400 Subject: [PATCH 3/8] plans: add production semantics phase --- ...px-drop-in-phase-1-production-semantics.md | 468 ++++++++++++++++++ 1 file changed, 468 insertions(+) create mode 100644 plans/httpx-drop-in-phase-1-production-semantics.md diff --git a/plans/httpx-drop-in-phase-1-production-semantics.md b/plans/httpx-drop-in-phase-1-production-semantics.md new file mode 100644 index 00000000..e71d9d97 --- /dev/null +++ b/plans/httpx-drop-in-phase-1-production-semantics.md @@ -0,0 +1,468 @@ +# HTTPX Drop-In Phase 1: Production Semantics and Lifecycle + +Status: ready for implementation handoff + +## Purpose + +Close the production-grade correctness gaps that must be resolved before eggfetch can safely serve as a long-lived HTTP client or support a credible HTTPX compatibility layer. + +This phase is deliberately prior to broad API expansion. Adding more HTTPX-shaped classes while connect deadlines are not independently enforced, Python resource limits are unavailable, and client closure does not deterministically tear down resources would increase surface area without fixing the operational foundation. + +## Baseline + +The current implementation already provides: + +- Rust async networking over Tokio/hyper/rustls; +- logical pool permits and hyper-managed connection reuse; +- pool, read, write, total, and nominal connect timeout fields; +- sync and asyncio Python clients; +- cancellation-safe permit ownership in several existing paths; +- Python context managers; +- resource-monitor and benchmark infrastructure; +- multi-platform Python tests. + +Known gaps to verify at phase start include: + +- connect timeout configuration is accepted but not independently enforced for the complete DNS/TCP/TLS path; +- default timeout phases are disabled in native eggfetch; +- Python does not expose an HTTPX-compatible `Limits` object or constructor argument; +- default logical concurrency is unlimited; +- `close()` and `aclose()` mark clients closed without necessarily dropping all owned client/runtime resources immediately; +- shared sync-client thread behavior is not established against HTTPX's contract; +- environment proxy behavior is currently deliberately disabled rather than selected by `trust_env`; +- long-running descriptor, thread, task, and memory stabilization evidence is incomplete. + +Record the exact baseline SHA, test counts, resource-monitor values, and open release-gate issues before implementation. + +## Non-goals + +- Implementing the complete HTTPX object model. +- Adding custom transports, mounts, event hooks, ASGI, WSGI, or mock transports. +- Adding full Python upload streaming beyond changes needed for lifecycle correctness. +- Enabling retries by default. +- Making HTTP/3 production-default or part of HTTPX compatibility. +- Optimizing benchmark numbers before correctness and boundedness are established. +- Relaxing TLS verification or timeout behavior to make tests easier. + +## Deliverables + +1. Independently enforced connect deadlines across DNS, TCP, proxy, and TLS phases. +2. Explicit native and compatibility timeout-default policies. +3. A core resource-limit model that can support HTTPX-compatible Python `Limits`. +4. Bounded compatibility defaults for connections and keep-alive behavior. +5. Deterministic sync and async client shutdown. +6. A defined and tested thread-sharing contract. +7. Complete cancellation and timeout cleanup tests. +8. Long-running resource-stability evidence. +9. Explicit environment-trust behavior. +10. A phase status file with acceptance evidence. + +## Track A — Correct timeout phase enforcement + +### A1. Map the actual request lifecycle + +Document and instrument the request path into explicit phases: + +1. pool acquisition; +2. DNS resolution; +3. TCP connect; +4. proxy TCP connect; +5. proxy CONNECT exchange; +6. TLS handshake to origin or over proxy tunnel; +7. request headers and body write; +8. response headers read; +9. response body read; +10. total request/redirect/retry envelope. + +Do not treat a single opaque connector future as evidence that every configured phase is enforced correctly. + +### A2. Enforce DNS and TCP deadlines + +Introduce connector-layer deadline propagation so `Timeout.connect` bounds at least: + +- hostname resolution; +- each address attempt; +- aggregate address-attempt behavior according to the selected policy; +- TCP connection establishment; +- direct TLS handshake; +- proxy connection establishment; +- TLS handshake over CONNECT. + +The implementation must define whether a connect timeout is: + +- one shared budget across DNS, address attempts, TCP, and TLS; or +- reset per subphase. + +The HTTPX compatibility layer must match the reference behavior as measured by Phase 0 fixtures. The native Rust API may expose additional explicit subphase controls only if they compose predictably. + +### A3. Deadline propagation and remaining budget + +Use an absolute deadline or remaining-budget model. Redirects and retries must not accidentally reset a total timeout. Nested timeout wrappers must report the correct phase without swallowing cancellation. + +Add tests where: + +- DNS blocks; +- the first resolved address stalls and a later address succeeds; +- TCP SYN remains pending; +- TLS handshake stalls after TCP success; +- proxy TCP connect stalls; +- CONNECT response stalls; +- origin TLS over tunnel stalls; +- total timeout expires during a phase with a longer phase timeout. + +### A4. Exception mapping + +Ensure timeout failures preserve: + +- timeout phase; +- elapsed or configured deadline information where policy permits; +- attached request in the Python compatibility layer; +- source error where useful internally; +- distinction between connect, pool, read, and write timeout classes. + +A total timeout may map to the compatibility hierarchy according to the measured reference contract, but it must never be mislabeled as an unrelated network error. + +## Track B — Define timeout defaults + +### B1. Separate native and compatibility defaults + +The project may retain a native eggfetch policy different from HTTPX, but the compatibility layer must use the target profile's defaults. + +Define explicitly: + +- native Rust default timeout; +- native Python `eggfetch` default timeout; +- HTTPX compatibility-layer default timeout; +- top-level helper default behavior; +- client constructor default behavior; +- `timeout=None` behavior; +- scalar timeout behavior; +- per-phase `Timeout` behavior; +- request-level override and merge behavior. + +The compatibility profile should use HTTPX 0.28.1's documented default of five seconds of network inactivity unless differential observation identifies a more specific nuance. + +### B2. Remove indefinite accidental behavior + +No production-facing default should allow an ordinary stalled network operation to hang indefinitely unless the user explicitly supplies `timeout=None` or an equivalent native opt-out. + +Add tests proving: + +- default connect stall raises; +- default read inactivity raises; +- periodic chunks reset the read inactivity deadline as expected; +- explicit `None` disables timeouts; +- partial per-phase objects require or inherit defaults according to the reference constructor rules; +- zero and negative timeout validation matches the target surface. + +## Track C — Resource limits and connection policy + +### C1. Add a core limits model + +Create or formalize a core resource-limit structure that distinguishes: + +- maximum concurrent logical requests; +- maximum concurrent requests per origin; +- maximum physical connections where the transport can enforce it; +- maximum keep-alive connections; +- maximum keep-alive connections per origin where supported; +- keep-alive expiry; +- HTTP/2 stream concurrency interaction; +- HTTP/3 stream concurrency interaction without exposing it as HTTPX parity. + +Avoid naming a logical semaphore `max_connections` if it cannot represent the HTTPX meaning. If the core needs both logical request limits and physical connection limits, model both explicitly. + +### C2. Expose HTTPX-compatible `Limits` + +The compatibility layer must support: + +- `Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0)` defaults for the pinned profile; +- `None` values where supported; +- constructor validation; +- stable repr and equality behavior where observed; +- propagation to sync and async clients; +- pool timeout interaction when maximum connections are exhausted. + +The native eggfetch API may expose additional per-origin limits, but compatibility defaults must not silently map to a semantically different control. + +### C3. Physical connection accounting + +Where hyper or another transport owns pooling, configure the transport's actual pool limits rather than relying only on eggfetch's logical permit layer. + +Add instrumentation or test-only observability sufficient to prove: + +- idle connection caps; +- keep-alive expiry; +- physical connection reuse; +- HTTP/1.1 maximum connection behavior; +- HTTP/2 multiplexing without one-per-request connection inflation; +- pool timeout when capacity is unavailable; +- dropped or closed bodies return capacity. + +Production APIs do not need to expose internal socket counters if the transport cannot do so safely, but tests need black-box evidence. + +## Track D — Deterministic client lifecycle + +### D1. Own resources explicitly + +Refactor Python client wrappers so close operations can take and drop owned resources deterministically. Likely patterns include: + +- `Option`; +- an explicitly owned runtime handle or shared runtime lease; +- a close-state object separate from object existence; +- idempotent teardown guarded against concurrent requests. + +`close()` and `aclose()` must do more than set a boolean. + +### D2. Define in-flight close behavior + +Specify and test what happens when a client is closed while: + +- a request is waiting for pool capacity; +- DNS is running; +- TCP or TLS connection is pending; +- a request body is being produced; +- response headers are pending; +- a response body is actively streaming; +- an iterator has been handed to Python; +- multiple threads or tasks are using the client. + +Match HTTPX where this is part of the public contract. Where behavior is undefined, choose a safe deterministic policy and document it. + +### D3. Interpreter shutdown and finalization + +Add subprocess tests for: + +- client not explicitly closed; +- streaming response abandoned; +- pending async request cancelled during interpreter exit; +- repeated construction and destruction; +- `atexit` ordering; +- object cycles containing a client; +- Windows interpreter shutdown. + +The process must terminate without deadlock, panic, leaked non-daemon threads, or excessive shutdown delay. + +### D4. Context-manager guarantees + +Prove that exiting sync and async client contexts: + +- rejects later requests with the expected exception; +- releases idle sockets within the documented bound; +- does not invalidate fully buffered response data; +- closes or detaches streaming bodies according to reference semantics; +- remains idempotent when close is called inside the context. + +## Track E — Thread and task concurrency contract + +### E1. Shared sync client + +Establish whether a single `Client` instance can be used concurrently from multiple Python threads, as HTTPX documents. + +The compatibility target requires: + +- safe concurrent method calls; +- no PyO3 mutable-borrow conflict exposed to users; +- no use of one non-reentrant runtime in a way that serializes or panics unexpectedly; +- connection pooling shared across threads; +- close/request races handled deterministically. + +Refactor the sync bridge if necessary. Candidate designs include: + +- one process-wide or module-wide shared Tokio runtime; +- a shared runtime service with per-call futures; +- `Arc`-owned core client with minimal Python mutable state; +- explicit synchronization around close state only. + +Do not create one runtime per request. + +### E2. Async concurrency + +Test one `AsyncClient` across many asyncio tasks for: + +- connection reuse; +- cancellation isolation; +- no global serialization; +- correct pool backpressure; +- close races; +- task-group cancellation; +- no retained tasks after completion. + +### E3. Fork behavior + +Document and test supported behavior when a client exists across `fork()` on POSIX. A safe policy may require clients to be constructed after fork. The implementation must fail clearly or reset state rather than reuse invalid runtime and socket state silently. + +## Track F — Environment trust policy + +### F1. Implement explicit `trust_env` + +The compatibility layer must accept `trust_env` with the HTTPX default and measured behavior. + +When enabled, evaluate at least: + +- `HTTP_PROXY`; +- `HTTPS_PROXY`; +- `ALL_PROXY`; +- `NO_PROXY`; +- lowercase variants according to reference behavior; +- `SSL_CERT_FILE`; +- `SSL_CERT_DIR` where supported; +- netrc behavior assigned to the authentication phase. + +The native eggfetch surface may default to explicit-only configuration, but the compatibility layer cannot ignore `trust_env` silently. + +### F2. Environment isolation and security + +Add tests that: + +- sanitize inherited CI proxy variables; +- verify `trust_env=False` ignores all relevant variables; +- prevent proxy credentials from appearing in reprs or logs; +- handle malformed environment URLs safely; +- apply `NO_PROXY` matching consistently; +- do not leak environment proxy settings into custom transports unexpectedly. + +## Track G — Resource stability and fault injection + +### G1. Metrics + +Extend test and benchmark instrumentation to observe: + +- file descriptors or handles; +- active TCP connections; +- Python threads; +- Tokio tasks where test instrumentation permits; +- resident memory; +- heap allocation trend; +- pool waiters and permits; +- DNS tasks; +- iterator bridge workers; +- client and response object counts in Python stress fixtures. + +### G2. Repeated-failure tests + +Run bounded high-iteration workloads for: + +- connection refused; +- DNS failure; +- TLS verification failure; +- read timeout; +- write timeout; +- pool timeout; +- proxy rejection; +- cancellation at every phase; +- early response drop; +- abandoned streaming iterator; +- repeated client open/close. + +Resource counts must return to a defined steady-state envelope. + +### G3. Soak tests + +Add scheduled or manually required soak profiles rather than placing all long tests in ordinary PR CI. + +At minimum: + +- sustained keep-alive requests; +- mixed origins; +- HTTP/2 multiplexing; +- slow streaming; +- repeated cancellation; +- proxy traffic; +- TLS session churn; +- client creation/destruction churn. + +Store machine-readable reports with candidate SHA, platform, duration, workload, peak values, and final stabilization values. + +## Expected files + +Likely changes include: + +- `crates/eggfetch-core/src/connector/` +- `crates/eggfetch-core/src/timeout.rs` +- `crates/eggfetch-core/src/pool.rs` +- `crates/eggfetch-core/src/client.rs` +- `crates/eggfetch-python/src/client.rs` +- `crates/eggfetch-python/src/async_client.rs` +- `crates/eggfetch-python/src/timeout.rs` +- `crates/eggfetch-python/src/limits.rs` +- `crates/eggfetch-python/tests/production/` +- `crates/eggfetch-bench/` +- `docs/concepts/timeouts.md` +- `docs/concepts/pooling.md` +- `docs/python/guide.md` +- `compat/httpx/0.28.1/allowed-differences.toml` +- `.github/workflows/ci.yml` +- `plans/httpx-drop-in-phase-1-status.md` + +## Required tests + +The implementation must add focused tests for: + +- DNS timeout; +- TCP timeout; +- TLS handshake timeout; +- proxy and tunneled TLS timeout; +- phase-versus-total deadline precedence; +- default timeout behavior; +- `timeout=None`; +- pool capacity and pool timeout; +- keep-alive limits and expiry; +- deterministic close; +- close during every request phase; +- sync client use from many threads; +- async client use from many tasks; +- close/request races; +- interpreter shutdown; +- repeated failure stabilization; +- fork policy; +- environment proxy and certificate behavior; +- `trust_env=False` isolation. + +## Validation commands + +The status file must record exact commands. Expected command families include: + +```bash +cargo test -p eggfetch-core timeout +cargo test -p eggfetch-core pool +cargo test -p eggfetch-core connector +pytest crates/eggfetch-python/tests/production -q +pytest crates/eggfetch-python/tests/compat -q +cargo run -p eggfetch-bench --bin resource_monitor +``` + +Long-running profiles should have explicit scripts and produce JSON reports. + +## Acceptance criteria + +This phase is complete only when: + +- [ ] DNS resolution is bounded by the configured connect deadline. +- [ ] TCP connection establishment is bounded by the configured connect deadline. +- [ ] Direct TLS handshake is bounded by the configured connect deadline. +- [ ] Proxy TCP, CONNECT, and tunneled TLS phases are bounded and correctly classified. +- [ ] Total timeout is an absolute envelope across redirects and retries. +- [ ] Timeout exceptions map to the correct compatibility classes and retain request context. +- [ ] Compatibility defaults match HTTPX 0.28.1's measured timeout policy. +- [ ] Explicit `timeout=None` disables timeout enforcement as expected. +- [ ] A core limits model distinguishes logical request limits from physical pool limits. +- [ ] Python exposes HTTPX-compatible `Limits` construction and defaults. +- [ ] Default compatibility clients are bounded to the reference connection and keep-alive limits. +- [ ] Pool timeout behavior is proven under exhausted capacity. +- [ ] `close()` deterministically releases client and runtime-owned resources. +- [ ] `aclose()` deterministically releases client-owned resources. +- [ ] Context manager exit has tested socket and stream behavior. +- [ ] Shared sync-client use from multiple threads is safe and compatible. +- [ ] Shared async-client use from many tasks is safe and non-serialized except by configured limits. +- [ ] Close/request races do not panic, deadlock, or leak resources. +- [ ] Interpreter shutdown tests pass on Linux, macOS, and Windows. +- [ ] `trust_env` matches the compatibility profile and `trust_env=False` isolates the process environment. +- [ ] Repeated-failure resource tests stabilize within committed thresholds. +- [ ] Scheduled soak profiles produce retained machine-readable evidence. +- [ ] No acceptance criterion is satisfied solely by documentation or a unit test that bypasses the real connector. +- [ ] `plans/httpx-drop-in-phase-1-status.md` links a green required CI run and exact SHA. + +## Handoff notes + +Implementation should prefer architectural correction over adapter-level timeout wrappers. A Python timer around an opaque request does not establish independently correct connect, pool, read, and write semantics. Likewise, a logical semaphore is not an adequate substitute for actual transport pool limits. The status document must explain how each public control maps to the transport behavior it claims to govern. From 333459ebbe0996eb9cd52016cb39f3d41b88df9e Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:15:55 -0400 Subject: [PATCH 4/8] plans: add HTTPX object model and API phase --- ...px-drop-in-phase-2-object-model-and-api.md | 477 ++++++++++++++++++ 1 file changed, 477 insertions(+) create mode 100644 plans/httpx-drop-in-phase-2-object-model-and-api.md diff --git a/plans/httpx-drop-in-phase-2-object-model-and-api.md b/plans/httpx-drop-in-phase-2-object-model-and-api.md new file mode 100644 index 00000000..bcd8c24f --- /dev/null +++ b/plans/httpx-drop-in-phase-2-object-model-and-api.md @@ -0,0 +1,477 @@ +# HTTPX Drop-In Phase 2: Object Model and Core API Parity + +Status: ready for implementation handoff + +## Purpose + +Implement the documented HTTPX 0.28.1 public data model and ordinary client API as a compatibility facade over the existing eggfetch Rust engine. + +This phase focuses on construction, signatures, configuration merging, object relationships, metadata, return values, and exceptions. It must not duplicate network behavior in Python. A request built by compatibility objects must still execute through `eggfetch-core` unless a later explicit in-process transport is selected. + +## Dependencies + +Phase 0 must be complete so every public-surface gap is measured against a pinned manifest. Phase 1 should be complete for timeout, limits, and lifecycle semantics before this phase's client API is considered production-ready. + +## Baseline + +The current Python package exports native `Client`, `AsyncClient`, buffered and streaming response wrappers, headers, cookies, basic/bearer auth, timeout, retry, file helpers, top-level request methods, and an eggfetch-specific exception hierarchy. + +The compatibility surface is missing or materially different in areas including: + +- structured `URL` and `QueryParams` objects; +- public `Request` construction; +- HTTPX-compatible `Response` construction and metadata; +- `Limits`, `Proxy`, status-code helpers, and stream base classes; +- `build_request()` and `send()`; +- `base_url`, client-level params, mounts, hooks, transport, trust environment, and default encoding; +- complete exception inheritance and attached request/response context; +- chainable `raise_for_status()`; +- request attachment, next request, elapsed time, extensions, and response stream metadata. + +Record exact manifest deltas before implementation begins. + +## Non-goals + +- Implementing custom transport execution, mounts, ASGI, WSGI, or mock behavior; only surface placeholders and validated rejection may land where necessary. +- Completing scalable Python request streaming; Phase 3 owns body-stream execution. +- Supporting private HTTPX modules. +- Matching arbitrary object identity or internal storage layout. +- Requiring Rust users to adopt HTTPX-shaped APIs. +- Creating the top-level `httpx` compatibility distribution before downstream validation. + +## Deliverables + +1. A dedicated compatibility module with documented import policy. +2. HTTPX-compatible public value objects. +3. HTTPX-compatible request and response objects. +4. HTTPX-compatible exception hierarchy and context attachment. +5. Client and async-client constructor signatures and state. +6. `build_request()`, `send()`, request helpers, and top-level helpers. +7. Deterministic configuration-merge semantics. +8. Manifest and behavioral tests with no unexplained Phase 2 deltas. +9. A phase implementation status file. + +## Track A — Compatibility module architecture + +### A1. Separate native and compatibility surfaces + +Create a clear module boundary, for example: + +- `eggfetch.compat.httpx` +- internal pure-Python modules under `eggfetch/compat/` +- native extension primitives imported behind the facade. + +The ordinary `eggfetch` API may preserve eggfetch-native additions. The compatibility module must avoid exposing unrelated native names that are absent from HTTPX unless they are under an explicitly eggfetch-specific namespace. + +### A2. Public export discipline + +Drive `__all__` and public-module manifests from an explicit compatibility export table. Validate: + +- top-level names; +- object modules and qualified names; +- aliases; +- constants; +- exception classes; +- status-code helpers; +- stream base classes; +- auth and transport names assigned to later phases. + +Unimplemented required-later objects may initially exist only if construction or use raises a precise compatibility-stage error and the Phase 0 profile marks them open. Do not provide nonfunctional silent stubs. + +### A3. Native bridge boundary + +Define conversion protocols between compatibility objects and native extension types: + +- URL to normalized core URL; +- headers preserving duplicate values and raw bytes; +- request body stream to core request body; +- timeout and limits to core configuration; +- proxy and TLS configuration to core builders; +- native response metadata to compatibility response; +- native errors to compatibility exceptions. + +Keep conversion centralized and testable. + +## Track B — URL and query model + +### B1. Implement `URL` + +Match the pinned reference for: + +- constructors from string, bytes where supported, and existing URL; +- scheme, userinfo, host, raw host, port, path, raw path, query, raw query, fragment; +- authority, netloc, origin, and absolute/relative status; +- IDNA and Unicode handling; +- percent encoding and normalization; +- default ports; +- copying and mutation helpers such as `copy_with()`; +- joining and relative resolution where public; +- equality, hashing, string, bytes, repr, and ordering behavior if defined; +- credential redaction in display paths; +- invalid URL exceptions. + +Do not use `url::Url` stringification as the sole compatibility definition; its normalization may differ from HTTPX. + +### B2. Implement `QueryParams` + +Support: + +- mapping and sequence construction; +- repeated keys; +- blank values; +- scalar and sequence values according to reference conversion rules; +- `get()`, `get_list()`, `multi_items()`, keys, values, items; +- add/set/remove/merge operations exposed by the target; +- equality, hashing if defined, string, repr; +- stable encoding rules. + +### B3. URL/query differential corpus + +Add cases for: + +- Unicode host and path; +- IPv4, IPv6, zone identifiers if supported; +- username/password; +- empty path and query; +- repeated and blank query keys; +- encoded slash and reserved characters; +- relative base URL resolution; +- invalid ports and malformed percent escapes; +- fragments excluded from wire requests. + +## Track C — Headers and cookies + +### C1. Complete `Headers` + +Match: + +- construction from mappings, sequences, bytes pairs, and existing headers; +- case-insensitive lookup with preserved raw representation; +- duplicate-field combination behavior; +- `get_list()`, `multi_items()`, raw iteration, keys, values, items; +- mutation where public; +- encoding selection and validation; +- equality and repr; +- CR/LF and invalid token rejection; +- `Set-Cookie` special handling. + +The core bridge must not lose duplicate header fields by converting through a normal Python dictionary. + +### C2. Complete `Cookies` + +Match the public mapping and jar interactions required by HTTPX, including: + +- construction from mappings and jars; +- set/get/delete/clear/update; +- domain and path disambiguation; +- conflict exceptions; +- request extraction and response update; +- iteration and repr; +- client-level mutable jar behavior. + +Do not weaken the existing core cookie security behavior. Where HTTPX exposes a broader Python cookie-jar interface, adapt through a controlled facade. + +## Track D — Timeout, limits, proxy, and status helpers + +### D1. Complete `Timeout` + +Match constructor forms, validation, repr, equality where defined, and attribute names for: + +- scalar default; +- connect/read/write/pool values; +- `None` values; +- copying or dictionary conversion where public. + +Map compatibility timeout fields to Phase 1 core deadlines without introducing a hidden total timeout unless the native API explicitly exposes one outside the HTTPX facade. + +### D2. Complete `Limits` + +Expose the pinned constructor, defaults, attributes, validation, repr, and core conversion from Phase 1. + +### D3. Implement `Proxy` + +Match public construction and attributes for URL, SSL context, auth, and headers. Preserve proxy credential redaction. Execution behavior belongs partly to the core and Phase 4 transport routing, but ordinary `proxy=` use must function in this phase where already supported. + +### D4. Status codes + +Implement the target's `codes` enumeration/helper behavior and any public constants or predicates included in the manifest. + +## Track E — Request object + +### E1. Construction + +Implement HTTPX-compatible `Request` construction with: + +- method; +- URL; +- params; +- headers; +- cookies; +- content/data/files/json; +- stream; +- extensions. + +Body mutual-exclusion and auto-header behavior must match the reference, including content length, transfer encoding, host, accept, accept-encoding, connection, and user-agent defaults where applicable. + +### E2. Request properties and methods + +Support the target's public properties and methods, including: + +- method mutation policy; +- URL and headers; +- content access state; +- stream access; +- extensions; +- `read()` and `aread()` behavior; +- `is_stream_consumed` where public; +- repr; +- copy/serialization behavior only where public. + +### E3. Replayability metadata + +Attach internal replayability classification without exposing incompatible public fields. Redirect and retry logic must use the same body object and state model as Phase 3. + +## Track F — Response object + +### F1. Construction and attachment + +Implement public response construction for test, transport, and user-created responses, including: + +- status code; +- headers; +- content/text/html/json-compatible input paths if public; +- stream; +- request; +- extensions; +- history; +- default encoding. + +A response returned by the client must attach the exact compatibility request object used for execution. + +### F2. Metadata and properties + +Match: + +- status helpers; +- reason phrase; +- URL derived from request; +- HTTP version from extensions or transport metadata; +- cookies; +- encoding getter and setter behavior; +- charset and apparent/default decoding policy; +- content/text/json; +- elapsed; +- history; +- next request; +- request property failure when not attached; +- extensions; +- stream/read state; +- repr. + +### F3. `raise_for_status()` + +Match the reference for: + +- informational and redirect responses where applicable; +- client and server errors; +- message formatting and documentation link format where observable; +- attached request and response; +- return value of the response itself; +- error when no request is attached. + +### F4. Redirect history bodies + +Do not replace redirect responses with metadata-only objects if the reference exposes readable history bodies. Preserve bounded behavior using configurable limits or consumed buffers consistent with the reference. + +## Track G — Exception hierarchy + +### G1. Class structure + +Implement the pinned public hierarchy, including the relationships among: + +- `HTTPError`; +- `RequestError`; +- `TransportError`; +- timeout subclasses; +- network subclasses; +- protocol subclasses; +- proxy errors where public; +- `DecodingError`; +- `TooManyRedirects`; +- `HTTPStatusError`; +- invalid URL and cookie conflict classes; +- stream state exceptions; +- unsupported protocol. + +The manifest test must validate MRO and subclass relationships. + +### G2. Exception context + +Every request-related exception must preserve a compatibility `request` attribute when the reference does. `HTTPStatusError` must preserve both request and response. + +Do not construct public exceptions only from a message string and discard context. + +### G3. Mapping policy + +Create one centralized mapping from core errors to compatibility exceptions. It must: + +- preserve the most specific class available; +- retain safe source details; +- redact credentials; +- avoid exposing Rust implementation reprs as the stable message contract; +- distinguish read/write/connect/close/protocol failures; +- map unsupported features precisely. + +## Track H — Client and AsyncClient surface + +### H1. Constructor signatures + +Match the pinned public signatures and defaults for: + +- auth; +- params; +- headers; +- cookies; +- verify; +- cert; +- trust environment; +- HTTP/1 and HTTP/2 flags; +- proxy; +- mounts; +- timeout; +- redirects; +- limits; +- max redirects; +- event hooks; +- base URL; +- transport; +- default encoding. + +Phase 4 may complete execution for mounts, hooks, transports, and additional auth flows, but constructor acceptance and state must be designed now. + +### H2. Configuration merge rules + +Differentially test client-level and request-level merging for: + +- URL/base URL; +- params; +- headers; +- cookies; +- auth; +- timeout; +- extensions; +- redirect policy; +- request body and auto headers. + +Use explicit merge functions rather than scattered conditionals in every verb method. + +### H3. `build_request()` + +Build a compatibility `Request` without sending. It must include the same merged configuration and auto headers that `request()` would send. + +### H4. `send()` + +Accept a compatibility `Request`, preserve object attachment, and support the target's public send options such as stream, auth, and redirects. + +`send()` must not reconstruct a semantically different request from only method and URL. + +### H5. Request methods + +Implement exact signatures and return types for: + +- `request()`; +- `get()`; +- `options()`; +- `head()`; +- `post()`; +- `put()`; +- `patch()`; +- `delete()`; +- `stream()`; +- `close()`/`aclose()`; +- context managers. + +### H6. Client properties + +Expose and validate mutable/read-only behavior for public properties such as headers, cookies, params, auth, timeout, base URL, trust environment, and closed state. + +## Track I — Top-level helpers + +Match top-level request functions and top-level streaming where public: + +- signatures and defaults; +- short-lived client behavior; +- timeout defaults; +- redirect defaults; +- environment trust; +- response and exception types; +- deterministic cleanup. + +Top-level helpers must use the same compatibility client implementation, not a separate simplified path. + +## Track J — Testing and evidence + +### J1. Manifest closure + +After implementation, Phase 2-required symbols must have no unexplained manifest differences. Required-later transport/backend items may remain only if assigned to Phase 4. + +### J2. Construction differential tests + +Compare reprs, signatures, properties, exceptions, and normalized state for every public object using safe deterministic fixtures. + +### J3. Merge matrix + +Generate a parameterized matrix for client/request configuration combinations. Include duplicate headers and params, cookie precedence, auth disable/override, timeout override, base URL edge cases, and extensions. + +### J4. Built-wheel tests + +Run the same API and construction corpus against a clean wheel install, not only an editable source tree. + +## Expected files + +Likely additions or changes include: + +- `crates/eggfetch-python/python/eggfetch/compat/httpx/` +- `crates/eggfetch-python/src/` native bridge modules; +- `crates/eggfetch-python/tests/compat/test_api_manifest.py` +- `crates/eggfetch-python/tests/compat/test_objects.py` +- `crates/eggfetch-python/tests/compat/test_client_merge.py` +- `crates/eggfetch-python/tests/compat/test_exceptions.py` +- compatibility profile and allowed-difference files; +- user and migration documentation; +- `plans/httpx-drop-in-phase-2-status.md`. + +## Acceptance criteria + +This phase is complete only when: + +- [ ] The compatibility module has a stable documented import path. +- [ ] HTTPX 0.28.1 public Phase 2 symbols import from the compatibility module. +- [ ] `URL` passes the pinned construction, normalization, copy, equality, hashing, and repr corpus. +- [ ] `QueryParams` preserves repeated keys and passes encoding and mutation semantics. +- [ ] `Headers` preserves raw duplicates and passes lookup, iteration, mutation, and validation semantics. +- [ ] `Cookies` passes mapping, conflict, domain/path, request, and response behavior. +- [ ] `Timeout`, `Limits`, and `Proxy` signatures, defaults, reprs, and validation match the profile. +- [ ] Status-code helpers match the public target. +- [ ] `Request` construction and auto-header behavior match the reference. +- [ ] `Request.read()` and `aread()` state behavior is correct. +- [ ] `Response` construction and public metadata match the reference. +- [ ] Client responses attach the original compatibility request. +- [ ] Redirect history contains reference-compatible response objects and bodies. +- [ ] `raise_for_status()` returns the response and raises context-rich errors. +- [ ] The exception hierarchy and MRO match the pinned manifest. +- [ ] Request-related exceptions expose the expected request attribute. +- [ ] Status exceptions expose request and response. +- [ ] `Client` and `AsyncClient` constructor signatures and defaults match the target. +- [ ] Client properties expose the expected mutability and types. +- [ ] `build_request()` matches the request that would be sent. +- [ ] `send()` accepts a constructed request without losing body, extensions, or object identity. +- [ ] All request verb signatures and top-level helper signatures match the manifest. +- [ ] Client/request merge behavior passes the generated differential matrix. +- [ ] Required Phase 2 manifest deltas are zero or explicitly reviewed allowed differences. +- [ ] Tests pass from built wheels on the supported Python matrix. +- [ ] `plans/httpx-drop-in-phase-2-status.md` links exact CI and manifest evidence. + +## Handoff notes + +Prefer pure-Python compatibility value objects where that produces exact semantics cheaply, but keep all network execution in the Rust core. Do not expose raw native wrapper constraints as the compatibility contract. In particular, PyO3 method signatures that are convenient for the extension are not sufficient if they differ from the pinned Python API. From 9be58a678c0357a235309af7d565428d9d5d03e0 Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:17:30 -0400 Subject: [PATCH 5/8] plans: add HTTPX streaming and body phase --- ...px-drop-in-phase-3-streaming-and-bodies.md | 413 ++++++++++++++++++ 1 file changed, 413 insertions(+) create mode 100644 plans/httpx-drop-in-phase-3-streaming-and-bodies.md diff --git a/plans/httpx-drop-in-phase-3-streaming-and-bodies.md b/plans/httpx-drop-in-phase-3-streaming-and-bodies.md new file mode 100644 index 00000000..d5a91bae --- /dev/null +++ b/plans/httpx-drop-in-phase-3-streaming-and-bodies.md @@ -0,0 +1,413 @@ +# HTTPX Drop-In Phase 3: Streaming and Body Architecture + +Status: ready for implementation handoff + +## Purpose + +Make Python request and response bodies genuinely streaming, bounded, backpressured, cancellation-safe, and behaviorally compatible with HTTPX 0.28.1. + +The Rust core already supports streamed bodies. The current Python adapter still buffers ordinary Python request bodies and multipart payloads into byte vectors, while synchronous response iterators may create a dedicated thread and Tokio runtime per stream. This phase replaces those adapter limitations with one coherent stream model shared by requests, redirects, retries, responses, transports, and future compatibility backends. + +## Dependencies + +Phase 0 must define the stream compatibility corpus. Phase 1 must provide stable lifecycle, cancellation, timeout, and shared-runtime behavior. Phase 2 must provide compatibility `Request`, `Response`, exceptions, and stream base classes. + +## Non-goals + +- Implementing mount routing, event hooks, or in-process application transports. +- Rewriting the Rust core's functioning stream implementation without evidence of a gap. +- Automatically replaying arbitrary one-shot streams across redirects or retries. +- Buffering unbounded bodies merely to imitate replayability. +- Requiring HTTP/3 parity with HTTPX. +- Adding application-level SSE parsing beyond ordinary line and text streaming. + +## Deliverables + +1. A unified request-body abstraction across Rust and Python compatibility objects. +2. Sync iterable, async iterable, file-like, byte, string, form, JSON, and multipart body support. +3. Lazy multipart encoding from Python without whole-payload buffering. +4. Raw and decoded response streaming methods. +5. Exact read/consume/close state transitions. +6. Shared-runtime stream bridges without one runtime and thread per stream. +7. Backpressure, cancellation, timeout, and early-close correctness. +8. Replayability integration for redirects and retries. +9. Differential and resource-stability evidence. +10. A phase status file. + +## Track A — Define the unified body model + +### A1. Body categories + +Represent at least: + +- empty body; +- known immutable bytes; +- known text encoded to bytes; +- sync iterable of bytes; +- async iterable of bytes; +- file-like reader; +- native Rust byte stream; +- multipart state-machine stream; +- form and JSON bodies that may remain buffered when naturally bounded; +- custom `SyncByteStream` and `AsyncByteStream` implementations. + +Every body must carry explicit metadata where known: + +- content length; +- replayability; +- sync/async consumption mode; +- consumed state; +- close/finalizer behavior; +- optional content type; +- source description safe for diagnostics. + +### A2. Replayability classes + +Define a closed internal classification such as: + +- replayable immutable; +- replayable seekable with reset operation; +- factory-replayable; +- one-shot sync stream; +- one-shot async stream; +- consumed; +- closed. + +Redirect and retry code must consult this classification rather than infer replayability from body size or Python object type ad hoc. + +### A3. State machine + +Document and test legal transitions: + +- fresh -> streaming -> consumed; +- fresh -> buffered -> consumed/readable; +- fresh -> closed; +- streaming -> closed/cancelled; +- consumed -> repeated-read behavior according to body type; +- buffered -> iterator behavior; +- error -> closed/released. + +State errors must map to HTTPX-compatible exceptions with request/response context where applicable. + +## Track B — Python request streaming + +### B1. Sync iterable content + +Support `content=` supplied as a sync iterable yielding bytes. + +Requirements: + +- lazy iteration only after send begins; +- no pre-collection into a list or byte vector; +- validation that yielded items are bytes-like according to the target behavior; +- bounded bridge queue; +- write timeout applied while waiting for the next producer item and while sending; +- producer exceptions mapped predictably; +- iterator close/finalization on cancellation, error, or client close; +- chunked transfer when length is unknown; +- content length when explicitly known through supported stream metadata. + +### B2. Async iterable content + +Support async iterables for `AsyncClient` and async request construction. + +Requirements: + +- iteration on the originating Python event loop where required; +- bounded transfer into the Rust core; +- cancellation propagation in both directions; +- no cross-loop use; +- deterministic finalization; +- no blocking Python event-loop thread; +- correct exception mapping. + +A sync client receiving an async-only stream and an async client receiving an invalid sync-only stream must match reference validation behavior. + +### B3. File-like content + +Support binary file objects and compatible readers without reading the whole file first. + +Requirements: + +- incremental reads; +- content-length detection only when safe and position-aware; +- preserve current file position semantics according to the reference; +- do not close user-owned files unless the target contract does; +- cancellation releases internal references; +- seekable replay may reset only when the original offset is recorded and restoration succeeds; +- non-seekable files remain one-shot. + +### B4. Custom stream classes + +Implement HTTPX-compatible `SyncByteStream` and `AsyncByteStream` public base protocols. User subclasses must work without private eggfetch hooks. + +Validate: + +- iteration method names; +- close/aclose behavior; +- type errors for wrong stream kind; +- response construction with custom streams; +- transport interaction in Phase 4. + +## Track C — Multipart and form bodies + +### C1. Remove Python multipart buffering + +Refactor Python `files=` handling so file paths, file objects, byte streams, and custom file tuples are represented as lazy multipart parts and passed to the Rust multipart encoder. + +Do not convert the completed multipart body into `Vec` before send. + +### C2. Match tuple and value forms + +Differentially implement supported file forms, including: + +- raw file object; +- filename and file object; +- filename, content, and content type; +- filename, content, content type, and per-part headers; +- bytes and string field behavior; +- repeated field names; +- `None` filename behavior where supported; +- mapping and sequence inputs; +- `data=` combined with `files=`. + +### C3. Multipart length and chunking + +Compute total content length only when every part length and encoder overhead are known without overflow. Otherwise use streaming transfer semantics. + +Add tests for: + +- empty files; +- large files; +- non-seekable file objects; +- Unicode filenames and field names; +- quoted header parameters; +- custom part headers; +- boundary collision policy; +- cancellation midway through a part; +- redirect and retry replayability. + +### C4. Resource ownership + +Clarify and test which objects eggfetch opens and therefore closes versus which objects are user-owned. Path inputs opened by eggfetch must close on success, failure, cancellation, and abandoned requests. + +## Track D — Response streaming parity + +### D1. Raw versus decoded streams + +Implement the target methods and semantics for: + +- `iter_raw()`; +- `aiter_raw()`; +- `iter_bytes()`; +- `aiter_bytes()`; +- `iter_text()`; +- `aiter_text()`; +- `iter_lines()`; +- `aiter_lines()`; +- `read()`; +- `aread()`. + +Raw iterators must expose transport bytes before content decoding. Decoded byte iterators must apply content encodings. Text iterators must incrementally decode character sets without corrupting multibyte characters across chunks. + +### D2. Chunk-size behavior + +Match the reference for: + +- default chunk sizes; +- explicit chunk size; +- zero or invalid values; +- transport chunk coalescing and splitting; +- final partial chunks; +- empty chunks; +- compressed-body chunk boundaries; +- line boundary handling across chunks. + +### D3. Line semantics + +Differentially verify: + +- `\n` and `\r\n`; +- trailing final line without newline; +- empty lines; +- Unicode line boundaries only where the reference recognizes them; +- decoded text with split multibyte characters; +- raw bytes not incorrectly decoded. + +### D4. Buffered response iterators + +Do not build a complete Python list simply to return an iterator. Buffered response iteration may slice the already buffered body lazily, but should not duplicate it into a second unbounded list. + +## Track E — Runtime and bridge architecture + +### E1. Shared sync runtime + +Use the shared runtime architecture established in Phase 1. A synchronous streaming iterator must not spawn one OS thread and one Tokio runtime per response. + +Preferred characteristics: + +- one shared runtime service; +- bounded channels per active stream; +- worker tasks rather than worker runtimes; +- prompt task cancellation when the iterator is dropped; +- no daemon thread accumulation; +- deterministic module shutdown. + +### E2. Python GIL policy + +Release the GIL while blocking for stream chunks, but reacquire it only for Python producer/consumer interaction. Ensure a slow Python iterator does not hold the GIL while Rust waits on network I/O. + +### E3. Async loop affinity + +Record the event loop associated with async Python producers and consumers when required. Reject cross-loop use with the reference-compatible exception rather than deadlocking. + +### E4. Channel bounds and backpressure + +Every bridge queue must be explicitly bounded. Add instrumentation and tests proving: + +- producer cannot outrun the network indefinitely; +- network reader cannot buffer an unbounded response when Python is slow; +- cancellation unblocks a full queue; +- close unblocks both sides; +- queue capacity does not alter visible chunk order. + +## Track F — Timeout, cancellation, and close semantics + +### F1. Request producer failures + +Test and classify: + +- sync iterator raises; +- async iterator raises; +- file read fails; +- multipart part fails; +- producer yields invalid type; +- producer blocks beyond write timeout; +- client closes during production; +- request task is cancelled. + +The core connection must be reusable only when protocol state permits. Otherwise it must be discarded safely. + +### F2. Response consumer failures + +Test: + +- consumer stops early; +- iterator object is dropped; +- context exits without reading; +- response closes during blocked read; +- client closes during active response; +- cancellation during decompression; +- malformed compressed stream; +- read timeout after partial data. + +Pool permits and transport resources must release deterministically. + +### F3. Context-manager semantics + +Match HTTPX for sync and async stream contexts, including the point at which the request is sent, the type returned by `stream()`, and close behavior on exceptions inside the context. + +## Track G — Redirect and retry integration + +### G1. Body replay decisions + +For every redirect status and retry decision, test: + +- immutable body replay; +- seekable file replay; +- one-shot stream rejection; +- method rewriting that removes the body; +- `Content-Length` and transfer-encoding header changes; +- user-provided body headers; +- cancellation between attempts. + +### G2. Error compatibility + +Map non-replayable behavior to the reference contract where one exists. Eggfetch-specific retry features may raise eggfetch-specific native exceptions outside the compatibility module, but the HTTPX facade must not expose unrelated classes for ordinary HTTPX behavior. + +## Track H — Differential and stress validation + +### H1. Reference stream server + +Use deterministic endpoints for: + +- one-byte chunks; +- random but seeded chunk boundaries; +- delayed chunks; +- infinite stream with explicit test cancellation; +- compressed streams; +- truncated streams; +- upload echo with read pacing; +- server stops reading request body; +- bidirectional backpressure. + +### H2. Memory envelopes + +Prove bounded resident memory for: + +- multi-gigabyte synthetic download consumed slowly; +- multi-gigabyte synthetic upload generated lazily; +- multipart upload of large files; +- many concurrent small streams; +- many abandoned streams; +- compressed expansion up to configured safety limits. + +Tests may use generated data and bounded run sizes in PR CI, with larger scheduled profiles. + +### H3. Thread/task envelopes + +Assert that active threads and runtime tasks scale according to the shared architecture, not one unbounded thread/runtime per stream. + +## Expected files + +Likely changes include: + +- `crates/eggfetch-core/src/body.rs` +- `crates/eggfetch-core/src/multipart/` +- `crates/eggfetch-core/src/client.rs` +- `crates/eggfetch-python/src/streaming.rs` +- `crates/eggfetch-python/src/conversion.rs` +- `crates/eggfetch-python/src/multipart.rs` +- Python compatibility stream modules; +- `crates/eggfetch-python/tests/compat/test_request_streaming.py` +- `crates/eggfetch-python/tests/compat/test_response_streaming.py` +- `crates/eggfetch-python/tests/production/test_stream_resources.py` +- benchmark and resource-monitor workloads; +- streaming and multipart documentation; +- `plans/httpx-drop-in-phase-3-status.md`. + +## Acceptance criteria + +This phase is complete only when: + +- [ ] Sync iterable request content is consumed lazily with bounded buffering. +- [ ] Async iterable request content is consumed lazily on the correct event loop. +- [ ] File-like request bodies stream without whole-file buffering. +- [ ] User-owned file lifecycle matches the reference contract. +- [ ] Eggfetch-opened files close on all success and failure paths. +- [ ] Public sync and async byte-stream base classes work for user subclasses. +- [ ] Python multipart uploads use the core streaming encoder rather than a completed byte vector. +- [ ] Multipart tuple forms, repeated fields, headers, and filenames match the differential corpus. +- [ ] Multipart content length is emitted only when safely known. +- [ ] Raw response iterators expose undecoded transport bytes. +- [ ] Decoded byte iterators apply content encoding correctly. +- [ ] Text iterators preserve multibyte characters across arbitrary chunk boundaries. +- [ ] Line iterators match reference handling of CRLF, empty lines, and final partial lines. +- [ ] Buffered iterators do not allocate a second whole-body Python list. +- [ ] Synchronous streams do not create one Tokio runtime or OS thread per stream. +- [ ] Every Python/Rust bridge queue is bounded and cancellation-safe. +- [ ] Write timeout covers waiting on Python producers and network writes according to the profile. +- [ ] Read timeout covers headers and body inactivity according to the profile. +- [ ] Early close releases pool permits and transport resources. +- [ ] Dropped iterators do not retain background tasks or threads. +- [ ] Redirect and retry replayability decisions are deterministic and tested. +- [ ] Request and response stream exceptions match the compatibility hierarchy. +- [ ] Large synthetic upload and download tests remain within committed memory thresholds. +- [ ] Concurrent stream stress tests remain within committed thread/task thresholds. +- [ ] Sync and asyncio differential stream suites have no unexplained differences. +- [ ] Built-wheel streaming tests pass on Linux, macOS, and Windows. +- [ ] `plans/httpx-drop-in-phase-3-status.md` links exact test, resource, and CI evidence. + +## Handoff notes + +The implementation should avoid solving Python streaming by adding larger buffers. The core design test is whether a producer or consumer can be arbitrarily slow without unbounded memory growth, leaked background work, or incorrect timeout behavior. Preserve backpressure end to end. From 5562399d2fea2a65ca36275f74b286cd57963734 Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:19:15 -0400 Subject: [PATCH 6/8] plans: add transports extensions and backends phase --- ...se-4-transports-extensions-and-backends.md | 478 ++++++++++++++++++ 1 file changed, 478 insertions(+) create mode 100644 plans/httpx-drop-in-phase-4-transports-extensions-and-backends.md diff --git a/plans/httpx-drop-in-phase-4-transports-extensions-and-backends.md b/plans/httpx-drop-in-phase-4-transports-extensions-and-backends.md new file mode 100644 index 00000000..0b552079 --- /dev/null +++ b/plans/httpx-drop-in-phase-4-transports-extensions-and-backends.md @@ -0,0 +1,478 @@ +# HTTPX Drop-In Phase 4: Transports, Extensions, Authentication, and Async Backends + +Status: ready for implementation handoff + +## Purpose + +Implement the public extension boundaries that distinguish an HTTPX-like request API from an actual HTTPX-compatible client used by frameworks, test suites, SDKs, instrumentation, and custom networking environments. + +This phase adds transport protocols, mount routing, event hooks, request/response extensions, custom authentication flows, in-process test transports, environment integration, and supported async backend behavior. Real network I/O remains in `eggfetch-core`; Python-only mock, WSGI, and ASGI transports may execute entirely in Python because they do not perform network I/O. + +## Dependencies + +Phase 0 defines the target surface and mandatory oracle. Phase 1 provides production lifecycle and environment controls. Phase 2 provides compatible requests, responses, errors, clients, and value objects. Phase 3 provides stream types and body bridges used by all transports. + +## Non-goals + +- Supporting private HTTPX transport internals. +- Making HTTP/3 part of HTTPX 0.28.1 parity. +- Reimplementing a general application server. +- Running WSGI or ASGI applications over a real socket unless a separate explicit test asks for it. +- Adding unsupported proxy protocols without an optional feature boundary. +- Claiming Trio support through a blocking shim without cancellation and context semantics evidence. +- Silently falling back to the default network transport when a custom transport rejects a request. + +## Deliverables + +1. Compatible sync and async transport base interfaces. +2. Rust-backed HTTP transport adapters. +3. URL-pattern mount routing. +4. Mock, WSGI, and ASGI transports. +5. Event hooks with reference-compatible sequencing and error behavior. +6. Request/response extension propagation. +7. Custom authentication flow interfaces and required built-ins. +8. Explicit environment proxy, certificate, and netrc behavior. +9. Low-level transport options such as UDS and local address where included by the target. +10. Optional SOCKS support if required for the target extra. +11. A validated asyncio and Trio/AnyIO backend strategy. +12. A phase status file. + +## Track A — Transport protocols + +### A1. Public base transports + +Implement public interfaces equivalent to: + +- `BaseTransport` with `handle_request(request)` and `close()`; +- `AsyncBaseTransport` with `handle_async_request(request)` and `aclose()`. + +Match: + +- method signatures; +- request and response object types; +- context-manager behavior if public; +- subclassing expectations; +- exception propagation; +- close idempotence; +- stream ownership. + +The compatibility facade may define these as Python abstract/protocol-style classes while adapting Rust-backed transports behind them. + +### A2. HTTP transports + +Implement public `HTTPTransport` and `AsyncHTTPTransport` objects backed by eggfetch-core. + +Support target-profile constructor options such as: + +- TLS verification and certificates; +- trust environment where applicable; +- HTTP/1 and HTTP/2 flags; +- limits; +- proxy; +- local address; +- Unix domain socket; +- transport-level retries; +- socket options if public in the pinned target. + +Transport-level retries must remain distinct from eggfetch's richer native retry policy. The compatibility adapter must reproduce HTTPX behavior rather than expose unrelated defaults. + +### A3. Transport error boundary + +Custom transports may return responses or raise compatibility transport exceptions. Normalize only errors that belong to the public transport contract. Do not wrap arbitrary user exceptions into generic network errors if HTTPX lets them propagate. + +### A4. Transport lifecycle + +Clients own transports they construct internally. Ownership of user-supplied transports must match the reference. Test shared transport objects, client closure, nested clients, and repeated close. + +## Track B — Mount routing + +### B1. URL pattern model + +Implement the target's URL-pattern matching and priority rules for mount keys, including combinations of: + +- scheme; +- host; +- wildcard host; +- port; +- path if supported; +- catch-all patterns. + +Do not implement mounts as unordered dictionary prefix checks. Generate differential routing cases against the reference. + +### B2. Per-route transports and proxies + +Support: + +- separate HTTP and HTTPS transports; +- per-domain transports; +- per-domain proxies; +- explicit `None` routes where meaningful; +- direct bypass routes; +- custom schemes; +- no-proxy patterns implemented through mounts where the reference does so. + +### B3. Routing observability + +Test which transport receives each request and ensure: + +- the original compatibility request object is passed; +- base URL resolution occurs before route selection as in the reference; +- redirects are rerouted for the new URL; +- auth and sensitive-header stripping occur at the correct layer; +- transport close occurs once even if mounted multiple times according to ownership rules. + +## Track C — Mock transport + +### C1. Handler contract + +Implement `MockTransport` with sync and async handler compatibility. The handler must receive a compatibility `Request` and may return a compatibility `Response`. + +Match: + +- handler signatures; +- response request attachment; +- stream handling; +- handler exception propagation; +- sync/async mismatch errors; +- close behavior. + +### C2. Streaming mocks + +Allow mock responses with custom sync or async streams. Ensure single-consumption and close semantics are identical to network responses where applicable. + +### C3. Test utility independence + +Mock transport tests must not require a local socket server. They should be usable by downstream package fixtures in Phase 5. + +## Track D — WSGI transport + +### D1. Environ construction + +Implement the public WSGI transport with correct: + +- request method; +- script name and path info; +- query string; +- server name and port; +- URL scheme; +- WSGI version, threading, multiprocess, and run-once fields; +- input stream; +- error stream; +- header translation; +- remote address option. + +### D2. Start-response and body lifecycle + +Handle: + +- status parsing; +- duplicate response headers; +- `exc_info` behavior; +- iterable body streaming; +- iterable `close()`; +- application exceptions; +- body read and early close; +- request body input. + +### D3. App error policy + +Match the target's `raise_app_exceptions` behavior and response-generation policy for app failures. + +## Track E — ASGI transport + +### E1. Scope construction + +Implement HTTP ASGI scopes matching the reference for: + +- ASGI version/spec version; +- HTTP version; +- method; +- scheme; +- path and raw path; +- query string; +- headers as bytes pairs; +- server and client tuples; +- root path. + +### E2. Receive channel + +Stream request bodies through ASGI `receive` messages without eager buffering. Correctly emit `more_body`, disconnect behavior, and cancellation. + +### E3. Send channel + +Handle: + +- response start; +- multiple response body messages; +- empty chunks; +- completion; +- invalid message order; +- application exceptions; +- early client close; +- async response streaming. + +### E4. Backend compatibility + +The ASGI transport must operate under each async backend claimed by the compatibility stage. Avoid asyncio-specific futures inside a Trio run. + +## Track F — Event hooks + +### F1. Hook configuration + +Support client-level event hooks for request and response events, preserving list semantics and mutability where public. + +### F2. Sequencing + +Differentially establish: + +- whether request hooks run before auth, redirect, transport dispatch, and body send; +- whether response hooks run before body read in buffered methods; +- hook order across redirect chains; +- hook execution for retries where native retry features are used outside strict HTTPX parity; +- sync versus async hook requirements; +- behavior when hooks mutate request or response objects. + +### F3. Exceptions and cleanup + +Match propagation when a hook raises. Ensure transport response streams are closed when a response hook fails and no body/resource leak remains. + +## Track G — Extensions + +### G1. Request extension dictionary + +Preserve the public request `extensions` mapping through: + +- request construction; +- client merge/build; +- transport dispatch; +- redirects where the reference copies or changes values; +- response attachment. + +### G2. Standard extensions + +Support or preserve target-profile extensions used for: + +- timeout values; +- HTTP version and reason phrase metadata; +- network stream access where public; +- tracing callbacks; +- socket or transport metadata. + +Do not invent stable public semantics for undocumented internal extension keys. The profile should distinguish documented and observed-but-internal keys. + +### G3. Custom extension passthrough + +Unknown user extension keys must survive transport round trips according to the reference without being serialized onto the wire. + +## Track H — Authentication interfaces + +### H1. Public auth protocol + +Implement custom authentication flow contracts for sync and async use. Match the target's generator or flow behavior, including multiple request/response exchanges. + +Support: + +- request transformation; +- response challenge inspection; +- body access requirements; +- sync and async flow variants; +- auth object reuse across requests; +- thread/task safety expectations; +- redirect credential policy. + +### H2. Built-in auth + +Implement and validate target-profile built-ins, including at least: + +- basic auth; +- digest auth; +- netrc auth where public; +- tuple shorthand; +- explicit auth disable/override behavior. + +Bearer auth may remain an eggfetch-native convenience if it is not a public HTTPX built-in, but must not pollute the compatibility manifest. + +### H3. Digest correctness + +Test digest variants included by the target: + +- algorithms; +- qop modes; +- nonce count; +- stale challenges; +- repeated challenges; +- body hashing if required; +- quoted parameter parsing; +- redirect and cross-origin behavior. + +Use deterministic local challenge fixtures and compare emitted authorization fields after normalizing nonce-dependent values. + +### H4. Netrc security + +When environment trust permits netrc: + +- match lookup precedence; +- validate file permissions or errors according to the reference/platform; +- avoid logging credentials; +- isolate tests from the developer's real home directory; +- honor `trust_env=False`. + +## Track I — Proxy and environment parity + +### I1. Environment variables + +Complete measured behavior for: + +- HTTP, HTTPS, and all-proxy variables; +- lowercase and uppercase precedence; +- CGI safety behavior if applicable; +- `NO_PROXY` host, domain, IP, CIDR, port, and wildcard cases supported by the reference; +- percent-encoded credentials; +- malformed proxy URLs. + +### I2. Certificate environment + +Implement `SSL_CERT_FILE` and `SSL_CERT_DIR` behavior where supported by the target and Rust TLS stack. If a platform or rustls limitation prevents exact behavior, the allowed difference must block the relevant stage unless an equivalent safe implementation exists. + +### I3. Explicit versus environmental configuration + +Explicit constructor arguments must override or compose with environment settings exactly as measured. `trust_env=False` must disable proxy, certificate, and netrc environment discovery. + +## Track J — Low-level networking options + +### J1. Unix domain sockets + +Expose UDS through the low-level HTTP transport on supported platforms. Test host header behavior, URL scheme handling, connection reuse, error mapping, and unsupported-platform errors. + +### J2. Local address + +Support binding outbound sockets to the configured local address where included by the target. Test IPv4/IPv6 and invalid address behavior. + +### J3. Socket options + +If present in the pinned public target, support validated socket option tuples without allowing unsafe arbitrary memory interaction. Map platform errors clearly. + +## Track K — SOCKS optional support + +If HTTPX 0.28.1's optional SOCKS extra is included in the final Stage D contract, implement it behind an optional Python and Rust feature. + +Required coverage: + +- SOCKS5 and SOCKS5h name-resolution behavior; +- authentication; +- TCP connect timeout; +- proxy errors; +- TLS over SOCKS; +- environment and mounts integration; +- wheel extras and dependency policy. + +If deferred, record it as a Stage D blocker rather than silently excluding it from a full drop-in claim. + +## Track L — Async backend architecture + +### L1. Backend contract + +HTTPX operates through AnyIO-compatible asyncio and Trio environments. Define a compatibility backend layer that does not expose Tokio or asyncio implementation assumptions to user code. + +### L2. Asyncio path + +Retain the direct efficient Tokio/asyncio bridge where correct, but remove explicit construction of asyncio-only futures from compatibility objects when a backend-neutral awaitable can be used. + +### L3. Trio path + +Choose and document an implementation capable of: + +- Trio cancellation semantics; +- task-local context behavior; +- no blocking Trio run thread; +- async streaming producers and consumers; +- ASGI transport operation; +- timeout and close semantics; +- no orphan Tokio tasks after Trio cancellation. + +Potential designs include a dedicated shared Tokio service accessed through a backend-neutral portal, or a Rust future bridge integrated with Trio guest mode. A simple call to a blocking sync client in a worker thread is not acceptable for Stage D unless it passes the full semantics and performance envelope and is explicitly approved. + +### L4. Backend detection and errors + +Match the reference when async APIs are called outside an async context or with incompatible streams. Avoid importing optional backend packages unless needed. + +### L5. AnyIO test matrix + +Run the same async compatibility corpus under: + +- asyncio; +- asyncio with alternative loop policy where supported; +- Trio; +- cancellation and task-group fixtures. + +## Track M — CI and evidence + +Add required jobs for: + +- custom sync and async transports; +- mount routing; +- mock transport; +- WSGI transport; +- ASGI transport under asyncio; +- ASGI and network compatibility under Trio when implemented; +- event hooks; +- custom auth and digest; +- environment trust; +- UDS on Unix; +- SOCKS extra if included; +- built-wheel optional-extra smoke tests. + +Upload route traces, backend matrix summaries, and manifest deltas on failure. + +## Expected files + +Likely additions or changes include: + +- Python compatibility transport modules; +- Python compatibility auth modules; +- core connector support for UDS/local address/SOCKS; +- compatibility client mount and hook dispatch; +- request/response extension handling; +- `crates/eggfetch-python/tests/compat/test_transports.py`; +- `test_mounts.py`; +- `test_mock_transport.py`; +- `test_wsgi.py`; +- `test_asgi.py`; +- `test_hooks.py`; +- `test_auth.py`; +- `test_environment.py`; +- `test_backends.py`; +- optional dependency metadata; +- compatibility documentation; +- `plans/httpx-drop-in-phase-4-status.md`. + +## Acceptance criteria + +This phase is complete only when: + +- [ ] Public sync and async base transports match signatures and subclass behavior. +- [ ] Rust-backed HTTP transports support the pinned constructor options. +- [ ] User-supplied transport ownership and close behavior match the reference. +- [ ] Mount routing matches the reference priority corpus. +- [ ] Redirects reroute through mounts using the redirected URL. +- [ ] Mock transport supports sync, async, streaming, and exception cases. +- [ ] WSGI environ, response, iterable, close, and app-exception behavior match the target. +- [ ] ASGI scope, request messages, response messages, streaming, and app-exception behavior match the target. +- [ ] Event hooks run in the measured order and clean up resources when they fail. +- [ ] Request and response extensions survive every public compatibility path. +- [ ] Custom sync and async authentication flows work without private eggfetch APIs. +- [ ] Basic, digest, and netrc auth meet the pinned compatibility corpus. +- [ ] Environment proxy and no-proxy behavior matches the target profile. +- [ ] `trust_env=False` disables proxy, certificate, and netrc discovery. +- [ ] UDS and local-address support pass on supported platforms. +- [ ] SOCKS support is implemented and tested or remains an explicit blocker to Stage D. +- [ ] Asyncio compatibility tests pass without leaked tasks or backend-specific public objects. +- [ ] Trio compatibility tests pass for requests, streaming, cancellation, ASGI, auth, and close. +- [ ] The async API does not block the active event-loop or Trio run thread. +- [ ] Optional dependencies are isolated behind documented extras and wheel smoke tests. +- [ ] Phase 4 required manifest deltas are zero or explicitly stage-blocking. +- [ ] `plans/httpx-drop-in-phase-4-status.md` links exact backend, transport, and CI evidence. + +## Handoff notes + +This is the largest architectural phase. Implement it incrementally behind the compatibility module and keep native eggfetch paths stable. Do not route custom transports through serialized method/URL calls; transports must receive the full compatibility `Request` with its stream and extensions intact. Backend support must be proven with cancellation and streaming, not only a single successful GET. From 7e02666835bd31c33543a4981765dab6109eaf19 Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:20:54 -0400 Subject: [PATCH 7/8] plans: add downstream compatibility validation phase --- ...x-drop-in-phase-5-downstream-validation.md | 430 ++++++++++++++++++ 1 file changed, 430 insertions(+) create mode 100644 plans/httpx-drop-in-phase-5-downstream-validation.md diff --git a/plans/httpx-drop-in-phase-5-downstream-validation.md b/plans/httpx-drop-in-phase-5-downstream-validation.md new file mode 100644 index 00000000..3267b96e --- /dev/null +++ b/plans/httpx-drop-in-phase-5-downstream-validation.md @@ -0,0 +1,430 @@ +# HTTPX Drop-In Phase 5: Downstream Compatibility and Substitution Validation + +Status: ready for implementation handoff + +## Purpose + +Prove that the compatibility layer works for real HTTPX consumers, not only for hand-selected eggfetch tests. + +This phase expands the pinned manifest and differential oracle into a representative substitution program. It runs unmodified consumer code, exercises framework test clients, mock and custom transports, SDK patterns, streaming, proxying, custom auth, and error handling, and validates package substitution in clean environments. + +A passing native suite is not sufficient. A passing API manifest is not sufficient. The exit criterion is evidence that representative downstream users can run without eggfetch-specific branches. + +## Dependencies + +Phase 0 provides the oracle and allowed-difference policy. Phase 1 provides production semantics. Phase 2 provides the object model and client surface. Phase 3 provides streaming. Phase 4 provides transports, extensions, auth, and backend behavior. + +Phase 5 fixtures may be added incrementally earlier, but this phase cannot close until the required prior-phase gates are green. + +## Non-goals + +- Claiming compatibility with every package that imports private HTTPX internals. +- Modifying downstream packages to recognize eggfetch-specific types. +- Treating monkeypatches that alter assertions as successful compatibility. +- Running arbitrary untrusted downstream test suites with production credentials or network access. +- Depending on live public endpoints for required CI. +- Chasing unpinned latest versions on every CI run. +- Benchmark optimization that weakens correctness. + +## Deliverables + +1. A versioned downstream compatibility inventory. +2. A broad deterministic HTTPX differential behavior corpus. +3. Selected upstream HTTPX public-contract tests or equivalent derived cases. +4. Pinned representative downstream package suites run unmodified. +5. Clean-environment substitution and import-origin tests. +6. Compatibility resource and performance budgets. +7. A machine-readable downstream evidence report. +8. A compatibility-stage decision document. +9. A phase status file. + +## Track A — Define the downstream compatibility portfolio + +### A1. Consumer categories + +Select at least one maintained, pinned representative for each applicable category: + +- ordinary synchronous API client; +- ordinary asyncio API client; +- framework test client using ASGI transport; +- WSGI test client or integration; +- mock transport user; +- custom transport subclass; +- event-hook instrumentation; +- custom auth flow; +- streaming upload and download; +- proxy and environment configuration; +- HTTP/2-capable consumer; +- SDK that inspects request/response exceptions; +- package using `base_url`, params, headers, cookies, and timeouts heavily; +- Trio/AnyIO consumer for Stage D. + +Do not choose only trivial clients that call `httpx.get()`. + +### A2. Selection criteria + +Each fixture must record: + +- package and exact version; +- license; +- why it represents a compatibility category; +- public versus private HTTPX usage; +- test subset executed; +- expected network isolation; +- optional dependencies; +- known incompatibilities; +- update owner and review cadence. + +Prefer packages that use documented public APIs. A package that relies on private internals may be included as informational evidence but cannot define the public contract automatically. + +### A3. Pinning and updates + +Commit lock files or exact constraints for downstream fixtures. Updates require a dependency-delta review and must not silently change compatibility acceptance. + +Add scheduled discovery that reports newer versions without updating required CI automatically. + +## Track B — Expand the behavior corpus + +### B1. Request construction cases + +Cover: + +- all methods and arbitrary methods; +- base URL resolution; +- repeated query parameters; +- duplicate headers; +- cookies and conflicts; +- all body types; +- auto headers; +- explicit host and content headers; +- auth and auth disable; +- timeout and extensions; +- invalid inputs and exception classes. + +### B2. Redirect cases + +Cover status-specific method and body handling for 301, 302, 303, 307, and 308, including: + +- relative and absolute locations; +- scheme-relative locations; +- malformed locations; +- fragments; +- cross-origin auth stripping; +- cookie updates; +- proxy/mount rerouting; +- history bodies; +- maximum redirects; +- non-replayable streams; +- total timeout budget. + +### B3. Protocol and body cases + +Cover: + +- HTTP/1.0 and HTTP/1.1; +- keep-alive and close; +- chunked bodies; +- content length mismatch; +- interim responses where supported; +- HTTP/2 negotiation and multiplexing; +- connection close at each protocol point; +- compressed and multiply encoded bodies where supported; +- malformed encodings; +- slow headers, slow chunks, and stalled uploads; +- early consumer close. + +### B4. TLS and proxy cases + +Cover: + +- trusted and untrusted roots; +- hostname mismatch; +- custom CA; +- client certificates; +- minimum/maximum TLS policy where exposed; +- HTTP proxy forwarding; +- CONNECT; +- proxy auth; +- environment proxies; +- `NO_PROXY` cases; +- SOCKS when included; +- proxy and origin failures separately. + +### B5. Transport and extension cases + +Cover: + +- custom sync and async transports; +- mounts and route priority; +- mock transport; +- WSGI and ASGI; +- hooks and hook failures; +- custom extensions; +- custom auth multi-exchange flows; +- backend cancellation. + +### B6. Exception normalization + +For every failure case compare: + +- class; +- superclass relationships; +- message after approved normalization; +- request attachment; +- response attachment; +- URL and method context; +- cause/context behavior where public; +- resource cleanup. + +## Track C — Upstream HTTPX test leverage + +### C1. Inventory upstream tests + +At the pinned HTTPX tag, classify tests into: + +- public contract and suitable to run unchanged; +- public contract requiring only fixture adaptation; +- httpcore-internal and not applicable; +- packaging or implementation-internal; +- private behavior intentionally excluded. + +Record license attribution and source commit. + +### C2. Run unchanged where possible + +Prefer executing selected tests against an import-substituted compatibility package with no assertion changes. + +Allowed harness changes include: + +- selecting the package under test through environment or isolated installation; +- providing equivalent local certificate fixtures; +- adapting test collection paths; +- excluding explicitly classified private implementation tests. + +Do not rewrite expected values. + +### C3. Derived cases + +Where an upstream test is too coupled to HTTPX internals but describes a public behavior, reproduce the behavior in the repository's own differential schema and cite the source test identifier in fixture metadata. + +### C4. Coverage report + +Generate a report showing which public HTTPX modules, symbols, and behavior categories are covered by upstream-derived or local tests. Uncovered required symbols must block the stage or receive an explicit plan. + +## Track D — Unmodified downstream suites + +### D1. Isolation + +Run each downstream fixture in an isolated environment with: + +- no upstream HTTPX installed when testing the compatibility distribution; +- no live credentials; +- network disabled except deterministic local fixtures; +- temporary home/config directories; +- sanitized proxy and certificate environment; +- strict time limits; +- captured package and import metadata. + +### D2. No source modifications + +The downstream package source and tests must remain byte-identical to the pinned fixture, except for a generic package-under-test selection mechanism that does not contain eggfetch-specific behavior. + +Patches that change expected exception types, skip failures, or branch on eggfetch are prohibited for required evidence. + +### D3. Framework test clients + +Include representative use of: + +- Starlette/FastAPI-style test client integration where compatible versions use HTTPX public APIs; +- ASGI lifespan policy if the target transport does or does not handle it; +- streaming request/response tests; +- app exception propagation; +- base URL and client-address configuration. + +### D4. SDK fixtures + +Select SDKs that exercise: + +- sync and async clients; +- streaming responses; +- multipart uploads; +- custom timeouts and limits; +- request/response exception inspection; +- retry behavior implemented above the HTTP layer; +- event hooks or custom transports where available. + +Mock remote APIs locally. Do not use production service credentials. + +### D5. Mocking ecosystem + +Test at least one public-API mocking pattern. If common mocking packages rely primarily on private HTTPX internals, classify that explicitly and decide whether public transport compatibility is sufficient or a narrow optional adapter is justified. + +## Track E — Package substitution strategy tests + +### E1. Compatibility module mode + +Test consumers with an explicit compatibility import mode during development, such as import injection or a dedicated module path, while preserving consumer code otherwise. + +### E2. Top-level compatibility distribution + +Once Phase 5 is near closure, build a separate candidate distribution that provides the `httpx` top-level module. + +Validate: + +- installation into a clean environment without upstream HTTPX; +- declared conflict or mutually exclusive install policy; +- `import httpx` origin points to the compatibility distribution; +- emulated HTTPX version is available where consumers inspect it; +- eggfetch implementation version is separately available; +- uninstall removes the shim cleanly; +- installing upstream HTTPX afterward fails clearly or replaces the shim according to documented package-manager behavior; +- ordinary `eggfetch` installation does not shadow `httpx`. + +### E3. Metadata and dependency resolution + +Test pip resolution for: + +- a package requiring `httpx>=0.27,<0.29`; +- direct compatibility-distribution installation; +- extras such as HTTP/2, SOCKS, or CLI where relevant; +- editable and wheel installs; +- constraints files; +- uninstall/reinstall cycles. + +A distribution with a different project name may not satisfy a dependency declared on `httpx` automatically. Document this packaging limitation honestly and determine whether an explicit replacement workflow, wheel name, or controlled environment image is required. Do not claim transparent dependency resolution unless it is proven. + +## Track F — Compatibility performance and resource budgets + +### F1. Purpose + +Performance is not the primary parity oracle, but catastrophic regressions can make an otherwise compatible client unusable. + +Measure eggfetch compatibility mode against pinned HTTPX for: + +- import time; +- client construction; +- one-shot request; +- reused HTTP/1.1 request; +- HTTP/2 multiplexing; +- small and large body throughput; +- sync and async streaming; +- multipart upload; +- proxy request; +- mock/ASGI transport overhead; +- memory and allocations; +- threads and tasks. + +### F2. Budgets + +Commit threshold policy that distinguishes: + +- correctness blockers; +- severe regression blockers; +- informational differences; +- expected Rust-engine advantages. + +Do not require eggfetch to beat HTTPX in every microbenchmark. Require no unbounded resource growth and no unacceptable compatibility-facade overhead. + +### F3. Reproducibility + +Record hardware/runner class, Python version, build profile, warmup, sample count, confidence interval, and baseline commit. Avoid comparing noisy shared-runner values with narrow thresholds. + +## Track G — Failure triage and allowed differences + +### G1. Stable failure IDs + +Every downstream or differential failure must map to: + +- compatibility case ID; +- public symbol or behavior; +- roadmap phase owner; +- severity; +- stage impact; +- allowed-difference record if approved. + +### G2. No blanket skips + +Do not skip an entire downstream suite because one optional feature is missing. Split profiles or mark individual cases with machine-readable policy. + +### G3. Flake policy + +A flaky compatibility test is a test defect or product defect to investigate. Required jobs must not use unrestricted retries. If one rerun is temporarily allowed for diagnosis, retain both attempts and keep the gate failed until the cause is resolved or a time-bounded quarantine is approved. + +## Track H — Evidence report + +Generate `compatibility-evidence.json` containing: + +- schema version; +- eggfetch commit and package version; +- reference HTTPX version; +- compatibility stage under evaluation; +- platform/Python/backend matrix; +- API manifest summary; +- differential case totals and failures; +- upstream test inventory and result; +- downstream package versions and results; +- package substitution result; +- resource/performance summary; +- allowed differences; +- overall pass determined fail-closed. + +Also generate a concise Markdown report for review. + +## Track I — Compatibility-stage decision + +At phase end, write a decision record stating the highest justified stage: + +- Stage A: production-grade eggfetch; +- Stage B: HTTPX-compatible network subset; +- Stage C: asyncio drop-in; +- Stage D: full supported drop-in. + +The decision must list blockers to the next stage and must be generated from evidence, not roadmap completion labels. + +## Expected files + +Likely additions include: + +- `compat/downstream/manifest.toml`; +- per-package fixture metadata and lock files; +- `compat/httpx/0.28.1/behavior-cases/`; +- scripts to create isolated environments and run fixtures; +- selected upstream test inventory; +- compatibility report generators; +- benchmark compatibility profiles; +- CI workflow jobs or reusable workflows; +- `docs/reference/downstream-compatibility.md`; +- `plans/httpx-drop-in-phase-5-status.md`; +- a compatibility-stage decision record. + +## Acceptance criteria + +This phase is complete only when: + +- [ ] A versioned downstream portfolio covers every required consumer category. +- [ ] Every fixture records exact package version, license, public API use, and test scope. +- [ ] Required fixtures run without live public network or credentials. +- [ ] The differential corpus covers request construction, redirects, protocol failures, TLS, proxies, streaming, transports, hooks, auth, and cancellation. +- [ ] Exception class and context are compared for every failure case. +- [ ] Public-contract tests from the pinned HTTPX source are inventoried and appropriately reused or derived. +- [ ] Public API coverage has no unexplained required gaps. +- [ ] Representative sync and asyncio consumers run unmodified. +- [ ] Framework test-client fixtures pass with unmodified consumer code. +- [ ] Mock/custom transport fixtures pass with unmodified consumer code. +- [ ] Streaming and multipart SDK fixtures pass with unmodified consumer code. +- [ ] Exception-inspecting SDK fixtures receive compatible request and response context. +- [ ] Trio/AnyIO downstream fixtures pass before Stage D is claimed. +- [ ] No required fixture branches on eggfetch or changes expected assertions. +- [ ] Clean-environment compatibility-module substitution succeeds. +- [ ] The top-level compatibility distribution installs and imports according to documented policy. +- [ ] Ordinary eggfetch installation never shadows upstream `httpx`. +- [ ] Dependency-resolution limitations are explicitly proven and documented. +- [ ] Compatibility mode has committed resource and severe-regression budgets. +- [ ] Required compatibility jobs do not use blanket skips or unrestricted reruns. +- [ ] `compatibility-evidence.json` is generated and fails closed. +- [ ] A compatibility-stage decision is committed and matches the evidence. +- [ ] `plans/httpx-drop-in-phase-5-status.md` links exact CI, fixture, manifest, and package evidence. + +## Handoff notes + +Choose the downstream portfolio for breadth of public API behavior, not brand recognition. A few large SDKs that all use the same simple `AsyncClient.post(json=...)` pattern provide less evidence than a smaller set spanning transports, test clients, streaming, auth, hooks, proxies, exceptions, and multiple async backends. From 43a62f53e97b26cc649aad606b67c90f37d94c83 Mon Sep 17 00:00:00 2001 From: David Bowman Date: Tue, 21 Jul 2026 15:22:35 -0400 Subject: [PATCH 8/8] plans: add compatibility release qualification phase --- ...x-drop-in-phase-6-release-qualification.md | 532 ++++++++++++++++++ 1 file changed, 532 insertions(+) create mode 100644 plans/httpx-drop-in-phase-6-release-qualification.md diff --git a/plans/httpx-drop-in-phase-6-release-qualification.md b/plans/httpx-drop-in-phase-6-release-qualification.md new file mode 100644 index 00000000..f3d3c11c --- /dev/null +++ b/plans/httpx-drop-in-phase-6-release-qualification.md @@ -0,0 +1,532 @@ +# HTTPX Drop-In Phase 6: Compatibility Release Qualification + +Status: ready for implementation handoff + +## Purpose + +Convert a passing implementation and downstream compatibility program into defensible, immutable release evidence for the exact compatibility stage claimed. + +This phase does not assume that completion of the earlier implementation phases automatically authorizes a drop-in claim. It validates built artifacts, packaging and import behavior, security and resource properties, supported platforms, compatibility manifests, canary operation, and rollback procedures against one frozen candidate commit. + +## Dependencies + +The intended release stage determines prerequisites: + +- Stage A requires Phase 1 plus production validation. +- Stage B requires Phases 0 through 3 and the relevant Phase 5 evidence. +- Stage C requires Phases 0 through 5 for asyncio and extension surfaces. +- Stage D requires all prior phases, including supported Trio/AnyIO and optional-extra decisions. + +The release workflow and required CI gate must be green before an immutable candidate dry run is accepted. + +## Non-goals + +- Publishing before dry-run evidence is complete. +- Expanding API or protocol scope during release qualification. +- Changing compatibility target from HTTPX 0.28.1. +- Waiving a failed supported platform without updating support claims and restarting qualification. +- Treating source-tree tests as artifact tests. +- Claiming full drop-in behavior when packaging cannot transparently satisfy downstream dependency resolution. +- Enabling experimental HTTP/3 as a compatibility default. + +## Deliverables + +1. Final compatibility packaging and import policy. +2. Version and compatibility metadata policy. +3. Built artifact matrix and clean-install smoke suite. +4. Immutable compatibility and production evidence manifests. +5. Security, fuzzing, fault-injection, and soak evidence. +6. Platform and Python support evidence. +7. Canary deployment and rollback procedure. +8. Documentation and package metadata aligned to the achieved stage. +9. A successful immutable non-publishing release dry run. +10. A release decision and phase status file. + +## Track A — Finalize package architecture + +### A1. Native distribution + +Keep `eggfetch` as the primary native distribution and top-level module. It may expose eggfetch-native additions and a stable compatibility submodule. + +Validate that ordinary installation: + +- never creates a top-level `httpx` module; +- does not conflict with upstream HTTPX; +- supports using eggfetch and upstream HTTPX in the same environment; +- reports the native eggfetch version accurately; +- includes the compatibility profile and runtime version helpers needed by users. + +### A2. Compatibility distribution + +If the achieved stage justifies a top-level substitution distribution, define a separate artifact, for example an explicitly named replacement package that installs the `httpx` module. + +The final name and metadata must be reviewed against package-index policy. The design must account for the fact that a differently named distribution does not automatically satisfy another package's dependency on the project name `httpx`. + +The release decision must distinguish: + +- import drop-in after explicit environment preparation; +- source drop-in after changing one import; +- transparent package dependency replacement; +- fully transparent installation replacement. + +Only claim the level actually proven. + +### A3. Conflict policy + +Prove behavior when: + +- upstream HTTPX is already installed; +- compatibility distribution is installed first; +- either package is upgraded; +- either package is uninstalled; +- editable installs are involved; +- user-site packages shadow virtual-environment packages; +- zipapp or packaged application environments are used where supported. + +Do not permit two distributions to write the same top-level files silently. + +### A4. Import-origin diagnostics + +Expose a safe runtime diagnostic showing: + +- compatibility provider; +- eggfetch implementation version; +- emulated HTTPX version/profile; +- native extension build/version; +- active compatibility stage. + +Do not overload `httpx.__version__` with the eggfetch implementation version if consumers expect the emulated HTTPX version. Provide a separate implementation-version attribute or module. + +## Track B — Versioning and compatibility metadata + +### B1. Version dimensions + +Maintain separate dimensions for: + +- eggfetch release version; +- Rust crate versions; +- native extension version; +- compatibility profile version; +- emulated HTTPX version; +- compatibility stage; +- evidence schema version. + +Define which changes require major, minor, or patch increments under the pre-1.0 and post-1.0 policy. + +### B2. Compatibility manifest + +Generate a signed or checksummed immutable manifest containing: + +- candidate SHA; +- eggfetch version; +- emulated HTTPX version; +- achieved stage; +- supported Python versions; +- supported platforms and architectures; +- supported async backends; +- supported optional extras; +- public API comparator totals; +- differential behavior totals; +- downstream fixture results; +- allowed differences; +- known limitations; +- build workflow and run IDs; +- artifact hashes; +- generation timestamp. + +The manifest's overall pass must be computed fail-closed. + +### B3. Runtime compatibility query + +Provide a supported API or metadata file allowing applications to determine the compatibility profile without parsing documentation. + +## Track C — Artifact matrix + +### C1. Python artifacts + +Define and build the declared matrix for: + +- Python 3.10 through 3.13 or the then-approved support range; +- Linux x86_64; +- Linux aarch64 if claimed; +- macOS x86_64; +- macOS arm64; +- Windows x86_64; +- source distribution; +- optional compatibility distribution artifacts; +- optional extras that alter native dependencies. + +If abi3 is adopted, prove compatibility on every declared interpreter rather than assuming one wheel tag is sufficient. + +### C2. Rust and CLI artifacts + +Continue validating publishable Rust crates and native CLI artifacts, but keep HTTPX compatibility qualification focused on Python artifacts. Cross-language releases must identify whether they share the same candidate SHA. + +### C3. Artifact provenance + +For every artifact record: + +- filename; +- target and Python tag; +- size; +- SHA-256; +- build job and run attempt; +- candidate SHA; +- toolchain versions; +- SBOM or package dependency manifest; +- signature/attestation status; +- smoke-test result. + +### C4. No post-candidate changes + +Any release-relevant change after the validated candidate SHA requires a new candidate and complete rerun. Documentation that changes the compatibility claim is release relevant. + +## Track D — Clean-install artifact smoke tests + +### D1. Native eggfetch wheel + +Install each built wheel into a new environment and test: + +- import and version; +- native compatibility submodule; +- sync and async request; +- HTTP/1.1 and HTTP/2 where available; +- timeout and limits; +- TLS verification; +- proxy; +- cookies and auth; +- streaming upload and download; +- multipart; +- close and interpreter shutdown; +- coexistence with upstream HTTPX. + +### D2. Compatibility wheel + +For each compatibility wheel, test: + +- `import httpx` origin; +- public API manifest from installed files; +- representative request and response behavior; +- transport, ASGI, WSGI, mock, hooks, auth, and backend extras required by the stage; +- downstream fixture subset; +- version/profile diagnostics; +- uninstall cleanliness; +- upstream conflict behavior. + +### D3. Source distribution + +Build wheels from the sdist in an isolated environment without repository files. Run the required smoke subset and compare generated artifact metadata to directly built wheels. + +### D4. Package content + +Reject: + +- source tests or corpora not intended for distribution; +- secrets or local paths; +- duplicate native libraries; +- unexpected top-level modules; +- stale compatibility manifests; +- generated artifacts with mismatched versions; +- missing type information or marker files if promised; +- non-deterministic file ownership between distributions. + +## Track E — Security qualification + +### E1. Dependency policy + +Run and retain: + +- Rust advisory audit; +- dependency license/source policy; +- Python dependency audit; +- lockfile review; +- SBOM generation; +- action pin verification; +- artifact provenance checks. + +A known advisory requires an explicit severity and exposure decision. Critical reachable advisories block release. + +### E2. Compatibility threat review + +Review at least: + +- environment proxy injection; +- netrc credential discovery; +- redirect credential stripping; +- URL display redaction; +- proxy authorization leakage; +- TLS verify/cert combinations; +- custom transport trust boundary; +- WSGI/ASGI app exception handling; +- event-hook secret exposure; +- request/response exception reprs; +- decompression and stream limits; +- SOCKS credential handling; +- compatibility distribution shadowing and dependency confusion. + +### E3. Fuzzing + +Run relevant fuzz targets for a defined budget and candidate SHA, including: + +- URLs and query parameters; +- headers; +- cookies; +- redirect locations; +- proxy URLs and no-proxy matching; +- auth challenges; +- multipart encoding; +- content decoding; +- timeout and stream state machines; +- transport routing patterns; +- compatibility manifest parsing. + +No reproducible crash, panic, memory-safety issue, credential leak, or unbounded allocation may remain open. + +### E4. Malformed peer tests + +Retain candidate evidence for malformed HTTP/1.1, HTTP/2, TLS, proxy, compression, and stream behavior. The client must fail safely and release resources. + +## Track F — Resource, concurrency, and soak qualification + +### F1. Required short profiles + +Run on every release candidate: + +- repeated client create/close; +- repeated connection failure; +- timeout/cancellation churn; +- concurrent sync thread use; +- concurrent asyncio task use; +- concurrent Trio use for Stage D; +- many active streams; +- early-close streams; +- proxy and TLS churn; +- ASGI/mock transport churn. + +### F2. Long soak profiles + +Run defined-duration workloads for: + +- keep-alive HTTP/1.1; +- HTTP/2 multiplexing; +- mixed-origin traffic; +- streaming uploads/downloads; +- cancellation under load; +- proxy traffic; +- repeated auth challenges; +- downstream SDK workload; +- compatibility distribution import/client churn. + +### F3. Stability thresholds + +Commit thresholds for: + +- resident memory trend; +- open descriptors/handles; +- threads; +- runtime tasks; +- active connections; +- pool permits/waiters; +- request latency percentiles; +- error-rate consistency; +- shutdown duration. + +A plateau within a defined envelope is required. Merely avoiding process failure is insufficient. + +## Track G — Performance qualification + +### G1. Regression baseline + +Compare the candidate to: + +- the previous eggfetch release; +- the approved Phase 5 baseline; +- pinned HTTPX for contextual comparison. + +### G2. Required workloads + +Include: + +- import and startup; +- one-shot sync request; +- reused sync request; +- concurrent async requests; +- HTTP/2 multiplexing; +- streaming throughput; +- multipart upload; +- proxy; +- mock and ASGI transport; +- custom auth; +- object construction and URL/query operations. + +### G3. Gate policy + +Fail on severe regression relative to the previous approved eggfetch baseline. Do not fail solely because a microbenchmark is slower than HTTPX if the committed product budget is satisfied. + +## Track H — Canary and operational validation + +### H1. Canary applications + +Run the candidate in controlled applications representing: + +- sync service worker; +- asyncio service; +- framework test suite; +- streaming client; +- proxy-enabled client; +- SDK consumer; +- Trio consumer for Stage D. + +### H2. Observability + +Collect: + +- request counts and errors; +- timeout classes; +- connection reuse indicators; +- resource metrics; +- shutdown behavior; +- compatibility fallback or unsupported-surface errors; +- performance relative to the existing client. + +### H3. Rollback criteria + +Define immediate rollback triggers, including: + +- credential leakage; +- TLS validation regression; +- deadlock or process hang; +- unbounded resource growth; +- materially elevated timeout/error rate; +- downstream incompatibility not present in qualification; +- package import conflict. + +Canary evidence must identify candidate SHA and artifact hashes. + +## Track I — Documentation and claims + +### I1. Stage-specific language + +Use only the achieved claim: + +- `production-grade eggfetch client`; +- `HTTPX-compatible network-client subset`; +- `HTTPX-compatible asyncio drop-in`; +- `HTTPX 0.28.1-compatible drop-in for the supported profile`. + +Avoid unqualified `full HTTPX replacement` unless Stage D passes with no stage-blocking differences. + +### I2. Compatibility documentation + +Publish: + +- target HTTPX version; +- supported modules and extras; +- backend support; +- packaging/import procedure; +- allowed differences; +- unsupported private APIs; +- migration and rollback instructions; +- runtime profile diagnostic; +- security implications of `trust_env`, proxies, netrc, and verification options. + +### I3. Classifiers and metadata + +Update development-status classifiers only when the release evidence supports them. Ensure project descriptions do not overstate compatibility. + +## Track J — Immutable release dry run + +### J1. Freeze candidate + +Select one full candidate SHA after required CI is green. Use an immutable non-publishing validation ref. Verify every job checks out the same commit. + +### J2. Run with publishing disabled + +The dry run must build and validate every declared artifact while being technically unable to publish to package registries or create the final release/tag. + +### J3. Aggregate evidence + +Produce a final release evidence bundle containing: + +- compatibility manifest; +- production resource report; +- API and behavior comparator reports; +- downstream evidence; +- artifact hashes and SBOMs; +- security and fuzz reports; +- platform smoke results; +- canary report; +- CI job result map; +- overall pass. + +### J4. Prove no side effects + +Record that no package, release, final tag, or production deployment occurred because of the dry run. + +## Track K — Release decision + +Create a decision record with: + +- candidate SHA; +- requested version; +- achieved compatibility stage; +- exact claim text approved for release; +- all allowed differences; +- all unsupported surfaces; +- artifact/platform coverage; +- canary outcome; +- known risks; +- rollback owner and procedure; +- approve or reject decision. + +A rejected candidate is a valid outcome and must not be relabeled as a partial success release. + +## Expected files + +Likely changes or additions include: + +- compatibility distribution packaging metadata; +- runtime compatibility-profile module; +- release and CI workflows; +- artifact smoke scripts; +- compatibility and release evidence generators; +- security/fuzz/soak scripts and reports; +- package conflict tests; +- release documentation; +- canary runbook; +- compatibility-stage decision record; +- `plans/httpx-drop-in-phase-6-status.md`. + +## Acceptance criteria + +This phase is complete only when: + +- [ ] Native eggfetch and upstream HTTPX coexist cleanly in one environment. +- [ ] Ordinary eggfetch installation never shadows the `httpx` module. +- [ ] The compatibility distribution has a tested, explicit conflict and replacement policy. +- [ ] Runtime diagnostics report provider, implementation version, emulated version, profile, and stage. +- [ ] Version fields across crates, Python packages, extension, profile, and release input are consistent. +- [ ] The compatibility manifest is immutable, checksummed, and fail-closed. +- [ ] Every declared Python/platform artifact is built from the same candidate SHA. +- [ ] Every wheel passes clean-install native and compatibility smoke tests appropriate to its stage. +- [ ] The sdist builds and passes smoke tests without repository-only files. +- [ ] Package contents contain no unexpected top-level modules, secrets, stale manifests, or duplicate native libraries. +- [ ] Artifact hashes, SBOMs, provenance, toolchains, and smoke results are recorded. +- [ ] Rust and Python dependency security checks satisfy release policy. +- [ ] Compatibility threat review has no unresolved release-blocking finding. +- [ ] Candidate fuzz runs have no unresolved reproducible failure. +- [ ] Malformed peer tests fail safely and release resources. +- [ ] Required concurrency and cancellation profiles stay within committed limits. +- [ ] Long soak profiles plateau within memory, descriptor, thread, task, and connection thresholds. +- [ ] Severe performance regressions against the approved eggfetch baseline are absent. +- [ ] Canary applications pass without rollback triggers. +- [ ] Documentation and metadata use only the achieved compatibility-stage claim. +- [ ] One complete immutable non-publishing release dry run is green. +- [ ] The evidence bundle reports overall pass and is internally consistent. +- [ ] No release-relevant changes exist after the validated candidate SHA. +- [ ] A release decision explicitly approves or rejects the candidate and records the exact claim. +- [ ] `plans/httpx-drop-in-phase-6-status.md` links all immutable evidence and workflow runs. + +## Handoff notes + +The final claim should be narrower than the evidence only by choice, never broader. Packaging constraints are part of drop-in compatibility: matching Python behavior does not make a differently named distribution transparently satisfy dependencies on `httpx`. The release decision must state exactly what substitution workflow is supported.