fix(python): preserve row alignment for OpenAI embeddings (#5260)

Fixes #5259.

## Problem

The Python OpenAI adapter pairs the response list and the input batch by
position. An OpenAI-compatible endpoint that returns the data items in a
different order from their `index` values causes LanceDB to write
otherwise valid embeddings to the wrong rows.

## Changes

- Map response indices back to the original source rows, including when
empty inputs were filtered out of the request.
- Preserve the existing null result for a missing embedding and reject
duplicate or out-of-range indices before writing rows.

## Validation

- Tested `Table.add()` and `to_arrow()` using the real OpenAI Python SDK
and a loopback OpenAI-compatible endpoint. On `main`, `alpha` and `beta`
received each other's vectors. With this patch each row retained its
vector.
- `pytest -c python/pyproject.toml
python/python/tests/test_embeddings.py -q -k openai` passed 20 tests.
Two live provider tests were skipped because no API key was supplied.
- Ruff lint and formatting passed. The Python source used the
release-matching `0.42.0b38` native wheel.

AI-assisted investigation, implementation and testing.
This commit is contained in:
Divyam Talwar
2026-11-30 20:12:19 +08:00
committed by GitHub
parent 2d7dceaad1
commit 70ab010a47
2 changed files with 65 additions and 2 deletions
+14 -1
View File
@@ -121,7 +121,20 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
kwargs["dimensions"] = self.dim
rs = self._openai_client.embeddings.create(**kwargs)
return {idx: v.embedding for v, idx in zip(rs.data, indices_batch)}
embeddings = {}
for item in rs.data:
index = item.index
if type(index) is not int or not 0 <= index < len(indices_batch):
raise ValueError(
f"OpenAI returned an invalid embedding index: {index!r}"
)
row_index = indices_batch[index]
if row_index in embeddings:
raise ValueError(
f"OpenAI returned a duplicate embedding index: {index}"
)
embeddings[row_index] = item.embedding
return embeddings
def embed_one_or_log(idx, text):
# Retry a single rejected input
+51 -1
View File
@@ -3,6 +3,7 @@
import os
import pickle
from types import SimpleNamespace
from typing import List, Optional, Union
from unittest.mock import MagicMock, patch
@@ -1086,6 +1087,7 @@ def test_openai_bad_request_partial_batch_recovery():
if input[0] == "bad text":
raise FakeBadRequestError("bad request")
embedding = MagicMock()
embedding.index = 0
embedding.embedding = [0.1, 0.2, 0.3]
result = MagicMock()
result.data = [embedding]
@@ -1112,12 +1114,60 @@ def mock_openai_client(monkeypatch):
client = MagicMock()
client.embeddings.create.return_value.data = []
monkeypatch.setattr(
"lancedb.embeddings.openai.attempt_import_or_raise", MagicMock()
"lancedb.embeddings.openai.attempt_import_or_raise",
lambda _: SimpleNamespace(
AuthenticationError=type("AuthenticationError", (Exception,), {}),
BadRequestError=type("BadRequestError", (Exception,), {}),
),
)
monkeypatch.setattr(get_registry().get("openai"), "_openai_client", client)
return client
def test_openai_keeps_embedding_indices_aligned_with_input_rows(mock_openai_client):
model = get_registry().get("openai").create(name="text-embedding-3-small", dim=2)
mock_openai_client.embeddings.create.return_value.data = [
SimpleNamespace(index=1, embedding=[0.0, 1.0]),
SimpleNamespace(index=0, embedding=[1.0, 0.0]),
]
assert model.compute_source_embeddings(["alpha", None, "beta", ""]) == [
[1.0, 0.0],
None,
[0.0, 1.0],
None,
]
mock_openai_client.embeddings.create.assert_called_once_with(
input=["alpha", "beta"], model="text-embedding-3-small", dimensions=2
)
def test_openai_preserves_a_missing_embedding_at_its_original_row(mock_openai_client):
model = get_registry().get("openai").create()
mock_openai_client.embeddings.create.return_value.data = [
SimpleNamespace(index=1, embedding=[0.0, 1.0]),
]
assert model.compute_source_embeddings(["alpha", None, "beta"]) == [
None,
None,
[0.0, 1.0],
]
@pytest.mark.parametrize("indices", [[0, 0], [0, 2], [0, -1]])
def test_openai_rejects_duplicate_or_out_of_range_embedding_indices(
mock_openai_client, indices
):
model = get_registry().get("openai").create()
mock_openai_client.embeddings.create.return_value.data = [
SimpleNamespace(index=index, embedding=[1.0, 0.0]) for index in indices
]
with pytest.raises(ValueError, match="embedding index"):
model.compute_source_embeddings(["alpha", "beta"])
@pytest.mark.parametrize(
("texts", "expected"),
[([], []), ([None, ""], [None, None])],