Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(sdk): retain encode timing and call-local trace context (#733)
Attila László Nagy7eb2f08c30a9
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.mdindex cdee60058..648cd0429 100644--- a/packages/sie_sdk/README.md+++ b/packages/sie_sdk/README.md@@ -289,6 +289,65 @@ reuses the client's key on requests to an explicitly configured`control_plane_url`, so a client whose `control_plane_url` is on anotherorigin must pass `api_key` explicitly rather than rely on `SIE_API_KEY`.+## Encode timing evidence++Both Python clients preserve optional response-body timing in `result["timing"]`.+Queue gateways instead publish timing headers; successful `encode()` results+expose valid values separately in `result["gateway_timing"]`:++| Field | Response header | Meaning |+| --- | --- | --- |+| `publish_ms` | `x-queue-publish-time` | Gateway publish-operation duration |+| `result_wait_ms` | `x-queue-wait-time` | Gateway wait for published results |+| `worker_queue_ms_max` | `x-queue-time` | Largest worker-reported work-item age at result |+| `worker_inference_ms_max` | `x-inference-time` | Largest reported worker inference duration |+| `worker_tokenization_ms_max` | `x-tokenization-time` | Largest reported tokenization duration |+| `worker_postprocessing_ms_max` | `x-postprocessing-time` | Largest reported postprocessing duration |+| `worker_payload_fetch_ms_max` | `x-payload-fetch-time` | Largest reported payload-fetch duration |++All values are milliseconds from the terminal response only, not sums across+retries or continuation requests. Missing or malformed fields are omitted; if+none are valid, `gateway_timing` is absent. Existing body timing is unchanged.+Queue gateways round headers to one decimal place. Worker maxima include only+reported values from successful items, which can be partial coverage. Each+maximum can come from a different item; do not add them as a request breakdown.+Worker queue timing is measured from publication to result and can include+loading and execution; it is not a separate pre-inference wait interval and can+be affected by clock skew.+Queue/inference zero can also be the gateway's fallback for missing worker+measurements, so it does not prove zero work. These fields exclude portions of+the complete gateway/client round trip; the SDK does not synthesize `total_ms`,+and subtracting them from client latency does not isolate network latency.+Direct Python servers can emit the worker-named headers for their own stage+timings without publish/wait headers. Those values are preserved too; header+presence alone does not identify the serving path.++## Encode trace correlation++Both Python clients accept an optional `traceparent` keyword on `encode()`:++```python+result = client.encode(+ "BAAI/bge-m3",+ {"text": "Hello world"},+ traceparent="00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",+)+```++Supply a valid [W3C version-00 trace context](https://www.w3.org/TR/trace-context/#traceparent-header)+from your tracer, using a distinct parent span for each logical call. The SDK+validates the fixed-length lowercase format and nonzero trace/span IDs before+I/O. It neither creates spans nor changes sampling flags. This value is sent+unchanged on retry POSTs and bounded same-origin continuation GETs; it therefore+identifies a logical call, not a unique HTTP attempt or a complete attempt count.++The option retains the pooled client and overrides constructor `traceparent`+only for this call. Inherited `tracestate` is omitted for the override; other+headers and origin restrictions are unchanged. No shared client headers are+mutated, so concurrent calls can supply independent contexts. With `None` (the+default), constructor tracing headers and existing request behavior are unchanged.+This option applies only to `encode()`, not its ancillary pool-management calls.+## Generation execution evidence`SIEClient.last_model_revision` retains the `X-SIE-Model-Revision` responsediff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 8823aa40b..20fc8103d 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -28,6 +28,7 @@ _logger = logging.getLogger(__name__)_HTTP_HEADER_NAME = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")_HTTP_MEDIA_TYPE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+/[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")+_TRACEPARENT_V00 = re.compile(r"00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}")_CONTENT_SAFE_MEDIA_TYPES = frozenset({"application/json", "application/msgpack", "application/problem+json", "text/html"})@@ -57,6 +58,17 @@ MODAL_CONTINUATION_MAX_HOPS = 20_MODAL_CONTINUATION_QUERY_PARAMETER = "__modal_attempt_token"+def validate_encode_traceparent(traceparent: str | None) -> None:+ """Accept a bounded version-00 trace context without changing its flags."""+ if traceparent is None:+ return+ if not isinstance(traceparent, str):+ raise TypeError("traceparent must be a string or None")+ match = _TRACEPARENT_V00.fullmatch(traceparent) if len(traceparent) == 55 else None+ if match is None or match[1] == "0" * 32 or match[2] == "0" * 16:+ raise ValueError("traceparent must be a valid W3C version-00 trace context")++def copy_base_url_headers(headers: Mapping[str, str] | None) -> dict[str, str]:"""Validate and detach additional gateway-origin request headers.@@ -299,6 +311,7 @@ from sie_sdk.types import (EntityResult,ExtractItemErrorDetail,ExtractResult,+ GatewayTimingInfo,GenerateGrammar,Relation,RequestMetadata,@@ -981,6 +994,42 @@ def _parse_nonnegative_meter_header(headers: Any, name: str) -> int | None:return parsed if parsed <= _MAX_METER_VALUE else None+_GATEWAY_TIMING_HEADERS = {+ "publish_ms": "x-queue-publish-time",+ "result_wait_ms": "x-queue-wait-time",+ "worker_queue_ms_max": "x-queue-time",+ "worker_inference_ms_max": "x-inference-time",+ "worker_tokenization_ms_max": "x-tokenization-time",+ "worker_postprocessing_ms_max": "x-postprocessing-time",+ "worker_payload_fetch_ms_max": "x-payload-fetch-time",+}+++def parse_gateway_timing(headers: Any) -> GatewayTimingInfo | None:+ """Read bounded nonnegative decimal timing headers without inventing totals."""+ timing: dict[str, float] = {}+ for field, header in _GATEWAY_TIMING_HEADERS.items():+ value = _header_value(headers, header)+ if (+ not isinstance(value, str)+ or not 0 < len(value) <= 64+ or re.fullmatch(r"[0-9]+(?:\.[0-9]+)?", value) is None+ ):+ continue+ parsed = float(value)+ if math.isfinite(parsed):+ timing[field] = parsed+ return cast("GatewayTimingInfo", timing) if timing else None+++def attach_gateway_timing(results: Sequence[EncodeResult], headers: Any) -> None:+ """Attach detached terminal-response timing without altering body timing."""+ timing = parse_gateway_timing(headers)+ if timing is not None:+ for result in results:+ result["gateway_timing"] = timing.copy()++def settled_charge_from_usage(usage: Any) -> tuple[int, str] | None:"""The settled charge carried by one ``usage`` block (#2434).diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 9f4b85341..75ddd09d7 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -123,6 +123,7 @@ from ._shared import (SERVER_VERSION_HEADER,_coerce_token_count,admission_retry_delay,+ attach_gateway_timing,attach_request_metadata,attempt_timeout_cap,base_url_accepts_origin_credentials,@@ -167,6 +168,7 @@ from ._shared import (valid_stream_request_id,validate_base_url,validate_batch_result_count,+ validate_encode_traceparent,validate_generate_grammar,validate_generate_request_body,websocket_matches_base_url_origin,@@ -661,13 +663,16 @@ class SIEAsyncClient:timeout_s: float | None = None,include_base_url_headers: bool = True,client_timeout: aiohttp.ClientTimeout | None = None,+ traceparent: str | None = None,) -> _AioResponse:kw: dict[str, Any] = {}if data is not None:kw["data"] = dataif json_data is not None:kw["json"] = json_data- request_headers = self._headers_for_request(url, headers, include_base_url_headers=include_base_url_headers)+ request_headers = self._headers_for_request(+ url, headers, include_base_url_headers=include_base_url_headers, traceparent=traceparent+ )if request_headers:kw["headers"] = request_headersif client_timeout is not None:@@ -717,11 +722,21 @@ class SIEAsyncClient:headers: Mapping[str, str] | None,*,include_base_url_headers: bool = True,+ traceparent: str | None = None,) -> dict[str, str]:"""Build detached request headers with exact-origin edge credentials."""merged = dict(headers or {})if include_base_url_headers and self._base_url_headers and request_matches_base_url_origin(self._base_url, url):merged.update(self._base_url_headers)+ if (+ traceparent is not None+ and include_base_url_headers+ and request_matches_base_url_origin(self._base_url, url)+ ):+ merged = {+ name: value for name, value in merged.items() if name.lower() not in {"traceparent", "tracestate"}+ }+ merged["traceparent"] = traceparentreturn mergeddef _check_server_version(self, response: _AioResponse) -> None:@@ -743,6 +758,7 @@ class SIEAsyncClient:start_time: float,budget_s: float,accept: str = JSON_CONTENT_TYPE,+ traceparent: str | None = None,) -> _AioResponse:"""Consume bounded same-origin Modal 303 result URLs without replaying POST."""for _ in range(MODAL_CONTINUATION_MAX_HOPS):@@ -758,7 +774,7 @@ class SIEAsyncClient:self._throttle(),self._ensure_session().get(path,- headers=self._headers_for_request(path, {"Accept": accept}),+ headers=self._headers_for_request(path, {"Accept": accept}, traceparent=traceparent),timeout=self._attempt_timeout(remaining),allow_redirects=False,) as raw,@@ -1327,6 +1343,7 @@ class SIEAsyncClient:wait_for_capacity: bool = True,provision_timeout_s: float | None = None,max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,+ traceparent: str | None = None,) -> EncodeResult: ...@overload@@ -1344,6 +1361,7 @@ class SIEAsyncClient:wait_for_capacity: bool = True,provision_timeout_s: float | None = None,max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,+ traceparent: str | None = None,) -> list[EncodeResult]: ...async def encode(@@ -1360,8 +1378,10 @@ class SIEAsyncClient:wait_for_capacity: bool = True,provision_timeout_s: float | None = None,max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,+ traceparent: str | None = None,) -> EncodeResult | list[EncodeResult]:"""Async version of encode(). See SIEClient.encode() for details."""+ validate_encode_traceparent(traceparent)self._reset_retry_count()# Track if single item was passedsingle_item = not isinstance(items, list)@@ -1440,6 +1460,7 @@ class SIEAsyncClient:data=body,headers=headers,client_timeout=request_timeout,+ traceparent=traceparent,)except _RETRYABLE_TRANSPORT_ERRORS as e:if wait_for_capacity:@@ -1486,6 +1507,7 @@ class SIEAsyncClient:start_time=start_time,budget_s=timeout,accept=MSGPACK_CONTENT_TYPE,+ traceparent=traceparent,)# Short-circuit terminal load failures.@@ -1636,6 +1658,7 @@ class SIEAsyncClient:result["timing"] = timingattach_request_metadata(results, response.headers, response_data)+ attach_gateway_timing(results, response.headers)# Guard the 1:1 input↔output contract before any positional access# (``results[0]`` below, or batch reassembly in callers). The gateway's# queue path returns mixed-success batches as 200 with only thediff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex e17daf369..1d5b9293d 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -132,6 +132,7 @@ from ._shared import (SERVER_VERSION_HEADER,_coerce_token_count,admission_retry_delay,+ attach_gateway_timing,attach_request_metadata,attempt_timeout_cap,base_url_accepts_origin_credentials,@@ -176,6 +177,7 @@ from ._shared import (valid_stream_request_id,validate_base_url,validate_batch_result_count,+ validate_encode_traceparent,validate_generate_grammar,validate_generate_request_body,websocket_matches_base_url_origin,@@ -313,6 +315,10 @@ def _attach_origin_scoped_headers(returnif request_matches_base_url_origin(base_url, str(request.url)):request.headers.update(headers)+ traceparent = request.extensions.get("sie_encode_traceparent")+ if traceparent is not None:+ request.headers["traceparent"] = traceparent+ request.headers.pop("tracestate", None)def _handle_oom_retry(@@ -552,16 +558,15 @@ class SIEClient:"headers": headers,"follow_redirects": False,}- if self._base_url_headers:- client_kwargs["event_hooks"] = {- "request": [- partial(- _attach_origin_scoped_headers,- base_url=self._base_url,- headers=self._base_url_headers,- )- ]- }+ client_kwargs["event_hooks"] = {+ "request": [+ partial(+ _attach_origin_scoped_headers,+ base_url=self._base_url,+ headers=self._base_url_headers,+ )+ ]+ }if max_connections is not None:client_kwargs["limits"] = httpx.Limits(max_connections=max_connections,@@ -665,8 +670,12 @@ class SIEClient:start_time: float,budget_s: float,accept: str = JSON_CONTENT_TYPE,+ traceparent: str | None = None,) -> httpx.Response:"""Consume bounded same-origin Modal 303 result URLs without replaying POST."""+ request_options: dict[str, Any] = {}+ if traceparent is not None:+ request_options["extensions"] = {"sie_encode_traceparent": traceparent}for _ in range(MODAL_CONTINUATION_MAX_HOPS):path = modal_continuation_path(self._base_url, response)if path is None:@@ -680,6 +689,7 @@ class SIEClient:path,headers={"Accept": accept},timeout=self._attempt_timeout(remaining),+ **request_options,)except httpx.HTTPError as exc:msg = f"Failed to retrieve the in-flight generation result: {type(exc).__name__}"@@ -1208,6 +1218,7 @@ class SIEClient:wait_for_capacity: bool = True,provision_timeout_s: float | None = None,max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,+ traceparent: str | None = None,) -> EncodeResult: ...@overload@@ -1225,6 +1236,7 @@ class SIEClient:wait_for_capacity: bool = True,provision_timeout_s: float | None = None,max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,+ traceparent: str | None = None,) -> list[EncodeResult]: ...def encode(@@ -1241,6 +1253,7 @@ class SIEClient:wait_for_capacity: bool = True,provision_timeout_s: float | None = None,max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,+ traceparent: str | None = None,) -> EncodeResult | list[EncodeResult]:"""Encode items into vector representations.@@ -1257,6 +1270,10 @@ class SIEClient:or individual options like "muvera", "smve", "normalize", etc.gpu: Target GPU type (e.g., "l4", "a100-80gb"). Routes request to workerswith matching GPU. Required when using the gateway with multiple GPU pools.+ traceparent: Optional W3C version-00 context for this logical call,+ unchanged across retries and same-origin continuations. Overrides+ constructor tracing headers without changing the pooled client.+ Inherited tracestate is omitted only when this option is set.wait_for_capacity: When True (default), auto-retry transient "notenough capacity yet" responses under ``provision_timeout_s`` —``503 PROVISIONING`` (scale-from-zero provisioning);@@ -1357,6 +1374,10 @@ class SIEClient:... {"images": ["photo.jpg"]},... )"""+ validate_encode_traceparent(traceparent)+ request_options: dict[str, Any] = {}+ if traceparent is not None:+ request_options["extensions"] = {"sie_encode_traceparent": traceparent}self._reset_retry_count()# Track if single item was passedsingle_item = not isinstance(items, list)@@ -1434,7 +1455,11 @@ class SIEClient:try:response = self._client.post(- f"/v1/encode/{model}", content=body, headers=headers, timeout=request_timeout+ f"/v1/encode/{model}",+ content=body,+ headers=headers,+ timeout=request_timeout,+ **request_options,)except _CONNECT_PHASE_ERRORS as e:if wait_for_capacity and is_transient_connect_error(e):@@ -1481,6 +1506,7 @@ class SIEClient:start_time=start_time,budget_s=timeout,accept=MSGPACK_CONTENT_TYPE,+ traceparent=traceparent,)# Short-circuit terminal load failures BEFORE engaging the@@ -1639,6 +1665,7 @@ class SIEClient:result["timing"] = timingattach_request_metadata(results, response.headers, response_data)+ attach_gateway_timing(results, response.headers)# Guard the 1:1 input↔output contract before any positional access# (``results[0]`` below, or batch reassembly in callers). The gateway's# queue path returns mixed-success batches as 200 with only thediff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex d1b7407b7..b734115e8 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -142,6 +142,27 @@ class TimingInfo(TypedDict, total=False):inference_ms: float+class GatewayTimingInfo(TypedDict, total=False):+ """Terminal response-header durations, in milliseconds.++ Queue gateways report independent worker maxima, not additive request+ phases. Their worker queue timing can include execution because it is+ measured from publication to result. Queue/inference zero can be a gateway+ missing-value fallback; any zero can also reflect header rounding. Direct+ servers can report their own stage timings under the same worker headers.+ Missing fields stay absent. These durations do not measure the complete+ gateway request or client round trip.+ """++ publish_ms: float+ result_wait_ms: float+ worker_queue_ms_max: float+ worker_inference_ms_max: float+ worker_tokenization_ms_max: float+ worker_postprocessing_ms_max: float+ worker_payload_fetch_ms_max: float++class RequestUsage(TypedDict, total=False):"""Authoritative metered units for one completed inference request.@@ -256,6 +277,8 @@ class EncodeResult(TypedDict, total=False):the default dtype; an explicit output_dtype request overrides it.request: Request-scoped id, metered usage, and settled debit whensupplied by the gateway.+ gateway_timing: Optional terminal response-header durations,+ distinct from the response body's timing breakdown."""model: str@@ -264,6 +287,7 @@ class EncodeResult(TypedDict, total=False):sparse: SparseResultmultivector: NDArray[np.float16] | NDArray[np.float32]timing: TimingInfo+ gateway_timing: GatewayTimingInforequest: RequestMetadatadiff --git a/packages/sie_sdk/tests/client/test_encode_traceparent.py b/packages/sie_sdk/tests/client/test_encode_traceparent.pynew file mode 100644index 000000000..d17af1857--- /dev/null+++ b/packages/sie_sdk/tests/client/test_encode_traceparent.py@@ -0,0 +1,259 @@+"""Call-local encode trace contexts never mutate pooled-client defaults."""++from __future__ import annotations++import asyncio+from collections import Counter+from concurrent.futures import ThreadPoolExecutor+from threading import Barrier+from typing import Any, Self+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import numpy as np+import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk._msgpack import packb as pack_msgpack+from sie_sdk.client._shared import validate_encode_traceparent+from sie_sdk.client.errors import RequestError++_BASE = "https://gateway.example.test"+_DEFAULT = "00-11111111111111111111111111111111-1111111111111111-01"+_FIRST = "00-22222222222222222222222222222222-2222222222222222-01"+_SECOND = "00-33333333333333333333333333333333-3333333333333333-00"+_EDGE = {"TraceParent": _DEFAULT, "TraceState": "vendor=default", "X-Edge": "edge-test"}+_INVALID = [+ "",+ _FIRST.replace("2", "A"),+ _FIRST.replace("00-", "01-", 1),+ _FIRST.replace("00-", "ff-", 1),+ "00-" + "0" * 32 + "-2222222222222222-01",+ "00-22222222222222222222222222222222-" + "0" * 16 + "-01",+ _FIRST + "-extra",+ " " + _FIRST,+ _FIRST + "\r\nX-Other: value",+ pytest.param("x" * 10000, id="oversized"),+ True,+ 42,+]+++def _success() -> httpx.Response:+ return httpx.Response(+ 200,+ headers={"content-type": "application/msgpack"},+ content=pack_msgpack({"items": [{"dense": {"dims": 1, "values": np.array([0.5], dtype=np.float32)}}]}),+ )+++def _retry() -> httpx.Response:+ return httpx.Response(+ 503,+ headers={"Retry-After": "0"},+ json={"error": {"code": "PROVISIONING", "message": "starting"}},+ )+++def _redirect(location: str = "/v1/encode/m?__modal_attempt_token=opaque") -> httpx.Response:+ return httpx.Response(303, headers={"Location": location})+++class _AsyncContext:+ def __init__(self, response: httpx.Response) -> None:+ self.status = response.status_code+ self.headers = response.headers+ self.content = response.content++ async def __aenter__(self) -> Self:+ await asyncio.sleep(0)+ return self++ async def __aexit__(self, *_args: object) -> None:+ return None++ async def read(self) -> bytes:+ return self.content++[email protected]("value", _INVALID)+def test_sync_invalid_traceparent_fails_before_io(value: Any) -> None:+ with SIEClient(_BASE, api_key="") as client, patch.object(client._client, "post") as post:+ with pytest.raises((TypeError, ValueError), match="traceparent"):+ client.encode("m", {"text": "one"}, traceparent=value)+ post.assert_not_called()++[email protected]("value", _INVALID)+async def test_async_invalid_traceparent_fails_before_io(value: Any) -> None:+ async with SIEAsyncClient(_BASE, api_key="") as client:+ with patch.object(client, "_post") as post:+ with pytest.raises((TypeError, ValueError), match="traceparent"):+ await client.encode("m", {"text": "one"}, traceparent=value)+ post.assert_not_called()+ assert client._session is None++[email protected]("flags", ["00", "01", "02", "ff"])+def test_traceparent_preserves_all_w3c_flag_bits(flags: str) -> None:+ validate_encode_traceparent(_FIRST[:-2] + flags)++[email protected]("edge", [{}, _EDGE])+def test_sync_override_is_call_local_and_keeps_body_and_auth(edge: dict[str, str]) -> None:+ requests: list[httpx.Request] = []++ def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return _success()++ with httpx.Client(base_url=_BASE, transport=httpx.MockTransport(respond)) as http:+ with SIEClient(_BASE, api_key="api-test", base_url_headers=edge, http_client=http) as client:+ for context in [None, _FIRST, None]:+ client.encode("m", {"text": "one"}, traceparent=context)+ assert client._base_url_headers == edge+ assert "traceparent" not in http.headers++ assert len(requests) == 3+ assert requests[0].content == requests[1].content == requests[2].content+ for index in [0, 2]:+ assert requests[index].headers.get("traceparent") == (_DEFAULT if edge else None)+ assert requests[index].headers.get("tracestate") == ("vendor=default" if edge else None)+ assert requests[1].headers["traceparent"] == _FIRST+ assert "tracestate" not in requests[1].headers+ assert all(request.headers["authorization"] == "Bearer api-test" for request in requests)+ assert all(request.headers.get("x-edge") == ("edge-test" if edge else None) for request in requests)++[email protected]("edge", [{}, _EDGE])+async def test_async_override_is_call_local_and_keeps_body_and_auth(edge: dict[str, str]) -> None:+ session = MagicMock(closed=False)+ session.post.side_effect = lambda *_args, **_kwargs: _AsyncContext(_success())+ session.close = AsyncMock()+ with patch("sie_sdk.client.async_.aiohttp.ClientSession", return_value=session) as factory:+ async with SIEAsyncClient(_BASE, api_key="api-test", base_url_headers=edge) as client:+ for context in [None, _FIRST, None]:+ await client.encode("m", {"text": "one"}, traceparent=context)+ assert client._base_url_headers == edge+ assert "traceparent" not in client._headers+ factory.assert_called_once()+ assert factory.call_args.kwargs["headers"]["Authorization"] == "Bearer api-test"+ calls = session.post.call_args_list+ headers = [httpx.Headers(call.kwargs.get("headers", {})) for call in calls]+ assert calls[0].kwargs["data"] == calls[1].kwargs["data"] == calls[2].kwargs["data"]+ for index in [0, 2]:+ assert headers[index].get("traceparent") == (_DEFAULT if edge else None)+ assert headers[index].get("tracestate") == ("vendor=default" if edge else None)+ assert headers[1]["traceparent"] == _FIRST+ assert "tracestate" not in headers[1]+ assert all(header.get("x-edge") == ("edge-test" if edge else None) for header in headers)+++def test_sync_concurrent_calls_keep_context_through_retry_and_continuation() -> None:+ barrier = Barrier(2)+ calls: list[tuple[str, str]] = []+ posts: Counter[str] = Counter()++ def respond(request: httpx.Request) -> httpx.Response:+ context = request.headers["traceparent"]+ calls.append((context, request.method))+ assert "tracestate" not in request.headers+ if request.method == "POST":+ posts[context] += 1+ if posts[context] == 1:+ barrier.wait(timeout=5)+ return _retry()+ return _redirect()+ return _success()++ with httpx.Client(base_url=_BASE, transport=httpx.MockTransport(respond)) as http:+ with SIEClient(_BASE, api_key="", base_url_headers=_EDGE, http_client=http) as client:+ with ThreadPoolExecutor(max_workers=2) as executor:+ futures = [+ executor.submit(client.encode, "m", {"text": "one"}, traceparent=c) for c in [_FIRST, _SECOND]+ ]+ assert all(future.result()["dense"].shape == (1,) for future in futures)+ assert client._client is http+ assert client._base_url_headers == _EDGE+ for context in [_FIRST, _SECOND]:+ assert [method for observed, method in calls if observed == context] == ["POST", "POST", "GET"]+++async def test_async_concurrent_calls_keep_context_through_retry_and_continuation() -> None:+ calls: list[tuple[str, str]] = []+ posts: Counter[str] = Counter()++ def respond(method: str, _url: str, **kwargs: Any) -> _AsyncContext:+ headers = httpx.Headers(kwargs["headers"])+ context = headers["traceparent"]+ calls.append((context, method))+ assert "tracestate" not in headers+ assert kwargs["allow_redirects"] is False+ if method == "POST":+ posts[context] += 1+ return _AsyncContext(_retry() if posts[context] == 1 else _redirect())+ return _AsyncContext(_success())++ session = MagicMock(closed=False)+ session.post.side_effect = lambda url, **kwargs: respond("POST", url, **kwargs)+ session.get.side_effect = lambda url, **kwargs: respond("GET", url, **kwargs)+ session.close = AsyncMock()+ with patch("sie_sdk.client.async_.aiohttp.ClientSession", return_value=session) as factory:+ async with SIEAsyncClient(_BASE, api_key="", base_url_headers=_EDGE) as client:+ results = await asyncio.gather(+ client.encode("m", {"text": "one"}, traceparent=_FIRST),+ client.encode("m", {"text": "one"}, traceparent=_SECOND),+ )+ assert all(result["dense"].shape == (1,) for result in results)+ assert client._base_url_headers == _EDGE+ factory.assert_called_once()+ for context in [_FIRST, _SECOND]:+ assert [method for observed, method in calls if observed == context] == ["POST", "POST", "GET"]+++def test_sync_call_context_is_not_forwarded_to_cross_origin_or_control_plane() -> None:+ with SIEClient(_BASE, api_key="", base_url_headers=_EDGE) as client:+ hook = client._client.event_hooks["request"][0]+ for url, skip in [("https://other.example.test/path", False), (f"{_BASE}/control-plane", True)]:+ request = httpx.Request(+ "POST", url, extensions={"sie_encode_traceparent": _FIRST, "sie_skip_base_url_headers": skip}+ )+ hook(request)+ assert "traceparent" not in request.headers+ assert "tracestate" not in request.headers+++async def test_async_call_context_is_not_forwarded_to_cross_origin_or_control_plane() -> None:+ async with SIEAsyncClient(_BASE, api_key="", base_url_headers=_EDGE) as client:+ for url, include in [("https://other.example.test/path", True), ("/control-plane", False)]:+ headers = client._headers_for_request(url, {}, include_base_url_headers=include, traceparent=_FIRST)+ assert "traceparent" not in {key.lower() for key in headers}+ assert "tracestate" not in {key.lower() for key in headers}+++def test_sync_cross_origin_continuation_is_not_followed() -> None:+ seen: list[httpx.Request] = []++ def respond(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return _redirect("https://other.example.test/v1/encode/m?__modal_attempt_token=opaque")++ with httpx.Client(base_url=_BASE, transport=httpx.MockTransport(respond)) as http:+ with SIEClient(_BASE, api_key="", http_client=http) as client:+ with pytest.raises(RequestError, match="Unexpected encode HTTP response"):+ client.encode("m", {"text": "one"}, traceparent=_FIRST)+ assert len(seen) == 1+ assert seen[0].url.host == "gateway.example.test"+++async def test_async_cross_origin_continuation_is_not_followed() -> None:+ session = MagicMock(closed=False)+ session.post.return_value = _AsyncContext(+ _redirect("https://other.example.test/v1/encode/m?__modal_attempt_token=opaque")+ )+ session.close = AsyncMock()+ with patch("sie_sdk.client.async_.aiohttp.ClientSession", return_value=session):+ async with SIEAsyncClient(_BASE, api_key="") as client:+ with pytest.raises(RequestError, match="Unexpected encode HTTP response"):+ await client.encode("m", {"text": "one"}, traceparent=_FIRST)+ session.post.assert_called_once()+ session.get.assert_not_called()diff --git a/packages/sie_sdk/tests/client/test_gateway_timing.py b/packages/sie_sdk/tests/client/test_gateway_timing.pynew file mode 100644index 000000000..afba0b8a6--- /dev/null+++ b/packages/sie_sdk/tests/client/test_gateway_timing.py@@ -0,0 +1,221 @@+"""Terminal encode timing headers remain separate from response-body timing."""++from __future__ import annotations++from typing import Self+from unittest.mock import AsyncMock, MagicMock, patch++import httpx+import numpy as np+import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk._msgpack import packb as pack_msgpack+from sie_sdk.client._shared import parse_gateway_timing+from sie_sdk.client.async_ import _AioResponse++_HEADERS = {+ "x-queue-publish-time": "1.2",+ "x-queue-wait-time": "3.4",+ "x-queue-time": "4.6",+ "x-inference-time": "2.1",+ "x-tokenization-time": "0.0",+ "x-postprocessing-time": "0.2",+ "x-payload-fetch-time": "0.3",+}+_EXPECTED = {+ "publish_ms": 1.2,+ "result_wait_ms": 3.4,+ "worker_queue_ms_max": 4.6,+ "worker_inference_ms_max": 2.1,+ "worker_tokenization_ms_max": 0.0,+ "worker_postprocessing_ms_max": 0.2,+ "worker_payload_fetch_ms_max": 0.3,+}+_REQUEST_ID = "69ed6ea7-df59-4b0e-bd1f-73922bedc5f9"+++def test_gateway_timing_uses_only_allowlisted_headers_and_keeps_units() -> None:+ headers = httpx.Headers({**_HEADERS, "x-total-time": "99", "x-private": "not-retained"})+ assert parse_gateway_timing(headers) == _EXPECTED+++ "value",+ [None, True, 1, 1.5, "", "-1", "NaN", "inf", "1e3", "1, 2", " 1", "1 ", "\uff11", "0x10", "9" * 65],+)+def test_gateway_timing_omits_invalid_values_independently(value: object) -> None:+ assert parse_gateway_timing({"x-queue-time": value, "x-queue-wait-time": "0.0"}) == {"result_wait_ms": 0.0}+ assert parse_gateway_timing({"x-queue-time": value}) is None+++def test_gateway_timing_missing_headers_do_not_create_values() -> None:+ assert parse_gateway_timing({}) is None+ assert parse_gateway_timing(httpx.Headers({"X-Queue-Time": "0.0", "X-Inference-Time": "0"})) == {+ "worker_queue_ms_max": 0.0,+ "worker_inference_ms_max": 0.0,+ }+++def _success(headers: dict[str, str], *, body_timing: bool = False, count: int = 2) -> httpx.Response:+ payload: dict[str, object] = {+ "model": "m",+ "items": [{"dense": {"dims": 1, "values": np.array([0.5], dtype=np.float32)}} for _ in range(count)],+ }+ if body_timing:+ payload["timing"] = {"total_ms": 30.0, "queue_ms": 20.0}+ return httpx.Response(+ 200,+ content=pack_msgpack(payload),+ headers={"content-type": "application/msgpack", "x-sie-request-id": _REQUEST_ID, **headers},+ )+++def _async_response(response: httpx.Response) -> _AioResponse:+ return _AioResponse(response.status_code, response.content, response.headers)++[email protected]("body_timing", [False, True])[email protected]("request_metadata", [False, True])+def test_sync_encode_preserves_gateway_and_body_timing_separately(body_timing: bool, request_metadata: bool) -> None:+ response = _success(_HEADERS, body_timing=body_timing)+ if not request_metadata:+ del response.headers["x-sie-request-id"]+ with httpx.Client(+ base_url="https://gateway.example.test", transport=httpx.MockTransport(lambda _: response)+ ) as http:+ with SIEClient("https://gateway.example.test", http_client=http) as client:+ results = client.encode("m", [{"text": "one"}, {"text": "two"}])++ assert len(results) == 2+ assert all(result["gateway_timing"] == _EXPECTED for result in results)+ assert all(result.get("request") == ({"id": _REQUEST_ID} if request_metadata else None) for result in results)+ assert all(+ result.get("timing") == ({"total_ms": 30.0, "queue_ms": 20.0} if body_timing else None) for result in results+ )+ results[0]["gateway_timing"]["publish_ms"] = 999+ assert results[1]["gateway_timing"]["publish_ms"] == 1.2++[email protected]("body_timing", [False, True])[email protected]("request_metadata", [False, True])+async def test_async_encode_preserves_gateway_and_body_timing_separately(+ body_timing: bool, request_metadata: bool+) -> None:+ response = _success(_HEADERS, body_timing=body_timing)+ if not request_metadata:+ del response.headers["x-sie-request-id"]+ client = SIEAsyncClient("https://gateway.example.test")+ with patch.object(client, "_post", AsyncMock(return_value=_async_response(response))):+ try:+ results = await client.encode("m", [{"text": "one"}, {"text": "two"}])+ finally:+ await client.close()++ assert len(results) == 2+ assert all(result["gateway_timing"] == _EXPECTED for result in results)+ assert all(result.get("request") == ({"id": _REQUEST_ID} if request_metadata else None) for result in results)+ assert all(+ result.get("timing") == ({"total_ms": 30.0, "queue_ms": 20.0} if body_timing else None) for result in results+ )+ results[0]["gateway_timing"]["publish_ms"] = 999+ assert results[1]["gateway_timing"]["publish_ms"] == 1.2+++def _retry() -> httpx.Response:+ return httpx.Response(+ 503,+ headers={"Retry-After": "0", "x-queue-time": "999", "x-queue-publish-time": "999"},+ json={"error": {"code": "PROVISIONING", "message": "starting"}},+ )++[email protected]("terminal_headers", [{}, {"x-queue-time": "NaN"}, {"x-queue-time": "2.5"}])+def test_sync_retry_and_next_call_never_reuse_previous_timing(terminal_headers: dict[str, str]) -> None:+ responses = iter([_success(_HEADERS, count=1), _retry(), _success(terminal_headers, count=1)])+ with httpx.Client(+ base_url="https://gateway.example.test", transport=httpx.MockTransport(lambda _: next(responses))+ ) as http:+ with SIEClient("https://gateway.example.test", http_client=http) as client:+ assert client.encode("m", {"text": "one"})["gateway_timing"] == _EXPECTED+ with patch("sie_sdk.client.sync.time.sleep"):+ result = client.encode("m", {"text": "two"})+ assert client.last_retry_count == 1+ assert result.get("gateway_timing") == (+ {"worker_queue_ms_max": 2.5} if "2.5" in terminal_headers.values() else None+ )+ assert "timing" not in result++[email protected]("terminal_headers", [{}, {"x-queue-time": "NaN"}, {"x-queue-time": "2.5"}])+async def test_async_retry_and_next_call_never_reuse_previous_timing(terminal_headers: dict[str, str]) -> None:+ responses = [+ _async_response(r) for r in [_success(_HEADERS, count=1), _retry(), _success(terminal_headers, count=1)]+ ]+ client = SIEAsyncClient("https://gateway.example.test")+ with patch.object(client, "_post", AsyncMock(side_effect=responses)):+ try:+ assert (await client.encode("m", {"text": "one"}))["gateway_timing"] == _EXPECTED+ with patch("sie_sdk.client.async_.asyncio.sleep", AsyncMock()):+ result = await client.encode("m", {"text": "two"})+ assert client.last_retry_count == 1+ finally:+ await client.close()+ assert result.get("gateway_timing") == (+ {"worker_queue_ms_max": 2.5} if "2.5" in terminal_headers.values() else None+ )+ assert "timing" not in result+++class _AsyncResponseContext:+ def __init__(self, response: httpx.Response) -> None:+ self.status = response.status_code+ self.headers = response.headers+ self._content = response.content++ async def __aenter__(self) -> Self:+ return self++ async def __aexit__(self, *_args: object) -> None:+ return None++ async def read(self) -> bytes:+ return self._content++[email protected]("terminal_headers", [{}, _HEADERS])+def test_sync_continuation_uses_only_terminal_headers(terminal_headers: dict[str, str]) -> None:+ methods: list[str] = []++ def respond(request: httpx.Request) -> httpx.Response:+ methods.append(request.method)+ if request.method == "POST":+ return httpx.Response(303, headers={"Location": "/v1/encode/m?__modal_attempt_token=opaque", **_HEADERS})+ return _success(terminal_headers, count=1)++ with httpx.Client(base_url="https://gateway.example.test", transport=httpx.MockTransport(respond)) as http:+ with SIEClient("https://gateway.example.test", http_client=http) as client:+ result = client.encode("m", {"text": "one"})+ assert client.last_retry_count == 0++ assert methods == ["POST", "GET"]+ assert result.get("gateway_timing") == (_EXPECTED if terminal_headers else None)++[email protected]("terminal_headers", [{}, _HEADERS])+async def test_async_continuation_uses_only_terminal_headers(terminal_headers: dict[str, str]) -> None:+ redirect = _AioResponse(303, b"", {"Location": "/v1/encode/m?__modal_attempt_token=opaque", **_HEADERS})+ session = MagicMock(closed=False)+ session.get.return_value = _AsyncResponseContext(_success(terminal_headers, count=1))+ session.close = AsyncMock()+ client = SIEAsyncClient("https://gateway.example.test")+ client._session = session+ with patch.object(client, "_post", AsyncMock(return_value=redirect)) as post:+ try:+ result = await client.encode("m", {"text": "one"})+ assert client.last_retry_count == 0+ finally:+ await client.close()++ post.assert_awaited_once()+ session.get.assert_called_once()+ assert result.get("gateway_timing") == (_EXPECTED if terminal_headers else None)