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(integrations): send explicit item ids so rerankers map scores back (#410)

Krisztian Gajdarc07db0638d51
diff --git a/integrations/conftest.py b/integrations/conftest.py
index 53f481e2d..96075d86d 100644
--- a/integrations/conftest.py
+++ b/integrations/conftest.py
@@ -7,9 +7,14 @@ Fixtures are automatically available to all tests under integrations/.
from __future__ import annotations
import os
+import re
+import threading
+from collections.abc import Iterator
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
from unittest.mock import NonCallableMagicMock, create_autospec
+import msgpack
import numpy as np
import pytest
from sie_sdk import SIEAsyncClient, SIEClient
@@ -90,6 +95,16 @@ def _create_mock_encode_result(
return result
+def _server_item_id(item: Any, index: int) -> str:
+ """Return the ``item_id`` the SIE server reports for a scored item.
+
+ The server echoes an item's ``id`` and reports ``item-<index>`` for an item
+ sent without one.
+ """
+ item_id = item.get("id") if isinstance(item, dict) else None
+ return item_id if item_id is not None else f"item-{index}"
+
+
def _create_mock_score_result(query: str, items: list[dict]) -> list[dict[str, Any]]:
"""Create mock score results."""
rng = np.random.default_rng(hash(query) % (2**32))
@@ -207,10 +222,7 @@ def mock_sie_client() -> NonCallableMagicMock:
...}`` envelope with ranked entries under ``scores`` (not a bare list).
"""
query_text = _get_text(query)
- item_dicts = [
- {"id": i.get("id", str(idx)) if isinstance(i, dict) else str(idx), "text": _get_text(i)}
- for idx, i in enumerate(items)
- ]
+ item_dicts = [{"id": _server_item_id(i, idx), "text": _get_text(i)} for idx, i in enumerate(items)]
return {
"model": _model,
"scores": _create_mock_score_result(query_text, item_dicts),
@@ -269,10 +281,7 @@ def mock_sie_async_client() -> NonCallableMagicMock:
async def mock_score(_model: str, query: Any, items: list[Any], **kwargs: Any) -> dict[str, Any]:
query_text = _get_text(query)
- item_dicts = [
- {"id": i.get("id", str(idx)) if isinstance(i, dict) else str(idx), "text": _get_text(i)}
- for idx, i in enumerate(items)
- ]
+ item_dicts = [{"id": _server_item_id(i, idx), "text": _get_text(i)} for idx, i in enumerate(items)]
return {
"model": _model,
"scores": _create_mock_score_result(query_text, item_dicts),
@@ -293,6 +302,82 @@ def mock_sie_async_client() -> NonCallableMagicMock:
return client
+def _query_word_overlap(query: str, text: str) -> float:
+ """Count the distinct query words that appear in ``text``."""
+ query_words = set(re.findall(r"[a-z0-9]+", query.lower()))
+ return float(len(query_words & set(re.findall(r"[a-z0-9]+", text.lower()))))
+
+
+class _ScoreStubServer:
+ """Local HTTP server that answers ``POST /v1/score/{model}`` in the SIE server's wire format.
+
+ An item's score is the number of distinct query words it contains. Entries
+ are sorted by descending score, ranked from 0, and carry the ``item_id`` the
+ SIE server reports (see ``_server_item_id``). Decoded request bodies are
+ recorded in ``requests``.
+ """
+
+ def __init__(self) -> None:
+ self.requests: list[dict[str, Any]] = []
+ stub = self
+
+ class _Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self) -> None:
+ body = msgpack.unpackb(self.rfile.read(int(self.headers.get("Content-Length") or 0)), raw=False)
+ stub.requests.append(body)
+ reply = msgpack.packb(
+ {"model": self.path.removeprefix("/v1/score/"), "scores": _stub_score_entries(body)},
+ use_bin_type=True,
+ )
+ self.send_response(200)
+ self.send_header("Content-Type", "application/msgpack")
+ self.send_header("Content-Length", str(len(reply)))
+ self.end_headers()
+ self.wfile.write(reply)
+
+ def log_message(self, *_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 close(self) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+
+
+def _stub_score_entries(body: dict[str, Any]) -> list[dict[str, Any]]:
+ query = body["query"].get("text") or ""
+ scored = sorted(
+ (
+ (_server_item_id(item, index), _query_word_overlap(query, item.get("text") or ""))
+ for index, item in enumerate(body["items"])
+ ),
+ key=lambda pair: pair[1],
+ reverse=True,
+ )
+ return [{"item_id": item_id, "score": score, "rank": rank} for rank, (item_id, score) in enumerate(scored)]
+
+
+def score_stub_server() -> Iterator[_ScoreStubServer]:
+ """A running ``_ScoreStubServer``; point a real ``SIEClient`` at its ``url``."""
+ server = _ScoreStubServer()
+ try:
+ yield server
+ finally:
+ server.close()
+
+
@pytest.fixture
def extract_error_text() -> str:
"""Item text for which the shared mock clients return a per-item extract ``error``."""
diff --git a/integrations/sie_crewai/src/sie_crewai/tools.py b/integrations/sie_crewai/src/sie_crewai/tools.py
index d0b28e90b..3c41aa2fd 100644
--- a/integrations/sie_crewai/src/sie_crewai/tools.py
+++ b/integrations/sie_crewai/src/sie_crewai/tools.py
@@ -24,10 +24,11 @@ def _raise_for_item_error(result: Any) -> None:
def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
"""Map ScoreResult entries back to input positions by item_id.
- Parses each entry's ``item_id`` defensively: a missing, non-integer,
- negative, or out-of-range id is skipped (that document keeps its 0.0
- default) so a malformed entry can neither crash the rerank nor mis-assign a
- score to the wrong document.
+ Each input is sent with ``id=str(position)``, which the server echoes as
+ the entry's ``item_id``. Only an exact echo of a sent id is used: an entry
+ whose ``item_id`` is missing, not a string, or not a sent id is skipped
+ (that document keeps its 0.0 default), so a malformed entry can neither
+ crash the rerank nor mis-assign a score to the wrong document.
Args:
results: ScoreResult envelope from ``SIEClient.score()``.
@@ -36,25 +37,12 @@ def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
Returns:
Scores indexed by input position (0.0 for any unscored/invalid item).
"""
+ positions = {str(index): index for index in range(count)}
scores = [0.0] * count
for entry in results.get("scores", []):
- item_id = entry.get("item_id", entry.get("index"))
- # Accept only a genuine integer or an integer string. Reject bool (an int
- # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer
- # strings, so a malformed id cannot silently overwrite the wrong position.
- if isinstance(item_id, bool):
- continue
- if isinstance(item_id, int):
- idx = item_id
- elif isinstance(item_id, str):
- try:
- idx = int(item_id)
- except ValueError:
- continue
- else:
- continue
- if 0 <= idx < count:
- scores[idx] = float(entry.get("score", 0.0))
+ item_id = entry.get("item_id")
+ if isinstance(item_id, str) and item_id in positions:
+ scores[positions[item_id]] = float(entry.get("score", 0.0))
return scores
@@ -140,17 +128,17 @@ class SIERerankerTool(BaseTool):
from sie_sdk.types import Item
query_item = Item(text=query)
- doc_items = [Item(text=doc) for doc in documents]
+ doc_items = [Item(text=doc, id=str(idx)) for idx, doc in enumerate(documents)]
results = self.client.score(self.model, query_item, doc_items)
# ``results`` is a ScoreResult envelope; ranked entries are under
- # ``results["scores"]`` (each a ScoreEntry keyed by ``item_id`` = input
- # position, plus ``score``). Map scores back to input order by item_id
- # rather than zipping positionally — the entries are sorted by relevance,
- # not by input order. ``results["request"]`` (request id) and
- # ``results["usage"]`` (token usage) are also available but intentionally
- # not surfaced here.
+ # ``results["scores"]`` (each a ScoreEntry whose ``item_id`` echoes the
+ # input position sent as the item ``id``, plus ``score``). Map scores
+ # back to input order by item_id rather than zipping positionally — the
+ # entries are sorted by relevance, not by input order.
+ # ``results["request"]`` (request id) and ``results["usage"]`` (token
+ # usage) are also available but intentionally not surfaced here.
score_by_index = _scores_by_index(results, len(documents))
# Build scored documents
diff --git a/integrations/sie_crewai/tests/conftest.py b/integrations/sie_crewai/tests/conftest.py
index f6ce2daf6..71effac9c 100644
--- a/integrations/sie_crewai/tests/conftest.py
+++ b/integrations/sie_crewai/tests/conftest.py
@@ -51,12 +51,18 @@ def _create_mock_encode_result(
return results
+def _server_item_id(item: Any, index: int) -> str:
+ """Return the ``item_id`` the SIE server reports: the sent ``id``, else ``item-<index>``."""
+ item_id = item.get("id") if isinstance(item, dict) else None
+ return item_id if item_id is not None else f"item-{index}"
+
+
def _create_mock_score_result(query: str, items: list[dict]) -> list[dict[str, Any]]:
"""Create mock score results matching the ranked-envelope contract.
The SDK's ScoreResult is sorted by descending score, so sort here too and
- assign ``rank`` from the sorted position (``item_id`` stays the original
- input index).
+ assign ``rank`` from the sorted position. ``item_id`` is the id the SIE
+ server reports for that input.
"""
rng = np.random.default_rng(hash(query) % (2**32))
scores = rng.uniform(0, 1, len(items))
@@ -64,7 +70,7 @@ def _create_mock_score_result(query: str, items: list[dict]) -> list[dict[str, A
sorted_indices = np.argsort(scores)[::-1]
return [
{
- "item_id": str(idx),
+ "item_id": items[idx]["id"],
"score": float(scores[idx]),
"rank": rank,
}
@@ -129,7 +135,7 @@ def mock_sie_client() -> NonCallableMagicMock:
# Mirror the real SDK: a ScoreResult envelope with ranked entries under
# "scores", not a bare list.
query_text = _get_text(query)
- item_dicts = [{"id": str(idx), "text": _get_text(i)} for idx, i in enumerate(items)]
+ item_dicts = [{"id": _server_item_id(i, idx), "text": _get_text(i)} for idx, i in enumerate(items)]
return {
"model": _model,
"scores": _create_mock_score_result(query_text, item_dicts),
diff --git a/integrations/sie_crewai/tests/test_integration.py b/integrations/sie_crewai/tests/test_integration.py
index c3f4dfff6..d0a99b192 100644
--- a/integrations/sie_crewai/tests/test_integration.py
+++ b/integrations/sie_crewai/tests/test_integration.py
@@ -12,6 +12,7 @@ Prerequisites:
from __future__ import annotations
import os
+import re
import pytest
@@ -25,6 +26,20 @@ def sie_url() -> str:
return os.environ.get("SIE_SERVER_URL", "http://localhost:8080")
+def _ranked(result: str) -> list[tuple[float, str]]:
+ """Parse ``SIERerankerTool`` output into ``(score, document)`` pairs, most relevant first."""
+ lines = result.splitlines()
+ assert lines[0] == "Ranked documents (most relevant first):"
+ ranked = []
+ for position, line in enumerate(lines[1:], 1):
+ match = re.fullmatch(rf"{position}\. \[Score: (-?\d+\.\d+)\] (.*)", line)
+ assert match, line
+ ranked.append((float(match[1]), match[2]))
+ scores = [score for score, _ in ranked]
+ assert scores == sorted(scores, reverse=True)
+ return ranked
+
+
class TestResearchAgentWorkflow:
"""Integration tests demonstrating research agent use case.
@@ -60,9 +75,9 @@ class TestResearchAgentWorkflow:
top_k=3,
)
- assert "Ranked documents" in result
- assert "Score:" in result
- # Top results should be about ML/neural networks, not weather/stocks
+ ranked = [document for _, document in _ranked(result)]
+ assert len(ranked) == 3
+ assert not {research_sources[1], research_sources[4]} & set(ranked)
class TestLeadQualificationWorkflow:
@@ -153,7 +168,7 @@ class TestContentCreationWorkflow:
top_k=3,
)
- assert "Ranked documents" in ranked
+ assert {document for _, document in _ranked(ranked)} == {articles[0], articles[2], articles[3]}
# Step 2: Extract key entities from top result
extractor = SIEExtractorTool(
@@ -199,7 +214,7 @@ class TestMultiAgentCollaboration:
top_k=2,
)
- assert "Ranked documents" in analyst_result
+ assert _ranked(analyst_result)[0][1] == market_reports[2]
# Writer agent: extract specific facts for report
writer_extractor = SIEExtractorTool(
diff --git a/integrations/sie_crewai/tests/test_tools.py b/integrations/sie_crewai/tests/test_tools.py
index 69da9fde4..c73024f4f 100644
--- a/integrations/sie_crewai/tests/test_tools.py
+++ b/integrations/sie_crewai/tests/test_tools.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from typing import Any
from unittest.mock import NonCallableMagicMock, create_autospec
import pytest
@@ -118,6 +119,26 @@ class TestSIERerankerTool:
assert result.index("bravo") < result.index("alpha")
assert result.index("bravo") < result.index("charlie")
+ def test_rerank_ranks_through_sie_client(self, score_stub_server: Any) -> None:
+ """Scores returned by a real ``SIEClient.score()`` call rank the matching document first."""
+ documents = [
+ "The weather today is sunny with clear skies.",
+ "Python is a popular programming language.",
+ "Nearest neighbor search uses distance metrics.",
+ "Vector similarity search finds similar embeddings.",
+ ]
+ reranker = SIERerankerTool(base_url=score_stub_server.url, model="test-reranker")
+
+ result = reranker._run(query="vector similarity search", documents=documents)
+
+ assert result.splitlines() == [
+ "Ranked documents (most relevant first):",
+ f"1. [Score: 3.0000] {documents[3]}",
+ f"2. [Score: 1.0000] {documents[2]}",
+ f"3. [Score: 0.0000] {documents[0]}",
+ f"4. [Score: 0.0000] {documents[1]}",
+ ]
+
def test_custom_model(self, mock_sie_client: object, research_documents: list[str]) -> None:
"""Test using a custom reranker model."""
reranker = SIERerankerTool(model="custom/reranker-model")
diff --git a/integrations/sie_dspy/src/sie_dspy/modules.py b/integrations/sie_dspy/src/sie_dspy/modules.py
index 4f9a60c1a..0cdcd2ca4 100644
--- a/integrations/sie_dspy/src/sie_dspy/modules.py
+++ b/integrations/sie_dspy/src/sie_dspy/modules.py
@@ -24,10 +24,11 @@ def _raise_for_item_error(result: Any) -> None:
def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
"""Map ScoreResult entries back to input positions by item_id.
- Parses each entry's ``item_id`` defensively: a missing, non-integer,
- negative, or out-of-range id is skipped (that passage keeps its 0.0
- default) so a malformed entry can neither crash the rerank nor mis-assign a
- score to the wrong passage.
+ Each input is sent with ``id=str(position)``, which the server echoes as
+ the entry's ``item_id``. Only an exact echo of a sent id is used: an entry
+ whose ``item_id`` is missing, not a string, or not a sent id is skipped
+ (that passage keeps its 0.0 default), so a malformed entry can neither
+ crash the rerank nor mis-assign a score to the wrong passage.
Args:
results: ScoreResult envelope from ``SIEClient.score()``.
@@ -36,25 +37,12 @@ def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
Returns:
Scores indexed by input position (0.0 for any unscored/invalid item).
"""
+ positions = {str(index): index for index in range(count)}
scores = [0.0] * count
for entry in results.get("scores", []):
- item_id = entry.get("item_id", entry.get("index"))
- # Accept only a genuine integer or an integer string. Reject bool (an int
- # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer
- # strings, so a malformed id cannot silently overwrite the wrong position.
- if isinstance(item_id, bool):
- continue
- if isinstance(item_id, int):
- idx = item_id
- elif isinstance(item_id, str):
- try:
- idx = int(item_id)
- except ValueError:
- continue
- else:
- continue
- if 0 <= idx < count:
- scores[idx] = float(entry.get("score", 0.0))
+ item_id = entry.get("item_id")
+ if isinstance(item_id, str) and item_id in positions:
+ scores[positions[item_id]] = float(entry.get("score", 0.0))
return scores
@@ -177,17 +165,17 @@ class SIEReranker(dspy.Module):
from sie_sdk.types import Item
query_item = Item(text=query)
- passage_items = [Item(text=p) for p in passages]
+ passage_items = [Item(text=p, id=str(idx)) for idx, p in enumerate(passages)]
results = self.client.score(self._model, query_item, passage_items)
# ``results`` is a ScoreResult envelope; ranked entries are under
- # ``results["scores"]`` (each a ScoreEntry keyed by ``item_id`` = input
- # position, plus ``score``). Map scores back to input order by item_id
- # rather than zipping positionally — the entries are sorted by relevance,
- # not by input order. ``results["request"]`` (request id) and
- # ``results["usage"]`` (token usage) are also available but intentionally
- # not surfaced here.
+ # ``results["scores"]`` (each a ScoreEntry whose ``item_id`` echoes the
+ # input position sent as the item ``id``, plus ``score``). Map scores
+ # back to input order by item_id rather than zipping positionally — the
+ # entries are sorted by relevance, not by input order.
+ # ``results["request"]`` (request id) and ``results["usage"]`` (token
+ # usage) are also available but intentionally not surfaced here.
score_by_index = _scores_by_index(results, len(passages))
# Build scored passages
diff --git a/integrations/sie_dspy/tests/conftest.py b/integrations/sie_dspy/tests/conftest.py
index ffa6fa5f5..e22881602 100644
--- a/integrations/sie_dspy/tests/conftest.py
+++ b/integrations/sie_dspy/tests/conftest.py
@@ -57,12 +57,18 @@ def _create_mock_encode_result(
return results
+def _server_item_id(item: Any, index: int) -> str:
+ """Return the ``item_id`` the SIE server reports: the sent ``id``, else ``item-<index>``."""
+ item_id = item.get("id") if isinstance(item, dict) else None
+ return item_id if item_id is not None else f"item-{index}"
+
+
def _create_mock_score_result(query: str, items: list[dict]) -> list[dict[str, Any]]:
"""Create mock score results matching the ranked-envelope contract.
The SDK's ScoreResult is sorted by descending score, so sort here too and
- assign ``rank`` from the sorted position (``item_id`` stays the original
- input index).
+ assign ``rank`` from the sorted position. ``item_id`` is the id the SIE
+ server reports for that input.
"""
rng = np.random.default_rng(hash(query) % (2**32))
scores = rng.uniform(0, 1, len(items))
@@ -70,7 +76,7 @@ def _create_mock_score_result(query: str, items: list[dict]) -> list[dict[str, A
sorted_indices = np.argsort(scores)[::-1]
return [
{
- "item_id": str(idx),
+ "item_id": items[idx]["id"],
"score": float(scores[idx]),
"rank": rank,
}
@@ -139,7 +145,7 @@ def mock_sie_client() -> NonCallableMagicMock:
# Mirror the real SDK: a ScoreResult envelope with ranked entries under
# "scores", not a bare list.
query_text = _get_text(query)
- item_dicts = [{"id": str(idx), "text": _get_text(i)} for idx, i in enumerate(items)]
+ item_dicts = [{"id": _server_item_id(i, idx), "text": _get_text(i)} for idx, i in enumerate(items)]
return {
"model": _model,
"scores": _create_mock_score_result(query_text, item_dicts),
diff --git a/integrations/sie_dspy/tests/test_integration.py b/integrations/sie_dspy/tests/test_integration.py
index dd0a22ae4..c7dd9779f 100644
--- a/integrations/sie_dspy/tests/test_integration.py
+++ b/integrations/sie_dspy/tests/test_integration.py
@@ -97,7 +97,9 @@ class TestRAGPipeline:
assert len(result.passages) == 2
assert len(result.scores) == 2
- # Top results should be about ML/neural networks
+ assert result.scores == sorted(result.scores, reverse=True)
+ assert result.passages[0] == "Neural networks learn through backpropagation algorithms."
+ assert not {retrieved_passages[0], retrieved_passages[2]} & set(result.passages)
class TestProgramOptimization:
@@ -195,6 +197,8 @@ class TestResearchWorkflows:
k=2,
)
assert len(reranked.passages) == 2
+ assert reranked.scores == sorted(reranked.scores, reverse=True)
+ assert reranked.passages[0] == papers[0]
# Step 3: Extract key information
extractor = SIEExtractor(
@@ -276,3 +280,5 @@ class TestModuleComposition:
assert len(result.passages) == 2
assert len(result.scores) == 2
+ assert result.scores == sorted(result.scores, reverse=True)
+ assert result.passages[0] == "TensorFlow and PyTorch are deep learning frameworks."
diff --git a/integrations/sie_dspy/tests/test_modules.py b/integrations/sie_dspy/tests/test_modules.py
index ae2e5dfc7..58288e4c4 100644
--- a/integrations/sie_dspy/tests/test_modules.py
+++ b/integrations/sie_dspy/tests/test_modules.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections import Counter
+from typing import Any
from unittest.mock import NonCallableMagicMock, create_autospec
import dspy
@@ -122,6 +123,21 @@ class TestSIEReranker:
assert by_passage == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}
assert result.passages[0] == "doc-1"
+ def test_rerank_ranks_through_sie_client(self, score_stub_server: Any) -> None:
+ """Scores returned by a real ``SIEClient.score()`` call rank the matching passage first."""
+ passages = [
+ "The weather today is sunny with clear skies.",
+ "Python is a popular programming language.",
+ "Nearest neighbor search uses distance metrics.",
+ "Vector similarity search finds similar embeddings.",
+ ]
+ reranker = SIEReranker(base_url=score_stub_server.url, model="test-reranker")
+
+ result = reranker(query="vector similarity search", passages=passages)
+
+ assert result.passages == [passages[i] for i in (3, 2, 0, 1)]
+ assert result.scores == [3.0, 1.0, 0.0, 0.0]
+
def test_rerank_k_larger_than_passages(self, mock_sie_client: object) -> None:
"""Test reranking when k is larger than passage count."""
reranker = SIEReranker(model="test-reranker")
diff --git a/integrations/sie_haystack/src/sie_haystack/rankers.py b/integrations/sie_haystack/src/sie_haystack/rankers.py
index f37970236..042f90f6c 100644
--- a/integrations/sie_haystack/src/sie_haystack/rankers.py
+++ b/integrations/sie_haystack/src/sie_haystack/rankers.py
@@ -14,10 +14,11 @@ from haystack import Document, component
def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
"""Map ScoreResult entries back to input positions by item_id.
- Parses each entry's ``item_id`` defensively: a missing, non-integer,
- negative, or out-of-range id is skipped (that document keeps its 0.0
- default) so a malformed entry can neither crash the rerank nor mis-assign a
- score to the wrong document.
+ Each input is sent with ``id=str(position)``, which the server echoes as
+ the entry's ``item_id``. Only an exact echo of a sent id is used: an entry
+ whose ``item_id`` is missing, not a string, or not a sent id is skipped
+ (that document keeps its 0.0 default), so a malformed entry can neither
+ crash the rerank nor mis-assign a score to the wrong document.
Args:
results: ScoreResult envelope from ``SIEClient.score()``.
@@ -26,25 +27,12 @@ def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
Returns:
Scores indexed by input position (0.0 for any unscored/invalid item).
"""
+ positions = {str(index): index for index in range(count)}
scores = [0.0] * count
for entry in results.get("scores", []):
- item_id = entry.get("item_id", entry.get("index"))
- # Accept only a genuine integer or an integer string. Reject bool (an int
- # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer
- # strings, so a malformed id cannot silently overwrite the wrong position.
- if isinstance(item_id, bool):
- continue
- if isinstance(item_id, int):
- idx = item_id
- elif isinstance(item_id, str):
- try:
- idx = int(item_id)
- except ValueError:
- continue
- else:
- continue
- if 0 <= idx < count:
- scores[idx] = float(entry.get("score", 0.0))
+ item_id = entry.get("item_id")
+ if isinstance(item_id, str) and item_id in positions:
+ scores[positions[item_id]] = float(entry.get("score", 0.0))
return scores
@@ -141,18 +129,19 @@ class SIERanker:
# Prepare items
query_item = Item(text=query)
- doc_items = [Item(text=doc.content or "") for doc in documents]
+ doc_items = [Item(text=doc.content or "", id=str(idx)) for idx, doc in enumerate(documents)]
# Score documents
results = self.client.score(self._model, query_item, doc_items)
# ``results`` is a ScoreResult envelope; ranked entries are under
- # ``results["scores"]`` (each a ScoreEntry keyed by ``item_id`` = input
- # position, plus ``score``). Map scores back to input order by item_id
- # rather than zipping positionally — the entries are sorted by relevance,
- # not by input order. The envelope also carries ``results["request"]``
- # (request id) and ``results["usage"]`` (token usage); those are
- # available but intentionally not surfaced through the Haystack contract.
+ # ``results["scores"]`` (each a ScoreEntry whose ``item_id`` echoes the
+ # input position sent as the item ``id``, plus ``score``). Map scores
+ # back to input order by item_id rather than zipping positionally — the
+ # entries are sorted by relevance, not by input order. The envelope also
+ # carries ``results["request"]`` (request id) and ``results["usage"]``
+ # (token usage); those are available but intentionally not surfaced
+ # through the Haystack contract.
score_by_index = _scores_by_index(results, len(documents))
# Build scored documents
diff --git a/integrations/sie_haystack/tests/conftest.py b/integrations/sie_haystack/tests/conftest.py
index 5a0ab349b..3494c8a61 100644
--- a/integrations/sie_haystack/tests/conftest.py
+++ b/integrations/sie_haystack/tests/conftest.py
@@ -85,6 +85,12 @@ def _create_mock_encode_result(
return result
+def _server_item_id(item: Any, index: int) -> str:
+ """Return the ``item_id`` the SIE server reports: the sent ``id``, else ``item-<index>``."""
+ item_id = item.get("id") if isinstance(item, dict) else None
+ return item_id if item_id is not None else f"item-{index}"
+
+
def _create_mock_score_result(query: str, items: list[dict], top_k: int | None = None) -> list[dict[str, Any]]:
"""Create mock score results."""
rng = np.random.default_rng(hash(query) % (2**32))
@@ -160,10 +166,7 @@ def mock_sie_client() -> NonCallableMagicMock:
# Mirror the real SDK: a ScoreResult envelope with ranked entries under
# "scores", not a bare list.
query_text = _get_text(query)
- item_dicts = [
- {"id": i.get("id", str(idx)) if isinstance(i, dict) else str(idx), "text": _get_text(i)}
- for idx, i in enumerate(items)
- ]
+ item_dicts = [{"id": _server_item_id(i, idx), "text": _get_text(i)} for idx, i in enumerate(items)]
return {
"model": _model,
"scores": _create_mock_score_result(query_text, item_dicts, kwargs.get("top_k")),
diff --git a/integrations/sie_haystack/tests/test_integration.py b/integrations/sie_haystack/tests/test_integration.py
index 1bb9d7c55..6db11671f 100644
--- a/integrations/sie_haystack/tests/test_integration.py
+++ b/integrations/sie_haystack/tests/test_integration.py
@@ -16,16 +16,6 @@ import pytest
# Skip all tests in this module if not running integration tests
pytestmark = pytest.mark.integration
-_SERVER_ITEM_IDS = (
- "The server returns item-<index> ids for items sent without an id, but SIERanker parses "
- "item_id with int(), so every score falls back to 0.0 and the input order is kept"
-)
-
-
-def _xfail_if_scores_dropped(scores: list[float]) -> None:
- if scores and all(score == 0.0 for score in scores):
- pytest.xfail(_SERVER_ITEM_IDS)
-
@pytest.fixture
def sie_url() -> str:
@@ -320,7 +310,6 @@ class TestRAGPipelineIntegration:
final_docs = result["ranker"]["documents"]
assert len(final_docs) == 2
- _xfail_if_scores_dropped([d.meta["score"] for d in final_docs])
# The encoding API doc should be highly ranked
top_content = final_docs[0].content.lower()
assert "encode" in top_content or "embedding" in top_content
diff --git a/integrations/sie_haystack/tests/test_rankers.py b/integrations/sie_haystack/tests/test_rankers.py
index 7f9e958bd..fb31cf323 100644
--- a/integrations/sie_haystack/tests/test_rankers.py
+++ b/integrations/sie_haystack/tests/test_rankers.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections import Counter
+from typing import Any
from haystack import Document
from sie_haystack import SIERanker
@@ -95,6 +96,21 @@ class TestSIERanker:
assert by_content == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}
assert ranked[0].content == "doc-1"
+ def test_run_ranks_through_sie_client(self, score_stub_server: Any) -> None:
+ """Scores returned by a real ``SIEClient.score()`` call rank the matching document first."""
+ documents = [
+ Document(content="The weather today is sunny with clear skies."),
+ Document(content="Python is a popular programming language."),
+ Document(content="Nearest neighbor search uses distance metrics."),
+ Document(content="Vector similarity search finds similar embeddings."),
+ ]
+ ranker = SIERanker(base_url=score_stub_server.url, model="test-reranker")
+
+ ranked = ranker.run(query="vector similarity search", documents=documents)["documents"]
+
+ assert [d.content for d in ranked] == [documents[i].content for i in (3, 2, 0, 1)]
+ assert [d.meta["score"] for d in ranked] == [3.0, 1.0, 0.0, 0.0]
+
def test_run_empty_list(self, mock_sie_client: object) -> None:
"""Test that run handles empty document list."""
ranker = SIERanker(model="test-reranker")
diff --git a/integrations/sie_lancedb/src/sie_lancedb/rerankers.py b/integrations/sie_lancedb/src/sie_lancedb/rerankers.py
index 2388e9958..d29559520 100644
--- a/integrations/sie_lancedb/src/sie_lancedb/rerankers.py
+++ b/integrations/sie_lancedb/src/sie_lancedb/rerankers.py
@@ -12,9 +12,36 @@ import pyarrow as pa
from lancedb.rerankers import Reranker
if TYPE_CHECKING:
+ from collections.abc import Mapping
+
from sie_sdk import SIEClient
+def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
+ """Map ScoreResult entries back to input positions by item_id.
+
+ Each input is sent with ``id=str(position)``, which the server echoes as
+ the entry's ``item_id``. Only an exact echo of a sent id is used: an entry
+ whose ``item_id`` is missing, not a string, or not a sent id is skipped
+ (that row keeps its 0.0 default), so a malformed entry can neither crash
+ the rerank nor mis-assign a score to the wrong row.
+
+ Args:
+ results: ScoreResult envelope from ``SIEClient.score()``.
+ count: Number of input rows.
+
+ Returns:
+ Scores indexed by input position (0.0 for any unscored/invalid row).
+ """
+ positions = {str(index): index for index in range(count)}
+ scores = [0.0] * count
+ for entry in results.get("scores", []):
+ item_id = entry.get("item_id")
+ if isinstance(item_id, str) and item_id in positions:
+ scores[positions[item_id]] = float(entry.get("score", 0.0))
+ return scores
+
+
class SIEReranker(Reranker):
"""LanceDB reranker using SIE's cross-encoder scoring.
@@ -147,26 +174,11 @@ class SIEReranker(Reranker):
texts = table.column(self._column).to_pylist()
query_item = Item(text=query)
- doc_items = [Item(text=str(t)) for t in texts]
+ doc_items = [Item(text=str(t), id=str(idx)) for idx, t in enumerate(texts)]
results = self.client.score(self._model, query_item, doc_items)
- # Build score array indexed by input position
- scores = [0.0] * len(texts)
- for result in results["scores"]:
- if isinstance(result, dict):
- idx = result.get("item_id", result.get("index"))
- score = result.get("score", 0.0)
- else:
- idx = getattr(result, "item_id", getattr(result, "index", None))
- score = getattr(result, "score", 0.0)
-
- if idx is None:
- continue
- if isinstance(idx, str):
- idx = int(idx)
- if idx < len(scores):
- scores[idx] = float(score)
+ scores = _scores_by_index(results, len(texts))
# Add _relevance_score column and sort
table = table.append_column(
diff --git a/integrations/sie_lancedb/tests/conftest.py b/integrations/sie_lancedb/tests/conftest.py
index 7dc9f0ac1..bd0ca0cc8 100644
--- a/integrations/sie_lancedb/tests/conftest.py
+++ b/integrations/sie_lancedb/tests/conftest.py
@@ -45,6 +45,12 @@ def _create_mock_encode_result(
return result
+def _server_item_id(item: Any, index: int) -> str:
+ """Return the ``item_id`` the SIE server reports: the sent ``id``, else ``item-<index>``."""
+ item_id = item.get("id") if isinstance(item, dict) else None
+ return item_id if item_id is not None else f"item-{index}"
+
+
def _create_mock_score_result(
query: str,
items: list[dict],
@@ -58,7 +64,7 @@ def _create_mock_score_result(
for rank, idx in enumerate(sorted_indices):
results.append(
{
- "item_id": idx,
+ "item_id": items[idx]["id"],
"score": float(scores[idx]),
"rank": rank,
}
@@ -127,7 +133,7 @@ def mock_sie_client() -> NonCallableMagicMock:
**kwargs: Any,
) -> dict[str, Any]:
query_text = _get_text(query)
- item_dicts = [{"text": _get_text(i)} for i in items]
+ item_dicts = [{"id": _server_item_id(i, idx), "text": _get_text(i)} for idx, i in enumerate(items)]
return {
"model": _model,
"scores": _create_mock_score_result(query_text, item_dicts),
diff --git a/integrations/sie_lancedb/tests/test_integration.py b/integrations/sie_lancedb/tests/test_integration.py
index b50d80574..0f0d1c956 100644
--- a/integrations/sie_lancedb/tests/test_integration.py
+++ b/integrations/sie_lancedb/tests/test_integration.py
@@ -22,11 +22,6 @@ from lancedb.pydantic import LanceModel, Vector
# Skip all tests in this module if not running integration tests
pytestmark = pytest.mark.integration
-_SERVER_ITEM_IDS = (
- "The server returns item-<index> ids for items sent without an id, but SIEReranker parses "
- "item_id with int(), which raises ValueError"
-)
-
@pytest.fixture
def sie_url() -> str:
@@ -131,20 +126,14 @@ class TestHybridSearchWithReranker:
)
query = "How does hybrid search improve results?"
- assert len(table.search(query, query_type="hybrid").limit(3).to_list()) == 3
-
- try:
- results = table.search(query, query_type="hybrid").rerank(reranker).limit(3).to_list()
- except ValueError as exc:
- if "'item-" not in str(exc):
- raise
- pytest.xfail(_SERVER_ITEM_IDS)
+ results = table.search(query, query_type="hybrid").rerank(reranker).limit(3).to_list()
assert len(results) == 3
assert "_relevance_score" in results[0]
# Scores should be descending
scores = [r["_relevance_score"] for r in results]
assert scores == sorted(scores, reverse=True)
+ assert results[0]["text"] == "Hybrid search combines vector and full-text search."
class TestEntityExtraction:
diff --git a/integrations/sie_lancedb/tests/test_rerankers.py b/integrations/sie_lancedb/tests/test_rerankers.py
index 95fc62c1c..72aedc8f3 100644
--- a/integrations/sie_lancedb/tests/test_rerankers.py
+++ b/integrations/sie_lancedb/tests/test_rerankers.py
@@ -2,6 +2,9 @@
from __future__ import annotations
+from typing import Any
+from unittest.mock import NonCallableMagicMock
+
import lancedb
import pyarrow as pa
import pytest
@@ -151,6 +154,49 @@ class TestSIEReranker:
assert all(isinstance(s, float) for s in scores)
assert all(s > 0 for s in scores)
+ def test_rerank_ranks_through_sie_client(self, score_stub_server: Any) -> None:
+ """Scores returned by a real ``SIEClient.score()`` call rank the matching row first."""
+ texts = [
+ "The weather today is sunny with clear skies.",
+ "Python is a popular programming language.",
+ "Nearest neighbor search uses distance metrics.",
+ "Vector similarity search finds similar embeddings.",
+ ]
+ table = pa.table({"text": texts, "_rowid": [0, 1, 2, 3]})
+ reranker = SIEReranker(base_url=score_stub_server.url, model="test-reranker")
+
+ result = reranker.rerank_vector("vector similarity search", table)
+
+ assert result.column("text").to_pylist()[:2] == [texts[3], texts[2]]
+ assert result.column("_relevance_score").to_pylist() == [3.0, 1.0, 0.0, 0.0]
+
+ def test_rerank_skips_malformed_item_id(self, mock_sie_client: NonCallableMagicMock) -> None:
+ """Malformed item_ids are skipped (no crash, no misassignment)."""
+ mock_sie_client.score.side_effect = None
+ mock_sie_client.score.return_value = {
+ "model": "test-model",
+ "scores": [
+ {"item_id": "1", "score": 0.5, "rank": 0},
+ {"item_id": "item-0", "score": 0.95, "rank": 1},
+ {"item_id": "-1", "score": 0.9, "rank": 2},
+ {"item_id": "99", "score": 0.7, "rank": 3},
+ {"score": 0.6, "rank": 4},
+ {"item_id": 1.5, "score": 0.99, "rank": 5},
+ {"item_id": True, "score": 0.98, "rank": 6},
+ ],
+ }
+ reranker = SIEReranker(model="test-model")
+ reranker._client = mock_sie_client
+ table = pa.table({"text": ["alpha", "bravo", "charlie"], "_rowid": [0, 1, 2]})
+
+ result = reranker.rerank_vector("query", table)
+
+ by_text = dict(
+ zip(result.column("text").to_pylist(), result.column("_relevance_score").to_pylist(), strict=True)
+ )
+ assert by_text == {"bravo": 0.5, "alpha": 0.0, "charlie": 0.0}
+ assert result.column("text").to_pylist()[0] == "bravo"
+
def test_rerank_on_real_lance_table(self, mock_sie_client: object, db) -> None:
"""Reranker works with a real LanceDB table's search results."""
import numpy as np
diff --git a/integrations/sie_langchain/src/sie_langchain/rerankers.py b/integrations/sie_langchain/src/sie_langchain/rerankers.py
index 5cbdb9f0e..ba009d484 100644
--- a/integrations/sie_langchain/src/sie_langchain/rerankers.py
+++ b/integrations/sie_langchain/src/sie_langchain/rerankers.py
@@ -21,10 +21,11 @@ if TYPE_CHECKING:
def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
"""Map ScoreResult entries back to input positions by item_id.
- Parses each entry's ``item_id`` defensively: a missing, non-integer,
- negative, or out-of-range id is skipped (that input keeps its 0.0 default)
- so a malformed entry can neither crash the rerank nor mis-assign a score to
- the wrong input.
+ Each input is sent with ``id=str(position)``, which the server echoes as
+ the entry's ``item_id``. Only an exact echo of a sent id is used: an entry
+ whose ``item_id`` is missing, not a string, or not a sent id is skipped
+ (that input keeps its 0.0 default), so a malformed entry can neither
+ crash the rerank nor mis-assign a score to the wrong input.
Args:
results: ScoreResult envelope from ``SIEClient.score()``.
@@ -33,25 +34,12 @@ def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
Returns:
Scores indexed by input position (0.0 for any unscored/invalid item).
"""
+ positions = {str(index): index for index in range(count)}
scores = [0.0] * count
for entry in results.get("scores", []):
- item_id = entry.get("item_id", entry.get("index"))
- # Accept only a genuine integer or an integer string. Reject bool (an int
- # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer
- # strings, so a malformed id cannot silently overwrite the wrong position.
- if isinstance(item_id, bool):
- continue
- if isinstance(item_id, int):
- idx = item_id
- elif isinstance(item_id, str):
- try:
- idx = int(item_id)
- except ValueError:
- continue
- else:
- continue
- if 0 <= idx < count:
- scores[idx] = float(entry.get("score", 0.0))
+ item_id = entry.get("item_id")
+ if isinstance(item_id, str) and item_id in positions:
+ scores[positions[item_id]] = float(entry.get("score", 0.0))
return scores
@@ -159,7 +147,7 @@ class SIEReranker(BaseDocumentCompressor):
from sie_sdk.types import Item
query_item = Item(text=query)
- doc_items = [Item(text=doc.page_content) for doc in documents]
+ doc_items = [Item(text=doc.page_content, id=str(idx)) for idx, doc in enumerate(documents)]
results = self.client.score(
self.model,
@@ -196,7 +184,7 @@ class SIEReranker(BaseDocumentCompressor):
from sie_sdk.types import Item
query_item = Item(text=query)
- doc_items = [Item(text=doc.page_content) for doc in documents]
+ doc_items = [Item(text=doc.page_content, id=str(idx)) for idx, doc in enumerate(documents)]
results = await self.async_client.score(
self.model,
@@ -217,20 +205,16 @@ class SIEReranker(BaseDocumentCompressor):
Args:
documents: Original documents.
results: ScoreResult envelope from ``SIEClient.score()``. Ranked
- entries live under ``results["scores"]`` (each a ScoreEntry with
- ``item_id`` = input position and ``score``), already sorted by
- relevance descending. The envelope also carries
- ``results["request"]`` (request id) and ``results["usage"]``
- (token usage); those are available but intentionally not plumbed
- through the LangChain contract.
+ entries live under ``results["scores"]`` (each a ScoreEntry whose
+ ``item_id`` echoes the input position sent as the item ``id``,
+ plus ``score``), already sorted by relevance descending. The
+ envelope also carries ``results["request"]`` (request id) and
+ ``results["usage"]`` (token usage); those are available but
+ intentionally not plumbed through the LangChain contract.
Returns:
Reranked documents (relevance descending) with scores in metadata.
"""
- # Map each ScoreEntry back to its input position by item_id. Parse
- # defensively: a missing, non-integer, negative, or out-of-range id is
- # skipped (its document keeps the 0.0 default) rather than crashing the
- # whole rerank or mis-assigning a score to the wrong document.
scores = _scores_by_index(results, len(documents))
order = sorted(range(len(documents)), key=lambda i: scores[i], reverse=True)
return [
diff --git a/integrations/sie_langchain/tests/test_integration.py b/integrations/sie_langchain/tests/test_integration.py
index e08d1dadd..3f7e71f9f 100644
--- a/integrations/sie_langchain/tests/test_integration.py
+++ b/integrations/sie_langchain/tests/test_integration.py
@@ -16,16 +16,6 @@ import pytest
# Skip all tests in this module if not running integration tests
pytestmark = pytest.mark.integration
-_SERVER_ITEM_IDS = (
- "The server returns item-<index> ids for items sent without an id, but SIEReranker parses "
- "item_id with int(), so every score falls back to 0.0 and the input order is kept"
-)
-
-
-def _xfail_if_scores_dropped(scores: list[float]) -> None:
- if scores and all(score == 0.0 for score in scores):
- pytest.xfail(_SERVER_ITEM_IDS)
-
@pytest.fixture
def sie_url() -> str:
@@ -201,7 +191,6 @@ class TestRerankerIntegration:
assert all("relevance_score" in d.metadata for d in reranked)
# Scores should be in descending order
scores = [d.metadata["relevance_score"] for d in reranked]
- _xfail_if_scores_dropped(scores)
assert scores == sorted(scores, reverse=True)
# Scores must be distinct, not all 0.0. The envelope-read bug returned the
# same document duplicated at 0.0, which still satisfied len==3 and the
@@ -266,7 +255,6 @@ class TestRAGPipelineIntegration:
final_results = reranker.compress_documents(candidates, query)
assert len(final_results) == 2
- _xfail_if_scores_dropped([d.metadata["relevance_score"] for d in final_results])
# The encoding API doc should be highly ranked
top_content = final_results[0].page_content
assert "encode" in top_content.lower() or "embedding" in top_content.lower()
diff --git a/integrations/sie_langchain/tests/test_rerankers.py b/integrations/sie_langchain/tests/test_rerankers.py
index 70f5a7d87..b042ca310 100644
--- a/integrations/sie_langchain/tests/test_rerankers.py
+++ b/integrations/sie_langchain/tests/test_rerankers.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections import Counter
+from typing import Any
import pytest
from langchain_core.documents import Document
@@ -38,6 +39,15 @@ _MALFORMED_ENVELOPE = {
],
}
+_STUB_QUERY = "vector similarity search"
+_STUB_DOCUMENTS = [
+ "The weather today is sunny with clear skies.",
+ "Python is a popular programming language.",
+ "Nearest neighbor search uses distance metrics.",
+ "Vector similarity search finds similar embeddings.",
+]
+_STUB_RANKING = [_STUB_DOCUMENTS[i] for i in (3, 2, 0, 1)]
+
class TestSIEReranker:
"""Tests for SIEReranker class."""
@@ -88,6 +98,16 @@ class TestSIEReranker:
assert by_content == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}
assert result[0].page_content == "doc-1"
+ def test_compress_documents_ranks_through_sie_client(self, score_stub_server: Any) -> None:
+ """Scores returned by a real ``SIEClient.score()`` call rank the matching document first."""
+ reranker = SIEReranker(base_url=score_stub_server.url, model="test-reranker")
+ documents = [Document(page_content=text) for text in _STUB_DOCUMENTS]
+
+ result = reranker.compress_documents(documents, _STUB_QUERY)
+
+ assert [d.page_content for d in result] == _STUB_RANKING
+ assert [d.metadata["relevance_score"] for d in result] == [3.0, 1.0, 0.0, 0.0]
+
def test_compress_documents_empty(self, mock_sie_client: object) -> None:
"""Test reranking empty list returns empty."""
reranker = SIEReranker(client=mock_sie_client, model="test-reranker")
@@ -144,6 +164,20 @@ class TestSIERerankerAsync:
for doc in result:
assert "relevance_score" in doc.metadata
+ @pytest.mark.asyncio
+ async def test_acompress_documents_ranks_through_sie_client(self, score_stub_server: Any) -> None:
+ """Scores returned by a real ``SIEAsyncClient.score()`` call rank the matching document first."""
+ reranker = SIEReranker(base_url=score_stub_server.url, model="test-reranker")
+ documents = [Document(page_content=text) for text in _STUB_DOCUMENTS]
+
+ try:
+ result = await reranker.acompress_documents(documents, _STUB_QUERY)
+ finally:
+ await reranker.async_client.close()
+
+ assert [d.page_content for d in result] == _STUB_RANKING
+ assert [d.metadata["relevance_score"] for d in result] == [3.0, 1.0, 0.0, 0.0]
+
@pytest.mark.asyncio
async def test_acompress_documents_empty(self, mock_sie_async_client: object) -> None:
"""Test async reranking empty list returns empty."""
diff --git a/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.py b/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.py
index 94d1b15ba..e4f73d59c 100644
--- a/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.py
+++ b/integrations/sie_llamaindex/src/sie_llamaindex/rerankers.py
@@ -20,10 +20,11 @@ if TYPE_CHECKING:
def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
"""Map ScoreResult entries back to input positions by item_id.
- Parses each entry's ``item_id`` defensively: a missing, non-integer,
- negative, or out-of-range id is skipped (that input keeps its 0.0 default)
- so a malformed entry can neither crash the rerank nor mis-assign a score to
- the wrong input.
+ Each input is sent with ``id=str(position)``, which the server echoes as
+ the entry's ``item_id``. Only an exact echo of a sent id is used: an entry
+ whose ``item_id`` is missing, not a string, or not a sent id is skipped
+ (that input keeps its 0.0 default), so a malformed entry can neither
+ crash the rerank nor mis-assign a score to the wrong input.
Args:
results: ScoreResult envelope from ``SIEClient.score()``.
@@ -32,25 +33,12 @@ def _scores_by_index(results: Mapping[str, Any], count: int) -> list[float]:
Returns:
Scores indexed by input position (0.0 for any unscored/invalid item).
"""
+ positions = {str(index): index for index in range(count)}
scores = [0.0] * count
for entry in results.get("scores", []):
- item_id = entry.get("item_id", entry.get("index"))
- # Accept only a genuine integer or an integer string. Reject bool (an int
- # subclass, int(True) == 1), float (int(1.5) == 1), and non-integer
- # strings, so a malformed id cannot silently overwrite the wrong position.
- if isinstance(item_id, bool):
- continue
- if isinstance(item_id, int):
- idx = item_id
- elif isinstance(item_id, str):
- try:
- idx = int(item_id)
- except ValueError:
- continue
- else:
- continue
- if 0 <= idx < count:
- scores[idx] = float(entry.get("score", 0.0))
+ item_id = entry.get("item_id")
+ if isinstance(item_id, str) and item_id in positions:
+ scores[positions[item_id]] = float(entry.get("score", 0.0))
return scores
@@ -174,7 +162,7 @@ class SIENodePostprocessor(BaseNodePostprocessor):
query_text = query_bundle.query_str
query_item = Item(text=query_text)
- doc_items = [Item(text=node.node.get_content()) for node in nodes]
+ doc_items = [Item(text=node.node.get_content(), id=str(idx)) for idx, node in enumerate(nodes)]
results = self.client.score(
self.model,
@@ -200,20 +188,16 @@ class SIENodePostprocessor(BaseNodePostprocessor):
Args:
nodes: Original nodes.
results: ScoreResult envelope from ``SIEClient.score()``. Ranked
- entries live under ``results["scores"]`` (each a ScoreEntry with
- ``item_id`` = input position and ``score``), already sorted by
- relevance descending. The envelope also exposes
- ``results["request"]`` (request id) and ``results["usage"]``
- (token usage); those are available but intentionally not plumbed
- through the LlamaIndex contract.
+ entries live under ``results["scores"]`` (each a ScoreEntry whose
+ ``item_id`` echoes the input position sent as the item ``id``,
+ plus ``score``), already sorted by relevance descending. The
+ envelope also exposes ``results["request"]`` (request id) and
+ ``results["usage"]`` (token usage); those are available but
+ intentionally not plumbed through the LlamaIndex contract.
Returns:
Reranked nodes (relevance descending) with new scores.
"""
- # Map each ScoreEntry back to its input position by item_id. Parse
- # defensively: a missing, non-integer, negative, or out-of-range id is
- # skipped (its node keeps the 0.0 default) rather than crashing the whole
- # rerank or mis-assigning a score to the wrong node.
scores = _scores_by_index(results, len(nodes))
order = sorted(range(len(nodes)), key=lambda i: scores[i], reverse=True)
return [NodeWithScore(node=nodes[i].node, score=scores[i]) for i in order]
diff --git a/integrations/sie_llamaindex/tests/test_integration.py b/integrations/sie_llamaindex/tests/test_integration.py
index 1e1e85ef5..d550c310c 100644
--- a/integrations/sie_llamaindex/tests/test_integration.py
+++ b/integrations/sie_llamaindex/tests/test_integration.py
@@ -16,16 +16,6 @@ import pytest
# Skip all tests in this module if not running integration tests
pytestmark = pytest.mark.integration
-_SERVER_ITEM_IDS = (
- "The server returns item-<index> ids for items sent without an id, but SIENodePostprocessor parses "
- "item_id with int(), so every score falls back to 0.0 and the input order is kept"
-)
-
-
-def _xfail_if_scores_dropped(scores: list[float]) -> None:
- if scores and all(score == 0.0 for score in scores):
- pytest.xfail(_SERVER_ITEM_IDS)
-
@pytest.fixture
def sie_url() -> str:
@@ -267,7 +257,6 @@ class TestRAGPipelineIntegration:
)
assert len(final_results) == 2
- _xfail_if_scores_dropped([n.score for n in final_results])
# The encoding API doc should be highly ranked
top_content = final_results[0].node.get_content()
assert "encode" in top_content.lower() or "embedding" in top_content.lower()
@@ -306,7 +295,6 @@ class TestRAGPipelineIntegration:
assert len(response.source_nodes) == 2 # Limited by top_n
scores = [node.score for node in response.source_nodes]
assert all(isinstance(score, float) for score in scores)
- _xfail_if_scores_dropped(scores)
assert scores == sorted(scores, reverse=True)
diff --git a/integrations/sie_llamaindex/tests/test_rerankers.py b/integrations/sie_llamaindex/tests/test_rerankers.py
index fc9b94790..412421b38 100644
--- a/integrations/sie_llamaindex/tests/test_rerankers.py
+++ b/integrations/sie_llamaindex/tests/test_rerankers.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections import Counter
+from typing import Any
from llama_index.core.schema import NodeWithScore, QueryBundle, TextNode
from sie_llamaindex import SIENodePostprocessor
@@ -91,6 +92,22 @@ class TestSIENodePostprocessor:
assert by_content == {"doc-1": 0.8, "doc-0": 0.0, "doc-2": 0.0}
assert result[0].node.get_content() == "doc-1"
+ def test_postprocess_nodes_ranks_through_sie_client(self, score_stub_server: Any) -> None:
+ """Scores returned by a real ``SIEClient.score()`` call rank the matching node first."""
+ texts = [
+ "The weather today is sunny with clear skies.",
+ "Python is a popular programming language.",
+ "Nearest neighbor search uses distance metrics.",
+ "Vector similarity search finds similar embeddings.",
+ ]
+ nodes = [NodeWithScore(node=TextNode(text=text), score=0.5) for text in texts]
+ postprocessor = SIENodePostprocessor(base_url=score_stub_server.url, model="test-reranker")
+
+ result = postprocessor._postprocess_nodes(nodes, QueryBundle(query_str="vector similarity search"))
+
+ assert [n.node.get_content() for n in result] == [texts[i] for i in (3, 2, 0, 1)]
+ assert [n.score for n in result] == [3.0, 1.0, 0.0, 0.0]
+
def test_postprocess_nodes_empty(self, mock_sie_client: object) -> None:
"""Test reranking empty list returns empty."""
postprocessor = SIENodePostprocessor(model="test-reranker")
diff --git a/integrations/sie_ts_lancedb/src/index.ts b/integrations/sie_ts_lancedb/src/index.ts
index 5370f5f9c..28b3a1da7 100644
--- a/integrations/sie_ts_lancedb/src/index.ts
+++ b/integrations/sie_ts_lancedb/src/index.ts
@@ -286,14 +286,16 @@ export class SIEReranker {
}
// Score with SIE
- const items = texts.map((text) => ({ text }));
+ const items = texts.map((text, idx) => ({ id: String(idx), text }));
const scoreResult: ScoreResult = await this.client.score(this.model, { text: query }, items);
- // Build score array indexed by input position
+ // Build score array indexed by input position; each entry's itemId echoes
+ // the id sent for its row.
+ const positions = new Map(items.map((item, idx) => [item.id, idx]));
const scores = new Float32Array(texts.length);
for (const entry of scoreResult.scores) {
- const idx = typeof entry.itemId === "string" ? Number.parseInt(entry.itemId) : entry.itemId;
- if (idx < scores.length) {
+ const idx = positions.get(entry.itemId);
+ if (idx !== undefined) {
scores[idx] = entry.score;
}
}
diff --git a/integrations/sie_ts_lancedb/tests/embedding.test.ts b/integrations/sie_ts_lancedb/tests/embedding.test.ts
index 72c0d7155..4fc3a12ff 100644
--- a/integrations/sie_ts_lancedb/tests/embedding.test.ts
+++ b/integrations/sie_ts_lancedb/tests/embedding.test.ts
@@ -258,4 +258,46 @@ describe("SIEReranker", () => {
const reranker = new SIEReranker(options);
expect(reranker).toBeInstanceOf(SIEReranker);
});
+
+ it("rerankHybrid maps the server's item ids back to their rows", async () => {
+ const { SIEClient } = await import("@superlinked/sie-sdk");
+ const arrow = await import("apache-arrow");
+ const relevance: Record<string, number> = { "Doc A": 0.25, "Doc B": 0.75, "Doc C": 0.5 };
+ // Mirrors the SIE server: entries sorted by relevance, each `itemId`
+ // echoing the item's `id` or `item-<index>` without one.
+ const mockScore = vi.fn(
+ async (model: string, _query: unknown, items: { id?: string; text?: string }[]) => ({
+ model,
+ scores: items
+ .map((item, index) => ({
+ itemId: item.id ?? `item-${index}`,
+ score: relevance[item.text ?? ""] ?? 0,
+ }))
+ .sort((a, b) => b.score - a.score)
+ .map((entry, rank) => ({ ...entry, rank })),
+ }),
+ );
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ asConstructor({
+ score: mockScore,
+ close: vi.fn(),
+ }),
+ );
+ const vecResults = arrow.tableFromArrays({ text: ["Doc A", "Doc B"], _rowid: [0, 1] })
+ .batches[0];
+ const ftsResults = arrow.tableFromArrays({ text: ["Doc B", "Doc C"], _rowid: [1, 2] })
+ .batches[0];
+ if (!vecResults || !ftsResults) {
+ throw new Error("Failed to build result batches");
+ }
+
+ const reranker = new SIEReranker();
+ const batch = await reranker.rerankHybrid("query", vecResults, ftsResults);
+
+ const rows = Array.from({ length: batch.numRows }, (_, i) => [
+ batch.getChild("text")?.get(i),
+ batch.getChild("_relevance_score")?.get(i),
+ ]);
+ expect(Object.fromEntries(rows)).toEqual(relevance);
+ });
});
diff --git a/integrations/sie_ts_langchain/src/rerankers.ts b/integrations/sie_ts_langchain/src/rerankers.ts
index 682b18034..1e41d38a5 100644
--- a/integrations/sie_ts_langchain/src/rerankers.ts
+++ b/integrations/sie_ts_langchain/src/rerankers.ts
@@ -146,16 +146,19 @@ export class SIEReranker extends BaseDocumentCompressor {
}
const queryItem = { text: query };
- const docItems = documents.map((doc) => ({ text: doc.pageContent }));
+ const docItems = documents.map((doc, idx) => ({ id: String(idx), text: doc.pageContent }));
const result = await this.client.score(this.model, queryItem, docItems);
// Map score entries back to documents with relevance_score in metadata.
- // ScoreResult.scores are already sorted by score descending.
+ // ScoreResult.scores are already sorted by score descending, and each
+ // entry's itemId echoes the id sent for its document.
+ const positions = new Map(docItems.map((item, idx) => [item.id, idx]));
const reranked: DocumentInterface[] = [];
for (const entry of result.scores) {
- const idx = Number.parseInt(entry.itemId, 10);
- const doc = documents[idx];
+ const idx = positions.get(entry.itemId);
+ positions.delete(entry.itemId);
+ const doc = idx === undefined ? undefined : documents[idx];
if (doc) {
reranked.push({
pageContent: doc.pageContent,
diff --git a/integrations/sie_ts_langchain/tests/integration/rerankers.integration.test.ts b/integrations/sie_ts_langchain/tests/integration/rerankers.integration.test.ts
new file mode 100644
index 000000000..f3a186ea3
--- /dev/null
+++ b/integrations/sie_ts_langchain/tests/integration/rerankers.integration.test.ts
@@ -0,0 +1,69 @@
+/**
+ * Integration tests for the SIE LangChain.js reranker against a running server.
+ *
+ * These tests require a running SIE server with the
+ * jinaai/jina-reranker-v2-base-multilingual model.
+ * The server is started automatically via the SDK's globalSetup.
+ *
+ * To run integration tests:
+ * pnpm test:integration
+ */
+
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { SIEReranker } from "../../src/index.js";
+
+const SERVER_INFO_FILE = resolve(
+ __dirname,
+ "../../../../packages/sie_ts_sdk/tests/integration/.server-info.json",
+);
+
+interface ServerInfo {
+ url: string;
+ pid: number;
+}
+
+function getServerUrl(): string {
+ try {
+ const serverInfo: ServerInfo = JSON.parse(readFileSync(SERVER_INFO_FILE, "utf-8"));
+ return serverInfo.url;
+ } catch {
+ throw new Error("Server info file not found - globalSetup may have failed");
+ }
+}
+
+describe("SIEReranker integration tests", () => {
+ let reranker: SIEReranker;
+
+ beforeAll(() => {
+ reranker = new SIEReranker({
+ baseUrl: getServerUrl(),
+ model: "jinaai/jina-reranker-v2-base-multilingual",
+ timeout: 60_000,
+ });
+ });
+
+ afterAll(async () => {
+ await reranker.close();
+ });
+
+ it("ranks the relevant document first with distinct descending scores", async () => {
+ const documents = [
+ { pageContent: "The weather is sunny today.", metadata: { source: "weather" } },
+ { pageContent: "Python is used for data science.", metadata: { source: "python" } },
+ {
+ pageContent: "Semantic search understands the meaning of a query.",
+ metadata: { source: "search" },
+ },
+ ];
+
+ const result = await reranker.compressDocuments(documents, "How does semantic search work?");
+
+ expect(result).toHaveLength(3);
+ expect(result[0]?.metadata.source).toBe("search");
+ const scores = result.map((doc) => doc.metadata.relevance_score as number);
+ expect(scores).toEqual([...scores].sort((a, b) => b - a));
+ expect(new Set(scores).size).toBe(scores.length);
+ });
+});
diff --git a/integrations/sie_ts_langchain/tests/rerankers.test.ts b/integrations/sie_ts_langchain/tests/rerankers.test.ts
index 422ee3922..1240b4a91 100644
--- a/integrations/sie_ts_langchain/tests/rerankers.test.ts
+++ b/integrations/sie_ts_langchain/tests/rerankers.test.ts
@@ -25,6 +25,23 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
};
});
+/**
+ * A score mock with the SIE server's response contract: entries sorted by
+ * relevance, each `itemId` echoing the item's `id` or `item-<index>` without one.
+ */
+function serverScore(relevance: Record<string, number>) {
+ return vi.fn(async (model: string, _query: unknown, items: { id?: string; text?: string }[]) => ({
+ model,
+ scores: items
+ .map((item, index) => ({
+ itemId: item.id ?? `item-${index}`,
+ score: relevance[item.text ?? ""] ?? 0,
+ }))
+ .sort((a, b) => b.score - a.score)
+ .map((entry, rank) => ({ ...entry, rank })),
+ }));
+}
+
describe("SIEReranker", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -78,9 +95,9 @@ describe("SIEReranker", () => {
const result = await reranker.compressDocuments(documents, "search query");
expect(mockScore).toHaveBeenCalledWith("test-reranker", { text: "search query" }, [
- { text: "First document" },
- { text: "Second document" },
- { text: "Third document" },
+ { id: "0", text: "First document" },
+ { id: "1", text: "Second document" },
+ { id: "2", text: "Third document" },
]);
expect(result).toHaveLength(3);
@@ -96,6 +113,60 @@ describe("SIEReranker", () => {
expect(result[2].metadata.relevance_score).toBe(0.31);
});
+ it("compressDocuments maps the server's item ids back to their documents", async () => {
+ const { SIEClient } = await import("@superlinked/sie-sdk");
+ const mockScore = serverScore({ "Doc A": 0.2, "Doc B": 0.9, "Doc C": 0.5 });
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ asConstructor({
+ score: mockScore,
+ close: vi.fn(),
+ }),
+ );
+
+ const documents = [
+ { pageContent: "Doc A", metadata: {} },
+ { pageContent: "Doc B", metadata: {} },
+ { pageContent: "Doc C", metadata: {} },
+ ];
+
+ const reranker = new SIEReranker();
+ const result = await reranker.compressDocuments(documents, "query");
+
+ expect(result.map((doc) => doc.pageContent)).toEqual(["Doc B", "Doc C", "Doc A"]);
+ expect(result.map((doc) => doc.metadata.relevance_score)).toEqual([0.9, 0.5, 0.2]);
+ });
+
+ it("compressDocuments skips score entries whose itemId was not sent", async () => {
+ const { SIEClient } = await import("@superlinked/sie-sdk");
+ const mockScore = vi.fn().mockResolvedValue({
+ scores: [
+ { itemId: "item-0", score: 0.99, rank: 0 },
+ { itemId: "01", score: 0.98, rank: 1 },
+ { itemId: "1", score: 0.5, rank: 2 },
+ { itemId: "1", score: 0.4, rank: 3 },
+ { itemId: "7", score: 0.3, rank: 4 },
+ ],
+ });
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ asConstructor({
+ score: mockScore,
+ close: vi.fn(),
+ }),
+ );
+
+ const documents = [
+ { pageContent: "Doc A", metadata: {} },
+ { pageContent: "Doc B", metadata: {} },
+ ];
+
+ const reranker = new SIEReranker();
+ const result = await reranker.compressDocuments(documents, "query");
+
+ expect(result.map((doc) => [doc.pageContent, doc.metadata.relevance_score])).toEqual([
+ ["Doc B", 0.5],
+ ]);
+ });
+
it("compressDocuments applies topK client-side", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockScore = vi.fn().mockResolvedValue({
diff --git a/integrations/sie_ts_llamaindex/src/rerankers.ts b/integrations/sie_ts_llamaindex/src/rerankers.ts
index f617f81bb..448eca35c 100644
--- a/integrations/sie_ts_llamaindex/src/rerankers.ts
+++ b/integrations/sie_ts_llamaindex/src/rerankers.ts
@@ -160,16 +160,22 @@ export class SIENodePostprocessor implements BaseNodePostprocessor {
}
const queryItem = { text: queryText };
- const docItems = nodes.map((n) => ({ text: n.node.getContent(MetadataMode.NONE) }));
+ const docItems = nodes.map((n, idx) => ({
+ id: String(idx),
+ text: n.node.getContent(MetadataMode.NONE),
+ }));
const result = await this.client.score(this.modelName, queryItem, docItems);
// Map score entries back to NodeWithScore with updated scores.
- // ScoreResult.scores are already sorted by score descending.
+ // ScoreResult.scores are already sorted by score descending, and each
+ // entry's itemId echoes the id sent for its node.
+ const positions = new Map(docItems.map((item, idx) => [item.id, idx]));
const reranked: NodeWithScore[] = [];
for (const entry of result.scores) {
- const idx = Number.parseInt(entry.itemId, 10);
- const original = nodes[idx];
+ const idx = positions.get(entry.itemId);
+ positions.delete(entry.itemId);
+ const original = idx === undefined ? undefined : nodes[idx];
if (original) {
reranked.push({
node: original.node,
diff --git a/integrations/sie_ts_llamaindex/tests/integration/rerankers.integration.test.ts b/integrations/sie_ts_llamaindex/tests/integration/rerankers.integration.test.ts
new file mode 100644
index 000000000..609e133ff
--- /dev/null
+++ b/integrations/sie_ts_llamaindex/tests/integration/rerankers.integration.test.ts
@@ -0,0 +1,71 @@
+/**
+ * Integration tests for the SIE LlamaIndex.TS node postprocessor against a running server.
+ *
+ * These tests require a running SIE server with the
+ * jinaai/jina-reranker-v2-base-multilingual model.
+ * The server is started automatically via the SDK's globalSetup.
+ *
+ * To run integration tests:
+ * pnpm test:integration
+ */
+
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { type NodeWithScore, TextNode } from "llamaindex";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { SIENodePostprocessor } from "../../src/index.js";
+
+const SERVER_INFO_FILE = resolve(
+ __dirname,
+ "../../../../packages/sie_ts_sdk/tests/integration/.server-info.json",
+);
+
+interface ServerInfo {
+ url: string;
+ pid: number;
+}
+
+function getServerUrl(): string {
+ try {
+ const serverInfo: ServerInfo = JSON.parse(readFileSync(SERVER_INFO_FILE, "utf-8"));
+ return serverInfo.url;
+ } catch {
+ throw new Error("Server info file not found - globalSetup may have failed");
+ }
+}
+
+describe("SIENodePostprocessor integration tests", () => {
+ let postprocessor: SIENodePostprocessor;
+
+ beforeAll(() => {
+ postprocessor = new SIENodePostprocessor({
+ baseUrl: getServerUrl(),
+ modelName: "jinaai/jina-reranker-v2-base-multilingual",
+ timeout: 60_000,
+ });
+ });
+
+ afterAll(async () => {
+ await postprocessor.close();
+ });
+
+ it("ranks the relevant node first with distinct descending scores", async () => {
+ const texts = [
+ "The weather is sunny today.",
+ "Python is used for data science.",
+ "Semantic search understands the meaning of a query.",
+ ];
+ const nodes: NodeWithScore[] = texts.map((text) => ({
+ node: new TextNode({ text }),
+ score: 0.5,
+ }));
+
+ const result = await postprocessor.postprocessNodes(nodes, "How does semantic search work?");
+
+ expect(result).toHaveLength(3);
+ expect(result[0]?.node.getContent()).toBe(texts[2]);
+ const scores = result.map((node) => node.score as number);
+ expect(scores).toEqual([...scores].sort((a, b) => b - a));
+ expect(new Set(scores).size).toBe(scores.length);
+ });
+});
diff --git a/integrations/sie_ts_llamaindex/tests/rerankers.test.ts b/integrations/sie_ts_llamaindex/tests/rerankers.test.ts
index 166f3d6f2..14345d754 100644
--- a/integrations/sie_ts_llamaindex/tests/rerankers.test.ts
+++ b/integrations/sie_ts_llamaindex/tests/rerankers.test.ts
@@ -39,6 +39,23 @@ function mockNodeWithScore(text: string, score?: number) {
};
}
+/**
+ * A score mock with the SIE server's response contract: entries sorted by
+ * relevance, each `itemId` echoing the item's `id` or `item-<index>` without one.
+ */
+function serverScore(relevance: Record<string, number>) {
+ return vi.fn(async (model: string, _query: unknown, items: { id?: string; text?: string }[]) => ({
+ model,
+ scores: items
+ .map((item, index) => ({
+ itemId: item.id ?? `item-${index}`,
+ score: relevance[item.text ?? ""] ?? 0,
+ }))
+ .sort((a, b) => b.score - a.score)
+ .map((entry, rank) => ({ ...entry, rank })),
+ }));
+}
+
describe("SIENodePostprocessor", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -104,9 +121,9 @@ describe("SIENodePostprocessor", () => {
);
expect(mockScore).toHaveBeenCalledWith("test-reranker", { text: "search query" }, [
- { text: "First doc" },
- { text: "Second doc" },
- { text: "Third doc" },
+ { id: "0", text: "First doc" },
+ { id: "1", text: "Second doc" },
+ { id: "2", text: "Third doc" },
]);
expect(result).toHaveLength(3);
@@ -121,6 +138,57 @@ describe("SIENodePostprocessor", () => {
expect(result[2].score).toBe(0.31);
});
+ it("maps the server's item ids back to their nodes", async () => {
+ const { SIEClient } = await import("@superlinked/sie-sdk");
+ const mockScore = serverScore({ doc1: 0.2, doc2: 0.9, doc3: 0.5 });
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ asConstructor({
+ score: mockScore,
+ close: vi.fn(),
+ }),
+ );
+
+ const nodes = [mockNodeWithScore("doc1"), mockNodeWithScore("doc2"), mockNodeWithScore("doc3")];
+
+ const postprocessor = new SIENodePostprocessor();
+ const result = await postprocessor.postprocessNodes(
+ nodes as unknown as NodeWithScore[],
+ "query",
+ );
+
+ expect(result.map((n) => n.node.getContent())).toEqual(["doc2", "doc3", "doc1"]);
+ expect(result.map((n) => n.score)).toEqual([0.9, 0.5, 0.2]);
+ });
+
+ it("skips score entries whose itemId was not sent", async () => {
+ const { SIEClient } = await import("@superlinked/sie-sdk");
+ const mockScore = vi.fn().mockResolvedValue({
+ scores: [
+ { itemId: "item-0", score: 0.99, rank: 0 },
+ { itemId: "01", score: 0.98, rank: 1 },
+ { itemId: "1", score: 0.5, rank: 2 },
+ { itemId: "1", score: 0.4, rank: 3 },
+ { itemId: "7", score: 0.3, rank: 4 },
+ ],
+ });
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ asConstructor({
+ score: mockScore,
+ close: vi.fn(),
+ }),
+ );
+
+ const nodes = [mockNodeWithScore("doc1"), mockNodeWithScore("doc2")];
+
+ const postprocessor = new SIENodePostprocessor();
+ const result = await postprocessor.postprocessNodes(
+ nodes as unknown as NodeWithScore[],
+ "query",
+ );
+
+ expect(result.map((n) => [n.node.getContent(), n.score])).toEqual([["doc2", 0.5]]);
+ });
+
it("applies topN client-side", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockScore = vi.fn().mockResolvedValue({