Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): report GLiNER2 caller errors as invalid input (#526)
XuJian96066a311fd9
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.pyindex 8ab6fd069..1cfd91e9c 100644--- a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py@@ -286,14 +286,14 @@ class GLiNER2Adapter(BaseAdapter):classification_task = opts.get("classification_task", self._classification_task)multi_label = opts.get("multi_label", self._multi_label)if not isinstance(multi_label, bool):- raise ValueError("GLiNER2 multi_label must be boolean")+ raise InvalidInputError("GLiNER2 multi_label must be boolean")input_token_counts = self._doc_input_token_counts(texts)if output_schema is not None:if labels:- raise ValueError("GLiNER2 structured extraction does not accept labels")+ raise InvalidInputError("GLiNER2 structured extraction does not accept labels")if classification_task is not None:- raise ValueError("GLiNER2 structured extraction does not accept classification_task")+ raise InvalidInputError("GLiNER2 structured extraction does not accept classification_task")structures = self._json_schema_to_structures(output_schema)specs = [spec for fields in structures.values() for spec in fields]# A field's choices are listed in its structure, and each again in a prefix before the document.@@ -330,7 +330,9 @@ class GLiNER2Adapter(BaseAdapter):relation_entities = [self._extract_relation_entities(item) for item in items]if any(entities is not None for entities in relation_entities):if not all(entities for entities in relation_entities):- raise ValueError("GLiNER2 relation extraction requires non-empty entities in every item metadata")+ raise InvalidInputError(+ "GLiNER2 relation extraction requires non-empty entities in every item metadata"+ )normalized_entities = [self._normalize_input_entities(item, entities or []) for item, entities in zip(items, relation_entities)]@@ -365,7 +367,7 @@ class GLiNER2Adapter(BaseAdapter):if classification_task is not None:if not isinstance(classification_task, str) or not classification_task.strip():- raise ValueError("GLiNER2 classification_task must be a non-empty string")+ raise InvalidInputError("GLiNER2 classification_task must be a non-empty string")check_label_chars("GLiNER2", "classification_task", [classification_task])check_label_chars("GLiNER2", "labels", normalized_labels)positive_label = self._effective_positive_label(opts, normalized_labels)@@ -631,16 +633,16 @@ class GLiNER2Adapter(BaseAdapter):def _extract_text(self, item: Item) -> str:"""Extract text from an item."""if item.text is None:- raise ValueError(ERR_REQUIRES_TEXT.format(adapter_name="GLiNER2 adapter"))+ raise InvalidInputError(ERR_REQUIRES_TEXT.format(adapter_name="GLiNER2 adapter"))return item.text@staticmethoddef _validate_threshold(value: object) -> float:if isinstance(value, bool) or not isinstance(value, (int, float)):- raise ValueError("GLiNER2 threshold must be a finite number between 0 and 1")+ raise InvalidInputError("GLiNER2 threshold must be a finite number between 0 and 1")threshold = float(value)if not math.isfinite(threshold) or not 0.0 <= threshold <= 1.0:- raise ValueError("GLiNER2 threshold must be a finite number between 0 and 1")+ raise InvalidInputError("GLiNER2 threshold must be a finite number between 0 and 1")return threshold@staticmethod@@ -706,16 +708,16 @@ class GLiNER2Adapter(BaseAdapter):@staticmethoddef _validate_labels(labels: list[str] | None) -> list[str]:if labels is None:- raise ValueError(_ERR_REQUIRES_LABELS)+ raise InvalidInputError(_ERR_REQUIRES_LABELS)if not isinstance(labels, list):- raise ValueError("GLiNER2 labels must be a list")+ raise InvalidInputError("GLiNER2 labels must be a list")if not labels:- raise ValueError(_ERR_REQUIRES_LABELS)+ raise InvalidInputError(_ERR_REQUIRES_LABELS)if any(not isinstance(label, str) or not label.strip() for label in labels):- raise ValueError("GLiNER2 labels must be non-empty strings")+ raise InvalidInputError("GLiNER2 labels must be non-empty strings")normalized = [label.strip() for label in labels]if len(set(normalized)) != len(normalized):- raise ValueError("GLiNER2 labels must be unique")+ raise InvalidInputError("GLiNER2 labels must be unique")return normalized@staticmethod@@ -724,7 +726,7 @@ class GLiNER2Adapter(BaseAdapter):return Noneentities = item.metadata["entities"]if not isinstance(entities, list):- raise ValueError("GLiNER2 item metadata.entities must be a list")+ raise InvalidInputError("GLiNER2 item metadata.entities must be a list")return entities@classmethod@@ -733,7 +735,7 @@ class GLiNER2Adapter(BaseAdapter):normalized: list[Entity] = []for entity in entities:if not isinstance(entity, dict):- raise ValueError("GLiNER2 relation entities must be objects")+ raise InvalidInputError("GLiNER2 relation entities must be objects")start = entity.get("start")end = entity.get("end")entity_text = entity.get("text")@@ -751,8 +753,11 @@ class GLiNER2Adapter(BaseAdapter):or end > len(text)or text[start:end] != entity_text):- raise ValueError("GLiNER2 relation entities require valid character offsets")- score = cls._validate_score(entity.get("score", 1.0), "relation entity")+ raise InvalidInputError("GLiNER2 relation entities require valid character offsets")+ try:+ score = cls._validate_score(entity.get("score", 1.0), "relation entity")+ except ValueError as error:+ raise InvalidInputError(str(error)) from errornormalized.append(Entity(text=entity_text, label=label.strip(), score=score, start=start, end=end))return normalized@@ -812,10 +817,10 @@ class GLiNER2Adapter(BaseAdapter):@staticmethoddef _json_schema_to_structures(output_schema: dict[str, Any]) -> dict[str, list[str]]:if output_schema.get("type") != "object":- raise ValueError("GLiNER2 output_schema root type must be object")+ raise InvalidInputError("GLiNER2 output_schema root type must be object")properties = output_schema.get("properties")if not isinstance(properties, dict) or not properties:- raise ValueError("GLiNER2 output_schema requires non-empty properties")+ raise InvalidInputError("GLiNER2 output_schema requires non-empty properties")allowed_root = {"type","properties",@@ -826,46 +831,46 @@ class GLiNER2Adapter(BaseAdapter):}unsupported_root = set(output_schema) - allowed_rootif unsupported_root:- raise ValueError(f"GLiNER2 output_schema has unsupported root keywords: {sorted(unsupported_root)}")+ raise InvalidInputError(f"GLiNER2 output_schema has unsupported root keywords: {sorted(unsupported_root)}")required = output_schema.get("required", [])if (not isinstance(required, list)or any(not isinstance(name, str) or name not in properties for name in required)or len(set(required)) != len(required)):- raise ValueError("GLiNER2 output_schema required must contain unique property names")+ raise InvalidInputError("GLiNER2 output_schema required must contain unique property names")additional_properties = output_schema.get("additionalProperties", True)if not isinstance(additional_properties, bool):- raise ValueError("GLiNER2 output_schema additionalProperties must be boolean")+ raise InvalidInputError("GLiNER2 output_schema additionalProperties must be boolean")fields: list[str] = []for name, definition in properties.items():if not isinstance(name, str) or not name or any(delimiter in name for delimiter in _STRUCTURE_DELIMITERS):- raise ValueError("GLiNER2 output_schema property names contain unsupported delimiters")+ raise InvalidInputError("GLiNER2 output_schema property names contain unsupported delimiters")if not isinstance(definition, dict):- raise ValueError(f"GLiNER2 output_schema property {name!r} must be an object")+ raise InvalidInputError(f"GLiNER2 output_schema property {name!r} must be an object")unsupported = set(definition) - {"type", "description", "enum", "items", "title"}if unsupported:- raise ValueError(+ raise InvalidInputError(f"GLiNER2 output_schema property {name!r} has unsupported keywords: {sorted(unsupported)}")description = definition.get("description") or definition.get("title")if description is not None and not isinstance(description, str):- raise ValueError(f"GLiNER2 output_schema property {name!r} description must be a string")+ raise InvalidInputError(f"GLiNER2 output_schema property {name!r} description must be a string")description = description.replace("::", ":") if description else Nonefield_type = definition.get("type")enum = definition.get("enum")if enum is not None:if field_type != "string" or not isinstance(enum, list) or not enum:- raise ValueError(f"GLiNER2 output_schema property {name!r} has invalid enum")+ raise InvalidInputError(f"GLiNER2 output_schema property {name!r} has invalid enum")if any(not isinstance(choice, str)or not choiceor any(delimiter in choice for delimiter in _STRUCTURE_DELIMITERS)for choice in enum):- raise ValueError(+ raise InvalidInputError(f"GLiNER2 output_schema property {name!r} enum values contain unsupported delimiters")choices = "|".join(enum)@@ -875,7 +880,7 @@ class GLiNER2Adapter(BaseAdapter):elif field_type == "array" and definition.get("items") == {"type": "string"}:spec = f"{name}::list"else:- raise ValueError(+ raise InvalidInputError(f"GLiNER2 output_schema property {name!r} supports only string, string enum, or array of strings")if description:@@ -1081,10 +1086,10 @@ class GLiNER2Adapter(BaseAdapter):if value is None:return Noneif not isinstance(value, str) or not value.strip():- raise ValueError("GLiNER2 positive_label must be a non-empty string")+ raise InvalidInputError("GLiNER2 positive_label must be a non-empty string")label = value.strip()if labels is not None and label not in labels:- raise ValueError("GLiNER2 positive_label must be one of the labels")+ raise InvalidInputError("GLiNER2 positive_label must be one of the labels")return labeldef _doc_input_token_counts(self, texts: list[str]) -> list[int] | None:diff --git a/packages/sie_server/tests/adapters/test_gliner2_input_errors.py b/packages/sie_server/tests/adapters/test_gliner2_input_errors.pynew file mode 100644index 000000000..7ff93f118--- /dev/null+++ b/packages/sie_server/tests/adapters/test_gliner2_input_errors.py@@ -0,0 +1,93 @@+from typing import Any+from unittest.mock import MagicMock++import pytest+from sie_server.adapters.gliner2.adapter import GLiNER2Adapter+from sie_server.ipc_types import ExtractBatchItem+from sie_server.queue_executor import _inference_exception_outcome+from sie_server.types.inputs import Item+++ ("labels", "output_schema", "options", "metadata"),+ [+ (None, None, None, None),+ ([], None, None, None),+ (["PERSON", " PERSON "], None, None, None),+ ([""], None, None, None),+ (["PERSON"], None, {"threshold": float("nan")}, None),+ (["PERSON"], None, {"threshold": True}, None),+ (["PERSON"], None, {"multi_label": "yes"}, None),+ (["PERSON"], None, {"classification_task": ""}, None),+ (["PERSON"], None, {"classification_task": "task", "positive_label": ""}, None),+ (["PERSON"], None, {"classification_task": "task", "positive_label": "absent"}, None),+ (None, {"type": "array"}, None, None),+ (None, {"type": "object", "properties": {}}, None, None),+ (None, {"type": "object", "properties": {"age": {"type": "number"}}}, None, None),+ (["PERSON"], {"type": "object", "properties": {"name": {"type": "string"}}}, None, None),+ (["WORKS_AT"], None, None, {"entities": "Alice"}),+ (["WORKS_AT"], None, None, {"entities": []}),+ (["WORKS_AT"], None, None, {"entities": ["Alice"]}),+ (["WORKS_AT"], None, None, {"entities": [{"text": "Alice", "start": 0, "end": 99}]}),+ (["WORKS_AT"], None, None, {"entities": [{"text": "Alice", "start": 0, "end": 5, "score": "bad"}]}),+ ],+)+def test_invalid_request_is_invalid_input_on_the_queue_path(+ labels: list[str] | None,+ output_schema: dict[str, Any] | None,+ options: dict[str, Any] | None,+ metadata: dict[str, Any] | None,+) -> None:+ adapter = GLiNER2Adapter("test-model")+ adapter._model = MagicMock()+ item = Item(text="Alice works at Acme.", metadata=metadata)++ with pytest.raises(ValueError, match="GLiNER2") as error:+ adapter.extract([item], labels=labels, output_schema=output_schema, options=options)++ batch_item = ExtractBatchItem(+ work_item_id="req.0",+ request_id="req",+ item_index=0,+ total_items=1,+ timestamp=0,+ item={"text": item.text},+ labels=labels,+ output_schema=output_schema,+ options=options,+ )+ outcome = _inference_exception_outcome(batch_item, error.value)++ assert outcome.disposition == "publish_error_and_ack"+ assert outcome.error_code == "INVALID_INPUT"+ assert outcome.error == str(error.value)+ adapter._model.extract_entities.assert_not_called()+ adapter._model.batch_extract_entities.assert_not_called()+ adapter._model.batch_extract_relations.assert_not_called()+ adapter._model.batch_extract_json.assert_not_called()+ adapter._model.classify_text.assert_not_called()+++def test_invalid_model_result_remains_an_inference_error_on_the_queue_path() -> None:+ adapter = GLiNER2Adapter("test-model")+ adapter._model = MagicMock()+ adapter._model.extract_entities.return_value = {+ "entities": {"PERSON": [{"text": "Alice", "start": 0, "end": 5, "confidence": "bad"}]},+ }++ with pytest.raises(ValueError, match="invalid entity confidence") as error:+ adapter.extract([Item(text="Alice")], labels=["PERSON"])++ batch_item = ExtractBatchItem(+ work_item_id="req.0",+ request_id="req",+ item_index=0,+ total_items=1,+ timestamp=0,+ item={"text": "Alice"},+ labels=["PERSON"],+ )+ outcome = _inference_exception_outcome(batch_item, error.value)++ assert outcome.disposition == "publish_error_and_ack"+ assert outcome.error_code == "inference_error"diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex a7305b1ce..8c4dd910a 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -12,6 +12,7 @@ import numpy as npimport pytestfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpec+from sie_server.adapters.gliner2.adapter import GLiNER2Adapterfrom sie_server.adapters.laya.adapter import LayaAdapterfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.extract_cost import MAX_EXTRACT_LABELS@@ -1450,6 +1451,51 @@ class TestProcessScoreBatch:class TestProcessExtractBatch:+ @pytest.mark.asyncio+ async def test_gliner2_invalid_request_does_not_fail_valid_sibling(self) -> None:+ adapter = GLiNER2Adapter("test-model")+ adapter._model = MagicMock()+ adapter._model.extract_entities.return_value = {"entities": {}}+ reg = _make_registry()+ worker = AsyncMock()++ async def submit(requests, *, lora):+ futures: list[asyncio.Future[WorkerResult]] = []+ for request in requests:+ future: asyncio.Future[WorkerResult] = asyncio.Future()+ try:+ output = adapter.extract(+ request.items,+ labels=request.labels,+ output_schema=request.output_schema,+ options=request.options,+ )+ except ValueError as error:+ future.set_exception(error)+ else:+ future.set_result(WorkerResult(output=output, timing=RequestTiming()))+ futures.append(future)+ return futures++ worker.submit_extract_preformed_batch = AsyncMock(side_effect=submit)+ reg.start_worker = AsyncMock(return_value=worker)+ outcome = await QueueExecutor(reg).process_extract_batch(+ ProcessExtractBatchRequest(+ model_id="test/model",+ items=[+ _extract_item(wiid="bad.0", options={"multi_label": "yes"}),+ _extract_item(wiid="good.0"),+ ],+ )+ )++ by_id = {item.work_item_id: item for item in outcome.outcomes}+ assert by_id["bad.0"].disposition == "publish_error_and_ack"+ assert by_id["bad.0"].error_code == "INVALID_INPUT"+ assert by_id["good.0"].disposition == "publish_and_ack"+ assert by_id["good.0"].error_code is None+ adapter._model.extract_entities.assert_called_once()+@pytest.mark.asyncioasync def test_image_item_uses_registered_preprocessor_payload(self) -> None:reg = _make_registry()