diff --git a/pinecone/_internal/http_client.py b/pinecone/_internal/http_client.py index ca9727f5a..e0d4b66bc 100644 --- a/pinecone/_internal/http_client.py +++ b/pinecone/_internal/http_client.py @@ -16,7 +16,7 @@ from collections.abc import AsyncGenerator, Generator, Mapping, Sequence from enum import Enum from typing import Any, NoReturn -from urllib.parse import urlsplit +from urllib.parse import quote, urlencode, urlsplit import httpx import orjson @@ -301,6 +301,48 @@ def _prepare_params(kwargs: dict[str, Any]) -> dict[str, Any]: return kwargs +def _encode_query_params(params: Any) -> str: + """Serialize query parameters with RFC 3986 percent-encoding (``%20`` for spaces). + + httpx's default query serializer uses ``application/x-www-form-urlencoded`` + (``quote_plus``), which encodes spaces as ``+``. Pinecone endpoints such as + ``/vectors/fetch``, ``/vectors/list``, and ``/namespaces`` expect ``%20`` + so IDs, namespaces, and prefixes containing spaces match on the server + (issue #705). + + Normalizing through ``httpx.QueryParams`` first preserves httpx's exact + scalar coercion (e.g. ``True`` -> ``"true"``, ``None`` -> ``""``, repeated + keys for sequence values) before re-encoding each key/value pair with + ``urllib.parse.quote`` (``safe=""``). + """ + items = httpx.QueryParams(params).multi_items() + if not items: + return "" + return urlencode(items, quote_via=quote, safe="") + + +def _prepare_url_and_params(path: str, kwargs: dict[str, Any]) -> tuple[str, dict[str, Any]]: + """Normalize *path* and attach RFC 3986-encoded ``params=`` directly onto *path*. + + Attaching the pre-encoded query string onto *path* prevents httpx from + re-encoding ``%20`` back into ``+`` while leaving callers that pass an + already-encoded ``str`` or ``bytes`` query string untouched. + """ + path = _prepare_path(path) + kwargs = _prepare_params(kwargs) + params = kwargs.get("params") + if params is None or isinstance(params, (str, bytes)): + return path, kwargs + kwargs = dict(kwargs) + kwargs.pop("params", None) + encoded = _encode_query_params(params) + if not encoded: + return path, kwargs + head, sep, fragment = path.partition("#") + joined = f"{head}&{encoded}" if "?" in head else f"{head}?{encoded}" + return f"{joined}{sep}{fragment}", kwargs + + _DOT_SEGMENT_WIRE_FORMS = {".": "%2E", "..": "%2E%2E"} @@ -1015,11 +1057,11 @@ def _build_url(self, path: str) -> str: def get( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) + path, kwargs = _prepare_url_and_params(path, kwargs) _log_curl("GET", self._build_url(path), dict(self._headers)) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = self._client.get(path, timeout=effective_timeout, **_prepare_params(kwargs)) + response = self._client.get(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1089,7 +1131,7 @@ def post( return response # Slow path: caller passed params=, files=, headers=, content=, etc. - kwargs = _prepare_params(_prepare_json_kwargs(kwargs)) + path, kwargs = _prepare_url_and_params(path, _prepare_json_kwargs(kwargs)) body = kwargs.get("content") if isinstance(kwargs.get("content"), bytes) else None merged_headers = {**self._headers, **kwargs.get("headers", {})} _log_curl("POST", self._build_url(path), merged_headers, body=body) @@ -1112,14 +1154,13 @@ def post( def put( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) - kwargs = _prepare_json_kwargs(kwargs) + path, kwargs = _prepare_url_and_params(path, _prepare_json_kwargs(kwargs)) body = kwargs.get("content") if isinstance(kwargs.get("content"), bytes) else None merged_headers = {**self._headers, **kwargs.get("headers", {})} _log_curl("PUT", self._build_url(path), merged_headers, body=body) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = self._client.put(path, timeout=effective_timeout, **_prepare_params(kwargs)) + response = self._client.put(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1129,16 +1170,13 @@ def put( def patch( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) - kwargs = _prepare_json_kwargs(kwargs) + path, kwargs = _prepare_url_and_params(path, _prepare_json_kwargs(kwargs)) body = kwargs.get("content") if isinstance(kwargs.get("content"), bytes) else None merged_headers = {**self._headers, **kwargs.get("headers", {})} _log_curl("PATCH", self._build_url(path), merged_headers, body=body) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = self._client.patch( - path, timeout=effective_timeout, **_prepare_params(kwargs) - ) + response = self._client.patch(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1148,13 +1186,11 @@ def patch( def delete( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) + path, kwargs = _prepare_url_and_params(path, kwargs) _log_curl("DELETE", self._build_url(path), dict(self._headers)) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = self._client.delete( - path, timeout=effective_timeout, **_prepare_params(kwargs) - ) + response = self._client.delete(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1249,12 +1285,10 @@ def _ensure_client(self) -> httpx.AsyncClient: async def get( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) + path, kwargs = _prepare_url_and_params(path, kwargs) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = await self._ensure_client().get( - path, timeout=effective_timeout, **_prepare_params(kwargs) - ) + response = await self._ensure_client().get(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1264,12 +1298,10 @@ async def get( async def post( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) + path, kwargs = _prepare_url_and_params(path, _prepare_json_kwargs(kwargs)) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = await self._ensure_client().post( - path, timeout=effective_timeout, **_prepare_params(_prepare_json_kwargs(kwargs)) - ) + response = await self._ensure_client().post(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1279,12 +1311,10 @@ async def post( async def put( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) + path, kwargs = _prepare_url_and_params(path, _prepare_json_kwargs(kwargs)) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = await self._ensure_client().put( - path, timeout=effective_timeout, **_prepare_params(_prepare_json_kwargs(kwargs)) - ) + response = await self._ensure_client().put(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1294,12 +1324,10 @@ async def put( async def patch( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) + path, kwargs = _prepare_url_and_params(path, _prepare_json_kwargs(kwargs)) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = await self._ensure_client().patch( - path, timeout=effective_timeout, **_prepare_params(_prepare_json_kwargs(kwargs)) - ) + response = await self._ensure_client().patch(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) @@ -1309,12 +1337,10 @@ async def patch( async def delete( self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any ) -> httpx.Response: - path = _prepare_path(path) + path, kwargs = _prepare_url_and_params(path, kwargs) effective_timeout = timeout if timeout is not None else self._config.timeout try: - response = await self._ensure_client().delete( - path, timeout=effective_timeout, **_prepare_params(kwargs) - ) + response = await self._ensure_client().delete(path, timeout=effective_timeout, **kwargs) except httpx.TransportError as exc: _raise_transport_error(exc) _raise_for_status(response) diff --git a/tests/unit/test_query_param_space_encoding_705.py b/tests/unit/test_query_param_space_encoding_705.py new file mode 100644 index 000000000..d1a989abc --- /dev/null +++ b/tests/unit/test_query_param_space_encoding_705.py @@ -0,0 +1,121 @@ +"""Query parameters must percent-encode spaces as ``%20``, not ``+`` (#705). + +httpx serializes query parameters with ``application/x-www-form-urlencoded`` +(``quote_plus``), encoding spaces as ``+``. Pinecone endpoints such as +``/vectors/fetch``, ``/vectors/list``, and ``/namespaces`` expect RFC 3986 +``%20`` encoding (matching v8.x / urllib3) so IDs, namespaces, and prefixes +containing spaces match on the server. +""" + +from __future__ import annotations + +import httpx +import pytest +import respx + +from pinecone import AsyncPinecone, Pinecone +from pinecone._internal.config import PineconeConfig +from pinecone._internal.http_client import AsyncHTTPClient, HTTPClient + +INDEX_HOST = "https://idx-space-test.svc.pinecone.io" + + +def _sync_http() -> HTTPClient: + return HTTPClient(PineconeConfig(api_key="test-key", host=INDEX_HOST), api_version="2026-07") + + +def _async_http() -> AsyncHTTPClient: + return AsyncHTTPClient( + PineconeConfig(api_key="test-key", host=INDEX_HOST), api_version="2026-07" + ) + + +class TestSyncQuerySpaceEncoding: + @respx.mock + def test_get_encodes_spaces_as_percent20_and_preserves_literal_plus(self) -> None: + route = respx.get(url__startswith=f"{INDEX_HOST}/vectors/fetch").mock( + return_value=httpx.Response(200, json={"vectors": {}}) + ) + _sync_http().get( + "/vectors/fetch", + params={"ids": ["doc 42", "a+b"], "namespace": "my namespace"}, + ) + assert route.called + raw_path = route.calls.last.request.url.raw_path.decode("ascii") + assert "ids=doc%2042" in raw_path + assert "ids=a%2Bb" in raw_path + assert "namespace=my%20namespace" in raw_path + assert "+" not in raw_path.split("?", 1)[1] + + @respx.mock + def test_get_appends_to_existing_query_string(self) -> None: + route = respx.get(url__startswith=f"{INDEX_HOST}/vectors/list").mock( + return_value=httpx.Response(200, json={"vectors": []}) + ) + _sync_http().get("/vectors/list?limit=10", params={"namespace": "team alpha"}) + assert route.called + raw_path = route.calls.last.request.url.raw_path.decode("ascii") + assert raw_path == "/vectors/list?limit=10&namespace=team%20alpha" + + @respx.mock + def test_index_fetch_list_paginated_and_list_namespaces_use_percent20(self) -> None: + fetch_route = respx.get(url__startswith=f"{INDEX_HOST}/vectors/fetch").mock( + return_value=httpx.Response(200, json={"vectors": {}, "namespace": "my ns"}) + ) + list_route = respx.get(url__startswith=f"{INDEX_HOST}/vectors/list").mock( + return_value=httpx.Response(200, json={"vectors": [], "namespace": "my ns"}) + ) + ns_route = respx.get(url__startswith=f"{INDEX_HOST}/namespaces").mock( + return_value=httpx.Response(200, json={"namespaces": []}) + ) + + pc = Pinecone(api_key="test-key") + idx = pc.Index(host=INDEX_HOST) + + idx.fetch(ids=["doc 42"], namespace="my ns") + idx.list_paginated(prefix="doc ", namespace="my ns") + idx.list_namespaces_paginated(prefix="my ") + + assert ( + fetch_route.calls.last.request.url.raw_path.decode("ascii") + == "/vectors/fetch?ids=doc%2042&namespace=my%20ns" + ) + assert "prefix=doc%20" in list_route.calls.last.request.url.raw_path.decode("ascii") + assert "namespace=my%20ns" in list_route.calls.last.request.url.raw_path.decode("ascii") + assert "prefix=my%20" in ns_route.calls.last.request.url.raw_path.decode("ascii") + + +class TestAsyncQuerySpaceEncoding: + @pytest.mark.asyncio + @respx.mock + async def test_async_get_encodes_spaces_as_percent20(self) -> None: + route = respx.get(url__startswith=f"{INDEX_HOST}/vectors/fetch").mock( + return_value=httpx.Response(200, json={"vectors": {}}) + ) + client = _async_http() + try: + await client.get( + "/vectors/fetch", + params={"ids": ["doc 42"], "namespace": "my namespace"}, + ) + finally: + await client.close() + + assert route.called + raw_path = route.calls.last.request.url.raw_path.decode("ascii") + assert raw_path == "/vectors/fetch?ids=doc%2042&namespace=my%20namespace" + + @pytest.mark.asyncio + @respx.mock + async def test_async_index_fetch_uses_percent20(self) -> None: + fetch_route = respx.get(url__startswith=f"{INDEX_HOST}/vectors/fetch").mock( + return_value=httpx.Response(200, json={"vectors": {}, "namespace": "my ns"}) + ) + async with AsyncPinecone(api_key="test-key") as pc: + async with pc.IndexAsyncio(host=INDEX_HOST) as idx: + await idx.fetch(ids=["doc 42"], namespace="my ns") + + assert ( + fetch_route.calls.last.request.url.raw_path.decode("ascii") + == "/vectors/fetch?ids=doc%2042&namespace=my%20ns" + )