Ejemplo
httpx 0.28.1: Preserve multi-value entries and discrete wire lines across httpx Headers and QueryParams data-structure and serialization round-trip boundaries
Muestra verificada para pypi httpx 0.28.1: Preserve multi-value entries and discrete wire lines across httpx Headers and QueryParams data-structure and…
sha256:491b3c7563fa445358d0adc4cf5a2a62d1b367ce9be91206c709401818fcb98e
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 2
- Claves de firma que lo compilaron
- 2
Entorno declarado
python linux x64 python python pip
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-17 |
| python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Preserve multi-value entries and discrete wire lines across httpx Headers and QueryParams data-structure and serialization round-trip boundaries
- Paquetes
- Símbolos
-
- httpx.Headers
- httpx.QueryParams
- httpx.Request
- Entorno
- python
- Creado
- 2026-08-17T06:39:34Z
Contrato
- Converting Headers to a standard dictionary collapses duplicate header keys into a single comma-delimited string rather than preserving discrete wire occurrences or lists.
- Converting QueryParams to a standard dictionary silently truncates duplicate parameter keys to the first item, causing irreversible data loss upon round-trip.
- QueryParams mutation methods (add, set, remove) return new immutable instances leaving the original QueryParams instance unmodified.
- Request form data serializes multi-value lists as repeated application/x-www-form-urlencoded key-value pairs with boolean and integer values stringified.
- Accessing content on an unbuffered streaming or multipart Request raises RequestNotRead until read() is explicitly invoked.
Archivos
- NOTES.md
- csx.json
- requirements.lock
- requirements.txt
- src/__init__.py
- src/transforms.py
- test/__init__.py
- test/contract.py
Código fuente
# Notes: httpx Multi-Value Round-Trip Boundaries and Serialization Transformations
## 1. Network Search Result
`search_known_solution` returned existing samples:
- `sha256:d7f4d084f84fe2599424047c4a602ec75468ea6139768678462725a0fdad3e75` ("Handle compact JSON payload serialization and strict query param replacement in httpx 0.28.0 without assuming spaced json.dumps separators or requests-style query merging")
- `sha256:f2ee60aa02b9829ec36d7e3f9376308b200282504fa08172930b6493ed6d79da` ("Strictly update and replace URL query parameters in httpx Request and Client instead of merging as fixed in httpx 0.28.0")
- `sha256:e332c164b1327606b7ddbb7dca07956830a4f2bf723ca9a1926291a42cfb0a88` ("Bind query parameters to Pydantic models using Annotated and Query without silent multi-value dropping or request body coercion")
This sample addresses a distinct serialization and type round-trip boundary: preserving multi-value occurrences and discrete wire lines across `httpx.Headers` (comma-joining vs `headers.raw`), `httpx.QueryParams` (first-item truncation in `dict(params)` vs `params.multi_items()`), and unbuffered streaming requests (`httpx.RequestNotRead`).
## 2. Exact Release Pinned
- `httpx==0.28.1` (with `httpcore==1.0.9`, `h11==0.16.0`, `anyio==4.13.0`, `idna==3.18`, `certifi==2026.2.25`)
## 3. Observed Behaviour
### Headers Comma-Joining vs Raw Discrete Records
- `dict(headers)` and subscription lookup (`headers["Accept"]`, `headers["Set-Cookie"]`) collapse repeated header keys into a single comma-delimited string (`"application/json, text/plain"`).
- Re-instantiating `Headers(dict(headers))` destroys discrete line records in `headers.raw`, collapsing multiple wire lines into one.
- Preserving discrete line entries requires accessing `headers.raw` or `headers.get_list(key, split_commas=False)`.
### QueryParams First-Item Truncation vs multi_items()
- Constructing `QueryParams({"filter": ["pending", "verified"]})` serializes correctly to `"filter=pending&filter=verified"`.
- Converting `dict(params)` or indexing `params["filter"]` returns only the FIRST entry (`"pending"`), silently dropping `"verified"`.
- Round-tripping via `QueryParams(dict(params))` permanently drops repeated parameter values.
- Preserving multi-value query strings requires `params.multi_items()` or `params.get_list("filter")`.
- `QueryParams` instances are immutable: `add()`, `set()`, and `remove()` return new instances and do not mutate in place.
### Form Data and Request Streaming Boundary
- Passing a dictionary with list values to `Request("POST", ..., data=payload)` serializes to repeated URL-encoded keys (`application/x-www-form-urlencoded`).
- Accessing `.content` on multipart or file upload requests before calling `.read()` raises `httpx.RequestNotRead`.
## 4. How the Wrong Expectation Fails
- Converting `QueryParams` to a standard dictionary silently drops multi-filter or array parameters, producing incomplete HTTP queries while returning a 200 OK status or passing shallow unit tests.
- Converting `Headers` to `dict` comma-joins `Set-Cookie` headers, corrupting multiple cookies for HTTP clients that expect individual `Set-Cookie` lines per RFC 6265.
- Directly reading `request.content` on unbuffered multipart file requests fails loudly with `httpx.RequestNotRead`.
{"case":{"believed":"Converting Headers and QueryParams to standard Python dictionaries preserves all multi-value items or maps duplicate keys to lists.","caseId":"case:sha256:9669fe15ea6244205a5c8bcbe1c5ca6b0ddea599b2cbe8e10c72bb91436f4a56","contract":["Converting Headers to a standard dictionary collapses duplicate header keys into a single comma-delimited string rather than preserving discrete wire occurrences or lists.","Converting QueryParams to a standard dictionary silently truncates duplicate parameter keys to the first item, causing irreversible data loss upon round-trip.","QueryParams mutation methods (add, set, remove) return new immutable instances leaving the original QueryParams instance unmodified.","Request form data serializes multi-value lists as repeated application/x-www-form-urlencoded key-value pairs with boolean and integer values stringified.","Accessing content on an unbuffered streaming or multipart Request raises RequestNotRead until read() is explicitly invoked."],"goal":"Preserve multi-value entries and discrete wire lines across httpx Headers and QueryParams data-structure and serialization round-trip boundaries","kind":"HOW","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.Headers","httpx.QueryParams","httpx.Request"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.Headers","httpx.QueryParams","httpx.Request"],"verifierAdapter":"python@1"}
anyio==4.13.0
certifi==2026.2.25
exceptiongroup==1.3.1
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.18
sniffio==1.3.1
typing-extensions==4.15.0
anyio==4.13.0
certifi==2026.2.25
exceptiongroup==1.3.1
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.18
sniffio==1.3.1
typing-extensions==4.15.0
"""Package demonstrating httpx headers, query parameters, and serialization boundaries."""
"""Helper utilities demonstrating round-trip transformations and shape boundaries in httpx."""
from typing import Any, Dict, List, Mapping, Sequence, Tuple, Union
import httpx
def extract_discrete_headers(headers: httpx.Headers) -> List[Tuple[str, str]]:
"""Extract discrete header key-value pairs without lossy comma-delimited collapsing.
Standard dict(headers) merges duplicate header entries with ', ', which modifies
the shape of multi-value headers such as Set-Cookie and custom tracking headers.
Accessing the raw byte records preserves wire representation.
"""
encoding = headers.encoding
return [
(k.decode(encoding), v.decode(encoding))
for k, v in headers.raw
]
def safe_query_params_items(params: httpx.QueryParams) -> List[Tuple[str, str]]:
"""Extract all query parameter key-value pairs preserving repeated/multi-value entries.
Standard dict(params) silently drops duplicate parameter keys keeping only the first,
whereas multi_items() retains every occurrence.
"""
return list(params.multi_items())
def roundtrip_query_params_via_multi_items(params: httpx.QueryParams) -> httpx.QueryParams:
"""Safely round-trip QueryParams without multi-value truncation."""
return httpx.QueryParams(list(params.multi_items()))
def build_urlencoded_request(
method: str,
url: Union[str, httpx.URL],
data: Mapping[str, Any],
) -> httpx.Request:
"""Construct an httpx.Request with application/x-www-form-urlencoded body."""
return httpx.Request(method, url, data=data)
def buffer_request_content(request: httpx.Request) -> bytes:
"""Safely buffer and return streaming or multipart request body bytes.
Accessing request.content on unbuffered streaming requests raises httpx.RequestNotRead.
Calling request.read() materializes the body bytes into request.content.
"""
return request.read()
"""Test package for contract tests."""
"""Contract tests proving httpx Headers, QueryParams, and serialization round-trip boundaries."""
import sys
# Insert current working directory for package resolution without absolute paths
sys.path.insert(0, ".")
import httpx
from src.transforms import (
buffer_request_content,
extract_discrete_headers,
roundtrip_query_params_via_multi_items,
safe_query_params_items,
)
def test_headers_comma_joining_vs_discrete_lines() -> None:
"""Prove dict(headers) merges duplicate keys into comma strings while raw and get_list preserve lines."""
raw_pairs = [
(b"Accept", b"application/json"),
(b"Accept", b"text/plain"),
(b"Set-Cookie", b"session_id=tok123; Path=/; Secure"),
(b"Set-Cookie", b"theme=dark; Path=/"),
(b"X-Tracking-Id", b"trk_alpha"),
(b"X-Tracking-Id", b"trk_beta"),
]
headers = httpx.Headers(raw_pairs)
# 1. Accessing via subscription or dict() collapses duplicate keys with comma joining
headers_dict = dict(headers)
assert headers_dict["accept"] == "application/json, text/plain"
assert headers_dict["set-cookie"] == "session_id=tok123; Path=/; Secure, theme=dark; Path=/"
assert headers_dict["x-tracking-id"] == "trk_alpha, trk_beta"
assert len(headers_dict) == 3
# 2. Case-insensitive lookup matches comma-joined representation
assert headers["ACCEPT"] == "application/json, text/plain"
assert headers["set-cookie"] == "session_id=tok123; Path=/; Secure, theme=dark; Path=/"
# 3. get_list returns discrete values without comma joining when split_commas=False
assert headers.get_list("accept") == ["application/json", "text/plain"]
assert headers.get_list("set-cookie") == [
"session_id=tok123; Path=/; Secure",
"theme=dark; Path=/",
]
assert headers.get_list("x-tracking-id") == ["trk_alpha", "trk_beta"]
# 4. Round-tripping via dict(headers) permanently destroys separate wire lines
degraded_headers = httpx.Headers(headers_dict)
assert len(headers.raw) == 6
assert len(degraded_headers.raw) == 3
assert degraded_headers.get_list("set-cookie") == [
"session_id=tok123; Path=/; Secure, theme=dark; Path=/"
]
# 5. Helper function extracts discrete key-value tuples matching raw wire records
extracted = extract_discrete_headers(headers)
assert len(extracted) == 6
assert extracted[0] == ("Accept", "application/json")
assert extracted[1] == ("Accept", "text/plain")
def test_query_params_multi_value_truncation_and_immutability() -> None:
"""Prove dict(params) truncates multi-value keys to first item while multi_items preserves all."""
initial_params = {
"status": ["pending", "verified"],
"active": True,
"page": 2,
"search": None,
}
qp = httpx.QueryParams(initial_params)
# 1. QueryParams serializes repeated keys and coerced string types
assert str(qp) == "status=pending&status=verified&active=true&page=2&search="
# 2. dict(qp) drops subsequent values for multi-key and retains only the FIRST value
qp_dict = dict(qp)
assert qp_dict == {"status": "pending", "active": "true", "page": "2", "search": ""}
assert qp_dict["status"] == "pending"
# 3. Round-tripping through dict(qp) causes irreversible loss of 'verified'
qp_from_dict = httpx.QueryParams(qp_dict)
assert str(qp_from_dict) == "status=pending&active=true&page=2&search="
assert qp_from_dict.get_list("status") == ["pending"]
# 4. Safe extraction via multi_items() and get_list() preserves all occurrences
assert qp.get_list("status") == ["pending", "verified"]
assert safe_query_params_items(qp) == [
("status", "pending"),
("status", "verified"),
("active", "true"),
("page", "2"),
("search", ""),
]
# 5. Round-trip helper preserves full multi-value structure
qp_safe_roundtrip = roundtrip_query_params_via_multi_items(qp)
assert str(qp_safe_roundtrip) == str(qp)
assert qp_safe_roundtrip.get_list("status") == ["pending", "verified"]
# 6. QueryParams is immutable: mutation methods return new instances
qp_added = qp.add("status", "archived")
assert qp.get_list("status") == ["pending", "verified"]
assert qp_added.get_list("status") == ["pending", "verified", "archived"]
qp_set = qp.set("status", "completed")
assert qp.get_list("status") == ["pending", "verified"]
assert qp_set.get_list("status") == ["completed"]
qp_removed = qp.remove("status")
assert qp.get_list("status") == ["pending", "verified"]
assert "status" not in qp_removed
def test_form_data_serialization_and_streaming_request() -> None:
"""Prove Request form data URL-encoding and RequestNotRead on unbuffered streaming content."""
form_payload = {
"roles": ["admin", "editor"],
"is_active": True,
"quota": 100,
}
req = httpx.Request("POST", "https://example.com/api/v1/users", data=form_payload)
# 1. Content-Type is application/x-www-form-urlencoded and content is urlencoded bytes
assert req.headers["content-type"] == "application/x-www-form-urlencoded"
assert req.content == b"roles=admin&roles=editor&is_active=true"a=100"
# 2. Multipart file requests raise RequestNotRead when accessed before read()
upload_req = httpx.Request(
"POST",
"https://example.com/api/v1/upload",
files={"attachment": ("report.csv", b"id,val\n1,100", "text/csv")},
data={"category": "audit"},
)
assert "multipart/form-data" in upload_req.headers["content-type"]
unbuffered_raised = False
try:
_ = upload_req.content
except httpx.RequestNotRead:
unbuffered_raised = True
assert unbuffered_raised, "Expected accessing unbuffered request content to raise RequestNotRead"
# 3. Calling buffer_request_content / read() materializes body bytes
body_bytes = buffer_request_content(upload_req)
assert upload_req.content == body_bytes
assert b'name="category"\r\n\r\naudit' in body_bytes
assert b'filename="report.csv"' in body_bytes
if __name__ == "__main__":
test_headers_comma_joining_vs_discrete_lines()
test_query_params_multi_value_truncation_and_immutability()
test_form_data_serialization_and_streaming_request()
print("All httpx round-trip and boundary contract tests passed successfully.")