Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 73 additions & 28 deletions pinecone/_internal/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -301,6 +301,58 @@ def _prepare_params(kwargs: dict[str, Any]) -> dict[str, Any]:
return kwargs


def _encode_query_params(params: Any) -> str:
"""Encode query parameters with RFC 3986 percent-encoding (%20 for spaces).

httpx encodes spaces as '+' via quote_plus, but Pinecone interprets '+' as a literal
plus sign, causing searches and fetches on namespaces or IDs containing spaces to fail (#705).
Encoding spaces as '%20' via quote ensures Pinecone servers decode the exact ID/namespace.
"""
if isinstance(params, (str, bytes)):
return params if isinstance(params, str) else params.decode("utf-8")

def _format_val(val: Any) -> str:
if isinstance(val, bool):
return "true" if val else "false"
return "" if val is None else str(val)

if isinstance(params, httpx.QueryParams):
items = params.multi_items()
elif isinstance(params, Mapping):
items = []
for key, value in params.items():
resolved = _resolve_query_value(value)
if isinstance(resolved, (list, tuple)):
for item in resolved:
items.append((key, _format_val(item)))
else:
items.append((key, _format_val(resolved)))
elif isinstance(params, (list, tuple)):
items = []
for key, value in params:
resolved = _resolve_query_value(value)
if isinstance(resolved, (list, tuple)):
for item in resolved:
items.append((key, _format_val(item)))
else:
items.append((key, _format_val(resolved)))
else:
return str(params)

return urlencode(items, doseq=True, quote_via=quote)


def _prepare_path_and_kwargs(path: str, kwargs: dict[str, Any]) -> tuple[str, dict[str, Any]]:
path = _prepare_path(path)
kwargs = dict(kwargs)
params = kwargs.pop("params", None)
if params is not None:
encoded = _encode_query_params(params)
if encoded:
path = f"{path}&{encoded}" if "?" in path else f"{path}?{encoded}"
return path, kwargs


_DOT_SEGMENT_WIRE_FORMS = {".": "%2E", "..": "%2E%2E"}


Expand Down Expand Up @@ -1015,11 +1067,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_path_and_kwargs(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)
Expand Down Expand Up @@ -1089,7 +1141,8 @@ def post(
return response

# Slow path: caller passed params=, files=, headers=, content=, etc.
kwargs = _prepare_params(_prepare_json_kwargs(kwargs))
path, kwargs = _prepare_path_and_kwargs(path, kwargs)
kwargs = _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)
Expand All @@ -1112,14 +1165,14 @@ def post(
def put(
self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any
) -> httpx.Response:
path = _prepare_path(path)
path, kwargs = _prepare_path_and_kwargs(path, kwargs)
kwargs = _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)
Expand All @@ -1129,16 +1182,14 @@ def put(
def patch(
self, path: str, timeout: float | httpx.Timeout | None = None, **kwargs: Any
) -> httpx.Response:
path = _prepare_path(path)
path, kwargs = _prepare_path_and_kwargs(path, kwargs)
kwargs = _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)
Expand All @@ -1148,13 +1199,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_path_and_kwargs(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)
Expand Down Expand Up @@ -1249,12 +1298,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_path_and_kwargs(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)
Expand All @@ -1264,11 +1311,11 @@ 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_path_and_kwargs(path, 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))
path, timeout=effective_timeout, **_prepare_json_kwargs(kwargs)
)
except httpx.TransportError as exc:
_raise_transport_error(exc)
Expand All @@ -1279,11 +1326,11 @@ 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_path_and_kwargs(path, 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))
path, timeout=effective_timeout, **_prepare_json_kwargs(kwargs)
)
except httpx.TransportError as exc:
_raise_transport_error(exc)
Expand All @@ -1294,11 +1341,11 @@ 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_path_and_kwargs(path, 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))
path, timeout=effective_timeout, **_prepare_json_kwargs(kwargs)
)
except httpx.TransportError as exc:
_raise_transport_error(exc)
Expand All @@ -1309,12 +1356,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_path_and_kwargs(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)
Expand Down
100 changes: 100 additions & 0 deletions tests/unit/test_query_param_spaces_705.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Query parameters must encode spaces as %20 rather than + (#705).

In Pinecone, query parameter values like namespace names or vector IDs can contain
spaces (e.g. 'doc 42', 'repro namespace'). The Pinecone data plane treats literal '+'
characters distinctly from spaces. When query parameters were sent through httpx's default
urlencode(quote_via=quote_plus), spaces were encoded as '+' instead of '%20', causing
endpoints like /vectors/fetch and /vectors/list to miss records or namespaces.

These tests verify that query parameters with spaces and plus signs are encoded with
RFC 3986 percent-encoding (%20 for spaces and %2B for pluses) across sync and async clients.
"""

from __future__ import annotations

import httpx
import pytest
import respx

from pinecone._internal.config import PineconeConfig
from pinecone._internal.http_client import AsyncHTTPClient, HTTPClient

BASE_URL = "https://api.test.pinecone.io"


def _sync_http() -> HTTPClient:
return HTTPClient(PineconeConfig(api_key="key", host=BASE_URL), api_version="2026-07")


def _async_http() -> AsyncHTTPClient:
return AsyncHTTPClient(PineconeConfig(api_key="key", host=BASE_URL), api_version="2026-07")


class TestSyncSpacesInQueryParams:
@respx.mock
def test_get_spaces_in_ids_and_namespaces_encoded_as_percent_20(self) -> None:
route = respx.get(f"{BASE_URL}/vectors/fetch").mock(
return_value=httpx.Response(200, json={})
)
_sync_http().get(
"/vectors/fetch",
params={"ids": ["doc-42", "doc 42", "doc+42"], "namespace": "repro namespace"},
)
raw_path = route.calls.last.request.url.raw_path.decode()
assert "ids=doc%2042" in raw_path
assert "ids=doc%2B42" in raw_path
assert "ids=doc-42" in raw_path
assert "namespace=repro%20namespace" in raw_path
assert "+" not in raw_path # Spaces must never be encoded as '+'

# Ensure httpx still parses params accurately
call_params = route.calls.last.request.url.params
assert call_params["namespace"] == "repro namespace"
assert call_params.get_list("ids") == ["doc-42", "doc 42", "doc+42"]

@respx.mock
def test_delete_spaces_encoded_as_percent_20(self) -> None:
route = respx.delete(f"{BASE_URL}/namespaces").mock(
return_value=httpx.Response(200, json={})
)
_sync_http().delete("/namespaces", params={"namespace": "my namespace"})
raw_path = route.calls.last.request.url.raw_path.decode()
assert "namespace=my%20namespace" in raw_path
assert "namespace=my+namespace" not in raw_path


@pytest.mark.asyncio
class TestAsyncSpacesInQueryParams:
@respx.mock
async def test_get_spaces_in_ids_and_namespaces_encoded_as_percent_20(self) -> None:
route = respx.get(f"{BASE_URL}/vectors/fetch").mock(
return_value=httpx.Response(200, json={})
)
client = _async_http()
try:
await client.get(
"/vectors/fetch",
params={"ids": ["doc 42", "doc+42"], "namespace": "async namespace"},
)
finally:
await client.close()

raw_path = route.calls.last.request.url.raw_path.decode()
assert "ids=doc%2042" in raw_path
assert "ids=doc%2B42" in raw_path
assert "namespace=async%20namespace" in raw_path
assert "+" not in raw_path

@respx.mock
async def test_delete_spaces_encoded_as_percent_20(self) -> None:
route = respx.delete(f"{BASE_URL}/namespaces").mock(
return_value=httpx.Response(200, json={})
)
client = _async_http()
try:
await client.delete("/namespaces", params={"namespace": "async namespace"})
finally:
await client.close()

raw_path = route.calls.last.request.url.raw_path.decode()
assert "namespace=async%20namespace" in raw_path