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(server): validate GLiNER2 prompts before document work (#793)

svonava2281ba860f3c
diff --git a/packages/sie_server/src/sie_server/adapters/_prompt_limit.py b/packages/sie_server/src/sie_server/adapters/_prompt_limit.py
index 5f3de48b4..1f135ec21 100644
--- a/packages/sie_server/src/sie_server/adapters/_prompt_limit.py
+++ b/packages/sie_server/src/sie_server/adapters/_prompt_limit.py
@@ -15,7 +15,7 @@ GLiFormer and GLiNER2.5-Decide bound theirs. A request is rejected with
The defaults sit far above the label sets these models are used with: the
largest label set among this repository's examples takes about 40 tokens, a
60-type PII list about 230, and a structured-extraction schema of 50 described
-fields about 1,200, while ``DEFAULT_MAX_PROMPT_TOKENS`` holds several hundred
+fields about 1,260, while ``DEFAULT_MAX_PROMPT_TOKENS`` holds several hundred
entity types and ``DEFAULT_MAX_SCHEMA_PROMPT_TOKENS`` a schema of dozens of
described fields with their choices.
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
index 7c1f10dcc..0a04a0dfa 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
@@ -277,16 +277,14 @@ class GLiNER2Adapter(BaseAdapter):
"""Extract entities, relations, classifications, or flat structured data."""
self._check_loaded()
texts = [self._extract_text(item) for item in items]
- # gliner2 reads a bounded window of words: pass it only the prefix holding them.
- reads = [self._read(text) for text in texts]
- windows = [(model_text, subwords) for model_text, subwords, _ in reads]
+ # Validate the selected task's prompt before reading or metering document
+ # windows. Text and option errors retain their precedence over prompt errors.
opts = options or {}
effective_threshold = self._validate_threshold(opts.get("threshold", self._threshold))
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 InvalidInputError("GLiNER2 multi_label must be boolean")
- input_token_counts = self._doc_input_token_counts(texts)
if output_schema is not None:
if labels:
@@ -302,6 +300,9 @@ class GLiNER2Adapter(BaseAdapter):
check_label_chars("GLiNER2", "output_schema property names", output_schema["properties"])
check_label_chars("GLiNER2", "output_schema enum values", choices)
prompt = self._prompt_tokens(specs, key=("json", tuple(specs)), extra=len(choices))
+ reads = [self._read(text) for text in texts]
+ windows = [(model_text, subwords) for model_text, subwords, _ in reads]
+ input_token_counts = self._doc_input_token_counts(texts)
rows = self._row_tokens(windows, prompt)
with torch.inference_mode():
raw_results, errors, input_token_counts = self._run_complete(
@@ -347,6 +348,9 @@ class GLiNER2Adapter(BaseAdapter):
prompt = self._prompt_tokens(
normalized_labels, per_entry=_PROMPT_TOKENS_PER_RELATION, key=("relations", tuple(normalized_labels))
)
+ reads = [self._read(text) for text in texts]
+ windows = [(model_text, subwords) for model_text, subwords, _ in reads]
+ input_token_counts = self._doc_input_token_counts(texts)
rows = self._row_tokens(windows, prompt)
with torch.inference_mode():
raw_results, errors, input_token_counts = self._run_complete(
@@ -388,6 +392,8 @@ class GLiNER2Adapter(BaseAdapter):
[classification_task, *normalized_labels],
key=("classification", classification_task, tuple(normalized_labels)),
)
+ reads = [self._read(text) for text in texts]
+ input_token_counts = self._doc_input_token_counts(texts)
item_windows = [self._classification_windows(text, read) for text, read in zip(texts, reads, strict=True)]
if any(len(one) > 1 for one in item_windows):
input_token_counts = self._windowed_input_token_counts(texts, item_windows)
@@ -425,6 +431,9 @@ class GLiNER2Adapter(BaseAdapter):
check_label_chars("GLiNER2", "labels", normalized_labels)
prompt = self._prompt_tokens(normalized_labels, key=("entities", tuple(normalized_labels)))
+ reads = [self._read(text) for text in texts]
+ windows = [(model_text, subwords) for model_text, subwords, _ in reads]
+ input_token_counts = self._doc_input_token_counts(texts)
with torch.inference_mode():
raw_results, errors, input_token_counts = self._run_complete(
texts,
diff --git a/packages/sie_server/tests/adapters/test_gliner2_validation_order.py b/packages/sie_server/tests/adapters/test_gliner2_validation_order.py
new file mode 100644
index 000000000..9abb3dc1b
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner2_validation_order.py
@@ -0,0 +1,270 @@
+from __future__ import annotations
+
+from threading import RLock
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, call
+
+import pytest
+from sie_server.adapters.gliner2.adapter import GLiNER2Adapter
+from sie_server.adapters.gliner2.classification import GLiNER2ClassificationAdapter
+from sie_server.adapters.gliner2.entity_lora import GLiNER2EntityLoraAdapter
+from sie_server.types.inputs import InvalidInputError, Item
+
+_TEXT = "Alice Acme"
+_ENTITIES = [{"text": "Alice", "start": 0, "end": 5}, {"text": "Acme", "start": 6, "end": 10}]
+_SCHEMA = {"type": "object", "properties": {"name": {"type": "string"}}}
+
+
+def _adapter(*, max_prompt_tokens: int = 2048) -> GLiNER2Adapter:
+ adapter = GLiNER2Adapter("test", max_seq_length=8, max_prompt_tokens=max_prompt_tokens)
+ adapter._model = MagicMock()
+ adapter._count_subwords = MagicMock(side_effect=lambda values: [len(value) for value in values])
+ return adapter
+
+
+def _forbid_document_work(monkeypatch: pytest.MonkeyPatch, adapter: GLiNER2Adapter) -> list[MagicMock]:
+ guards = []
+ for name in ("_read", "_doc_input_token_counts", "_classification_windows", "_windowed_input_token_counts"):
+ guard = MagicMock(side_effect=AssertionError(f"Rejected prompt reached {name}"))
+ monkeypatch.setattr(adapter, name, guard)
+ guards.append(guard)
+ return guards
+
+
+def _request(task: str) -> tuple[list[Item], dict[str, Any]]:
+ if task == "structured":
+ return [Item(text=_TEXT)], {"output_schema": _SCHEMA}
+ if task == "relations":
+ return [Item(text=_TEXT, metadata={"entities": _ENTITIES})], {"labels": ["knows"]}
+ if task == "classification":
+ return [Item(text=_TEXT)], {"labels": ["yes", "no"], "options": {"classification_task": "topic"}}
+ return [Item(text=_TEXT)], {"labels": ["person"]}
+
+
+ ("kwargs", "metadata", "match"),
+ [
+ ({}, None, "requires labels"),
+ ({"labels": ["person", " person "]}, None, "unique"),
+ ({"labels": ["x" * 129]}, None, "labels may have at most"),
+ ({"output_schema": {"type": "array"}}, None, "root type"),
+ ({"output_schema": {"type": "object", "properties": {}}}, None, "non-empty properties"),
+ ({"output_schema": {"type": "object", "properties": {"x" * 129: {"type": "string"}}}}, None, "property names"),
+ (
+ {"output_schema": {"type": "object", "properties": {"name": {"type": "string", "enum": ["x" * 129]}}}},
+ None,
+ "enum values",
+ ),
+ ({"output_schema": _SCHEMA, "labels": ["person"]}, None, "does not accept labels"),
+ (
+ {"output_schema": _SCHEMA, "options": {"classification_task": ""}},
+ None,
+ "does not accept classification_task",
+ ),
+ ({"labels": ["knows"]}, {"entities": "Alice"}, "metadata.entities must be a list"),
+ ({"labels": ["knows"]}, {"entities": []}, "non-empty entities"),
+ ({"labels": ["knows"]}, {"entities": [{"text": "Alice", "start": 0, "end": 99}]}, "valid character offsets"),
+ ({"labels": ["knows"], "options": {"classification_task": ""}}, {"entities": "Alice"}, "metadata.entities"),
+ ({"labels": ["yes"], "options": {"classification_task": ""}}, None, "non-empty string"),
+ ({"labels": ["yes"], "options": {"classification_task": "x" * 129}}, None, "classification_task may have"),
+ (
+ {"labels": ["yes"], "options": {"classification_task": "topic", "positive_label": "missing"}},
+ None,
+ "positive_label",
+ ),
+ ],
+)
+def test_invalid_task_prompt_never_reads_or_meters_documents(
+ monkeypatch: pytest.MonkeyPatch, kwargs: dict[str, Any], metadata: dict[str, Any] | None, match: str
+) -> None:
+ adapter = _adapter()
+ guards = _forbid_document_work(monkeypatch, adapter)
+
+ with pytest.raises(InvalidInputError, match=match):
+ adapter.extract([Item(text=_TEXT, metadata=metadata)], **kwargs)
+
+ for guard in guards:
+ guard.assert_not_called()
+ assert adapter._model.mock_calls == []
+
+
[email protected]("task", ["entities", "relations", "structured", "classification"])
[email protected](("option", "value"), [("threshold", float("nan")), ("multi_label", "yes")])
+def test_invalid_shared_options_never_read_or_meter_documents(
+ monkeypatch: pytest.MonkeyPatch, task: str, option: str, value: Any
+) -> None:
+ adapter = _adapter()
+ guards = _forbid_document_work(monkeypatch, adapter)
+ items, kwargs = _request(task)
+ kwargs.setdefault("options", {})[option] = value
+
+ with pytest.raises(InvalidInputError, match=option):
+ adapter.extract(items, **kwargs)
+
+ for guard in guards:
+ guard.assert_not_called()
+
+
[email protected]("task", ["entities", "relations", "structured", "classification"])
+def test_token_limit_checks_only_the_prompt_and_reuses_its_cached_rejection(
+ monkeypatch: pytest.MonkeyPatch, task: str
+) -> None:
+ adapter = _adapter(max_prompt_tokens=16)
+ count = MagicMock(side_effect=lambda values: [100] * len(values))
+ adapter._count_subwords = count
+ guards = _forbid_document_work(monkeypatch, adapter)
+ items, kwargs = _request(task)
+
+ for _ in range(2):
+ with pytest.raises(InvalidInputError, match="at most 16 tokens"):
+ adapter.extract(items, **kwargs)
+
+ count.assert_called_once()
+ assert all(_TEXT not in value for value in count.call_args.args[0])
+ for guard in guards:
+ guard.assert_not_called()
+
+
+ ("text", "kwargs", "match"),
+ [
+ (None, {"options": {"threshold": False}}, "requires text"),
+ (_TEXT, {"options": {"threshold": False, "multi_label": "bad"}}, "threshold"),
+ (_TEXT, {"labels": [], "output_schema": {"type": "array"}, "options": {"multi_label": "bad"}}, "multi_label"),
+ (_TEXT, {"labels": ["person"], "output_schema": {"type": "array"}}, "does not accept labels"),
+ ],
+)
+def test_existing_text_option_and_task_error_precedence(
+ monkeypatch: pytest.MonkeyPatch, text: str | None, kwargs: dict[str, Any], match: str
+) -> None:
+ adapter = _adapter()
+ _forbid_document_work(monkeypatch, adapter)
+
+ with pytest.raises(InvalidInputError, match=match):
+ adapter.extract([Item(text=text)], **kwargs)
+
+
+def _responding_model() -> MagicMock:
+ model = MagicMock()
+ model.processor.tokenizer.side_effect = lambda texts, **_kwargs: {
+ "input_ids": [[1] * (len(text.split()) + 2) for text in texts]
+ }
+ model.extract_entities.return_value = {
+ "entities": {"person": [{"text": "Alice", "start": 0, "end": 5, "confidence": 0.9}]}
+ }
+ model.batch_extract_json.return_value = [{"_sie_root": [{"name": "Alice"}]}]
+ model.batch_extract_relations.return_value = [
+ {
+ "relation_extraction": {
+ "knows": [{"head": {"text": "Alice", "confidence": 0.9}, "tail": {"text": "Acme", "confidence": 0.8}}]
+ }
+ }
+ ]
+ model.classify_text.return_value = {"topic": {"label": "yes", "confidence": 0.9}}
+ return model
+
+
[email protected]("task", ["entities", "relations", "structured", "classification"])
+def test_accepted_task_routing_output_and_usage_are_preserved(task: str) -> None:
+ adapter = _adapter()
+ model = _responding_model()
+ adapter._model = model
+ items, kwargs = _request(task)
+ # These options are intentionally validated only on the classification path.
+ if task != "classification":
+ kwargs["options"] = {"positive_label": ""}
+ if task == "relations":
+ kwargs["options"]["classification_task"] = ""
+ if task == "structured":
+ items[0].metadata = {"entities": "ignored by structured routing"}
+
+ output = adapter.extract(items, **kwargs)
+
+ assert output.input_token_counts == [4]
+ assert output.errors is None
+ if task == "entities":
+ assert output.entities == [[{"text": "Alice", "label": "person", "score": 0.9, "start": 0, "end": 5}]]
+ model.extract_entities.assert_called_once_with(
+ _TEXT, ["person"], threshold=0.5, include_confidence=True, include_spans=True, max_len=8
+ )
+ elif task == "relations":
+ assert output.entities == [
+ [
+ {"text": "Alice", "label": "ENTITY", "score": 1.0, "start": 0, "end": 5},
+ {"text": "Acme", "label": "ENTITY", "score": 1.0, "start": 6, "end": 10},
+ ]
+ ]
+ assert output.relations == [[{"head": "Alice", "tail": "Acme", "relation": "knows", "score": 0.8}]]
+ model.batch_extract_relations.assert_called_once_with(
+ [_TEXT], ["knows"], batch_size=1, threshold=0.5, include_confidence=True, include_spans=True, max_len=8
+ )
+ model.classify_text.assert_not_called()
+ elif task == "structured":
+ assert output.entities == [[]]
+ assert output.data == [{"name": "Alice"}]
+ model.batch_extract_json.assert_called_once_with(
+ [_TEXT],
+ {"_sie_root": ["name::str"]},
+ batch_size=1,
+ threshold=0.5,
+ include_confidence=False,
+ include_spans=False,
+ max_len=8,
+ )
+ else:
+ assert output.entities == [[]]
+ assert output.classifications == [[{"label": "yes", "score": 0.9}]]
+ model.classify_text.assert_called_once_with(
+ _TEXT,
+ {"topic": {"labels": ["yes", "no"], "multi_label": False, "cls_threshold": 0.5}},
+ threshold=0.5,
+ include_confidence=True,
+ max_len=8,
+ )
+
+
[email protected]("reject", [False, True])
+def test_classification_subclass_preserves_defaults_and_early_prompt_validation(
+ monkeypatch: pytest.MonkeyPatch, reject: bool
+) -> None:
+ adapter = GLiNER2ClassificationAdapter(
+ "test", classification_task="topic", default_labels=["yes", "no"], max_seq_length=8, max_prompt_tokens=16
+ )
+ adapter._model = _responding_model()
+ if reject:
+ adapter._count_subwords = lambda values: [100] * len(values)
+ guards = _forbid_document_work(monkeypatch, adapter)
+ with pytest.raises(InvalidInputError, match="at most 16 tokens"):
+ adapter.extract([Item(text=_TEXT)])
+ for guard in guards:
+ guard.assert_not_called()
+ else:
+ output = adapter.extract([Item(text=_TEXT)])
+ assert output.classifications == [[{"label": "yes", "score": 0.9}]]
+ assert output.input_token_counts == [4]
+
+
[email protected]("reject", [False, True])
+def test_entity_lora_subclass_keeps_selection_and_final_base_restoration(
+ monkeypatch: pytest.MonkeyPatch, reject: bool
+) -> None:
+ # Exercise the real guard/super/finally seam without loading optional weights.
+ adapter = GLiNER2EntityLoraAdapter.__new__(GLiNER2EntityLoraAdapter)
+ GLiNER2Adapter.__init__(adapter, "test", max_seq_length=8, max_prompt_tokens=16)
+ controller = SimpleNamespace(lock=RLock(), select=MagicMock(), source=MagicMock(return_value="org/a"))
+ monkeypatch.setattr(adapter, "_lora", controller, raising=False)
+ adapter._model = _responding_model()
+ if reject:
+ adapter._count_subwords = lambda values: [100] * len(values)
+ guards = _forbid_document_work(monkeypatch, adapter)
+ with pytest.raises(InvalidInputError, match="at most 16 tokens"):
+ adapter.extract([Item(text=_TEXT)], labels=["person"], options={"lora": "a"})
+ for guard in guards:
+ guard.assert_not_called()
+ else:
+ output = adapter.extract([Item(text=_TEXT)], labels=["person"], options={"lora": "a"})
+ assert output.entities == [[{"text": "Alice", "label": "person", "score": 0.9, "start": 0, "end": 5}]]
+ assert output.input_token_counts == [4]
+ controller.source.assert_called_once_with("a")
+ assert controller.select.call_args_list == [call("a"), call(None)]