fix(python): skip empty or null texts in bedrock-text embeddings (#4919)

With `bedrock-text`, a single empty or null cell in the source column
makes `add()` fail while computing embeddings, before `on_bad_vectors`
gets a chance to run, so `on_bad_vectors="drop"`, `"null"` and `"fill"`
have no effect.

**Root cause:** `BedRockText.generate_embeddings` sends every text to
`invoke_model`, including empty strings and `None`. Bedrock rejects an
empty `inputText` (minimum length 1), and the error is re-raised as a
`ValueError`. The `openai`, `oci_genai` and `nvidia` functions already
return `None` for such entries, and `table.py` passes `None` vectors on
to `on_bad_vectors`.

**Fix:** skip `None` and empty strings in `generate_embeddings` and put
`None` in their slot (other values, such as `False`, are still sent, so
their input error reaches the caller); the other texts are embedded as
before and keep their positions. With the default
`on_bad_vectors="error"`, `add()` still raises, now with the bad-vector
error that points at `on_bad_vectors` instead of a boto3 error.

**Tests:** `test_embeddings_bedrock.py` uses a fake bedrock-runtime
client that rejects an empty `inputText`, and checks `["alpha", "" /
None, "be"]` returns `[[5.0], None, [2.0]]` with only two calls made.
Both cases fail on `main` and pass with the change. An `add()` through
the same fake client with `drop`, `null` and `fill` fails on `main` and
succeeds here (2, 4 and 4 of 4 rows). A `table.add()` with a `False`
source under `on_bad_vectors="drop"` checks that the non-string input
error still reaches the caller. None of this was run against live
Bedrock.

This change was prepared with the help of an AI assistant (Claude), and
the submitter is responsible for it.


---------
This commit is contained in:
Alex Castillo González
2026-11-30 19:14:08 +08:00
committed by GitHub
parent fc13fd6e98
commit f639e178a1
2 changed files with 51 additions and 2 deletions
+6 -2
View File
@@ -176,11 +176,15 @@ class BedRockText(_BedrockEmbeddingFunction, TextEmbeddingFunction):
Returns
-------
list[list[float]]
The embeddings for the given texts
list[list[float] | None]
The embeddings for the given texts. Empty or null texts are not sent
to Bedrock (which rejects empty ``inputText``); their entry is None.
"""
results = []
for text in texts:
if text is None or (isinstance(text, str) and not text):
results.append(None)
continue
response = self._generate_embedding(text, *args, **kwargs)
results.append(response)
return results
@@ -328,3 +328,48 @@ def test_bedrock_text_cohere_v3(bedrock_runtime, mocker):
{"texts": ["document"], "input_type": "search_document"},
{"texts": ["query"], "input_type": "search_query"},
]
class _EmptyRejectingBedrockClient:
"""Mimics bedrock-runtime, which rejects an empty ``inputText``."""
def __init__(self):
self.calls = []
def invoke_model(self, body, modelId, accept, contentType):
payload = json.loads(body)
self.calls.append(payload)
text = payload["inputText"]
if not isinstance(text, str):
raise ValueError("inputText: expected a string")
if not text:
raise ValueError("inputText: Minimum length is 1")
body = json.dumps({"embedding": [float(len(text))]}).encode()
return {"body": io.BytesIO(body)}
@pytest.mark.parametrize("empty", [None, ""])
def test_empty_or_null_texts_are_skipped(empty):
func = get_registry().get("bedrock-text").create()
client = _EmptyRejectingBedrockClient()
func.__dict__["client"] = client
result = func.compute_source_embeddings(["alpha", empty, "be"])
assert result == [[5.0], None, [2.0]]
assert [c["inputText"] for c in client.calls] == ["alpha", "be"]
def test_add_surfaces_non_string_error_with_drop(tmp_path, monkeypatch):
client = _EmptyRejectingBedrockClient()
monkeypatch.setattr(boto3.Session, "client", lambda *args, **kwargs: client)
model = get_registry().get("bedrock-text").create(max_retries=0)
class Row(LanceModel):
text: bool = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
table = lancedb.connect(tmp_path).create_table("texts", schema=Row)
with pytest.raises(RuntimeError, match="expected a string"):
table.add([{"text": False}], on_bad_vectors="drop")
assert table.count_rows() == 0