Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(sdk): retry only requests that never reached the server (#400)

Krisztian Gajdar0860d417ed60
diff --git a/integrations/sie_crewai/src/sie_crewai/tools.py b/integrations/sie_crewai/src/sie_crewai/tools.py
index 5b2f86b12..d0b28e90b 100644
--- a/integrations/sie_crewai/src/sie_crewai/tools.py
+++ b/integrations/sie_crewai/src/sie_crewai/tools.py
@@ -10,6 +10,15 @@ from typing import Any
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
+from sie_sdk import RequestError
+
+
+def _raise_for_item_error(result: Any) -> None:
+ """Raise when SIE reports that extraction failed for this item."""
+ error = result.get("error") if isinstance(result, Mapping) else None
+ if isinstance(error, Mapping):
+ msg = f"Extraction failed: {error.get('message')}"
+ raise RequestError(msg, code=error.get("code"), request=result.get("request"))
def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
@@ -251,6 +260,7 @@ class SIEExtractorTool(BaseTool):
Item(text=text),
labels=effective_labels,
)
+ _raise_for_item_error(result)
entities = self._parse_items(result, "entities")
relations = self._parse_items(result, "relations")
diff --git a/integrations/sie_crewai/tests/test_tools.py b/integrations/sie_crewai/tests/test_tools.py
index ec10ec305..69da9fde4 100644
--- a/integrations/sie_crewai/tests/test_tools.py
+++ b/integrations/sie_crewai/tests/test_tools.py
@@ -2,10 +2,11 @@
from __future__ import annotations
-from unittest.mock import create_autospec
+from unittest.mock import NonCallableMagicMock, create_autospec
+import pytest
from sie_crewai import SIEExtractorTool, SIERerankerTool, SIESparseEmbedder
-from sie_sdk import SIEClient
+from sie_sdk import RequestError, SIEClient
class TestSIERerankerTool:
@@ -300,3 +301,23 @@ class TestSIESparseEmbedder:
embedder = SIESparseEmbedder(model="test-model")
assert embedder._client is None
+
+
+def test_extractor_tool_raises_on_item_error(
+ mock_sie_client: NonCallableMagicMock, extract_item_error: dict[str, str]
+) -> None:
+ mock_sie_client.extract.side_effect = None
+ mock_sie_client.extract.return_value = {
+ "entities": [],
+ "relations": [],
+ "classifications": [],
+ "objects": [],
+ "error": dict(extract_item_error),
+ }
+ extractor = SIEExtractorTool(model="test-extractor", labels=["person"])
+ extractor._client = mock_sie_client
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ extractor._run(text="text")
+
+ assert excinfo.value.code == extract_item_error["code"]
diff --git a/integrations/sie_dspy/src/sie_dspy/modules.py b/integrations/sie_dspy/src/sie_dspy/modules.py
index bf6a1d9c2..4f9a60c1a 100644
--- a/integrations/sie_dspy/src/sie_dspy/modules.py
+++ b/integrations/sie_dspy/src/sie_dspy/modules.py
@@ -10,6 +10,15 @@ from dataclasses import dataclass
from typing import Any
import dspy
+from sie_sdk import RequestError
+
+
+def _raise_for_item_error(result: Any) -> None:
+ """Raise when SIE reports that extraction failed for this item."""
+ error = result.get("error") if isinstance(result, Mapping) else None
+ if isinstance(error, Mapping):
+ msg = f"Extraction failed: {error.get('message')}"
+ raise RequestError(msg, code=error.get("code"), request=result.get("request"))
def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
@@ -280,6 +289,7 @@ class SIEExtractor(dspy.Module):
Item(text=text),
labels=effective_labels,
)
+ _raise_for_item_error(result)
entities = self._parse_entities(result)
relations = self._parse_relations(result)
diff --git a/integrations/sie_dspy/tests/test_modules.py b/integrations/sie_dspy/tests/test_modules.py
index 92c92305d..ae2e5dfc7 100644
--- a/integrations/sie_dspy/tests/test_modules.py
+++ b/integrations/sie_dspy/tests/test_modules.py
@@ -3,12 +3,13 @@
from __future__ import annotations
from collections import Counter
-from unittest.mock import create_autospec
+from unittest.mock import NonCallableMagicMock, create_autospec
import dspy
+import pytest
from sie_dspy import SIEExtractor, SIEReranker
from sie_dspy.modules import Entity
-from sie_sdk import SIEClient
+from sie_sdk import RequestError, SIEClient
class TestSIEReranker:
@@ -267,3 +268,23 @@ class TestSIEExtractor:
result = extractor.forward(text=research_text)
assert isinstance(result, dspy.Prediction)
+
+
+def test_extractor_forward_raises_on_item_error(
+ mock_sie_client: NonCallableMagicMock, extract_item_error: dict[str, str]
+) -> None:
+ mock_sie_client.extract.side_effect = None
+ mock_sie_client.extract.return_value = {
+ "entities": [],
+ "relations": [],
+ "classifications": [],
+ "objects": [],
+ "error": dict(extract_item_error),
+ }
+ extractor = SIEExtractor(model="test-extractor")
+ extractor._client = mock_sie_client
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ extractor.forward(text="text")
+
+ assert excinfo.value.code == extract_item_error["code"]
diff --git a/integrations/sie_haystack/src/sie_haystack/extractors.py b/integrations/sie_haystack/src/sie_haystack/extractors.py
index 48b8cce6d..e30f88b8e 100644
--- a/integrations/sie_haystack/src/sie_haystack/extractors.py
+++ b/integrations/sie_haystack/src/sie_haystack/extractors.py
@@ -6,13 +6,23 @@ and detected objects from text.
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
from haystack import component
+from sie_sdk import RequestError
from sie_sdk.types import Item
+def _raise_for_item_error(result: Any) -> None:
+ """Raise when SIE reports that extraction failed for this item."""
+ error = result.get("error") if isinstance(result, Mapping) else None
+ if isinstance(error, Mapping):
+ msg = f"Extraction failed: {error.get('message')}"
+ raise RequestError(msg, code=error.get("code"), request=result.get("request"))
+
+
@dataclass
class Entity:
"""Extracted entity with position and label information."""
@@ -162,6 +172,7 @@ class SIEExtractor:
Item(text=text, metadata=metadata),
labels=effective_labels,
)
+ _raise_for_item_error(result)
return {
"entities": self._build_entities(result),
diff --git a/integrations/sie_haystack/tests/test_extractors.py b/integrations/sie_haystack/tests/test_extractors.py
index b45172536..4970090c4 100644
--- a/integrations/sie_haystack/tests/test_extractors.py
+++ b/integrations/sie_haystack/tests/test_extractors.py
@@ -2,8 +2,12 @@
from __future__ import annotations
+from unittest.mock import NonCallableMagicMock
+
+import pytest
from sie_haystack import SIEExtractor
from sie_haystack.extractors import Entity
+from sie_sdk import RequestError
class TestSIEExtractor:
@@ -116,3 +120,21 @@ class TestSIEExtractor:
assert entity.score == 0.95
assert entity.start == 0
assert entity.end == 10
+
+
+def test_run_raises_on_item_error(mock_sie_client: NonCallableMagicMock, extract_item_error: dict[str, str]) -> None:
+ mock_sie_client.extract.side_effect = None
+ mock_sie_client.extract.return_value = {
+ "entities": [],
+ "relations": [],
+ "classifications": [],
+ "objects": [],
+ "error": dict(extract_item_error),
+ }
+ extractor = SIEExtractor(model="test-extractor")
+ extractor._client = mock_sie_client
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ extractor.run(text="text")
+
+ assert excinfo.value.code == extract_item_error["code"]
diff --git a/integrations/sie_lancedb/src/sie_lancedb/extractors.py b/integrations/sie_lancedb/src/sie_lancedb/extractors.py
index c3d0e1ea6..4b2bf45f7 100644
--- a/integrations/sie_lancedb/src/sie_lancedb/extractors.py
+++ b/integrations/sie_lancedb/src/sie_lancedb/extractors.py
@@ -11,9 +11,11 @@ The extractor supports two usage patterns:
from __future__ import annotations
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any
import pyarrow as pa
+from sie_sdk import RequestError
if TYPE_CHECKING:
import lancedb
@@ -137,7 +139,8 @@ class SIEExtractor:
items = [Item(text=t) for t in batch]
results = self.client.extract(self._model, items, labels=labels)
- for result in results:
+ for offset, result in enumerate(results):
+ _raise_for_item_error(result, i + offset)
entities = result.get("entities", []) if isinstance(result, dict) else getattr(result, "entities", [])
all_entities.append(_format_entities(entities))
@@ -199,6 +202,14 @@ class SIEExtractor:
table.merge(enrichment, id_column)
+def _raise_for_item_error(result: Any, index: int) -> None:
+ """Raise when SIE reports that extraction failed for the item at ``index``."""
+ error = result.get("error") if isinstance(result, Mapping) else None
+ if isinstance(error, Mapping):
+ msg = f"Extraction failed for item {index}: {error.get('message')}"
+ raise RequestError(msg, code=error.get("code"), request=result.get("request"))
+
+
def _format_entities(entities: list) -> list[dict[str, Any]]:
"""Format raw entity results into normalized dicts.
diff --git a/integrations/sie_lancedb/tests/test_extractors.py b/integrations/sie_lancedb/tests/test_extractors.py
index 71b3e1e5b..5a8b03fe3 100644
--- a/integrations/sie_lancedb/tests/test_extractors.py
+++ b/integrations/sie_lancedb/tests/test_extractors.py
@@ -2,11 +2,14 @@
from __future__ import annotations
+from unittest.mock import NonCallableMagicMock
+
import lancedb
import pyarrow as pa
import pytest
from sie_lancedb import SIEExtractor
from sie_lancedb.extractors import _build_entities_array, _format_entities
+from sie_sdk import RequestError
@pytest.fixture
@@ -247,3 +250,22 @@ class TestBuildEntitiesArray:
assert isinstance(result, pa.Array)
assert len(result) == 0
+
+
+def test_extract_raises_on_item_error_with_position(
+ mock_sie_client: NonCallableMagicMock, extract_item_error: dict[str, str]
+) -> None:
+ ok = {"entities": [], "relations": [], "classifications": [], "objects": []}
+ mock_sie_client.extract.side_effect = [
+ [ok, ok],
+ [
+ ok,
+ {"entities": [], "relations": [], "classifications": [], "objects": [], "error": dict(extract_item_error)},
+ ],
+ ]
+ extractor = SIEExtractor(model="test-model", client=mock_sie_client)
+
+ with pytest.raises(RequestError, match="for item 3") as excinfo:
+ extractor.extract(["a", "b", "c", "d"], labels=["person"], batch_size=2)
+
+ assert excinfo.value.code == extract_item_error["code"]
diff --git a/integrations/sie_langchain/src/sie_langchain/extractors.py b/integrations/sie_langchain/src/sie_langchain/extractors.py
index 053ba6d29..e7866bb59 100644
--- a/integrations/sie_langchain/src/sie_langchain/extractors.py
+++ b/integrations/sie_langchain/src/sie_langchain/extractors.py
@@ -5,10 +5,12 @@ Provides entity, relation, classification, and object extraction using SIE's ext
from __future__ import annotations
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any
from langchain_core.tools import BaseTool
from pydantic import ConfigDict, Field
+from sie_sdk import RequestError
from sie_sdk.types import Item
if TYPE_CHECKING:
@@ -16,6 +18,14 @@ if TYPE_CHECKING:
from sie_sdk import SIEAsyncClient, SIEClient
+def _raise_for_item_error(result: Any) -> None:
+ """Raise when SIE reports that extraction failed for this item."""
+ error = result.get("error") if isinstance(result, Mapping) else None
+ if isinstance(error, Mapping):
+ msg = f"Extraction failed: {error.get('message')}"
+ raise RequestError(msg, code=error.get("code"), request=result.get("request"))
+
+
class SIEExtractor(BaseTool):
"""LangChain tool for extraction using SIE.
@@ -166,7 +176,11 @@ class SIEExtractor(BaseTool):
Returns:
Dict with entities, relations, classifications, and objects.
+
+ Raises:
+ RequestError: If SIE reports that extraction failed for the text.
"""
+ _raise_for_item_error(result)
def _get(key: str) -> list:
if isinstance(result, dict):
diff --git a/integrations/sie_langchain/tests/test_extractors.py b/integrations/sie_langchain/tests/test_extractors.py
index e8d2212b8..977ab7ce6 100644
--- a/integrations/sie_langchain/tests/test_extractors.py
+++ b/integrations/sie_langchain/tests/test_extractors.py
@@ -2,8 +2,11 @@
from __future__ import annotations
+from unittest.mock import NonCallableMagicMock
+
import pytest
from sie_langchain import SIEExtractor
+from sie_sdk import RequestError
class TestSIEExtractor:
@@ -92,3 +95,26 @@ class TestSIEExtractorAsync:
result = await extractor.ainvoke(test_ner_text)
assert isinstance(result, dict)
+
+
+def test_extract_raises_on_item_error(
+ mock_sie_client: NonCallableMagicMock, extract_error_text: str, extract_item_error: dict[str, str]
+) -> None:
+ extractor = SIEExtractor(client=mock_sie_client, model="test-ner", labels=["PERSON"])
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ extractor._run(extract_error_text)
+
+ assert excinfo.value.code == extract_item_error["code"]
+
+
+async def test_aextract_raises_on_item_error(
+ mock_sie_async_client: NonCallableMagicMock, extract_error_text: str, extract_item_error: dict[str, str]
+) -> None:
+ extractor = SIEExtractor(async_client=mock_sie_async_client, model="test-ner", labels=["PERSON"])
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ await extractor._arun(extract_error_text)
+
+ assert excinfo.value.code == extract_item_error["code"]
diff --git a/integrations/sie_llamaindex/src/sie_llamaindex/extractors.py b/integrations/sie_llamaindex/src/sie_llamaindex/extractors.py
index e7ac2425b..eb9ec34bc 100644
--- a/integrations/sie_llamaindex/src/sie_llamaindex/extractors.py
+++ b/integrations/sie_llamaindex/src/sie_llamaindex/extractors.py
@@ -5,14 +5,24 @@ Provides entity, relation, classification, and object extraction using SIE's ext
from __future__ import annotations
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any
from llama_index.core.tools import FunctionTool
+from sie_sdk import RequestError
if TYPE_CHECKING:
from sie_sdk import SIEClient
+def _raise_for_item_error(result: Any) -> None:
+ """Raise when SIE reports that extraction failed for this item."""
+ error = result.get("error") if isinstance(result, Mapping) else None
+ if isinstance(error, Mapping):
+ msg = f"Extraction failed: {error.get('message')}"
+ raise RequestError(msg, code=error.get("code"), request=result.get("request"))
+
+
def create_sie_extractor_tool(
base_url: str = "http://localhost:8080",
model: str = "urchade/gliner_multi-v2.1",
@@ -148,6 +158,7 @@ class _SIEExtractor:
def _format_result(self, result: object) -> dict[str, list[dict[str, Any]]]:
"""Format extraction result into multi-type dict."""
+ _raise_for_item_error(result)
def _get(key: str) -> list:
if isinstance(result, dict):
diff --git a/integrations/sie_llamaindex/tests/test_extractors.py b/integrations/sie_llamaindex/tests/test_extractors.py
index 5b225decc..c257d91b0 100644
--- a/integrations/sie_llamaindex/tests/test_extractors.py
+++ b/integrations/sie_llamaindex/tests/test_extractors.py
@@ -2,7 +2,12 @@
from __future__ import annotations
+from unittest.mock import NonCallableMagicMock
+
+import pytest
from sie_llamaindex import create_sie_extractor_tool
+from sie_llamaindex.extractors import _SIEExtractor
+from sie_sdk import RequestError
class TestSIEExtractorTool:
@@ -105,3 +110,22 @@ class TestSIEExtractorTool:
# The tool wraps a function that uses _SIEExtractor
assert callable(tool.fn)
+
+
+def test_extract_raises_on_item_error(
+ mock_sie_client: NonCallableMagicMock, extract_error_text: str, extract_item_error: dict[str, str]
+) -> None:
+ extractor = _SIEExtractor(
+ base_url="http://localhost:8080",
+ model="test-extractor",
+ labels=["person"],
+ options=None,
+ gpu=None,
+ timeout_s=180.0,
+ )
+ extractor._client = mock_sie_client
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ extractor.extract(extract_error_text)
+
+ assert excinfo.value.code == extract_item_error["code"]
diff --git a/integrations/sie_ts_langchain/src/extractors.ts b/integrations/sie_ts_langchain/src/extractors.ts
index 0fe201b55..df998a7c2 100644
--- a/integrations/sie_ts_langchain/src/extractors.ts
+++ b/integrations/sie_ts_langchain/src/extractors.ts
@@ -27,6 +27,7 @@ import { Tool } from "@langchain/core/tools";
import {
type ExtractOptions,
type ExtractResult,
+ RequestError,
SIEClient,
type SIEClientOptions,
} from "@superlinked/sie-sdk";
@@ -179,6 +180,7 @@ export class SIEExtractor extends Tool {
*
* @param text - Text to extract from.
* @returns JSON string with entities, relations, classifications, and objects.
+ * @throws {RequestError} If SIE reports that extraction failed for the text.
*/
async _call(text: string): Promise<string> {
const extractOptions: ExtractOptions = {
@@ -189,6 +191,14 @@ export class SIEExtractor extends Tool {
}
const result: ExtractResult = await this.client.extract(this.model, { text }, extractOptions);
+ if (result.error) {
+ throw new RequestError(
+ `Extraction failed: ${result.error.message}`,
+ result.error.code,
+ undefined,
+ result.request?.id,
+ );
+ }
return JSON.stringify({
entities: result.entities.map((e) => ({
diff --git a/integrations/sie_ts_langchain/tests/extractors.test.ts b/integrations/sie_ts_langchain/tests/extractors.test.ts
index 7a23e28c6..820fee148 100644
--- a/integrations/sie_ts_langchain/tests/extractors.test.ts
+++ b/integrations/sie_ts_langchain/tests/extractors.test.ts
@@ -177,4 +177,30 @@ describe("SIEExtractor", () => {
expect(parsed.entities[0]).toEqual({ text: "Test", label: "thing", score: 0.9 });
expect(parsed.entities[0].start).toBeUndefined();
});
+
+ it("throws when SIE reports a per-item extraction failure", async () => {
+ const { RequestError, SIEClient } = await import("@superlinked/sie-sdk");
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ asConstructor({
+ extract: vi.fn().mockResolvedValue({
+ entities: [],
+ relations: [],
+ classifications: [],
+ objects: [],
+ error: {
+ code: "INPUT_TOO_LONG",
+ message: "Input exceeds the model's maximum token capacity",
+ },
+ request: { id: "req-1" },
+ }),
+ close: vi.fn(),
+ }),
+ );
+
+ const extractor = new SIEExtractor();
+ const error = await extractor._call("test").catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(RequestError);
+ expect(error).toMatchObject({ code: "INPUT_TOO_LONG", requestId: "req-1" });
+ });
});
diff --git a/integrations/sie_ts_llamaindex/src/extractors.ts b/integrations/sie_ts_llamaindex/src/extractors.ts
index 05b1f1629..b6a736f62 100644
--- a/integrations/sie_ts_llamaindex/src/extractors.ts
+++ b/integrations/sie_ts_llamaindex/src/extractors.ts
@@ -24,6 +24,7 @@
import {
type ExtractOptions,
type ExtractResult,
+ RequestError,
SIEClient,
type SIEClientOptions,
} from "@superlinked/sie-sdk";
@@ -121,6 +122,14 @@ class _SIEExtractor {
{ text },
extractOptions,
);
+ if (result.error) {
+ throw new RequestError(
+ `Extraction failed: ${result.error.message}`,
+ result.error.code,
+ undefined,
+ result.request?.id,
+ );
+ }
return JSON.stringify({
entities: result.entities.map((e) => ({
diff --git a/integrations/sie_ts_llamaindex/tests/extractors.test.ts b/integrations/sie_ts_llamaindex/tests/extractors.test.ts
index 5444c528f..e74487cc5 100644
--- a/integrations/sie_ts_llamaindex/tests/extractors.test.ts
+++ b/integrations/sie_ts_llamaindex/tests/extractors.test.ts
@@ -129,6 +129,32 @@ describe("createSIEExtractorTool", () => {
expect(parsed.relations).toEqual([]);
});
+ it("throws when SIE reports a per-item extraction failure", async () => {
+ const { RequestError, SIEClient } = await import("@superlinked/sie-sdk");
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ asConstructor({
+ extract: vi.fn().mockResolvedValue({
+ entities: [],
+ relations: [],
+ classifications: [],
+ objects: [],
+ error: {
+ code: "INPUT_TOO_LONG",
+ message: "Input exceeds the model's maximum token capacity",
+ },
+ request: { id: "req-1" },
+ }),
+ close: vi.fn(),
+ }),
+ );
+
+ const tool = createSIEExtractorTool();
+ const error = await tool.call({ text: "test" }).catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(RequestError);
+ expect(error).toMatchObject({ code: "INPUT_TOO_LONG", requestId: "req-1" });
+ });
+
it("includes label types in default description", () => {
const tool = createSIEExtractorTool({
labels: ["animal", "color"],
diff --git a/integrations/sie_weaviate/src/sie_weaviate/enricher.py b/integrations/sie_weaviate/src/sie_weaviate/enricher.py
index 5b5525784..17c65f65e 100644
--- a/integrations/sie_weaviate/src/sie_weaviate/enricher.py
+++ b/integrations/sie_weaviate/src/sie_weaviate/enricher.py
@@ -9,14 +9,22 @@ from __future__ import annotations
import asyncio
import dataclasses
-from collections.abc import AsyncIterator, Iterator
+from collections.abc import AsyncIterator, Iterator, Mapping
from typing import Any, Self
-from sie_sdk import SIEAsyncClient, SIEClient
+from sie_sdk import RequestError, SIEAsyncClient, SIEClient
from sie_sdk.encoding import dense_embedding
from sie_sdk.types import Item
+def _raise_for_item_error(result: Any) -> None:
+ """Raise when SIE reports that extraction failed for this item."""
+ error = result.get("error") if isinstance(result, Mapping) else None
+ if isinstance(error, Mapping):
+ msg = f"Extraction failed: {error.get('message')}"
+ raise RequestError(msg, code=error.get("code"), request=result.get("request"))
+
+
@dataclasses.dataclass
class EnrichedDocument:
"""A document enriched with SIE embeddings and extracted properties.
@@ -366,10 +374,12 @@ class SIEDocumentEnricher:
raw_classifications: list[dict[str, Any]] | None = None
if extract_results is not None:
+ _raise_for_item_error(extract_results[i])
raw_entities = self._get_entities(extract_results[i])
self._merge_entity_properties(properties, raw_entities)
if classify_results is not None:
+ _raise_for_item_error(classify_results[i])
raw_classifications = self._get_classifications(classify_results[i])
self._merge_classification_properties(properties, raw_classifications)
diff --git a/integrations/sie_weaviate/tests/test_enricher.py b/integrations/sie_weaviate/tests/test_enricher.py
index 4222a6f88..bac32141a 100644
--- a/integrations/sie_weaviate/tests/test_enricher.py
+++ b/integrations/sie_weaviate/tests/test_enricher.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
import pytest
+from sie_sdk import RequestError
from sie_weaviate import EnrichedDocument, SIEDocumentEnricher
@@ -327,3 +328,34 @@ class TestSIEDocumentEnricherAsync:
pass
mock_sie_async_client.close.assert_called_once()
+
+
+def test_enrich_raises_on_item_error(mock_sie_client: MagicMock, extract_item_error: dict[str, str]) -> None:
+ mock_sie_client.extract.side_effect = None
+ mock_sie_client.extract.return_value = [
+ {"entities": [], "relations": [], "classifications": [], "objects": [], "error": dict(extract_item_error)}
+ ]
+ enricher = SIEDocumentEnricher()
+ enricher._client = mock_sie_client
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ enricher.enrich(["text"])
+
+ assert excinfo.value.code == extract_item_error["code"]
+
+
+async def test_aenrich_raises_on_item_error(
+ mock_sie_async_client: AsyncMock, extract_item_error: dict[str, str]
+) -> None:
+ mock_sie_async_client.extract.side_effect = None
+ mock_sie_async_client.extract.return_value = [
+ {"entities": [], "relations": [], "classifications": [], "objects": [], "error": dict(extract_item_error)}
+ ]
+ enricher = SIEDocumentEnricher()
+ enricher._async_client = mock_sie_async_client
+
+ with pytest.raises(RequestError, match="Extraction failed") as excinfo:
+ await enricher.aenrich(["text"])
+
+ assert excinfo.value.code == extract_item_error["code"]
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index 15e5d81a3..b4046b00b 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -313,6 +313,34 @@ next section for the `RESOURCE_EXHAUSTED` budget):
`ResourceExhaustedError` when retries run out. Pass
`max_oom_retries=0` to disable these retries and fail fast.
+Admission rejections happen before any work is dispatched, so every call
+retries them within `provision_timeout_s`, honouring `Retry-After`:
+`429 RATE_LIMIT`, `503 QUEUE_FULL`, and the gateway's queue backpressure,
+a `503 QUEUE_UNAVAILABLE` that carries `Retry-After`. A
+`QUEUE_UNAVAILABLE` without `Retry-After` is terminal.
+[`packages/wire-fixtures/retry_classification.json`](../wire-fixtures/retry_classification.json)
+lists how each response is classified; the Python and TypeScript SDKs
+both test against it.
+
+### Timeouts
+
+Each attempt has a connect timeout (`connect_timeout_s`, default 10 s)
+and a read timeout (`read_timeout_s`, default 150 s, longer than the
+gateway's default 120 s request deadline). `timeout_s` sets both at
+once. A connection that cannot be established is retried under
+`wait_for_capacity`. A read timeout is never retried, because the server
+may still be processing the request. Buffered `generate`,
+`chat_completions` and `responses` accept a per-call `read_timeout_s`;
+set it to at least the model profile's `overall_timeout_s` for long
+generations.
+
+### Partial batches
+
+When a batch response carries fewer items than were sent, `encode` and
+`extract` raise `IncompleteBatchError`. Its `results` attribute holds the
+items that did come back (match them by `id`), and `missing_ids` names
+the dropped items when every submitted item carried an `id`.
+
One generation-specific error is terminal and never retried:
- `empty_model_output` — the generation finished nominally but produced
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index 2af9d39fd..0cc4ee99b 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -338,6 +338,31 @@ def validate_generate_request_body(request_body: MutableMapping[str, Any]) -> No
DEFAULT_PROVISION_TIMEOUT_S = 900.0 # 15 minutes
DEFAULT_RETRY_DELAY_S = 5.0 # Retry every 5 seconds if no Retry-After header
+# Per-attempt transport timeouts. The read timeout must outlast the gateway's
+# default 120 s request deadline so its typed 504 reaches the caller before
+# the client gives up on a request the server is still running.
+DEFAULT_CONNECT_TIMEOUT_S = 10.0
+DEFAULT_READ_TIMEOUT_S = 150.0
+
+
+def resolve_timeouts(
+ timeout_s: float | None,
+ connect_timeout_s: float | None,
+ read_timeout_s: float | None,
+) -> tuple[float, float]:
+ """Resolve the client's ``(connect, read)`` timeouts in seconds.
+
+ ``timeout_s`` keeps its original meaning of one limit for every phase of
+ an attempt, so it sets both values. ``connect_timeout_s`` and
+ ``read_timeout_s`` override the matching phase.
+ """
+ fallback_connect = timeout_s if timeout_s is not None else DEFAULT_CONNECT_TIMEOUT_S
+ fallback_read = timeout_s if timeout_s is not None else DEFAULT_READ_TIMEOUT_S
+ connect = connect_timeout_s if connect_timeout_s is not None else fallback_connect
+ read = read_timeout_s if read_timeout_s is not None else fallback_read
+ return connect, read
+
+
# Pool settings
DEFAULT_LEASE_RENEWAL_INTERVAL_S = 60.0 # Renew lease every 60s (lease is 1200s)
@@ -465,6 +490,14 @@ BILLING_CAPACITY_UNAVAILABLE_ERROR_CODE = "BILLING_CAPACITY_UNAVAILABLE"
QUEUE_FULL_ERROR_CODE = "QUEUE_FULL"
BACKPRESSURE_503_ERROR_CODES = frozenset({BILLING_CAPACITY_UNAVAILABLE_ERROR_CODE, QUEUE_FULL_ERROR_CODE})
BACKPRESSURE_503_DEFAULT_DELAY_S = 1.0 # Fallback when the server omits Retry-After
+# The gateway answers a publish rejected by queue backpressure with 503
+# QUEUE_UNAVAILABLE (``transport_failure`` in the OpenAI envelope used by the
+# generation routes) plus Retry-After. The same codes without Retry-After
+# report failures that may follow publication, so only the hinted form is
+# retryable.
+QUEUE_UNAVAILABLE_ERROR_CODE = "QUEUE_UNAVAILABLE"
+OPENAI_TRANSPORT_FAILURE_ERROR_CODE = "transport_failure"
+RETRY_AFTER_GATED_503_ERROR_CODES = frozenset({QUEUE_UNAVAILABLE_ERROR_CODE, OPENAI_TRANSPORT_FAILURE_ERROR_CODE})
# ── Terminal credit / account errors (pass-2 audit B3) — NEVER retried ──
# 402/403 credit/account failures are mapped to typed exceptions in
@@ -644,6 +677,14 @@ def is_transient_connect_error(exc: BaseException) -> bool:
return True
+def read_timeout_message(error: BaseException) -> str:
+ """Message for a timeout after the request was sent, which is never retried."""
+ return (
+ f"Request timed out waiting for the response ({type(error).__name__}). Not retried because the "
+ f"server may already be processing the request; increase the read timeout for slow calls: {error}"
+ )
+
+
def compute_retry_delay(
*,
start_time: float,
@@ -1318,6 +1359,16 @@ def provisioning_retry_delay(
return apply_jitter(min(DEFAULT_RETRY_DELAY_S, remaining))
+def is_backpressure_503(response: _HttpResponse) -> bool:
+ """Whether a 503 is a retryable pre-dispatch backpressure rejection."""
+ if response.status_code != HTTP_SERVICE_UNAVAILABLE:
+ return False
+ code = get_error_code(response)
+ if code in BACKPRESSURE_503_ERROR_CODES:
+ return True
+ return code in RETRY_AFTER_GATED_503_ERROR_CODES and get_retry_after(response) is not None
+
+
def admission_retry_delay(
response: _HttpResponse,
*,
@@ -1342,6 +1393,13 @@ def admission_retry_delay(
self-hosted queue backpressure, #3180). On give-up raises the server's
terminal 503 verbatim via :func:`handle_error` (a :class:`ServerError`
preserving the code).
+ * ``503 QUEUE_UNAVAILABLE`` / ``transport_failure`` carrying a usable
+ ``Retry-After``: the gateway rejected the publish under queue
+ backpressure. Without the hint these codes stay terminal. The give-up
+ matches the previous arm.
+
+ ``packages/wire-fixtures/retry_classification.json`` pins these
+ decisions for both SDKs.
Retry timing mirrors :func:`provisioning_retry_delay`: the server-supplied
``Retry-After`` is honored verbatim, and only the SDK's own fallback default
@@ -1370,7 +1428,7 @@ def admission_retry_delay(
request=parse_request_metadata(response.headers),
)
return delay
- if status == HTTP_SERVICE_UNAVAILABLE and get_error_code(response) in BACKPRESSURE_503_ERROR_CODES:
+ if status == HTTP_SERVICE_UNAVAILABLE and is_backpressure_503(response):
retry_after = get_retry_after(response)
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
@@ -1407,7 +1465,8 @@ def next_stream_retry_delay(
Returns ``(delay_seconds, new_oom_retries)`` to sleep-then-retry, or
raises a terminal error. Only explicit pre-execution signals are retried
- (503 PROVISIONING / MODEL_LOADING / RESOURCE_EXHAUSTED); a 504 and any
+ (503 PROVISIONING / MODEL_LOADING / RESOURCE_EXHAUSTED and the admission
+ rejections handled by :func:`admission_retry_delay`); a 504 and any
other error are terminal —
streaming generation is non-idempotent, so a post-publish retry could
double-bill.
@@ -1452,6 +1511,10 @@ def next_stream_retry_delay(
delay = compute_oom_backoff(get_retry_after(response), oom_retries)
return min(delay, timeout - elapsed), oom_retries + 1
+ admission_delay = admission_retry_delay(response, start_time=start_time, timeout=timeout)
+ if admission_delay is not None:
+ return admission_delay, oom_retries
+
if status == HTTP_GATEWAY_TIMEOUT:
msg = (
"Gateway timed out (504) after the request was published to the queue; "
@@ -1772,7 +1835,8 @@ def validate_batch_result_count(
Raising a typed, actionable :class:`IncompleteBatchError` keeps the
failure legible: it names the model, the expected vs. returned counts,
the gateway request id, and — when the submitted items carried ids — the
- ids the response dropped.
+ ids the response dropped. It also carries the returned ``results`` so a
+ caller can keep the items that succeeded.
Args:
results: Parsed results from the server response.
@@ -1808,6 +1872,7 @@ def validate_batch_result_count(
model=model,
missing_ids=missing_ids,
request=request,
+ results=results,
)
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index df14009a3..7f076aa1d 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -30,6 +30,7 @@ from __future__ import annotations
import asyncio
import contextlib
+import contextvars
import json
import logging
import time
@@ -151,7 +152,9 @@ from ._shared import (
raise_if_estimate_unroutable,
raise_if_input_too_long,
raise_if_model_load_failed,
+ read_timeout_message,
request_matches_base_url_origin,
+ resolve_timeouts,
retry_after_or_default,
settled_charge_from_usage,
sse_chunk_error,
@@ -205,23 +208,41 @@ def _fail_pool_creation(future: asyncio.Future[None], exc: BaseException) -> Non
future.exception()
-# Mid-flight transport errors retried under `wait_for_capacity=True`:
-# the request was in flight and the peer severed the connection before a
-# complete response arrived (proxy idle timeout, rolling restart,
-# ECONNRESET). `ClientConnectorError` is retried separately at each call
-# site to preserve its distinct "Failed to connect" message.
-# Call-site `except` order: `_RETRYABLE_TRANSPORT_ERRORS` →
-# `ClientConnectorError` → `(ClientError, OSError)` (first-match
-# routing requires most-specific first).
+# Failures before the request reached the server; retried under
+# `wait_for_capacity=True` on every path. aiohttp raises
+# `ConnectionTimeoutError` (3.10+) for connect-phase timeouts; older releases
+# report them as the ambiguous `ServerTimeoutError`, which stays terminal.
+_CONNECT_PHASE_ERRORS: tuple[type[BaseException], ...] = (
+ aiohttp.ClientConnectorError,
+ *(error for error in (getattr(aiohttp, "ConnectionTimeoutError", None),) if isinstance(error, type)),
+)
+
+# Mid-flight transport errors retried under `wait_for_capacity=True` on the
+# idempotent encode/score/extract paths: the peer severed the connection
+# before a complete response arrived (proxy idle timeout, rolling restart,
+# ECONNRESET).
_RETRYABLE_TRANSPORT_ERRORS: tuple[type[BaseException], ...] = (
- TimeoutError,
aiohttp.ServerDisconnectedError,
- aiohttp.ServerTimeoutError,
aiohttp.ClientPayloadError,
)
+# Timeouts after the request may have reached the server: never retried.
+# Call-site `except` order: `_CONNECT_PHASE_ERRORS` →
+# `_RETRYABLE_TRANSPORT_ERRORS` → `_SENT_REQUEST_TIMEOUT_ERRORS` →
+# `(ClientError, OSError)` (first-match routing requires most-specific first).
+_SENT_REQUEST_TIMEOUT_ERRORS: tuple[type[BaseException], ...] = (
+ TimeoutError,
+ aiohttp.ServerTimeoutError,
+)
+
_LEASE_RENEWAL_MAX_RETRIES = 5
+# Per-task retry counts keyed by client id. Each update stores a new dict, so
+# a task spawned from this context never shares counts with its parent.
+_LAST_RETRY_COUNTS: contextvars.ContextVar[dict[int, int] | None] = contextvars.ContextVar(
+ "sie_sdk_async_last_retry_counts", default=None
+)
+
def _parse_generate_result_async(
data: dict[str, Any],
@@ -401,7 +422,9 @@ class SIEAsyncClient:
Args:
base_url: Base URL of the SIE server (e.g., "http://localhost:8080").
- timeout_s: Request timeout in seconds (default: 30.0).
+ timeout_s: One per-attempt limit in seconds for both connecting and
+ waiting for response data. Sets ``connect_timeout_s`` and
+ ``read_timeout_s`` together; either of those overrides it.
api_key: Optional API key for authentication (sent as Bearer token).
gpu: GPU type for requests (e.g., "l4", "a100-80gb"). Can be overridden per-call.
options: Options dict for requests. Merged with per-call options (per-call wins).
@@ -411,6 +434,13 @@ class SIEAsyncClient:
origin. Values are copied at construction and never forwarded to a
control-plane URL, external payload-store reference, or redirect
target. Same-origin capability refs receive only these edge headers.
+ connect_timeout_s: Seconds allowed to establish a connection (default:
+ 10). A connection that cannot be established is retried under
+ ``wait_for_capacity``.
+ read_timeout_s: Seconds to wait for response data once a request is
+ sent (default: 150, longer than the gateway's default 120 s
+ request deadline). A read timeout is never retried, because the
+ server may still be processing the request.
Example:
>>> async with SIEAsyncClient("http://localhost:8080") as client:
@@ -440,7 +470,7 @@ class SIEAsyncClient:
self,
base_url: str,
*,
- timeout_s: float = 30.0,
+ timeout_s: float | None = None,
api_key: str | None = None,
gpu: str | None = None,
options: dict[str, Any] | None = None,
@@ -450,6 +480,8 @@ class SIEAsyncClient:
control_plane_url: str | None = None,
org: str | None = None,
base_url_headers: Mapping[str, str] | None = None,
+ connect_timeout_s: float | None = None,
+ read_timeout_s: float | None = None,
) -> None:
# Normalize base_url (remove trailing slash)
validate_base_url(base_url)
@@ -458,7 +490,7 @@ class SIEAsyncClient:
if self._base_url_headers and not base_url_accepts_origin_credentials(self._base_url):
msg = "base_url_headers require an absolute https base_url without embedded credentials"
raise ValueError(msg)
- self._timeout = timeout_s
+ self._connect_timeout, self._timeout = resolve_timeouts(timeout_s, connect_timeout_s, read_timeout_s)
self._default_gpu = gpu
self._default_options = options
self._api_key = api_key
@@ -520,7 +552,7 @@ class SIEAsyncClient:
self._session = aiohttp.ClientSession(
base_url=self._base_url,
connector=connector,
- timeout=aiohttp.ClientTimeout(total=self._timeout),
+ timeout=aiohttp.ClientTimeout(total=self._timeout, sock_connect=self._connect_timeout),
headers=self._headers,
)
return self._session
@@ -540,6 +572,41 @@ class SIEAsyncClient:
"""Return the base URL of the SIE server."""
return self._base_url
+ @property
+ def last_retry_count(self) -> int:
+ """Return SDK retries performed by the latest call awaited in this task.
+
+ Tracked per asyncio context, the async counterpart of the sync
+ client's per-thread value: a call run as a separate task (for example
+ through ``asyncio.gather``) records its count in that task only.
+ """
+ counts = _LAST_RETRY_COUNTS.get()
+ return counts.get(id(self), 0) if counts else 0
+
+ def _set_retry_count(self, value: int) -> None:
+ counts = dict(_LAST_RETRY_COUNTS.get() or {})
+ counts[id(self)] = value
+ _LAST_RETRY_COUNTS.set(counts)
+
+ def _reset_retry_count(self) -> None:
+ self._set_retry_count(0)
+
+ def _record_retry(self) -> None:
+ self._set_retry_count(self.last_retry_count + 1)
+
+ def _attempt_timeout(self, remaining: float, read_timeout_s: float | None = None) -> aiohttp.ClientTimeout:
+ """Timeouts for one attempt, capped by the remaining provision budget.
+
+ An explicit per-call ``read_timeout_s`` is honoured as given.
+ """
+ read = read_timeout_s if read_timeout_s is not None else min(self._timeout, remaining)
+ return aiohttp.ClientTimeout(
+ total=max(remaining, read),
+ connect=read,
+ sock_connect=min(self._connect_timeout, remaining),
+ sock_read=read,
+ )
+
# ------------------------------------------------------------------
# Low-level HTTP helpers (thin wrappers around aiohttp)
# ------------------------------------------------------------------
@@ -562,6 +629,7 @@ class SIEAsyncClient:
headers: dict[str, str] | None = None,
timeout_s: float | None = None,
include_base_url_headers: bool = True,
+ client_timeout: aiohttp.ClientTimeout | None = None,
) -> _AioResponse:
kw: dict[str, Any] = {}
if data is not None:
@@ -571,7 +639,9 @@ class SIEAsyncClient:
request_headers = self._headers_for_request(url, headers, include_base_url_headers=include_base_url_headers)
if request_headers:
kw["headers"] = request_headers
- if timeout_s is not None:
+ if client_timeout is not None:
+ kw["timeout"] = client_timeout
+ elif timeout_s is not None:
kw["timeout"] = aiohttp.ClientTimeout(total=timeout_s)
kw["allow_redirects"] = False
async with self._throttle(), self._ensure_session().post(url, **kw) as resp:
@@ -658,7 +728,7 @@ class SIEAsyncClient:
self._ensure_session().get(
path,
headers=self._headers_for_request(path, {"Accept": accept}),
- timeout=aiohttp.ClientTimeout(total=min(self._timeout, remaining)),
+ timeout=self._attempt_timeout(remaining),
allow_redirects=False,
) as raw,
):
@@ -1261,6 +1331,7 @@ class SIEAsyncClient:
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
) -> EncodeResult | list[EncodeResult]:
"""Async version of encode(). See SIEClient.encode() for details."""
+ self._reset_retry_count()
# Track if single item was passed
single_item = not isinstance(items, list)
items_list = [items] if single_item else items
@@ -1328,14 +1399,14 @@ class SIEAsyncClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining)
try:
response = await self._post(
f"/v1/encode/{model}",
data=body,
headers=headers,
- timeout_s=request_timeout,
+ client_timeout=request_timeout,
)
except _RETRYABLE_TRANSPORT_ERRORS as e:
if wait_for_capacity:
@@ -1346,17 +1417,15 @@ class SIEAsyncClient:
error=e,
)
if delay_s is not None:
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
- if isinstance(e, TimeoutError):
- msg = f"Request timed out: {e}"
- else:
- msg = (
- f"Connection lost mid-request ({type(e).__name__}); "
- f"the peer closed the connection before sending a complete response: {e}"
- )
+ msg = (
+ f"Connection lost mid-request ({type(e).__name__}); "
+ f"the peer closed the connection before sending a complete response: {e}"
+ )
raise SIEConnectionError(msg) from e
- except aiohttp.ClientConnectorError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -1368,10 +1437,13 @@ class SIEAsyncClient:
)
if delay_s is not None:
connect_retries += 1
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
+ except _SENT_REQUEST_TIMEOUT_ERRORS as e:
+ raise SIEConnectionError(read_timeout_message(e)) from e
except (aiohttp.ClientError, OSError) as e:
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
@@ -1402,6 +1474,7 @@ class SIEAsyncClient:
actual_delay,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -1423,6 +1496,7 @@ class SIEAsyncClient:
lora_retries,
LORA_LOADING_MAX_RETRIES,
)
+ self._record_retry()
await asyncio.sleep(delay)
continue
@@ -1444,6 +1518,7 @@ class SIEAsyncClient:
elapsed,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -1456,6 +1531,7 @@ class SIEAsyncClient:
timeout=timeout,
model=model,
)
+ self._record_retry()
continue
# Retryable pre-execution admission backpressure (pass-2 audit
@@ -1473,6 +1549,7 @@ class SIEAsyncClient:
admission_delay,
timeout,
)
+ self._record_retry()
await asyncio.sleep(admission_delay)
continue
@@ -1493,6 +1570,7 @@ class SIEAsyncClient:
elapsed,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -1513,6 +1591,11 @@ class SIEAsyncClient:
# Parse results and inject timing into each
results = parse_encode_results(response_data["items"])
+ if timing:
+ for result in results:
+ result["timing"] = timing
+
+ attach_request_metadata(results, response.headers, response_data)
# 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 the
@@ -1525,11 +1608,6 @@ class SIEAsyncClient:
operation="encode",
request=parse_request_metadata(response.headers),
)
- if timing:
- for result in results:
- result["timing"] = timing
-
- attach_request_metadata(results, response.headers, response_data)
# Return single result if single item was passed
return results[0] if single_item else results
@@ -1563,6 +1641,7 @@ class SIEAsyncClient:
timeout: float | None = None, # noqa: ASYNC109
) -> Recommendation:
"""Async version of recommend(). See SIEClient.recommend() for details."""
+ self._reset_retry_count()
try:
response = await self._post(
RECOMMEND_PATH,
@@ -1596,6 +1675,7 @@ class SIEAsyncClient:
timeout: float | None = None, # noqa: ASYNC109
) -> CostEstimate:
"""Async version of estimate(). See SIEClient.estimate() for details."""
+ self._reset_retry_count()
body = build_estimate_envelope(endpoint, request)
try:
response = await self._post(
@@ -1850,6 +1930,7 @@ class SIEAsyncClient:
Async version of :meth:`SIEClient.score`. See that method for full
parameter documentation.
"""
+ self._reset_retry_count()
# Resolve defaults and pool
pool_name, resolved_gpu = await self._resolve_pool_and_gpu(gpu)
resolved_options = self._resolve_options(options)
@@ -1893,14 +1974,14 @@ class SIEAsyncClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining)
try:
response = await self._post(
f"/v1/score/{model}",
data=body,
headers=headers,
- timeout_s=request_timeout,
+ client_timeout=request_timeout,
)
except _RETRYABLE_TRANSPORT_ERRORS as e:
if wait_for_capacity:
@@ -1911,17 +1992,15 @@ class SIEAsyncClient:
error=e,
)
if delay_s is not None:
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
- if isinstance(e, TimeoutError):
- msg = f"Request timed out: {e}"
- else:
- msg = (
- f"Connection lost mid-request ({type(e).__name__}); "
- f"the peer closed the connection before sending a complete response: {e}"
- )
+ msg = (
+ f"Connection lost mid-request ({type(e).__name__}); "
+ f"the peer closed the connection before sending a complete response: {e}"
+ )
raise SIEConnectionError(msg) from e
- except aiohttp.ClientConnectorError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -1933,10 +2012,13 @@ class SIEAsyncClient:
)
if delay_s is not None:
connect_retries += 1
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
+ except _SENT_REQUEST_TIMEOUT_ERRORS as e:
+ raise SIEConnectionError(read_timeout_message(e)) from e
except (aiohttp.ClientError, OSError) as e:
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
@@ -1967,6 +2049,7 @@ class SIEAsyncClient:
actual_delay,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -1986,6 +2069,7 @@ class SIEAsyncClient:
elapsed,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -1998,6 +2082,7 @@ class SIEAsyncClient:
timeout=timeout,
model=model,
)
+ self._record_retry()
continue
# Retryable pre-execution admission backpressure (pass-2 audit
@@ -2015,6 +2100,7 @@ class SIEAsyncClient:
admission_delay,
timeout,
)
+ self._record_retry()
await asyncio.sleep(admission_delay)
continue
@@ -2032,6 +2118,7 @@ class SIEAsyncClient:
elapsed,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -2072,6 +2159,7 @@ class SIEAsyncClient:
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ read_timeout_s: float | None = None,
) -> GenerateResult:
"""Async sibling of :meth:`SIEClient.generate`.
@@ -2079,6 +2167,7 @@ class SIEAsyncClient:
awaits the aggregated outcome; use :meth:`stream_generate` for
SIE-native chunk streaming.
"""
+ self._reset_retry_count()
resolved_grammar = validate_generate_grammar(grammar) if grammar is not None else None
pool_name, resolved_gpu = await self._resolve_pool_and_gpu(gpu)
@@ -2128,7 +2217,7 @@ class SIEAsyncClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout_s = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining, read_timeout_s)
try:
async with (
@@ -2137,25 +2226,15 @@ class SIEAsyncClient:
f"/v1/generate/{safe_model}",
data=body,
headers=self._headers_for_request(f"/v1/generate/{safe_model}", headers),
- timeout=aiohttp.ClientTimeout(total=request_timeout_s),
+ timeout=request_timeout,
allow_redirects=False,
) as raw,
):
content = await raw.read()
response = _AioResponse(raw.status, content, raw.headers)
- except _RETRYABLE_TRANSPORT_ERRORS as e:
- # Generation is NOT idempotent and carries no dedup key.
- # These errors fire after the request body was sent (read
- # timeout, peer reset, payload error), so the worker may
- # already be — or have finished — generating. Retrying would
- # issue a *second* billable generation with a different
- # completion, so surface the error instead of re-running.
- # (The idempotent encode/score/extract paths still retry.)
- msg = f"Request failed: {e}"
- raise SIEConnectionError(msg) from e
- except aiohttp.ClientConnectorError as e:
- # Connect errors fail before the request is sent, so no
- # generation could have started — safe to retry.
+ except _CONNECT_PHASE_ERRORS as e:
+ # Connect-phase failures happen before the request is sent,
+ # so no generation could have started — safe to retry.
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2167,17 +2246,17 @@ class SIEAsyncClient:
)
if delay_s is not None:
connect_retries += 1
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
except (aiohttp.ClientError, OSError) as e:
- # Catch-all transport failure. For the non-idempotent
- # generate path we do NOT retry: unlike a pure connect
- # failure (ClientConnectorError above), a generic
- # ClientError/OSError (e.g. ECONNRESET) can fire after the
- # request was sent, so the worker may already have generated.
- # Retrying would double-bill an inference. Surface instead.
+ # Every other transport failure, including read timeouts and
+ # peer resets, can fire after the request body was sent, so the
+ # worker may already be — or have finished — generating.
+ # Generation is NOT idempotent and carries no dedup key, so
+ # surface the error instead of re-running it.
msg = f"Request failed: {e}"
raise SIEConnectionError(msg) from e
@@ -2194,6 +2273,7 @@ class SIEAsyncClient:
start_time=start_time,
timeout=timeout,
)
+ self._record_retry()
await asyncio.sleep(delay)
continue
@@ -2218,6 +2298,7 @@ class SIEAsyncClient:
f"provision timeout ({timeout:.1f}s, {elapsed:.1f}s elapsed) for '{model}'"
)
raise ModelLoadingError(msg, model=model)
+ self._record_retry()
await asyncio.sleep(delay)
continue
if error_code == RESOURCE_EXHAUSTED_ERROR_CODE:
@@ -2229,6 +2310,7 @@ class SIEAsyncClient:
timeout=timeout,
model=model,
)
+ self._record_retry()
continue
# Retryable pre-execution admission backpressure (pass-2 audit
@@ -2246,6 +2328,7 @@ class SIEAsyncClient:
admission_delay,
timeout,
)
+ self._record_retry()
await asyncio.sleep(admission_delay)
continue
@@ -2299,15 +2382,18 @@ class SIEAsyncClient:
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ read_timeout_s: float | None = None,
) -> ResponseResult:
"""Async counterpart of :meth:`SIEClient.responses`.
The gateway's Responses MVP is stateless, text-only, and
non-streaming. Retry behavior matches the sync method: only explicit
- pre-execution capacity signals and connect-before-send failures are
- retried; mid-flight failures and post-publish 504 responses are
- terminal because generation is non-idempotent.
+ pre-execution capacity signals, pre-dispatch admission rejections and
+ connect-before-send failures are retried; mid-flight failures, read
+ timeouts and post-publish 504 responses are terminal because
+ generation is non-idempotent.
"""
+ self._reset_retry_count()
pool_name, resolved_gpu = await self._resolve_pool_and_gpu(gpu)
body = json.dumps(
build_responses_body(
@@ -2341,13 +2427,13 @@ class SIEAsyncClient:
"/v1/responses",
data=body,
headers=self._headers_for_request("/v1/responses", headers),
- timeout=aiohttp.ClientTimeout(total=min(self._timeout, remaining)),
+ timeout=self._attempt_timeout(remaining, read_timeout_s),
allow_redirects=False,
) as raw,
):
content = await raw.read()
response = _AioResponse(raw.status, content, raw.headers)
- except aiohttp.ClientConnectorError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2359,6 +2445,7 @@ class SIEAsyncClient:
)
if delay_s is not None:
connect_retries += 1
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
msg = f"Failed to connect to {self._base_url}: {e}"
@@ -2380,6 +2467,7 @@ class SIEAsyncClient:
oom_retries=oom_retries,
max_oom_retries=max_oom_retries,
)
+ self._record_retry()
await asyncio.sleep(delay)
self._check_server_version(response)
@@ -2419,19 +2507,23 @@ class SIEAsyncClient:
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ read_timeout_s: float | None = None,
) -> ChatCompletion:
"""Non-streaming OpenAI-compatible chat completion (``/v1/chat/completions``).
Async counterpart of :meth:`SIEClient.chat_completions`. For token
streaming use :meth:`stream_chat_completions`. Generation is
- non-idempotent, so only pre-execution 503 PROVISIONING / MODEL_LOADING responses are retried;
- a 504 surfaces as :class:`ServerError`.
+ non-idempotent, so only pre-execution capacity signals and
+ pre-dispatch admission rejections are retried; a 504 surfaces as
+ :class:`ServerError`. ``read_timeout_s`` sets how long to wait for the
+ complete response once the request is sent.
Typed kwargs cover the full gateway-supported field set (see
:func:`build_chat_body` for the canonical list); ``extra_body`` is
still merged last for forward-compat fields the typed surface does
not name yet.
"""
+ self._reset_retry_count()
pool_name, resolved_gpu = await self._resolve_pool_and_gpu(gpu)
body = json.dumps(
build_chat_body(
@@ -2485,13 +2577,13 @@ class SIEAsyncClient:
"/v1/chat/completions",
data=body,
headers=self._headers_for_request("/v1/chat/completions", headers),
- timeout=aiohttp.ClientTimeout(total=min(self._timeout, remaining)),
+ timeout=self._attempt_timeout(remaining, read_timeout_s),
allow_redirects=False,
) as raw,
):
content = await raw.read()
response = _AioResponse(raw.status, content, raw.headers)
- except aiohttp.ClientConnectorError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2503,6 +2595,7 @@ class SIEAsyncClient:
)
if delay_s is not None:
connect_retries += 1
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
msg = f"Failed to connect to {self._base_url}: {e}"
@@ -2526,6 +2619,7 @@ class SIEAsyncClient:
oom_retries=oom_retries,
max_oom_retries=max_oom_retries,
)
+ self._record_retry()
await asyncio.sleep(delay)
self._check_server_version(response)
@@ -2724,6 +2818,7 @@ class SIEAsyncClient:
failure is terminal (non-idempotent). The ``async with`` keeps the
connection open while the caller consumes the generator.
"""
+ self._reset_retry_count()
timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_S
start_time = time.monotonic()
oom_retries = 0
@@ -2755,6 +2850,7 @@ class SIEAsyncClient:
timeout=aiohttp.ClientTimeout(
total=None,
connect=min(self._timeout, remaining),
+ sock_connect=min(self._connect_timeout, remaining),
sock_read=self._timeout,
),
allow_redirects=False,
@@ -2836,7 +2932,7 @@ class SIEAsyncClient:
yielded_chunk = True
else:
return
- except aiohttp.ClientConnectorError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2848,6 +2944,7 @@ class SIEAsyncClient:
)
if delay_s is not None:
connect_retries += 1
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
msg = f"Failed to connect to {self._base_url}: {e}"
@@ -2858,6 +2955,7 @@ class SIEAsyncClient:
raise SIEConnectionError(msg) from e
# Reached only on the non-200 pre-stream retry path.
if retry_delay is not None:
+ self._record_retry()
await asyncio.sleep(retry_delay)
# Use overload for proper type hints when single item vs list
@@ -2908,6 +3006,7 @@ class SIEAsyncClient:
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
) -> ExtractResult | list[ExtractResult]:
"""Async version of extract(). See SIEClient.extract() for details."""
+ self._reset_retry_count()
# Track if single item was passed
single_item = not isinstance(items, list)
items_list = [items] if single_item else items
@@ -2972,14 +3071,14 @@ class SIEAsyncClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining)
try:
response = await self._post(
f"/v1/extract/{model}",
data=body,
headers=headers,
- timeout_s=request_timeout,
+ client_timeout=request_timeout,
)
except _RETRYABLE_TRANSPORT_ERRORS as e:
if wait_for_capacity:
@@ -2990,17 +3089,15 @@ class SIEAsyncClient:
error=e,
)
if delay_s is not None:
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
- if isinstance(e, TimeoutError):
- msg = f"Request timed out: {e}"
- else:
- msg = (
- f"Connection lost mid-request ({type(e).__name__}); "
- f"the peer closed the connection before sending a complete response: {e}"
- )
+ msg = (
+ f"Connection lost mid-request ({type(e).__name__}); "
+ f"the peer closed the connection before sending a complete response: {e}"
+ )
raise SIEConnectionError(msg) from e
- except aiohttp.ClientConnectorError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -3012,10 +3109,13 @@ class SIEAsyncClient:
)
if delay_s is not None:
connect_retries += 1
+ self._record_retry()
await asyncio.sleep(delay_s)
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
+ except _SENT_REQUEST_TIMEOUT_ERRORS as e:
+ raise SIEConnectionError(read_timeout_message(e)) from e
except (aiohttp.ClientError, OSError) as e:
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
@@ -3049,6 +3149,7 @@ class SIEAsyncClient:
actual_delay,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -3068,6 +3169,7 @@ class SIEAsyncClient:
elapsed,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -3080,6 +3182,7 @@ class SIEAsyncClient:
timeout=timeout,
model=model,
)
+ self._record_retry()
continue
# Retryable pre-execution admission backpressure (pass-2 audit
@@ -3097,6 +3200,7 @@ class SIEAsyncClient:
admission_delay,
timeout,
)
+ self._record_retry()
await asyncio.sleep(admission_delay)
continue
@@ -3114,6 +3218,7 @@ class SIEAsyncClient:
elapsed,
timeout,
)
+ self._record_retry()
await asyncio.sleep(actual_delay)
continue
@@ -3127,6 +3232,7 @@ class SIEAsyncClient:
response_data = parse_terminal_msgpack_object(response, owner="extract")
results = parse_extract_results(response_data["items"])
+ attach_request_metadata(results, response.headers, response_data)
# Same positional contract as encode: ``results[0]`` below and
# index-based reassembly in batch callers both assume one result per
# input, and the queue path drops failed items from a 200 body.
@@ -3138,8 +3244,6 @@ class SIEAsyncClient:
request=parse_request_metadata(response.headers),
)
- attach_request_metadata(results, response.headers, response_data)
-
return results[0] if single_item else results
diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.py
index a2654055f..b4c046376 100644
--- a/packages/sie_sdk/src/sie_sdk/client/errors.py
+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
+ from collections.abc import Sequence
+
from sie_sdk.types import RequestMetadata
@@ -460,9 +462,9 @@ class IncompleteBatchError(ServerError):
contract even though the HTTP status was 200 — so existing ``ServerError``
handlers keep working (this refines the untyped guard from #1526).
``status_code`` is ``None``: the response was not an HTTP error. Callers
- can catch :class:`IncompleteBatchError` specifically and retry item-wise
- (single-item batches get per-item error visibility) using
- :attr:`missing_ids` when available.
+ can catch :class:`IncompleteBatchError` specifically, keep the items in
+ :attr:`results`, and retry only the failed items (single-item batches get
+ per-item error visibility) using :attr:`missing_ids` when available.
Attributes:
expected: Number of items submitted in this HTTP request.
@@ -472,6 +474,11 @@ class IncompleteBatchError(ServerError):
when ids identify every item on both sides (every submitted item
carried an ``id`` and every returned item echoed one), ``None``
otherwise.
+ results: The results the response did carry, parsed exactly as a
+ successful call returns them, in response order. Positions do not
+ line up with the submitted items; match them by ``id``. Extract
+ results may still carry a per-item ``error``. The response body
+ names no reason for the items it dropped.
request_id: Gateway request id (``x-sie-request-id``) when the
response carried one; quote it when reporting the incident.
"""
@@ -486,12 +493,14 @@ class IncompleteBatchError(ServerError):
model: str | None = None,
missing_ids: list[str] | None = None,
request: RequestMetadata | None = None,
+ results: Sequence[Any] | None = None,
) -> None:
super().__init__(message, code=code, request=request)
self.expected = expected
self.received = received
self.model = model
self.missing_ids = missing_ids
+ self.results: list[Any] = list(results) if results is not None else []
self.request_id: str | None = (request or {}).get("id")
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index ee67f9451..d16cd3cb9 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -161,7 +161,9 @@ from ._shared import (
raise_if_estimate_unroutable,
raise_if_input_too_long,
raise_if_model_load_failed,
+ read_timeout_message,
request_matches_base_url_origin,
+ resolve_timeouts,
retry_after_or_default,
settled_charge_from_usage,
sse_chunk_error,
@@ -189,12 +191,29 @@ from .errors import (
logger = logging.getLogger(__name__)
-# Mid-flight transport errors retried under `wait_for_capacity=True`:
-# the request was in flight and the peer severed the connection before a
-# complete response arrived (proxy idle timeout, rolling restart,
-# TCP reset). `httpx.ConnectError` is retried separately at each call
-# site to preserve its distinct "Failed to connect" message.
+# Failures before the request reached the server; retried under
+# `wait_for_capacity=True` on every path.
+_CONNECT_PHASE_ERRORS: tuple[type[Exception], ...] = (
+ httpx.ConnectError,
+ httpx.ConnectTimeout,
+ httpx.PoolTimeout,
+)
+
+# Transport errors retried under `wait_for_capacity=True` on the idempotent
+# encode/score/extract paths: the body could not be written, or the peer
+# severed the connection before a complete response arrived (proxy idle
+# timeout, rolling restart, TCP reset). A read timeout is deliberately absent:
+# the server received the request and may still be running it.
_RETRYABLE_TRANSPORT_ERRORS: tuple[type[Exception], ...] = (
+ httpx.WriteTimeout,
+ httpx.RemoteProtocolError,
+ httpx.ReadError,
+ httpx.WriteError,
+)
+
+# Failures after the request may have reached the server; terminal on the
+# non-idempotent generation paths.
+_MID_FLIGHT_TRANSPORT_ERRORS: tuple[type[Exception], ...] = (
httpx.TimeoutException,
httpx.RemoteProtocolError,
httpx.ReadError,
@@ -372,7 +391,9 @@ class SIEClient:
Args:
base_url: Base URL of the SIE server (e.g., "http://localhost:8080").
- timeout_s: Request timeout in seconds (default: 30.0).
+ timeout_s: One per-attempt limit in seconds for both connecting and
+ waiting for response data. Sets ``connect_timeout_s`` and
+ ``read_timeout_s`` together; either of those overrides it.
api_key: Optional API key for authentication (sent as Bearer token).
gpu: Default GPU/machine profile for requests (e.g., "l4", "l4-spot").
Can be overridden per-call.
@@ -385,6 +406,13 @@ class SIEClient:
origin. Values are copied at construction and never forwarded to a
control-plane URL, external payload-store reference, or redirect
target. Same-origin capability refs receive only these edge headers.
+ connect_timeout_s: Seconds allowed to establish a connection (default:
+ 10). A connection that cannot be established is retried under
+ ``wait_for_capacity``.
+ read_timeout_s: Seconds to wait for response data once a request is
+ sent (default: 150, longer than the gateway's default 120 s
+ request deadline). A read timeout is never retried, because the
+ server may still be processing the request.
Example:
>>> client = SIEClient("http://localhost:8080")
@@ -414,7 +442,7 @@ class SIEClient:
self,
base_url: str,
*,
- timeout_s: float = 30.0,
+ timeout_s: float | None = None,
api_key: str | None = None,
gpu: str | None = None,
options: dict[str, Any] | None = None,
@@ -423,6 +451,8 @@ class SIEClient:
control_plane_url: str | None = None,
org: str | None = None,
base_url_headers: Mapping[str, str] | None = None,
+ connect_timeout_s: float | None = None,
+ read_timeout_s: float | None = None,
) -> None:
# Normalize base_url (remove trailing slash)
validate_base_url(base_url)
@@ -431,7 +461,7 @@ class SIEClient:
if self._base_url_headers and not base_url_accepts_origin_credentials(self._base_url):
msg = "base_url_headers require an absolute https base_url without embedded credentials"
raise ValueError(msg)
- self._timeout = timeout_s
+ self._connect_timeout, self._timeout = resolve_timeouts(timeout_s, connect_timeout_s, read_timeout_s)
self._default_gpu = gpu
self._default_options = options
self._api_key = api_key
@@ -473,7 +503,7 @@ class SIEClient:
client_kwargs: dict[str, Any] = {
"base_url": self._base_url,
- "timeout": timeout_s,
+ "timeout": httpx.Timeout(self._timeout, connect=self._connect_timeout),
"headers": headers,
"follow_redirects": False,
}
@@ -545,6 +575,14 @@ class SIEClient:
def _record_retry(self) -> None:
self._request_state.last_retry_count = self.last_retry_count + 1
+ def _attempt_timeout(self, remaining: float, read_timeout_s: float | None = None) -> httpx.Timeout:
+ """Timeouts for one attempt, capped by the remaining provision budget.
+
+ An explicit per-call ``read_timeout_s`` is honoured as given.
+ """
+ read = read_timeout_s if read_timeout_s is not None else min(self._timeout, remaining)
+ return httpx.Timeout(read, connect=min(self._connect_timeout, remaining))
+
def _check_server_version(self, response: httpx.Response) -> None:
revision = response.headers.get(MODEL_REVISION_HEADER)
self._request_state.last_model_revision = revision if isinstance(revision, str) and revision else None
@@ -580,7 +618,7 @@ class SIEClient:
response = self._client.get(
path,
headers={"Accept": accept},
- timeout=min(self._timeout, remaining),
+ timeout=self._attempt_timeout(remaining),
)
except httpx.HTTPError as exc:
msg = f"Failed to retrieve the in-flight generation result: {type(exc).__name__}"
@@ -1161,14 +1199,16 @@ class SIEClient:
wait_for_capacity: When True (default), auto-retry transient "not
enough capacity yet" responses under ``provision_timeout_s`` —
``503 PROVISIONING`` (scale-from-zero provisioning);
- ``504`` gateway result timeouts for idempotent queue paths; local
- ``httpx`` read/connect/pool timeouts; and transient
- mid-flight transport errors (``RemoteProtocolError``,
+ ``504`` gateway result timeouts for idempotent queue paths;
+ connection failures and connect/pool/write timeouts; and
+ transient mid-flight transport errors (``RemoteProtocolError``,
``ReadError``, ``WriteError`` — peer severed the connection
before a complete response arrived). Retries honour the
server's ``Retry-After`` header when present. When False,
these surface immediately as ``ProvisioningError`` /
- ``ServerError`` / ``SIEConnectionError``.
+ ``ServerError`` / ``SIEConnectionError``. A read timeout is
+ never retried: the request was sent and the server may still
+ be processing it, so it raises ``SIEConnectionError``.
Note: ``503 MODEL_LOADING``, ``503 LORA_LOADING`` and
``503 RESOURCE_EXHAUSTED`` are retried regardless of this
flag — the worker has already accepted the request and is
@@ -1178,10 +1218,11 @@ class SIEClient:
``ResourceExhaustedError`` below; the ``RESOURCE_EXHAUSTED``
branch can be disabled by passing ``max_oom_retries=0``.
The pre-dispatch admission signals ``429 RATE_LIMIT``,
- ``503 BILLING_CAPACITY_UNAVAILABLE`` and ``503 QUEUE_FULL``
- are likewise retried regardless of this flag — no work has
- been published yet — honouring ``Retry-After`` and capped by
- ``provision_timeout_s``. On give-up they raise
+ ``503 BILLING_CAPACITY_UNAVAILABLE``, ``503 QUEUE_FULL`` and
+ ``503 QUEUE_UNAVAILABLE`` with ``Retry-After`` (queue
+ backpressure) are likewise retried regardless of this flag —
+ no work has been published yet — honouring ``Retry-After`` and
+ capped by ``provision_timeout_s``. On give-up they raise
``RateLimitError`` (429) or the server's terminal 503.
provision_timeout_s: Maximum time to wait for capacity when wait_for_capacity=True.
Default: 900 seconds (15 minutes).
@@ -1326,13 +1367,13 @@ class SIEClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining)
try:
response = self._client.post(
f"/v1/encode/{model}", content=body, headers=headers, timeout=request_timeout
)
- except httpx.ConnectError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -1369,6 +1410,8 @@ class SIEClient:
f"the peer closed the connection before sending a complete response: {e}"
)
raise SIEConnectionError(msg) from e
+ except httpx.TimeoutException as e:
+ raise SIEConnectionError(read_timeout_message(e)) from e
response = self._follow_modal_continuations(
response,
@@ -1521,6 +1564,11 @@ class SIEClient:
if isinstance(response_model, str) and response_model:
for result in results:
result["model"] = response_model
+ if timing:
+ for result in results:
+ result["timing"] = timing
+
+ attach_request_metadata(results, response.headers, response_data)
# 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 the
@@ -1533,11 +1581,6 @@ class SIEClient:
operation="encode",
request=parse_request_metadata(response.headers),
)
- if timing:
- for result in results:
- result["timing"] = timing
-
- attach_request_metadata(results, response.headers, response_data)
# Return single result if single item was passed
return results[0] if single_item else results
@@ -2055,14 +2098,16 @@ class SIEClient:
wait_for_capacity: When True (default), auto-retry transient "not
enough capacity yet" responses under ``provision_timeout_s`` —
``503 PROVISIONING`` (scale-from-zero provisioning);
- ``504`` gateway result timeouts for idempotent queue paths; local
- ``httpx`` read/connect/pool timeouts; and transient
- mid-flight transport errors (``RemoteProtocolError``,
+ ``504`` gateway result timeouts for idempotent queue paths;
+ connection failures and connect/pool/write timeouts; and
+ transient mid-flight transport errors (``RemoteProtocolError``,
``ReadError``, ``WriteError`` — peer severed the connection
before a complete response arrived). Retries honour the
server's ``Retry-After`` header when present. When False,
these surface immediately as ``ProvisioningError`` /
- ``ServerError`` / ``SIEConnectionError``.
+ ``ServerError`` / ``SIEConnectionError``. A read timeout is
+ never retried: the request was sent and the server may still
+ be processing it, so it raises ``SIEConnectionError``.
Note: ``503 MODEL_LOADING`` and ``503 RESOURCE_EXHAUSTED``
are retried regardless of this flag — the worker has
already accepted the request and is loading the target
@@ -2071,9 +2116,10 @@ class SIEClient:
``ResourceExhaustedError`` below; the
``RESOURCE_EXHAUSTED`` branch can be disabled by passing
``max_oom_retries=0``. The pre-dispatch admission signals
- ``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE`` and
- ``503 QUEUE_FULL`` are likewise retried regardless of this
- flag — no work has been published yet — honouring
+ ``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE``,
+ ``503 QUEUE_FULL`` and ``503 QUEUE_UNAVAILABLE`` with
+ ``Retry-After`` (queue backpressure) are likewise retried
+ regardless of this flag — no work has been published yet — honouring
``Retry-After`` and capped by ``provision_timeout_s``. On
give-up they raise ``RateLimitError`` (429) or the server's
terminal 503.
@@ -2161,13 +2207,13 @@ class SIEClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining)
try:
response = self._client.post(
f"/v1/score/{model}", content=body, headers=headers, timeout=request_timeout
)
- except httpx.ConnectError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2204,6 +2250,8 @@ class SIEClient:
f"the peer closed the connection before sending a complete response: {e}"
)
raise SIEConnectionError(msg) from e
+ except httpx.TimeoutException as e:
+ raise SIEConnectionError(read_timeout_message(e)) from e
response = self._follow_modal_continuations(
response,
@@ -2350,6 +2398,7 @@ class SIEClient:
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ read_timeout_s: float | None = None,
) -> GenerateResult:
"""Generate text from a prompt (walking-skeleton SDK surface).
@@ -2407,13 +2456,22 @@ class SIEClient:
(matching encode/score/extract): the worker has already
accepted the request and is loading the target model. The
pre-dispatch admission signals ``429 RATE_LIMIT``,
- ``503 BILLING_CAPACITY_UNAVAILABLE`` and ``503 QUEUE_FULL``
- are also retried regardless of this flag — they reject the
- request before any generation is published, so retrying
- cannot double-bill — honouring ``Retry-After`` and capped by
+ ``503 BILLING_CAPACITY_UNAVAILABLE``, ``503 QUEUE_FULL`` and
+ ``503 QUEUE_UNAVAILABLE`` with ``Retry-After`` are also
+ retried regardless of this flag — they reject the request
+ before any generation is published, so retrying cannot
+ double-bill — honouring ``Retry-After`` and capped by
``provision_timeout_s``; on give-up they raise
``RateLimitError`` (429) or the server's terminal 503.
provision_timeout_s: Maximum time to wait for capacity.
+ max_oom_retries: Maximum number of worker-side
+ ``503 RESOURCE_EXHAUSTED`` retries.
+ read_timeout_s: Seconds to wait for the complete response once
+ the request is sent. Defaults to the client's
+ ``read_timeout_s``, capped by the remaining
+ ``provision_timeout_s``; an explicit value is used as given.
+ Set it to at least the model profile's ``overall_timeout_s``
+ for long generations. A read timeout is never retried.
Returns:
:class:`GenerateResult` with text, usage, finish_reason, and
@@ -2473,7 +2531,7 @@ class SIEClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining, read_timeout_s)
try:
response = self._client.post(
@@ -2482,9 +2540,9 @@ class SIEClient:
headers=headers,
timeout=request_timeout,
)
- except httpx.ConnectError as e:
- # ``ConnectError`` fails *before* the request is sent, so no
- # generation could have started — safe to retry.
+ except _CONNECT_PHASE_ERRORS as e:
+ # A connect-phase failure happens *before* the request is
+ # sent, so no generation could have started — safe to retry.
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2501,7 +2559,7 @@ class SIEClient:
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
- except _RETRYABLE_TRANSPORT_ERRORS as e:
+ except _MID_FLIGHT_TRANSPORT_ERRORS as e:
# Unlike the idempotent encode/score/extract paths, generation
# is NOT idempotent and carries no dedup key. By the time these
# mid-flight errors fire (read/write timeout, peer reset) the
@@ -2642,6 +2700,7 @@ class SIEClient:
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ read_timeout_s: float | None = None,
) -> ResponseResult:
"""Create one non-streaming OpenAI-compatible Responses result.
@@ -2652,10 +2711,11 @@ class SIEClient:
supported by this surface.
Generation is non-idempotent. Only explicit pre-execution 503
- PROVISIONING / MODEL_LOADING / RESOURCE_EXHAUSTED responses and
- connect-before-send failures are retried. Mid-flight transport errors
- and post-publish 504 responses are terminal so a retry cannot
- double-bill or create a second completion.
+ PROVISIONING / MODEL_LOADING / RESOURCE_EXHAUSTED responses,
+ pre-dispatch admission rejections (see :meth:`generate`) and
+ connect-before-send failures are retried. Mid-flight transport errors,
+ read timeouts and post-publish 504 responses are terminal so a retry
+ cannot double-bill or create a second completion.
Args:
model: Model name to use for generation.
@@ -2671,6 +2731,8 @@ class SIEClient:
provision_timeout_s: Maximum time to wait for capacity.
max_oom_retries: Maximum number of worker-side
``503 RESOURCE_EXHAUSTED`` retries.
+ read_timeout_s: Seconds to wait for the complete response once
+ the request is sent; see :meth:`generate`.
Returns:
A typed :class:`ResponseResult`.
@@ -2716,9 +2778,9 @@ class SIEClient:
"/v1/responses",
content=body,
headers=headers,
- timeout=min(self._timeout, remaining),
+ timeout=self._attempt_timeout(remaining, read_timeout_s),
)
- except httpx.ConnectError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2735,7 +2797,7 @@ class SIEClient:
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
- except _RETRYABLE_TRANSPORT_ERRORS as e:
+ except _MID_FLIGHT_TRANSPORT_ERRORS as e:
msg = f"Connection lost mid-request ({type(e).__name__}): {e}"
raise SIEConnectionError(msg) from e
@@ -2792,14 +2854,17 @@ class SIEClient:
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ read_timeout_s: float | None = None,
) -> ChatCompletion:
"""Non-streaming OpenAI-compatible chat completion (``/v1/chat/completions``).
Mirrors the subset of OpenAI's ``chat.completions.create`` the gateway
honours. For token streaming use :meth:`stream_chat_completions`.
Generation is non-idempotent, so — like :meth:`generate` — only
- pre-execution 503 PROVISIONING / MODEL_LOADING responses are retried; a 504 (post-publish)
- surfaces as :class:`ServerError`.
+ pre-execution capacity signals and pre-dispatch admission rejections
+ are retried; a 504 (post-publish) surfaces as :class:`ServerError`.
+ ``read_timeout_s`` sets how long to wait for the complete response
+ once the request is sent; see :meth:`generate`.
Typed kwargs cover the full gateway-supported field set (see
:func:`build_chat_body` for the canonical list); ``extra_body`` is
@@ -2858,9 +2923,9 @@ class SIEClient:
"/v1/chat/completions",
content=body,
headers=headers,
- timeout=min(self._timeout, remaining),
+ timeout=self._attempt_timeout(remaining, read_timeout_s),
)
- except httpx.ConnectError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -2877,7 +2942,7 @@ class SIEClient:
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
- except _RETRYABLE_TRANSPORT_ERRORS as e:
+ except _MID_FLIGHT_TRANSPORT_ERRORS as e:
# Non-idempotent: a mid-flight failure may have already started
# a generation, so surface it instead of silently re-running.
msg = f"Connection lost mid-request ({type(e).__name__}): {e}"
@@ -3120,7 +3185,7 @@ class SIEClient:
retry_delay: float | None = None
try:
with self._client.stream(
- "POST", url, content=body, headers=headers, timeout=min(self._timeout, remaining)
+ "POST", url, content=body, headers=headers, timeout=self._attempt_timeout(remaining)
) as response:
if response.status_code != 200:
# Buffer the body so the decision helper can read the
@@ -3199,7 +3264,7 @@ class SIEClient:
yielded_chunk = True
else:
return
- except httpx.ConnectError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -3216,7 +3281,7 @@ class SIEClient:
continue
msg = f"Failed to connect to {self._base_url}: {e}"
raise SIEConnectionError(msg) from e
- except _RETRYABLE_TRANSPORT_ERRORS as e:
+ except _MID_FLIGHT_TRANSPORT_ERRORS as e:
# Mid-stream/connection failure: non-idempotent, do not retry.
msg = f"Connection lost during stream ({type(e).__name__}): {e}"
raise SIEConnectionError(msg) from e
@@ -3285,14 +3350,16 @@ class SIEClient:
wait_for_capacity: When True (default), auto-retry transient "not
enough capacity yet" responses under ``provision_timeout_s`` —
``503 PROVISIONING`` (scale-from-zero provisioning);
- ``504`` gateway result timeouts for idempotent queue paths; local
- ``httpx`` read/connect/pool timeouts; and transient
- mid-flight transport errors (``RemoteProtocolError``,
+ ``504`` gateway result timeouts for idempotent queue paths;
+ connection failures and connect/pool/write timeouts; and
+ transient mid-flight transport errors (``RemoteProtocolError``,
``ReadError``, ``WriteError`` — peer severed the connection
before a complete response arrived). Retries honour the
server's ``Retry-After`` header when present. When False,
these surface immediately as ``ProvisioningError`` /
- ``ServerError`` / ``SIEConnectionError``.
+ ``ServerError`` / ``SIEConnectionError``. A read timeout is
+ never retried: the request was sent and the server may still
+ be processing it, so it raises ``SIEConnectionError``.
Note: ``503 MODEL_LOADING`` and ``503 RESOURCE_EXHAUSTED``
are retried regardless of this flag — the worker has
already accepted the request and is loading the target
@@ -3301,9 +3368,10 @@ class SIEClient:
``ResourceExhaustedError`` below; the
``RESOURCE_EXHAUSTED`` branch can be disabled by passing
``max_oom_retries=0``. The pre-dispatch admission signals
- ``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE`` and
- ``503 QUEUE_FULL`` are likewise retried regardless of this
- flag — no work has been published yet — honouring
+ ``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE``,
+ ``503 QUEUE_FULL`` and ``503 QUEUE_UNAVAILABLE`` with
+ ``Retry-After`` (queue backpressure) are likewise retried
+ regardless of this flag — no work has been published yet — honouring
``Retry-After`` and capped by ``provision_timeout_s``. On
give-up they raise ``RateLimitError`` (429) or the server's
terminal 503.
@@ -3424,13 +3492,13 @@ class SIEClient:
if remaining <= 0:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
- request_timeout = min(self._timeout, remaining)
+ request_timeout = self._attempt_timeout(remaining)
try:
response = self._client.post(
f"/v1/extract/{model}", content=body, headers=headers, timeout=request_timeout
)
- except httpx.ConnectError as e:
+ except _CONNECT_PHASE_ERRORS as e:
if wait_for_capacity and is_transient_connect_error(e):
delay_s = compute_retry_delay(
start_time=start_time,
@@ -3467,6 +3535,8 @@ class SIEClient:
f"the peer closed the connection before sending a complete response: {e}"
)
raise SIEConnectionError(msg) from e
+ except httpx.TimeoutException as e:
+ raise SIEConnectionError(read_timeout_message(e)) from e
response = self._follow_modal_continuations(
response,
@@ -3593,6 +3663,7 @@ class SIEClient:
if isinstance(response_model, str) and response_model:
for result in results:
result["model"] = response_model
+ attach_request_metadata(results, response.headers, response_data)
# Same positional contract as encode: ``results[0]`` below and
# index-based reassembly in batch callers both assume one result per
# input, and the queue path drops failed items from a 200 body.
@@ -3604,8 +3675,6 @@ class SIEClient:
request=parse_request_metadata(response.headers),
)
- attach_request_metadata(results, response.headers, response_data)
-
# Return single result if single item was passed
return results[0] if single_item else results
diff --git a/packages/sie_sdk/tests/client/test_generate.py b/packages/sie_sdk/tests/client/test_generate.py
index 2af84cc3f..2f2b4aa71 100644
--- a/packages/sie_sdk/tests/client/test_generate.py
+++ b/packages/sie_sdk/tests/client/test_generate.py
@@ -499,7 +499,7 @@ class TestSyncGenerate:
mock_client.return_value.get.assert_called_once_with(
"/v1/generate/m?__modal_attempt_token=opaque",
headers={"Accept": "application/json"},
- timeout=pytest.approx(30),
+ timeout=httpx.Timeout(150.0, connect=10.0),
)
assert client.last_retry_count == 0
diff --git a/packages/sie_sdk/tests/client/test_retry_classification.py b/packages/sie_sdk/tests/client/test_retry_classification.py
new file mode 100644
index 000000000..f63a5e89f
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_retry_classification.py
@@ -0,0 +1,437 @@
+"""Retry classification, timeouts and partial batches through the real clients.
+
+Both clients talk to a local HTTP server that replays scripted responses, so
+every decision below runs through the production transport, classification and
+retry code. The response table is shared with the TypeScript SDK through
+``packages/wire-fixtures/retry_classification.json``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import json
+import threading
+import time
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any
+
+import aiohttp
+import httpx
+import msgpack
+import numpy as np
+import pytest
+from sie_sdk import IncompleteBatchError, SIEAsyncClient, SIEClient, SIEConnectionError, SIEError
+from sie_sdk.client import async_ as async_module
+from sie_sdk.client import sync as sync_module
+from sie_sdk.client._shared import (
+ DEFAULT_CONNECT_TIMEOUT_S,
+ DEFAULT_READ_TIMEOUT_S,
+ get_retry_after,
+ resolve_timeouts,
+)
+
+_FIXTURE: dict[str, Any] = json.loads(
+ (Path(__file__).parents[3] / "wire-fixtures" / "retry_classification.json").read_text()
+)
+_RESPONSE_CASES: list[dict[str, Any]] = _FIXTURE["responses"]
+_RETRY_AFTER_CASES: list[dict[str, Any]] = _FIXTURE["retry_after"]
+_OPERATIONS = ("encode", "generate", "chat_completions")
+_MSGPACK_HEADERS = {"Content-Type": "application/msgpack"}
+_JSON_HEADERS = {"Content-Type": "application/json"}
+
+
+@dataclass
+class _Reply:
+ status: int
+ body: bytes = b""
+ headers: dict[str, str] = field(default_factory=dict)
+ delay_s: float = 0.0
+
+
+class _StubServer:
+ """Threaded HTTP server that replays scripted replies and records request paths."""
+
+ def __init__(self) -> None:
+ self.replies: list[_Reply] = []
+ self.paths: list[str] = []
+ self._lock = threading.Lock()
+ self._release = threading.Event()
+ stub = self
+
+ class _Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self) -> None:
+ self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ reply = stub._next(self.path)
+ if reply.delay_s:
+ stub._release.wait(reply.delay_s)
+ try:
+ self.send_response(reply.status)
+ for name, value in reply.headers.items():
+ self.send_header(name, value)
+ self.send_header("Content-Length", str(len(reply.body)))
+ self.end_headers()
+ self.wfile.write(reply.body)
+ except OSError:
+ self.close_connection = True
+
+ def log_message(self, format: str, *args: Any) -> None:
+ return None
+
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ self._server.daemon_threads = True
+ self._thread = threading.Thread(target=self._server.serve_forever, args=(0.01,), daemon=True)
+ self._thread.start()
+
+ @property
+ def url(self) -> str:
+ host, port = self._server.server_address[:2]
+ return f"http://{host!s}:{port}"
+
+ def _next(self, path: str) -> _Reply:
+ with self._lock:
+ self.paths.append(path)
+ if len(self.replies) > 1:
+ return self.replies.pop(0)
+ return self.replies[0]
+
+ def close(self) -> None:
+ self._release.set()
+ self._server.shutdown()
+ self._server.server_close()
+
+
+class _NoSleepTime:
+ def __getattr__(self, name: str) -> Any:
+ return getattr(time, name)
+
+ @staticmethod
+ def sleep(_seconds: float) -> None:
+ return None
+
+
+class _NoSleepAsyncio:
+ def __getattr__(self, name: str) -> Any:
+ return getattr(asyncio, name)
+
+ @staticmethod
+ async def sleep(_delay: float, result: Any = None) -> Any:
+ return result
+
+
+def stub() -> Iterator[_StubServer]:
+ server = _StubServer()
+ try:
+ yield server
+ finally:
+ server.close()
+
+
+def no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(sync_module, "time", _NoSleepTime())
+ monkeypatch.setattr(async_module, "asyncio", _NoSleepAsyncio())
+
+
+def _encode_ok(ids: list[str] | None = None) -> _Reply:
+ items = [{"id": item_id, "dense": {"dims": 4, "values": np.zeros(4, dtype=np.float32)}} for item_id in ids or ["a"]]
+ return _Reply(200, msgpack.packb({"model": "m", "items": items}, use_bin_type=True), dict(_MSGPACK_HEADERS))
+
+
+def _json_ok(operation: str) -> _Reply:
+ payloads = {
+ "generate": {"model": "m", "text": "ok"},
+ "chat_completions": {"id": "chat-1", "object": "chat.completion", "model": "m", "choices": []},
+ "responses": {"id": "resp-1", "object": "response", "model": "m", "output": []},
+ }
+ return _Reply(200, json.dumps(payloads[operation]).encode(), dict(_JSON_HEADERS))
+
+
+def _success(operation: str) -> _Reply:
+ return _encode_ok() if operation == "encode" else _json_ok(operation)
+
+
+def _fixture_reply(case: dict[str, Any]) -> _Reply:
+ return _Reply(case["status"], json.dumps(case["body"]).encode(), {**_JSON_HEADERS, **case["headers"]})
+
+
+def _operation_class(operation: str) -> str:
+ return "idempotent" if operation == "encode" else "generation"
+
+
+def _call_sync(client: SIEClient, operation: str, **kwargs: Any) -> Any:
+ if operation == "encode":
+ return client.encode("m", {"id": "a", "text": "hi"}, **kwargs)
+ if operation == "generate":
+ return client.generate("m", "hi", max_new_tokens=4, **kwargs)
+ if operation == "responses":
+ return client.responses("m", "hi", **kwargs)
+ return client.chat_completions("m", [{"role": "user", "content": "hi"}], **kwargs)
+
+
+async def _call_async(client: SIEAsyncClient, operation: str, **kwargs: Any) -> Any:
+ if operation == "encode":
+ return await client.encode("m", {"id": "a", "text": "hi"}, **kwargs)
+ if operation == "generate":
+ return await client.generate("m", "hi", max_new_tokens=4, **kwargs)
+ if operation == "responses":
+ return await client.responses("m", "hi", **kwargs)
+ return await client.chat_completions("m", [{"role": "user", "content": "hi"}], **kwargs)
+
+
[email protected]("no_sleep")
[email protected]("operation", _OPERATIONS)
[email protected]("case", _RESPONSE_CASES, ids=[case["name"] for case in _RESPONSE_CASES])
+def test_sync_client_follows_shared_retry_table(stub: _StubServer, case: dict[str, Any], operation: str) -> None:
+ stub.replies = [_fixture_reply(case), _success(operation)]
+ client = SIEClient(stub.url)
+ try:
+ if case[_operation_class(operation)] == "retry":
+ _call_sync(client, operation)
+ assert len(stub.paths) == 2
+ assert client.last_retry_count == 1
+ else:
+ with pytest.raises(SIEError):
+ _call_sync(client, operation)
+ assert len(stub.paths) == 1
+ assert client.last_retry_count == 0
+ finally:
+ client.close()
+
+
[email protected]("no_sleep")
[email protected]("operation", _OPERATIONS)
[email protected]("case", _RESPONSE_CASES, ids=[case["name"] for case in _RESPONSE_CASES])
+async def test_async_client_follows_shared_retry_table(stub: _StubServer, case: dict[str, Any], operation: str) -> None:
+ stub.replies = [_fixture_reply(case), _success(operation)]
+ async with SIEAsyncClient(stub.url) as client:
+ if case[_operation_class(operation)] == "retry":
+ await _call_async(client, operation)
+ assert len(stub.paths) == 2
+ assert client.last_retry_count == 1
+ else:
+ with pytest.raises(SIEError):
+ await _call_async(client, operation)
+ assert len(stub.paths) == 1
+ assert client.last_retry_count == 0
+
+
[email protected]("case", _RETRY_AFTER_CASES, ids=[repr(case["header"]) for case in _RETRY_AFTER_CASES])
+def test_retry_after_parsing_matches_shared_table(case: dict[str, Any]) -> None:
+ parsed = get_retry_after(httpx.Response(503, headers={"Retry-After": case["header"]}))
+ if case["seconds"] == "future":
+ assert parsed is not None
+ assert parsed > 0
+ else:
+ assert parsed == case["seconds"]
+
+
+def test_read_timeout_is_not_resent_by_sync_client(stub: _StubServer) -> None:
+ stub.replies = [_Reply(**{**_encode_ok().__dict__, "delay_s": 2.0})]
+ client = SIEClient(stub.url, read_timeout_s=0.2)
+ try:
+ with pytest.raises(SIEConnectionError, match="Not retried"):
+ client.encode("m", {"text": "hi"}, provision_timeout_s=10.0)
+ finally:
+ client.close()
+ assert stub.paths == ["/v1/encode/m"]
+
+
+async def test_read_timeout_is_not_resent_by_async_client(stub: _StubServer) -> None:
+ stub.replies = [_Reply(**{**_encode_ok().__dict__, "delay_s": 2.0})]
+ async with SIEAsyncClient(stub.url, read_timeout_s=0.2) as client:
+ with pytest.raises(SIEConnectionError, match="Not retried"):
+ await client.encode("m", {"text": "hi"}, provision_timeout_s=10.0)
+ assert stub.paths == ["/v1/encode/m"]
+
+
[email protected]("operation", ["generate", "chat_completions", "responses"])
+def test_sync_generation_read_timeout_is_per_call(stub: _StubServer, operation: str) -> None:
+ slow = _Reply(**{**_json_ok(operation).__dict__, "delay_s": 0.6})
+ stub.replies = [slow, slow]
+ client = SIEClient(stub.url, read_timeout_s=0.2)
+ try:
+ assert _call_sync(client, operation, read_timeout_s=5.0)["model"] == "m"
+ with pytest.raises(SIEConnectionError):
+ _call_sync(client, operation)
+ finally:
+ client.close()
+ assert len(stub.paths) == 2
+
+
[email protected]("operation", ["generate", "chat_completions", "responses"])
+async def test_async_generation_read_timeout_is_per_call(stub: _StubServer, operation: str) -> None:
+ slow = _Reply(**{**_json_ok(operation).__dict__, "delay_s": 0.6})
+ stub.replies = [slow, slow]
+ async with SIEAsyncClient(stub.url, read_timeout_s=0.2) as client:
+ assert (await _call_async(client, operation, read_timeout_s=5.0))["model"] == "m"
+ with pytest.raises(SIEConnectionError):
+ await _call_async(client, operation)
+ assert len(stub.paths) == 2
+
+
[email protected]("no_sleep")
+ ("error", "attempts"),
+ [(httpx.ConnectTimeout, 2), (httpx.PoolTimeout, 2), (httpx.ReadTimeout, 1)],
+ ids=["connect_timeout", "pool_timeout", "read_timeout"],
+)
[email protected]("operation", _OPERATIONS)
+def test_sync_transport_timeouts_retry_only_before_send(
+ monkeypatch: pytest.MonkeyPatch, operation: str, error: type[httpx.TimeoutException], attempts: int
+) -> None:
+ seen: list[str] = []
+ success = _success(operation)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request.url.path)
+ if len(seen) == 1:
+ raise error("timed out", request=request)
+ return httpx.Response(success.status, content=success.body, headers=success.headers)
+
+ monkeypatch.setattr(
+ sync_module.httpx, "Client", functools.partial(httpx.Client, transport=httpx.MockTransport(handler))
+ )
+ client = SIEClient("http://sie.test")
+ try:
+ if attempts == 2:
+ _call_sync(client, operation)
+ assert client.last_retry_count == 1
+ else:
+ with pytest.raises(SIEConnectionError):
+ _call_sync(client, operation)
+ finally:
+ client.close()
+ assert len(seen) == attempts
+
+
+class _FirstConnectTimesOut(aiohttp.TCPConnector):
+ attempts = 0
+
+ async def connect(self, req: Any, traces: Any, timeout: Any) -> Any: # noqa: ASYNC109
+ type(self).attempts += 1
+ if type(self).attempts == 1:
+ raise TimeoutError
+ return await super().connect(req, traces, timeout)
+
+
[email protected]("no_sleep")
[email protected]("operation", _OPERATIONS)
+async def test_async_connect_timeout_is_retried(
+ monkeypatch: pytest.MonkeyPatch, stub: _StubServer, operation: str
+) -> None:
+ monkeypatch.setattr(_FirstConnectTimesOut, "attempts", 0)
+ monkeypatch.setattr(async_module.aiohttp, "TCPConnector", _FirstConnectTimesOut)
+ stub.replies = [_success(operation)]
+ async with SIEAsyncClient(stub.url) as client:
+ await _call_async(client, operation)
+ assert client.last_retry_count == 1
+ assert _FirstConnectTimesOut.attempts == 2
+ assert len(stub.paths) == 1
+
+
+def test_timeout_resolution_keeps_timeout_s_meaning() -> None:
+ assert resolve_timeouts(None, None, None) == (DEFAULT_CONNECT_TIMEOUT_S, DEFAULT_READ_TIMEOUT_S)
+ assert resolve_timeouts(30.0, None, None) == (30.0, 30.0)
+ assert resolve_timeouts(30.0, 5.0, None) == (5.0, 30.0)
+ assert resolve_timeouts(None, None, 600.0) == (DEFAULT_CONNECT_TIMEOUT_S, 600.0)
+ assert DEFAULT_READ_TIMEOUT_S > 120.0
+
+
+def test_sync_incomplete_batch_keeps_returned_results(stub: _StubServer) -> None:
+ stub.replies = [_encode_ok(["b"])]
+ client = SIEClient(stub.url)
+ try:
+ with pytest.raises(IncompleteBatchError) as excinfo:
+ client.encode("m", [{"id": "a", "text": "x"}, {"id": "b", "text": "y"}])
+ finally:
+ client.close()
+ error = excinfo.value
+ assert error.missing_ids == ["a"]
+ assert [result["id"] for result in error.results] == ["b"]
+ assert error.results[0]["dense"].shape == (4,)
+ assert error.results[0]["model"] == "m"
+
+
+async def test_async_incomplete_batch_keeps_returned_results(stub: _StubServer) -> None:
+ extract_body = {
+ "model": "m",
+ "items": [{"id": "b", "entities": [], "error": {"code": "INPUT_TOO_LONG", "message": "too long"}}],
+ }
+ stub.replies = [_Reply(200, msgpack.packb(extract_body, use_bin_type=True), dict(_MSGPACK_HEADERS))]
+ async with SIEAsyncClient(stub.url) as client:
+ with pytest.raises(IncompleteBatchError) as excinfo:
+ await client.extract("m", [{"id": "a", "text": "x"}, {"id": "b", "text": "y"}], labels=["person"])
+ error = excinfo.value
+ assert error.missing_ids == ["a"]
+ assert error.results == [
+ {
+ "entities": [],
+ "relations": [],
+ "classifications": [],
+ "objects": [],
+ "id": "b",
+ "error": {"code": "INPUT_TOO_LONG", "message": "too long"},
+ }
+ ]
+
+
[email protected]("no_sleep")
+async def test_async_retry_count_is_scoped_to_the_calling_task(stub: _StubServer) -> None:
+ loading = _fixture_reply(next(case for case in _RESPONSE_CASES if case["name"] == "model_loading"))
+ async with SIEAsyncClient(stub.url) as client:
+ stub.replies = [loading, _encode_ok()]
+ await client.encode("m", {"id": "a", "text": "hi"})
+ assert client.last_retry_count == 1
+
+ stub.replies = [_encode_ok()]
+ await client.encode("m", {"id": "a", "text": "hi"})
+ assert client.last_retry_count == 0
+
+ async def retried_in_task() -> int:
+ await client.encode("m", {"id": "a", "text": "hi"})
+ return client.last_retry_count
+
+ stub.replies = [loading, _encode_ok()]
+ assert await asyncio.create_task(retried_in_task()) == 1
+ assert client.last_retry_count == 0
+
+
+def _sse_reply() -> _Reply:
+ chunk = {"request_id": "r", "seq": 0, "text_delta": "ok", "done": True}
+ return _Reply(200, f"data: {json.dumps(chunk)}\n\n".encode(), {"Content-Type": "text/event-stream"})
+
+
+def _backpressure_reply() -> _Reply:
+ return _fixture_reply(
+ next(case for case in _RESPONSE_CASES if case["name"] == "openai_transport_failure_backpressure")
+ )
+
+
[email protected]("no_sleep")
+def test_sync_stream_retries_queue_backpressure_before_opening(stub: _StubServer) -> None:
+ stub.replies = [_backpressure_reply(), _sse_reply()]
+ client = SIEClient(stub.url)
+ try:
+ chunks = list(client.stream_generate("m", "hi", max_new_tokens=4))
+ assert client.last_retry_count == 1
+ finally:
+ client.close()
+ assert [chunk["text_delta"] for chunk in chunks] == ["ok"]
+ assert len(stub.paths) == 2
+
+
[email protected]("no_sleep")
+async def test_async_stream_retries_queue_backpressure_before_opening(stub: _StubServer) -> None:
+ stub.replies = [_backpressure_reply(), _sse_reply()]
+ async with SIEAsyncClient(stub.url) as client:
+ chunks = [chunk async for chunk in client.stream_generate("m", "hi", max_new_tokens=4)]
+ assert client.last_retry_count == 1
+ assert [chunk["text_delta"] for chunk in chunks] == ["ok"]
+ assert len(stub.paths) == 2
diff --git a/packages/sie_sdk/tests/client/test_sync.py b/packages/sie_sdk/tests/client/test_sync.py
index e9cb3deb4..8ab9d5746 100644
--- a/packages/sie_sdk/tests/client/test_sync.py
+++ b/packages/sie_sdk/tests/client/test_sync.py
@@ -18,7 +18,7 @@ class TestSIEClientInit:
mock_client.assert_called_once()
call_kwargs = mock_client.call_args.kwargs
assert call_kwargs["base_url"] == "http://localhost:8080"
- assert call_kwargs["timeout"] == 30.0
+ assert call_kwargs["timeout"] == httpx.Timeout(150.0, connect=10.0)
assert call_kwargs["headers"]["Content-Type"] == "application/msgpack"
assert "limits" not in call_kwargs
client.close()
@@ -37,7 +37,15 @@ class TestSIEClientInit:
with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
client = SIEClient("http://localhost:8080", timeout_s=60.0)
call_kwargs = mock_client.call_args.kwargs
- assert call_kwargs["timeout"] == 60.0
+ assert call_kwargs["timeout"] == httpx.Timeout(60.0, connect=60.0)
+ client.close()
+
+ def test_connect_and_read_timeouts_override_timeout_s(self) -> None:
+ """Phase-specific timeouts override the combined ``timeout_s``."""
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ client = SIEClient("http://localhost:8080", timeout_s=60.0, connect_timeout_s=5.0, read_timeout_s=300.0)
+ call_kwargs = mock_client.call_args.kwargs
+ assert call_kwargs["timeout"] == httpx.Timeout(300.0, connect=5.0)
client.close()
def test_api_key_sets_auth_header(self) -> None:
diff --git a/packages/sie_sdk/tests/client/test_terminal_msgpack.py b/packages/sie_sdk/tests/client/test_terminal_msgpack.py
index c9b6b1a43..c2af6e25d 100644
--- a/packages/sie_sdk/tests/client/test_terminal_msgpack.py
+++ b/packages/sie_sdk/tests/client/test_terminal_msgpack.py
@@ -1,6 +1,7 @@
from typing import Self
from unittest.mock import AsyncMock, MagicMock, patch
+import httpx
import numpy as np
import pytest
from msgpack.exceptions import UnpackException
@@ -105,7 +106,7 @@ def test_sync_terminal_operation_consumes_same_origin_modal_continuation(operati
client_cls.return_value.get.assert_called_once_with(
path,
headers={"Accept": "application/msgpack"},
- timeout=30,
+ timeout=httpx.Timeout(150.0, connect=10.0),
)
diff --git a/packages/sie_sdk/tests/client/test_timeout.py b/packages/sie_sdk/tests/client/test_timeout.py
index 9f27fcc45..7d2efd18f 100644
--- a/packages/sie_sdk/tests/client/test_timeout.py
+++ b/packages/sie_sdk/tests/client/test_timeout.py
@@ -47,10 +47,12 @@ class TestTimeoutEnforcement:
# (should be capped to remaining provision time, not 300s)
calls = mock_client.return_value.post.call_args_list
for call in calls:
- # The timeout kwarg should be present and <= provision_timeout_s
+ # Every phase of the timeout should be present and <= provision_timeout_s
timeout_used = call.kwargs.get("timeout")
- assert timeout_used is not None, "Per-request timeout should be set"
- assert timeout_used <= 0.5, f"Request timeout {timeout_used}s should be <= provision_timeout 0.5s"
+ assert isinstance(timeout_used, httpx.Timeout), "Per-request timeout should be set"
+ for phase in (timeout_used.connect, timeout_used.read, timeout_used.write, timeout_used.pool):
+ assert phase is not None
+ assert phase <= 0.5, f"Request timeout {phase}s should be <= provision_timeout 0.5s"
client.close()
@@ -90,62 +92,61 @@ class TestTimeoutEnforcement:
client.close()
def test_httpx_timeout_exception_respects_provision_timeout(self) -> None:
- """httpx.TimeoutException is retried but respects provision_timeout_s.
-
- When httpx times out (e.g., server hanging), the SDK retries but still
- enforces the overall provision_timeout_s.
- """
+ """A timeout after the request was sent fails fast without a retry."""
with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
- # Always raise httpx.TimeoutException
mock_client.return_value.post = MagicMock(side_effect=httpx.TimeoutException("Request timed out"))
client = SIEClient("http://localhost:8080")
start_time = time.monotonic()
- provision_timeout = 0.15
-
- # Without wait_for_capacity, timeout is not retried
with pytest.raises(SIEConnectionError, match="timed out"):
- client.encode(
- "bge-m3", {"text": "hello"}, provision_timeout_s=provision_timeout, wait_for_capacity=False
- )
+ client.encode("bge-m3", {"text": "hello"}, provision_timeout_s=0.15, wait_for_capacity=False)
elapsed = time.monotonic() - start_time
-
- # Should fail quickly on first timeout (no retry without wait_for_capacity)
assert elapsed < 0.5, f"Should fail quickly, took {elapsed:.2f}s"
+ assert mock_client.return_value.post.call_count == 1
client.close()
- def test_httpx_timeout_retried_with_wait_for_capacity(self) -> None:
- """httpx.TimeoutException is retried when wait_for_capacity=True.
-
- The SDK retries on httpx timeout but enforces provision_timeout_s.
- """
+ @pytest.mark.parametrize(
+ "exc",
+ [httpx.ReadTimeout("read timed out"), httpx.TimeoutException("timed out")],
+ ids=["read_timeout", "unknown_phase_timeout"],
+ )
+ def test_sent_request_timeout_not_retried_with_wait_for_capacity(self, exc: httpx.TimeoutException) -> None:
+ """A request that may already be running is never re-sent after a timeout."""
with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
- # Always raise httpx.TimeoutException
- mock_client.return_value.post = MagicMock(side_effect=httpx.TimeoutException("Request timed out"))
+ mock_client.return_value.post = MagicMock(side_effect=exc)
client = SIEClient("http://localhost:8080")
- start_time = time.monotonic()
- provision_timeout = 0.05
-
- # With wait_for_capacity, timeout is retried until provision_timeout.
- # Depending on whether the budget is exhausted before the next
- # request or immediately after the final transport timeout, either
- # terminal error is valid.
- with pytest.raises((ProvisioningError, SIEConnectionError)) as exc_info:
- client.encode(
- "bge-m3",
- {"text": "hello"},
- wait_for_capacity=True,
- provision_timeout_s=provision_timeout,
- )
- message = str(exc_info.value).lower()
- assert "timeout" in message or "timed out" in message
+ with pytest.raises(SIEConnectionError, match="timed out") as exc_info:
+ client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=True, provision_timeout_s=10.0)
- elapsed = time.monotonic() - start_time
+ assert "Not retried" in str(exc_info.value)
+ assert mock_client.return_value.post.call_count == 1
+ assert client.last_retry_count == 0
+ client.close()
- # Should timeout around provision_timeout (with some overhead)
- assert elapsed < provision_timeout + 0.1, (
- f"Operation took {elapsed:.2f}s, should timeout around {provision_timeout}s"
- )
+ @pytest.mark.parametrize(
+ "exc",
+ [httpx.ConnectTimeout("connect timed out"), httpx.PoolTimeout("pool timed out")],
+ ids=["connect_timeout", "pool_timeout"],
+ )
+ def test_timeout_before_send_retried_with_wait_for_capacity(self, exc: httpx.TimeoutException) -> None:
+ """A timeout before the request reached the server is safe to retry."""
+ ok = MagicMock()
+ ok.status_code = 200
+ ok.headers = {"content-type": "application/msgpack"}
+ ok.content = msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True)
+ with (
+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,
+ patch("sie_sdk.client.sync.time.sleep"),
+ ):
+ mock_client.return_value.post = MagicMock(side_effect=[exc, ok])
+ client = SIEClient("http://localhost:8080")
+
+ result = client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=True, provision_timeout_s=10.0)
+
+ assert result["dense"].shape == (4,)
+ assert mock_client.return_value.post.call_count == 2
+ assert client.last_retry_count == 1
+ client.close()
diff --git a/packages/sie_sdk/tests/client/test_transport_error_retry.py b/packages/sie_sdk/tests/client/test_transport_error_retry.py
index ffd391af6..cd591220a 100644
--- a/packages/sie_sdk/tests/client/test_transport_error_retry.py
+++ b/packages/sie_sdk/tests/client/test_transport_error_retry.py
@@ -296,9 +296,9 @@ class TestAsyncTransportErrorRetry:
[
aiohttp.ServerDisconnectedError("Server disconnected"),
aiohttp.ClientPayloadError("Response payload is not completed"),
- aiohttp.ServerTimeoutError("Timeout on reading data from socket"),
+ aiohttp.ConnectionTimeoutError("Connection timeout to host"),
],
- ids=["server_disconnected", "client_payload_error", "server_timeout_error"],
+ ids=["server_disconnected", "client_payload_error", "connection_timeout_error"],
)
async def test_transport_error_retried_when_wait_for_capacity_true_then_succeeds(self, exc: Exception) -> None:
from sie_sdk import SIEAsyncClient
@@ -319,6 +319,30 @@ class TestAsyncTransportErrorRetry:
assert client._post.call_count == 2
await client.close()
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "exc",
+ [
+ aiohttp.SocketTimeoutError("Timeout on reading data from socket"),
+ aiohttp.ServerTimeoutError("Timeout on reading data from socket"),
+ TimeoutError(),
+ ],
+ ids=["socket_timeout_error", "server_timeout_error", "total_timeout"],
+ )
+ async def test_sent_request_timeout_not_retried(self, exc: Exception) -> None:
+ from sie_sdk import SIEAsyncClient
+ from sie_sdk.client.errors import SIEConnectionError
+
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(side_effect=[exc, _async_response_200()]) # type: ignore
+
+ with pytest.raises(SIEConnectionError, match="Not retried"):
+ await client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=True, provision_timeout_s=10.0)
+
+ assert client._post.call_count == 1
+ assert client.last_retry_count == 0
+ await client.close()
+
@pytest.mark.asyncio
async def test_transport_error_not_retried_when_wait_for_capacity_false(self) -> None:
from sie_sdk import SIEAsyncClient
diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.md
index ecb110f72..8ff9639f9 100644
--- a/packages/sie_ts_sdk/README.md
+++ b/packages/sie_ts_sdk/README.md
@@ -147,6 +147,29 @@ Retry semantics for transient `503` codes:
exponential backoff; throws `ResourceExhaustedError` (a `ServerError`
subclass) when retries run out.
+Admission rejections happen before any work is dispatched, so every call
+retries them within `provisionTimeout`, honouring `Retry-After` (delay
+seconds or an HTTP date): `429 RATE_LIMIT`, `503 QUEUE_FULL`, and the
+gateway's queue backpressure, a `503 QUEUE_UNAVAILABLE` that carries
+`Retry-After`. A `QUEUE_UNAVAILABLE` without `Retry-After` is terminal.
+[`packages/wire-fixtures/retry_classification.json`](../wire-fixtures/retry_classification.json)
+lists how each response is classified; the TypeScript and Python SDKs
+both test against it.
+
+Each attempt waits up to `timeoutMs` (default 150000 ms, longer than the
+gateway's default 120 s request deadline) for a response. A timed-out
+request is never retried, because the server may still be processing it.
+`generate` and `chatCompletions` accept a per-call `timeoutMs`; set it to
+at least the model profile's `overall_timeout_s` for long generations.
+Connection failures are classified by their cause: refused, unreachable
+or reset connections are retried under `waitForCapacity`, while DNS name,
+TLS and certificate failures fail immediately.
+
+When a batch response carries fewer items than were sent, `encode` and
+`extract` throw `IncompleteBatchError`. Its `results` holds the items
+that did come back (match them by `id`), and `missingIds` names the
+dropped items when every submitted item carried an `id`.
+
Streaming calls throw `SIEStreamError` for mid-stream error chunks —
the HTTP connection was healthy but the worker or gateway emitted an
error envelope partway through. Branch on `error.code` (for example
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index 53b9f2c2f..0c6228776 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -727,6 +727,53 @@ function urlOriginForLogging(url: string): string {
}
}
+/**
+ * Fetch failure codes worth retrying: the connection could not be made, or the
+ * peer dropped it before a response arrived. Mirrors the Python SDK's
+ * transient connect errnos plus undici's own connect-timeout and socket codes.
+ */
+const TRANSIENT_FETCH_ERROR_CODES: ReadonlySet<string> = new Set([
+ "ECONNREFUSED",
+ "ECONNRESET",
+ "ETIMEDOUT",
+ "EHOSTUNREACH",
+ "ENETUNREACH",
+ "ENETDOWN",
+ "EHOSTDOWN",
+ "EAI_AGAIN",
+ "EPIPE",
+ "UND_ERR_CONNECT_TIMEOUT",
+ "UND_ERR_SOCKET",
+]);
+
+/** Timeouts undici raises after the request was sent; never retried. */
+const SENT_REQUEST_TIMEOUT_CODES: ReadonlySet<string> = new Set([
+ "UND_ERR_HEADERS_TIMEOUT",
+ "UND_ERR_BODY_TIMEOUT",
+]);
+
+/** Error codes on a fetch failure's `cause` chain, including aggregated causes. */
+function fetchErrorCodes(error: unknown): string[] {
+ const codes: string[] = [];
+ let current: unknown = error;
+ for (let depth = 0; depth < 5 && typeof current === "object" && current !== null; depth += 1) {
+ const { code, errors, cause } = current as {
+ code?: unknown;
+ errors?: unknown;
+ cause?: unknown;
+ };
+ if (typeof code === "string") codes.push(code);
+ if (Array.isArray(errors)) {
+ for (const inner of errors) {
+ const innerCode = (inner as { code?: unknown } | null)?.code;
+ if (typeof innerCode === "string") codes.push(innerCode);
+ }
+ }
+ current = cause;
+ }
+ return codes;
+}
+
/**
* Convert a `fetch()` `TypeError` into a typed connection error.
*
@@ -734,13 +781,16 @@ function urlOriginForLogging(url: string): string {
* `TypeError: Failed to parse URL …` with `cause.code === "ERR_INVALID_URL"`)
* is a permanent configuration error, NOT a transient network failure —
* classify it as kind `"other"` so the connect-retry loops never spin on it,
- * and point at the fix. Every other fetch `TypeError` is a genuine
- * network-level connection failure and keeps kind `"connect"`.
+ * and point at the fix. The remaining failures are classified by the error
+ * codes on the `cause` chain: transient connection codes keep kind
+ * `"connect"`; a timeout after the request was sent is `"timeout"`; any other
+ * code (DNS name not found, TLS or certificate failures) is permanent and
+ * `"other"`. A failure without a code (browser `fetch`) stays `"connect"`.
*/
function connectionErrorFromFetchTypeError(error: TypeError): SIEConnectionError {
- const cause = (error as { cause?: { code?: unknown } }).cause;
+ const codes = fetchErrorCodes(error);
if (
- cause?.code === "ERR_INVALID_URL" ||
+ codes.includes("ERR_INVALID_URL") ||
error.message.includes("Failed to parse URL") ||
error.message.includes("Invalid URL")
) {
@@ -749,7 +799,20 @@ function connectionErrorFromFetchTypeError(error: TypeError): SIEConnectionError
"other",
);
}
- return new SIEConnectionError(`Connection failed: ${error.message}`, "connect");
+ if (codes.length === 0) {
+ return new SIEConnectionError(`Connection failed: ${error.message}`, "connect");
+ }
+ const detail = `${error.message} (${codes.join(", ")})`;
+ if (codes.some((code) => SENT_REQUEST_TIMEOUT_CODES.has(code))) {
+ return new SIEConnectionError(
+ `Request timed out waiting for the response: ${detail}. Not retried because the server may already be processing the request.`,
+ "timeout",
+ );
+ }
+ if (codes.every((code) => TRANSIENT_FETCH_ERROR_CODES.has(code))) {
+ return new SIEConnectionError(`Connection failed: ${detail}`, "connect");
+ }
+ return new SIEConnectionError(`Connection failed: ${detail}`, "other");
}
const MODAL_CONTINUATION_MAX_HOPS = 20;
@@ -1041,6 +1104,7 @@ export class SIEClient {
const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));
const results = parseEncodeResults(data.items);
+ attachRequestMetadata(results, response.headers, data);
// Guard the 1:1 input-to-output contract before any positional access
// (`results[0]` below, or index-based reassembly in callers). The queue
// path returns mixed-success batches as 200 with only the successful
@@ -1053,7 +1117,6 @@ export class SIEClient {
"encode",
response.headers.get("x-sie-request-id") ?? undefined,
);
- attachRequestMetadata(results, response.headers, data);
if (isSingleItem) {
const first = results[0];
@@ -1311,12 +1374,16 @@ export class SIEClient {
const url = `${this.baseUrl}/v1/generate/${encodeURIComponent(safeModel)}`;
const waitForCapacity = options.waitForCapacity ?? this.defaultWaitForCapacity;
- const response = await withProvisioningRetry(() => this.performJsonPost(url, body, headers), {
- model,
- gpu,
- waitForCapacity,
- provisionTimeoutMs: this.provisionTimeout,
- });
+ const timeoutMs = options.timeoutMs ?? this.timeout;
+ const response = await withProvisioningRetry(
+ () => this.performJsonPost(url, body, headers, timeoutMs),
+ {
+ model,
+ gpu,
+ waitForCapacity,
+ provisionTimeoutMs: this.provisionTimeout,
+ },
+ );
const data = await parseTerminalJsonObject(response, "generate");
const result = parseGenerateResult(data);
@@ -1337,16 +1404,17 @@ export class SIEClient {
* silently re-issuing a billable generation)
*
* Each call uses a fresh `AbortController` so concurrent retries don't
- * share state, and the per-attempt timeout is bounded by `this.timeout`
- * (NOT the cumulative provisioning budget).
+ * share state, and the per-attempt timeout is `timeoutMs` (NOT the
+ * cumulative provisioning budget).
*/
private async performJsonPost(
url: string,
body: unknown,
headers: Record<string, string>,
+ timeoutMs: number,
): Promise<Response> {
const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
let response = await fetch(url, {
method: "POST",
@@ -1375,7 +1443,7 @@ export class SIEClient {
return response;
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
- throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");
+ throw new SIEConnectionError(`Request timeout after ${timeoutMs}ms`, "timeout");
}
if (err instanceof TypeError) {
// `generate()` / `chatCompletions()` are non-idempotent and carry
@@ -1452,12 +1520,16 @@ export class SIEClient {
// The loop also surfaces `ProvisioningError` when the caller opted out
// (`waitForCapacity: false`) or the provision budget is exhausted,
// matching `generate()`.
- const response = await withProvisioningRetry(() => this.performJsonPost(url, body, headers), {
- model: req.model,
- gpu: undefined,
- waitForCapacity,
- provisionTimeoutMs,
- });
+ const timeoutMs = options.timeoutMs ?? this.timeout;
+ const response = await withProvisioningRetry(
+ () => this.performJsonPost(url, body, headers, timeoutMs),
+ {
+ model: req.model,
+ gpu: undefined,
+ waitForCapacity,
+ provisionTimeoutMs,
+ },
+ );
this.checkServerVersion(response);
@@ -1594,7 +1666,7 @@ export class SIEClient {
signal,
(chunk) => extractGenerateChunkError(chunk),
{ pool, gpu },
- { waitForCapacity },
+ { waitForCapacity, timeoutMs: options.timeoutMs },
);
}
@@ -1612,7 +1684,8 @@ export class SIEClient {
* Retry policy mirrors {@link generate}: only explicit SAFE
* pre-execution capacity signals — `503 PROVISIONING`,
* `503 MODEL_LOADING` and `503 RESOURCE_EXHAUSTED` (the latter only
- * under `waitForCapacity`) — are retried while the provision budget
+ * under `waitForCapacity`) — and the pre-dispatch admission rejections
+ * handled by `admissionRetryDelay` are retried while the provision budget
* remains; a `504` is post-publish and therefore terminal.
* Once the body opens we never retry (the call is non-idempotent; a
* mid-stream failure must not re-issue generation).
@@ -1626,12 +1699,13 @@ export class SIEClient {
signal: AbortSignal | undefined,
extractError: (chunk: T) => SIEStreamError | null,
routing?: { pool?: string; gpu?: string },
- provisioning?: { waitForCapacity?: boolean },
+ provisioning?: { waitForCapacity?: boolean; timeoutMs?: number },
): AsyncGenerator<T, void, undefined> {
const headers = this.buildChatHeaders("text/event-stream");
if (routing?.pool) headers["X-SIE-Pool"] = routing.pool;
if (routing?.gpu) headers["X-SIE-MACHINE-PROFILE"] = routing.gpu;
const waitForCapacity = provisioning?.waitForCapacity ?? this.defaultWaitForCapacity;
+ const preStreamTimeoutMs = provisioning?.timeoutMs ?? this.timeout;
const gpu = routing?.gpu;
// Compose the caller's signal with our internal timeout-controller so
@@ -1664,7 +1738,7 @@ export class SIEClient {
// three-tier taxonomy). Setting `this.timeout` for the whole stream
// would cap long generations at 30s. A fresh per-attempt timeout
// covers each pre-stream fetch.
- const preStreamTimeoutId = setTimeout(() => controller.abort(), this.timeout);
+ const preStreamTimeoutId = setTimeout(() => controller.abort(), preStreamTimeoutMs);
let attemptResponse: Response;
try {
attemptResponse = await fetch(url, {
@@ -1679,7 +1753,10 @@ export class SIEClient {
throw new SIEConnectionError("Stream aborted before response", "other");
}
if (error instanceof Error && error.name === "AbortError") {
- throw new SIEConnectionError(`Stream open timeout after ${this.timeout}ms`, "timeout");
+ throw new SIEConnectionError(
+ `Stream open timeout after ${preStreamTimeoutMs}ms`,
+ "timeout",
+ );
}
if (error instanceof TypeError) {
throw connectionErrorFromFetchTypeError(error);
@@ -1781,6 +1858,17 @@ export class SIEClient {
}
}
+ const admissionDelay = await admissionRetryDelay(attemptResponse, {
+ startTime,
+ provisionTimeoutMs: this.provisionTimeout,
+ });
+ if (admissionDelay !== undefined) {
+ if (await abortableSleep(admissionDelay, controller.signal)) {
+ throw new SIEConnectionError("Stream aborted while provisioning", "other");
+ }
+ continue;
+ }
+
// 504 is terminal on the streaming path: post-publish, a worker may
// already be generating, and generation is non-idempotent (Python
// SDK parity — see `next_stream_retry_delay`).
@@ -1974,6 +2062,7 @@ export class SIEClient {
const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));
const results = parseExtractResults(data.items);
+ attachRequestMetadata(results, response.headers, data);
// Same positional contract as encode: `results[0]` below and index-based
// reassembly in batch callers both assume one result per input, and the
// queue path drops failed items from a 200 body.
@@ -1984,7 +2073,6 @@ export class SIEClient {
"extract",
response.headers.get("x-sie-request-id") ?? undefined,
);
- attachRequestMetadata(results, response.headers, data);
if (isSingleItem) {
const first = results[0];
diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.ts
index 4c5a8501b..de379e9d7 100644
--- a/packages/sie_ts_sdk/src/errors.ts
+++ b/packages/sie_ts_sdk/src/errors.ts
@@ -19,6 +19,8 @@
* }
*/
+import type { EncodeResult, ExtractResult } from "./types.js";
+
/**
* Base error for all SIE SDK errors.
*
@@ -406,10 +408,10 @@ export class InputTooLongError extends RequestError {
* Subclass of {@link ServerError} — the server violated the response-shape
* contract even though the HTTP status was 200 — so existing `ServerError`
* handlers keep working. `statusCode` is 200 for the same reason: the response
- * was not an HTTP error. Catch this specifically to retry item-wise
- * (single-item batches get per-item error visibility), using {@link missingIds}
- * when the submitted items carried ids. Mirrors the Python SDK's
- * `IncompleteBatchError`.
+ * was not an HTTP error. Catch this specifically, keep the items in
+ * {@link results}, and retry only the failed items (single-item batches get
+ * per-item error visibility), using {@link missingIds} when the submitted items
+ * carried ids. Mirrors the Python SDK's `IncompleteBatchError`.
*/
export class IncompleteBatchError extends ServerError {
/** Number of items submitted in this HTTP request. */
@@ -431,6 +433,16 @@ export class IncompleteBatchError extends ServerError {
*/
readonly missingIds: string[] | undefined;
+ /**
+ * The results the response did carry, parsed exactly as a successful call
+ * returns them, in response order.
+ *
+ * Positions do not line up with the submitted items; match them by `id`.
+ * Extract results may still carry a per-item `error`. The response body
+ * names no reason for the items it dropped.
+ */
+ readonly results: readonly (EncodeResult | ExtractResult)[];
+
constructor(
message: string,
options: {
@@ -441,6 +453,7 @@ export class IncompleteBatchError extends ServerError {
missingIds?: string[];
requestId?: string;
param?: string | null;
+ results?: readonly (EncodeResult | ExtractResult)[];
},
) {
super(message, options.code, 200, options.requestId, options.param);
@@ -449,6 +462,7 @@ export class IncompleteBatchError extends ServerError {
this.received = options.received;
this.model = options.model;
this.missingIds = options.missingIds;
+ this.results = [...(options.results ?? [])];
}
}
diff --git a/packages/sie_ts_sdk/src/internal/constants.ts b/packages/sie_ts_sdk/src/internal/constants.ts
index 4c5f24919..03bcce109 100644
--- a/packages/sie_ts_sdk/src/internal/constants.ts
+++ b/packages/sie_ts_sdk/src/internal/constants.ts
@@ -11,8 +11,11 @@ export const HTTP_SERVER_ERROR_MIN = 500;
export const HTTP_SERVER_ERROR_MAX = 599;
export const HTTP_GATEWAY_TIMEOUT = 504;
-// Default timeouts and delays
-export const DEFAULT_TIMEOUT = 30_000; // 30 seconds
+// Default timeouts and delays. The per-attempt timeout must outlast the
+// gateway's default 120 s request deadline so its typed 504 reaches the caller
+// before the client gives up on a request the server is still running
+// (matches the Python SDK's DEFAULT_READ_TIMEOUT_S).
+export const DEFAULT_TIMEOUT = 150_000; // 150 seconds
// Floor for long-running POSTs (jobs.submit / files.upload / batches.create) so
// a large upload / connector preflight / batch creation does not abort while the
// server keeps working. Matches the Python SDK's 120s floor.
@@ -66,6 +69,17 @@ export const BACKPRESSURE_503_ERROR_CODES: ReadonlySet<string> = new Set([
QUEUE_FULL_ERROR_CODE,
]);
export const BACKPRESSURE_503_DEFAULT_DELAY = 1_000; // Fallback (ms) when the server omits Retry-After
+// The gateway answers a publish rejected by queue backpressure with 503
+// QUEUE_UNAVAILABLE (`transport_failure` in the OpenAI envelope used by the
+// generation routes) plus Retry-After. The same codes without Retry-After
+// report failures that may follow publication, so only the hinted form is
+// retryable.
+export const QUEUE_UNAVAILABLE_ERROR_CODE = "QUEUE_UNAVAILABLE";
+export const OPENAI_TRANSPORT_FAILURE_ERROR_CODE = "transport_failure";
+export const RETRY_AFTER_GATED_503_ERROR_CODES: ReadonlySet<string> = new Set([
+ QUEUE_UNAVAILABLE_ERROR_CODE,
+ OPENAI_TRANSPORT_FAILURE_ERROR_CODE,
+]);
// Terminal credit / account errors (pass-2 audit B3) — NEVER retried. 402/403
// credit/account failures are mapped to typed exceptions in `handleError` and,
diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.ts
index 2e74fc302..43a2c9702 100644
--- a/packages/sie_ts_sdk/src/internal/parsing.ts
+++ b/packages/sie_ts_sdk/src/internal/parsing.ts
@@ -588,7 +588,7 @@ function missingResultIds(
* @throws {IncompleteBatchError} If the counts differ.
*/
export function validateBatchResultCount(
- results: readonly unknown[],
+ results: readonly (EncodeResult | ExtractResult)[],
submitted: readonly unknown[],
model: string,
operation: "encode" | "extract",
@@ -613,6 +613,7 @@ export function validateBatchResultCount(
model,
missingIds,
requestId,
+ results,
});
}
diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.ts
index a679c56eb..5cc4f52e8 100644
--- a/packages/sie_ts_sdk/src/internal/provisioning.ts
+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts
@@ -44,6 +44,7 @@ import {
RATE_LIMIT_DEFAULT_DELAY,
RESOURCE_EXHAUSTED_ERROR_CODE,
RESOURCE_EXHAUSTED_MAX_RETRIES,
+ RETRY_AFTER_GATED_503_ERROR_CODES,
} from "./constants.js";
import {
getErrorCode,
@@ -149,6 +150,13 @@ export function nextOomRetryDelay(opts: {
* cap, NOT customer credit exhaustion) and `503 QUEUE_FULL` (B7 — self-hosted
* queue backpressure, #3180). On give-up throws the server's terminal 503
* verbatim via {@link handleError} (a {@link ServerError} preserving the code).
+ * - `503 QUEUE_UNAVAILABLE` / `transport_failure` carrying a usable
+ * `Retry-After`: the gateway rejected the publish under queue backpressure.
+ * Without the hint these codes stay terminal. The give-up matches the
+ * previous arm.
+ *
+ * `packages/wire-fixtures/retry_classification.json` pins these decisions for
+ * both SDKs.
*
* Retry timing mirrors the PROVISIONING arm: the server-supplied `Retry-After`
* is honored verbatim, and only the SDK's own fallback default is jittered.
@@ -194,8 +202,12 @@ export async function admissionRetryDelay(
if (status === 503) {
const code = await getErrorCode(response.clone());
- if (code !== undefined && BACKPRESSURE_503_ERROR_CODES.has(code)) {
- const retryAfter = getRetryAfter(response);
+ const retryAfter = getRetryAfter(response);
+ const backpressure =
+ code !== undefined &&
+ (BACKPRESSURE_503_ERROR_CODES.has(code) ||
+ (RETRY_AFTER_GATED_503_ERROR_CODES.has(code) && retryAfter !== undefined));
+ if (backpressure) {
const elapsed = Date.now() - startTime;
const remaining = provisionTimeoutMs - elapsed;
const delay =
diff --git a/packages/sie_ts_sdk/src/internal/retry.ts b/packages/sie_ts_sdk/src/internal/retry.ts
index e6682df62..72b72d4ab 100644
--- a/packages/sie_ts_sdk/src/internal/retry.ts
+++ b/packages/sie_ts_sdk/src/internal/retry.ts
@@ -75,27 +75,36 @@ export function computeOomBackoff(
return applyRetryJitter(capped);
}
+const RETRY_AFTER_SECONDS = /^\d+(?:\.\d+)?$/;
+const RETRY_AFTER_HTTP_DATE = /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/;
+
/**
* Parse Retry-After header value
+ *
+ * Accepts non-negative delay seconds (fractions allowed) and the IMF-fixdate
+ * HTTP-date form. A date in the past means "retry now" (0). Any other value is
+ * unusable. `packages/wire-fixtures/retry_classification.json` pins these
+ * cases for both SDKs.
+ *
* @param header - The Retry-After header value
- * @returns Delay in milliseconds, or undefined if invalid
+ * @returns Delay in milliseconds, or undefined if absent or invalid
*/
export function getRetryAfter(header: string | null): number | undefined {
if (!header) return undefined;
+ const value = header.trim();
- // Try parsing as seconds (integer). `Retry-After: 0` means "retry
- // immediately" and must be honored (>= 0), not treated as invalid and
- // replaced by the default delay.
- const seconds = Number.parseInt(header, 10);
- if (!Number.isNaN(seconds) && seconds >= 0) {
- return seconds * 1000;
+ // `Retry-After: 0` means "retry immediately" and must be honored, not
+ // treated as invalid and replaced by the default delay.
+ if (RETRY_AFTER_SECONDS.test(value)) {
+ const seconds = Number(value);
+ return Number.isFinite(seconds) ? seconds * 1000 : undefined;
}
- // Try parsing as HTTP-date
- const date = new Date(header);
- if (!Number.isNaN(date.getTime())) {
- const delay = date.getTime() - Date.now();
- return delay > 0 ? delay : undefined;
+ if (RETRY_AFTER_HTTP_DATE.test(value)) {
+ const when = Date.parse(value);
+ if (!Number.isNaN(when)) {
+ return Math.max(when - Date.now(), 0);
+ }
}
return undefined;
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index 4c5a09e30..3f8ebaf78 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -744,11 +744,16 @@ export type StatusMessage = WorkerStatusMessage | ClusterStatusMessage;
*/
export interface SIEClientOptions {
/**
- * Per-request timeout in MILLISECONDS (default: 30000).
+ * Per-attempt timeout in MILLISECONDS for receiving a response once the
+ * request is sent (default: 150000, longer than the gateway's default 120 s
+ * request deadline). A request that times out is never retried, because the
+ * server may still be processing it. Connection establishment is bounded
+ * by the runtime's own connect timeout.
*
- * Note the unit: the Python SDK's equivalent knob (`timeout_s`) is in
- * SECONDS, so a value ported verbatim is off by 1000x. Prefer the
- * unit-encoded `timeoutMs`, which reads identically but names the unit.
+ * Note the unit: the Python SDK's equivalent knob (`read_timeout_s`, or
+ * `timeout_s` for both phases) is in SECONDS, so a value ported verbatim is
+ * off by 1000x. Prefer the unit-encoded `timeoutMs`, which reads identically
+ * but names the unit.
*/
timeoutMs?: number;
/**
@@ -783,7 +788,8 @@ export interface SIEClientOptions {
* fixed retry count): the worker has already accepted the request.
*
* A read/pool `SIEConnectionError` (`kind === "timeout"`) is never
- * retried on any path.
+ * retried on any path. DNS name, TLS and certificate failures are
+ * permanent (`kind === "other"`) and are not retried either.
*
* Default: `true`, matching the Python SDK's `wait_for_capacity=True`.
* BREAKING (0.7): the default was previously `false` — pass `false`
@@ -1049,6 +1055,13 @@ export interface GenerateOptions {
gpu?: string;
/** Auto-retry under provisioning. */
waitForCapacity?: boolean;
+ /**
+ * Milliseconds to wait for the response once the request is sent, for this
+ * call only (for a stream, until it opens). Defaults to the client's
+ * `timeoutMs`. Set it to at least the model profile's `overall_timeout_s`
+ * for long buffered generations. A timeout is never retried.
+ */
+ timeoutMs?: number;
}
/** Options for streaming native generation. */
@@ -1400,6 +1413,12 @@ export interface ChatCompletionOptions {
* `provisionTimeout` (typically 15 minutes).
*/
provisionTimeoutMs?: number;
+ /**
+ * Milliseconds to wait for the response once the request is sent, for this
+ * call only. Defaults to the client's `timeoutMs`. A timeout is never
+ * retried.
+ */
+ timeoutMs?: number;
}
// ---------------------------------------------------------------------------
diff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.ts
index 6d1687d16..08d3316f9 100644
--- a/packages/sie_ts_sdk/tests/internal.test.ts
+++ b/packages/sie_ts_sdk/tests/internal.test.ts
@@ -143,12 +143,12 @@ describe("Retry-After header parsing", () => {
expect(delay).toBeLessThan(12000);
});
- it("should return undefined for past date", () => {
+ it("should treat a past date as retry-immediately (0ms)", () => {
const pastDate = new Date(Date.now() - 10000);
const httpDate = pastDate.toUTCString();
const delay = getRetryAfter(httpDate);
- expect(delay).toBeUndefined();
+ expect(delay).toBe(0);
});
it("should return undefined for invalid format", () => {
diff --git a/packages/sie_ts_sdk/tests/jobs.test.ts b/packages/sie_ts_sdk/tests/jobs.test.ts
index e5e458403..9b74870d1 100644
--- a/packages/sie_ts_sdk/tests/jobs.test.ts
+++ b/packages/sie_ts_sdk/tests/jobs.test.ts
@@ -568,7 +568,7 @@ describe("client.jobs", () => {
});
});
- it("submit floors the abort timeout to 120s (survives the 30s default)", () => {
+ it("submit floors the abort timeout to 120s (survives a 30s client timeout)", () => {
vi.useFakeTimers();
try {
let capturedInit: RequestInit | undefined;
@@ -576,11 +576,11 @@ describe("client.jobs", () => {
capturedInit = init;
return new Promise<Response>(() => {}); // never settles; we only inspect the signal
});
- const client = new SIEClient("http://gw:8080");
+ const client = new SIEClient("http://gw:8080", { timeoutMs: 30_000 });
client.jobs.submit({ source: ["a"], model: "m" }).catch(() => {}); // swallow the eventual abort
expect(capturedInit?.signal?.aborted).toBe(false);
vi.advanceTimersByTime(30_000);
- expect(capturedInit?.signal?.aborted).toBe(false); // past the 30s default, still alive
+ expect(capturedInit?.signal?.aborted).toBe(false); // past the 30s client timeout, still alive
vi.advanceTimersByTime(90_001);
expect(capturedInit?.signal?.aborted).toBe(true); // aborts at the 120s floor
} finally {
diff --git a/packages/sie_ts_sdk/tests/retryClassification.test.ts b/packages/sie_ts_sdk/tests/retryClassification.test.ts
new file mode 100644
index 000000000..a36093088
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/retryClassification.test.ts
@@ -0,0 +1,344 @@
+/**
+ * Retry classification, timeouts and partial batches through the real client.
+ *
+ * `fetch` is the stubbed transport: each case replays the shared
+ * `packages/wire-fixtures/retry_classification.json` response followed by a
+ * success, so every decision runs through the production retry loops. The
+ * Python SDK asserts the same table in `test_retry_classification.py`.
+ */
+
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import { IncompleteBatchError, SIEConnectionError, SIEError } from "../src/errors.js";
+import { getRetryAfter } from "../src/internal/retry.js";
+import { packMessage } from "../src/msgpack.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+interface ResponseCase {
+ name: string;
+ status: number;
+ headers: Record<string, string>;
+ body: unknown;
+ idempotent: "retry" | "terminal";
+ generation: "retry" | "terminal";
+}
+
+interface RetryAfterCase {
+ header: string;
+ seconds: number | null | "future";
+}
+
+const fixture = JSON.parse(
+ readFileSync(
+ fileURLToPath(new URL("../../wire-fixtures/retry_classification.json", import.meta.url)),
+ "utf8",
+ ),
+) as { responses: ResponseCase[]; retry_after: RetryAfterCase[] };
+
+type Operation = "encode" | "generate" | "chatCompletions";
+const OPERATIONS: Operation[] = ["encode", "generate", "chatCompletions"];
+
+function successFor(operation: Operation): Response {
+ if (operation === "encode") {
+ return new Response(
+ packMessage({ model: "m", items: [{ id: "a", dense: { values: new Float32Array([0.5]) } }] }),
+ { status: 200, headers: { "Content-Type": "application/msgpack" } },
+ );
+ }
+ const body =
+ operation === "generate"
+ ? { model: "m", text: "ok", finish_reason: "stop" }
+ : { id: "chat-1", object: "chat.completion", model: "m", choices: [] };
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+function fixtureResponse(testCase: ResponseCase): Response {
+ return new Response(JSON.stringify(testCase.body), {
+ status: testCase.status,
+ headers: { "Content-Type": "application/json", ...testCase.headers },
+ });
+}
+
+function call(
+ client: SIEClient,
+ operation: Operation,
+ options: { timeoutMs?: number } = {},
+): Promise<unknown> {
+ if (operation === "encode") {
+ return client.encode("m", { id: "a", text: "hi" });
+ }
+ if (operation === "generate") {
+ return client.generate("m", "hi", { maxNewTokens: 4, ...options });
+ }
+ return client.chatCompletions(
+ { model: "m", messages: [{ role: "user", content: "hi" }] },
+ options,
+ );
+}
+
+async function settle(promise: Promise<unknown>, advanceMs: number) {
+ const outcome = promise.then(
+ (value) => ({ ok: true as const, value }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ await vi.advanceTimersByTimeAsync(advanceMs);
+ return outcome;
+}
+
+function fetchFailure(cause: unknown): TypeError {
+ return new TypeError("fetch failed", { cause });
+}
+
+function codedError(code: string): Error {
+ return Object.assign(new Error(code), { code });
+}
+
+describe("shared retry classification table", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ for (const operation of OPERATIONS) {
+ const operationClass = operation === "encode" ? "idempotent" : "generation";
+ for (const testCase of fixture.responses) {
+ it(`${operation}: ${testCase.name} is ${testCase[operationClass]}`, async () => {
+ mockFetch
+ .mockResolvedValueOnce(fixtureResponse(testCase))
+ .mockResolvedValueOnce(successFor(operation));
+ const client = new SIEClient("http://localhost:8080");
+
+ const outcome = await settle(call(client, operation), 10_000);
+
+ if (testCase[operationClass] === "retry") {
+ expect(outcome.ok).toBe(true);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ } else {
+ expect(outcome.ok).toBe(false);
+ expect(outcome.ok ? undefined : outcome.error).toBeInstanceOf(SIEError);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ }
+ });
+ }
+ }
+
+ for (const testCase of fixture.retry_after) {
+ it(`parses Retry-After ${JSON.stringify(testCase.header)}`, () => {
+ vi.useRealTimers();
+ const parsed = getRetryAfter(testCase.header);
+ if (testCase.seconds === "future") {
+ expect(parsed).toBeGreaterThan(0);
+ } else if (testCase.seconds === null) {
+ expect(parsed).toBeUndefined();
+ } else {
+ expect(parsed).toBe(testCase.seconds * 1000);
+ }
+ });
+ }
+
+ it("retries queue backpressure before a stream opens", async () => {
+ const backpressure = fixture.responses.find(
+ (testCase) => testCase.name === "openai_transport_failure_backpressure",
+ );
+ if (!backpressure) throw new Error("fixture case missing");
+ mockFetch.mockResolvedValueOnce(fixtureResponse(backpressure)).mockResolvedValueOnce(
+ new Response('data: {"request_id":"r","seq":0,"text_delta":"ok","done":true}\n\n', {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ }),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const chunks: unknown[] = [];
+ const consumed = (async () => {
+ for await (const chunk of client.streamGenerate("m", "hi", { maxNewTokens: 4 })) {
+ chunks.push(chunk);
+ }
+ })();
+ await vi.advanceTimersByTimeAsync(10_000);
+ await consumed;
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(chunks).toHaveLength(1);
+ });
+});
+
+describe("fetch failure classification", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it.each([
+ ["DNS name not found", codedError("ENOTFOUND")],
+ ["expired certificate", codedError("CERT_HAS_EXPIRED")],
+ ["untrusted certificate", codedError("UNABLE_TO_VERIFY_LEAF_SIGNATURE")],
+ ["TLS protocol mismatch", codedError("ERR_SSL_WRONG_VERSION_NUMBER")],
+ ])("does not retry a permanent failure: %s", async (_label, cause) => {
+ mockFetch
+ .mockRejectedValueOnce(fetchFailure(cause))
+ .mockResolvedValueOnce(successFor("encode"));
+ const client = new SIEClient("https://gateway.example.test");
+
+ const outcome = await settle(call(client, "encode"), 10_000);
+
+ expect(outcome.ok).toBe(false);
+ const error = outcome.ok ? undefined : outcome.error;
+ expect(error).toBeInstanceOf(SIEConnectionError);
+ expect((error as SIEConnectionError).kind).toBe("other");
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ["connection refused", codedError("ECONNREFUSED")],
+ ["temporary DNS failure", codedError("EAI_AGAIN")],
+ ["connect timeout", codedError("UND_ERR_CONNECT_TIMEOUT")],
+ [
+ "every address refused",
+ Object.assign(new AggregateError([codedError("ECONNREFUSED"), codedError("ENETUNREACH")]), {
+ code: "ECONNREFUSED",
+ }),
+ ],
+ ["no cause", undefined],
+ ])("retries a transient connection failure: %s", async (_label, cause) => {
+ mockFetch
+ .mockRejectedValueOnce(fetchFailure(cause))
+ .mockResolvedValueOnce(successFor("encode"));
+ const client = new SIEClient("http://localhost:8080");
+
+ const outcome = await settle(call(client, "encode"), 10_000);
+
+ expect(outcome.ok).toBe(true);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not retry a response timeout reported by the runtime", async () => {
+ mockFetch
+ .mockRejectedValueOnce(fetchFailure(codedError("UND_ERR_HEADERS_TIMEOUT")))
+ .mockResolvedValueOnce(successFor("encode"));
+ const client = new SIEClient("http://localhost:8080");
+
+ const outcome = await settle(call(client, "encode"), 10_000);
+
+ expect(outcome.ok).toBe(false);
+ expect((outcome.ok ? undefined : outcome.error) as SIEConnectionError).toMatchObject({
+ kind: "timeout",
+ });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("per-call generation timeout", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ vi.useFakeTimers();
+ mockFetch.mockImplementation(
+ (_url: string, init: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init.signal?.addEventListener("abort", () =>
+ reject(new DOMException("aborted", "AbortError")),
+ );
+ }),
+ );
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it.each(["generate", "chatCompletions"] as const)(
+ "%s waits for the per-call timeoutMs instead of the client default",
+ async (operation) => {
+ const client = new SIEClient("http://localhost:8080", { timeoutMs: 1_000 });
+
+ const outcome = settle(call(client, operation, { timeoutMs: 5_000 }), 0);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(mockFetch.mock.calls[0]?.[1]?.signal?.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(4_000);
+ const settled = await outcome;
+
+ expect(settled.ok).toBe(false);
+ expect((settled.ok ? undefined : settled.error) as SIEConnectionError).toMatchObject({
+ kind: "timeout",
+ });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("defaults to a per-attempt timeout longer than the gateway's 120 s deadline", async () => {
+ const client = new SIEClient("http://localhost:8080");
+
+ const outcome = settle(call(client, "generate"), 0);
+ await vi.advanceTimersByTimeAsync(121_000);
+ expect(mockFetch.mock.calls[0]?.[1]?.signal?.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(30_000);
+ const settled = await outcome;
+
+ expect(settled.ok).toBe(false);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("partial batches", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("keeps the returned results on IncompleteBatchError", async () => {
+ mockFetch.mockResolvedValueOnce(
+ new Response(
+ packMessage({
+ model: "m",
+ items: [
+ {
+ id: "b",
+ entities: [],
+ error: { code: "INPUT_TOO_LONG", message: "too long" },
+ },
+ ],
+ }),
+ {
+ status: 200,
+ headers: { "Content-Type": "application/msgpack", "X-SIE-Request-ID": "req-1" },
+ },
+ ),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const error = await client
+ .extract(
+ "m",
+ [
+ { id: "a", text: "x" },
+ { id: "b", text: "y" },
+ ],
+ { labels: ["person"] },
+ )
+ .catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(IncompleteBatchError);
+ const incomplete = error as IncompleteBatchError;
+ expect(incomplete.missingIds).toEqual(["a"]);
+ expect(incomplete.results).toHaveLength(1);
+ expect(incomplete.results[0]).toMatchObject({
+ id: "b",
+ error: { code: "INPUT_TOO_LONG", message: "too long" },
+ request: { id: "req-1" },
+ });
+ });
+});
diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.md
index 8f4c9ad54..45873ead7 100644
--- a/packages/wire-fixtures/README.md
+++ b/packages/wire-fixtures/README.md
@@ -24,6 +24,11 @@ executable.
The gateway writes `prefix/plain_key`, the queue retains `plain_key`, and the
sidecar accepts that key or the exact `full_reference`; Python and both Rust
binaries load the same fixture to prevent prefix drift.
+- `retry_classification.json` — how the SDKs classify a non-2xx response to a
+ buffered call: `retry` or `terminal` for the idempotent operations (encode,
+ score, extract) and for generation, keyed by status, error code, and whether
+ a usable `Retry-After` is present. It also pins how a `Retry-After` value is
+ parsed (delay seconds or an HTTP date; a past date means retry now).
### Why `model_info.json` has two buckets
@@ -47,11 +52,16 @@ fixture set. Current consumers:
`typing.get_args(ModelState)` and `ModelInfo.__annotations__` match the
fixtures, and that
`RequestUsage`/`TERMINAL_UNIT_FIELDS`/`SETTLED_CHARGE_FIELDS` match
- `request_usage.json`).
+ `request_usage.json`), and
+ `packages/sie_sdk/tests/client/test_retry_classification.py` (replays every
+ `retry_classification.json` case through both clients against a local HTTP
+ server).
- TypeScript SDK — `packages/sie_ts_sdk/tests/wireContract.test.ts` (asserts the
runtime `MODEL_STATES` and `MODEL_INFO_WIRE_FIELDS` arrays — the single
sources the `ModelState` type and `WireModelInfo` interface are checked
- against — match the fixtures).
+ against — match the fixtures), and
+ `packages/sie_ts_sdk/tests/retryClassification.test.ts` (replays every
+ `retry_classification.json` case through the client with a stubbed `fetch`).
- Downstream gateways assert that the members they inject are exactly
`settled_charge_fields`, so a gateway that starts publishing a third field
cannot reach production before every consumer has declared it.
diff --git a/packages/wire-fixtures/retry_classification.json b/packages/wire-fixtures/retry_classification.json
new file mode 100644
index 000000000..80a3a48ff
--- /dev/null
+++ b/packages/wire-fixtures/retry_classification.json
@@ -0,0 +1,203 @@
+{
+ "description": "How the SDKs classify one non-2xx response to a buffered call. Each case is served verbatim, followed by a success; 'retry' means the SDK sends the request again and returns that success, 'terminal' means it raises after one request. 'idempotent' covers encode, score and extract; 'generation' covers buffered generate, chat completions and responses. Decisions assume the default wait_for_capacity=true.",
+ "responses": [
+ {
+ "name": "provisioning",
+ "status": 503,
+ "headers": {"Retry-After": "1"},
+ "body": {"detail": {"code": "PROVISIONING", "message": "Provisioning capacity"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "model_loading",
+ "status": 503,
+ "headers": {"Retry-After": "1"},
+ "body": {"detail": {"code": "MODEL_LOADING", "message": "Model is loading"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "resource_exhausted",
+ "status": 503,
+ "headers": {"Retry-After": "1"},
+ "body": {"detail": {"code": "RESOURCE_EXHAUSTED", "message": "Out of memory"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "queue_full",
+ "status": 503,
+ "headers": {"Retry-After": "1"},
+ "body": {"detail": {"code": "QUEUE_FULL", "message": "Queue is full"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "queue_full_without_retry_after",
+ "status": 503,
+ "headers": {},
+ "body": {"detail": {"code": "QUEUE_FULL", "message": "Queue is full"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "billing_capacity_unavailable",
+ "status": 503,
+ "headers": {"Retry-After": "1"},
+ "body": {"error": {"code": "BILLING_CAPACITY_UNAVAILABLE", "message": "Capacity unavailable"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "queue_unavailable_backpressure",
+ "status": 503,
+ "headers": {"Retry-After": "5"},
+ "body": {"detail": {"code": "QUEUE_UNAVAILABLE", "message": "Queue publish failed: backpressure"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "queue_unavailable_backpressure_http_date",
+ "status": 503,
+ "headers": {"Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"},
+ "body": {"detail": {"code": "QUEUE_UNAVAILABLE", "message": "Queue publish failed: backpressure"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "queue_unavailable_header_code",
+ "status": 503,
+ "headers": {"Retry-After": "5", "X-SIE-Error-Code": "QUEUE_UNAVAILABLE"},
+ "body": {"error": {"message": "queue unavailable", "type": "server_error", "param": null, "code": "transport_failure"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "queue_unavailable_without_retry_after",
+ "status": 503,
+ "headers": {},
+ "body": {"detail": {"code": "QUEUE_UNAVAILABLE", "message": "Queue durability confirmation failed"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "queue_unavailable_malformed_retry_after",
+ "status": 503,
+ "headers": {"Retry-After": "soon"},
+ "body": {"detail": {"code": "QUEUE_UNAVAILABLE", "message": "Queue unavailable"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "openai_transport_failure_backpressure",
+ "status": 503,
+ "headers": {"Retry-After": "5"},
+ "body": {"error": {"message": "Queue publish failed: backpressure", "type": "server_error", "param": null, "code": "transport_failure"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "openai_transport_failure_without_retry_after",
+ "status": 503,
+ "headers": {},
+ "body": {"error": {"message": "Queue durability confirmation failed", "type": "server_error", "param": null, "code": "transport_failure"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "account_state_unavailable",
+ "status": 503,
+ "headers": {"Retry-After": "1"},
+ "body": {"error": {"code": "ACCOUNT_STATE_UNAVAILABLE", "message": "Account state unavailable"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "service_unavailable_without_code",
+ "status": 503,
+ "headers": {},
+ "body": {"detail": "Service unavailable"},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "rate_limit",
+ "status": 429,
+ "headers": {"Retry-After": "1"},
+ "body": {"error": {"code": "RATE_LIMIT", "message": "Rate limited"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "rate_limit_without_retry_after",
+ "status": 429,
+ "headers": {},
+ "body": {"error": {"code": "RATE_LIMIT", "message": "Rate limited"}},
+ "idempotent": "retry",
+ "generation": "retry"
+ },
+ {
+ "name": "gateway_timeout",
+ "status": 504,
+ "headers": {"Retry-After": "5"},
+ "body": {"detail": {"code": "GATEWAY_TIMEOUT", "message": "Timed out waiting for a worker result"}},
+ "idempotent": "retry",
+ "generation": "terminal"
+ },
+ {
+ "name": "model_load_failed",
+ "status": 502,
+ "headers": {},
+ "body": {"detail": {"code": "MODEL_LOAD_FAILED", "message": "Model failed to load", "error_class": "GATED", "permanent": true, "attempts": 1}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "internal_error",
+ "status": 500,
+ "headers": {},
+ "body": {"detail": {"code": "INTERNAL_SERVER_ERROR", "message": "Internal error"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "input_too_long",
+ "status": 400,
+ "headers": {},
+ "body": {"detail": {"code": "INPUT_TOO_LONG", "message": "Input exceeds the model's maximum token capacity"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "insufficient_credits",
+ "status": 402,
+ "headers": {},
+ "body": {"error": {"code": "INSUFFICIENT_CREDITS", "message": "Insufficient credits"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ },
+ {
+ "name": "account_suspended",
+ "status": 403,
+ "headers": {},
+ "body": {"error": {"code": "ACCOUNT_SUSPENDED", "message": "Account suspended"}},
+ "idempotent": "terminal",
+ "generation": "terminal"
+ }
+ ],
+ "retry_after": [
+ {"header": "5", "seconds": 5},
+ {"header": "0", "seconds": 0},
+ {"header": "1.5", "seconds": 1.5},
+ {"header": "300", "seconds": 300},
+ {"header": "-1", "seconds": null},
+ {"header": "nan", "seconds": null},
+ {"header": "inf", "seconds": null},
+ {"header": "12abc", "seconds": null},
+ {"header": "soon", "seconds": null},
+ {"header": "", "seconds": null},
+ {"header": "Wed, 21 Oct 2015 07:28:00 GMT", "seconds": 0},
+ {"header": "Fri, 31 Dec 9999 23:59:59 GMT", "seconds": "future"}
+ ]
+}