mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-28 05:24:00 +00:00
Continues #2519 (originally contributed by @1jamesthompson1) to address #2518 for text retrieval with Cohere Embed models deployed on Azure AI Foundry. ## Summary Adds an opt-in native Cohere Embed API v2 (`ClientV2`) path to the existing `cohere` embedding registry entry (`CohereEmbeddingFunction`) for text-only retrieval against custom endpoints such as Azure AI Foundry (`https://<resource>.services.ai.azure.com/providers/cohere`, where the Cohere SDK appends `/v2/embed`). ### Behavior and Defaults - **Opt-in v2 route (`base_url`)**: When `base_url` is set, requests use `cohere.ClientV2` (`POST <base_url>/v2/embed`) with `embedding_types=["float"]`, split inputs into batches of up to 96 texts, disable SDK-level retries, and validate returned vector counts and dimensions. Application retries use `retry_with_exponential_backoff` in `embeddings/utils.py`, which adds an optional `do_not_retry` predicate used only by Cohere v2 so `3xx` redirects fail immediately without backoff while transient failures such as `429` retry only the failed batch. Non-string inputs are rejected; this change covers text retrieval only. - **Fixed retrieval roles**: In `base_url` mode, document embeddings use `search_document` and query embeddings use `search_query`. Setting other `source_input_type` or `query_input_type` values is rejected. - **Explicit endpoint parameters**: Setting `base_url` requires explicit `name` (the deployed model name), `output_dimension` (`> 0`, used for both the Arrow vector column width and the v2 request `output_dimension`), and `api_key`. Setting `output_dimension` or `api_key` without `base_url` is rejected. - **Unchanged hosted path**: When `base_url` is omitted, existing behavior is preserved — `cohere.Client` (`/v1/embed`), `COHERE_API_KEY`, existing default model/role settings, legacy table metadata restoration, and the existing `cohere>=4.0` package floor. - **Runtime SDK requirement**: Opting into `base_url` checks `cohere>=5.15.0` at runtime and raises an `ImportError` on older SDK versions without raising the minimum requirement for hosted users. ### Credentials and Endpoint Trust - `api_key` is declared in `sensitive_keys()` and must be a registry `$var:` reference without an inline fallback default (`$var:<name>` only). Table metadata persists only the variable reference. - `base_url` must be an HTTP(S) URL without embedded credentials, query strings, or fragments, and is exposed through `endpoints()` so reopening a table in a new process requires explicit approval via `registry.allow_endpoint(...)`. - `ClientV2` is cached per embedding function instance (`@cached_property`) with `httpx.Client(follow_redirects=False, timeout=300)` so redirects cannot forward requests or credentials off the approved endpoint. Because Cohere v2 classifies `3xx` responses as non-retryable via `do_not_retry`, a redirected `table.add` or `table.search` call makes one `POST` with zero application backoff and no request to the `Location` target (`table.add` surfaces the `307` inside the existing Arrow/Rust `RuntimeError` wrapper; `table.search` surfaces the Cohere `ApiError`). ## Verification - **Loopback HTTP SDK tests (`test_cohere_embeddings.py`)**: Passed against local loopback HTTP fixtures with real Cohere SDK `5.15.0` (opt-in minimum), `7.0.5`, and `7.3.2`. Verified exact `/providers/cohere/v2/embed` path, bearer auth header, JSON payload, 256-dim vector schema, `table.add`/reopen, fresh-process `UntrustedEmbeddingConfigError` followed by `allow_endpoint(...)`, deterministic role-based ranking, 96-text batching with failed-batch-only `429` retry (single backoff), `307` redirect handling with retries enabled on both `table.add` (wrapped in Arrow/Rust `RuntimeError`) and `table.search` (Cohere `ApiError`) with one `POST`, zero application backoff, and no `Location` request, plus invalid input/dimension rejection. - **Adjacent embedding, retry, and trust suites (`cohere==7.3.2`)**: Passed across embedding, registry, trust (including the SDK-independent Cohere metadata restoration and endpoint authorization test in `test_embeddings_trust.py`), field metadata, NVIDIA embedding, and retry suites (OpenAI-key test skipped without a key). - **No-`cohere` environment**: Cohere config/legacy unit tests and SDK-independent `test_embeddings_trust.py` metadata restoration and endpoint authorization tests passed without `cohere` installed (real-SDK loopback tests skipped). - **Legacy SDK (`cohere==4.57`)**: Loopback wire check confirmed hosted document/query requests continue targeting `/v1/embed` and opt-in `base_url` usage raises `Cohere base_url requires cohere>=5.15.0`. - **Docs & lint**: Offline Foundry schema test (`test_embedding_cohere_foundry`), byte-identical regenerated snippet (`docs/web/snippets/integrations.mdx`), and `python/` Ruff format/lint checks passed. ### Scope of Verification All HTTP request, authentication, redirect, trust, and ranking checks were exercised against local loopback HTTP fixtures modeled on [Cohere's Azure Foundry workshop](https://github.com/cohere-ai/cohere-azure-workshops/tree/ca1c4cb162e2/lab-1-embed) and the [Cohere Embed v2 API reference](https://docs.cohere.com/v2/reference/embed). Acceptance against a live Azure AI Foundry service (real Foundry credentials and specific `output_dimension` overrides) has not been verified.
333 lines
11 KiB
Python
333 lines
11 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
"""
|
|
Restoring an embedding function from table metadata must not let the table grant
|
|
itself trust: remote model code and custom endpoints need approval from the
|
|
process that opens the table.
|
|
"""
|
|
|
|
import json
|
|
from unittest.mock import patch
|
|
|
|
import lancedb
|
|
import pyarrow as pa
|
|
import pytest
|
|
from lancedb.embeddings import (
|
|
EmbeddingFunctionConfig,
|
|
OCIGenAIEmbeddings,
|
|
OllamaEmbeddings,
|
|
OpenAIEmbeddings,
|
|
SentenceTransformerEmbeddings,
|
|
UntrustedEmbeddingConfigError,
|
|
get_registry,
|
|
)
|
|
from lancedb.embeddings.base import UntrustedEmbeddingFunction
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def fresh_trust(monkeypatch):
|
|
registry = get_registry()
|
|
monkeypatch.setattr(registry, "_allowed_remote_code", set())
|
|
monkeypatch.setattr(registry, "_allowed_endpoints", set())
|
|
|
|
|
|
def metadata_for(name: str, model: dict) -> dict:
|
|
entry = {
|
|
"name": name,
|
|
"model": model,
|
|
"source_column": "text",
|
|
"vector_column": "vector",
|
|
}
|
|
return {b"embedding_functions": json.dumps([entry]).encode()}
|
|
|
|
|
|
def restore(name: str, model: dict):
|
|
return get_registry().parse_functions(metadata_for(name, model))["vector"].function
|
|
|
|
|
|
def test_sentence_transformers_does_not_trust_remote_code_by_default():
|
|
assert SentenceTransformerEmbeddings.create().trust_remote_code is False
|
|
|
|
|
|
@pytest.mark.parametrize("name", ["sentence-transformers", "huggingface", "colbert"])
|
|
def test_restored_remote_code_requires_allowlist(name):
|
|
model = {"name": "attacker/model", "trust_remote_code": True}
|
|
func = restore(name, model)
|
|
|
|
with pytest.raises(UntrustedEmbeddingConfigError, match="attacker/model"):
|
|
func.compute_query_embeddings("hello")
|
|
with pytest.raises(UntrustedEmbeddingConfigError):
|
|
func.ndims()
|
|
|
|
|
|
def test_blocked_function_does_not_construct_model():
|
|
# huggingface loads its model in __init__, so the check has to happen first.
|
|
with patch(
|
|
"lancedb.embeddings.transformers.attempt_import_or_raise"
|
|
) as attempt_import:
|
|
restore("huggingface", {"name": "attacker/model", "trust_remote_code": True})
|
|
attempt_import.assert_not_called()
|
|
|
|
|
|
def test_allowlisted_model_restores_with_remote_code():
|
|
get_registry().allow_remote_code("org/model")
|
|
func = restore(
|
|
"sentence-transformers", {"name": "org/model", "trust_remote_code": True}
|
|
)
|
|
assert isinstance(func, SentenceTransformerEmbeddings)
|
|
assert func.trust_remote_code is True
|
|
|
|
|
|
def test_allowlist_does_not_cover_other_models():
|
|
get_registry().allow_remote_code("org/model")
|
|
func = restore(
|
|
"sentence-transformers", {"name": "org/other", "trust_remote_code": True}
|
|
)
|
|
with pytest.raises(UntrustedEmbeddingConfigError, match="org/other"):
|
|
func.compute_query_embeddings("hello")
|
|
|
|
|
|
def test_pinned_revision_must_match():
|
|
get_registry().allow_remote_code("org/model", revision="abc123")
|
|
|
|
pinned = restore(
|
|
"sentence-transformers",
|
|
{"name": "org/model", "revision": "abc123", "trust_remote_code": True},
|
|
)
|
|
assert pinned.trust_remote_code is True
|
|
|
|
for model in [
|
|
{"name": "org/model", "revision": "def456", "trust_remote_code": True},
|
|
{"name": "org/model", "trust_remote_code": True},
|
|
]:
|
|
func = restore("sentence-transformers", model)
|
|
with pytest.raises(UntrustedEmbeddingConfigError, match="org/model"):
|
|
func.compute_query_embeddings("hello")
|
|
|
|
|
|
def test_restored_trust_flag_follows_allowlist_when_absent():
|
|
# Tables written before the default changed don't record trust_remote_code.
|
|
assert restore(
|
|
"sentence-transformers", {"name": "org/model"}
|
|
).trust_remote_code is (False)
|
|
get_registry().allow_remote_code("org/model")
|
|
assert restore("sentence-transformers", {"name": "org/model"}).trust_remote_code
|
|
|
|
|
|
def test_created_function_records_trust_flag():
|
|
# Otherwise a new table using the default would look like a pre-fix table,
|
|
# where a missing flag meant True.
|
|
conf = EmbeddingFunctionConfig(
|
|
source_column="text",
|
|
vector_column="vector",
|
|
function=SentenceTransformerEmbeddings.create(name="org/model"),
|
|
)
|
|
assert get_registry().function_to_metadata(conf)["model"] == {
|
|
"name": "org/model",
|
|
"trust_remote_code": False,
|
|
}
|
|
|
|
get_registry().allow_remote_code("org/model")
|
|
metadata = get_registry().get_table_metadata([conf])
|
|
restored = get_registry().parse_functions(metadata)["vector"].function
|
|
assert restored.trust_remote_code is False
|
|
|
|
|
|
def test_huggingface_missing_flag_keeps_false_default():
|
|
# huggingface always defaulted to False, so approval must not flip it.
|
|
get_registry().allow_remote_code("org/model")
|
|
with patch("lancedb.embeddings.transformers.attempt_import_or_raise"):
|
|
func = restore("huggingface", {"name": "org/model"})
|
|
assert func.trust_remote_code is False
|
|
|
|
|
|
def test_restored_explicit_false_stays_false():
|
|
get_registry().allow_remote_code("org/model")
|
|
func = restore(
|
|
"sentence-transformers", {"name": "org/model", "trust_remote_code": False}
|
|
)
|
|
assert func.trust_remote_code is False
|
|
|
|
|
|
def test_create_trusts_its_own_config(tmp_path):
|
|
func = SentenceTransformerEmbeddings.create(
|
|
name="org/model", trust_remote_code=True
|
|
)
|
|
db = lancedb.connect(tmp_path)
|
|
schema = pa.schema(
|
|
[pa.field("text", pa.string()), pa.field("vector", pa.list_(pa.float32(), 4))]
|
|
)
|
|
db.create_table(
|
|
"t",
|
|
schema=schema,
|
|
embedding_functions=[
|
|
EmbeddingFunctionConfig(
|
|
source_column="text", vector_column="vector", function=func
|
|
)
|
|
],
|
|
)
|
|
|
|
restored = db.open_table("t").embedding_functions["vector"].function
|
|
assert isinstance(restored, SentenceTransformerEmbeddings)
|
|
assert restored.trust_remote_code is True
|
|
|
|
|
|
def test_create_trusts_only_the_revision_it_selected():
|
|
# Anyone can push a PR ref to a Hugging Face repo, so trusting a model's
|
|
# default branch must not extend to its other revisions.
|
|
SentenceTransformerEmbeddings.create(name="org/model", trust_remote_code=True)
|
|
func = restore(
|
|
"sentence-transformers",
|
|
{"name": "org/model", "revision": "refs/pr/123", "trust_remote_code": True},
|
|
)
|
|
assert isinstance(func, UntrustedEmbeddingFunction)
|
|
|
|
same = restore(
|
|
"sentence-transformers", {"name": "org/model", "trust_remote_code": True}
|
|
)
|
|
assert same.trust_remote_code is True
|
|
|
|
|
|
def test_explicit_unpinned_approval_covers_any_revision():
|
|
get_registry().allow_remote_code("org/model")
|
|
func = restore(
|
|
"sentence-transformers",
|
|
{"name": "org/model", "revision": "abc123", "trust_remote_code": True},
|
|
)
|
|
assert func.trust_remote_code is True
|
|
|
|
|
|
def test_missing_flag_does_not_inherit_unapproved_trust_default():
|
|
class LegacySentenceTransformer(SentenceTransformerEmbeddings):
|
|
trust_remote_code: bool = True
|
|
|
|
registry = get_registry()
|
|
registry.register("legacy-trust-default")(LegacySentenceTransformer)
|
|
try:
|
|
func = restore("legacy-trust-default", {"name": "attacker/model"})
|
|
assert not func.trust_remote_code
|
|
finally:
|
|
del registry._functions["legacy-trust-default"]
|
|
|
|
|
|
def test_trusting_one_model_does_not_trust_a_swapped_name():
|
|
SentenceTransformerEmbeddings.create(name="org/model", trust_remote_code=True)
|
|
func = restore(
|
|
"sentence-transformers", {"name": "attacker/model", "trust_remote_code": True}
|
|
)
|
|
with pytest.raises(UntrustedEmbeddingConfigError):
|
|
func.compute_query_embeddings("hello")
|
|
|
|
|
|
ATTACKER_URL = "https://attacker.example/v1"
|
|
OCI_REGION_ENDPOINT = (
|
|
"https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com"
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"name,model",
|
|
[
|
|
("openai", {"base_url": ATTACKER_URL}),
|
|
("ollama", {"host": ATTACKER_URL}),
|
|
("ollama", {"ollama_client_kwargs": {"proxy": ATTACKER_URL}}),
|
|
("watsonx", {"url": ATTACKER_URL}),
|
|
(
|
|
"cohere",
|
|
{
|
|
"name": "embed-v-4-0",
|
|
"base_url": ATTACKER_URL,
|
|
"output_dimension": 256,
|
|
"api_key": "$var:cohere-test-key",
|
|
},
|
|
),
|
|
],
|
|
)
|
|
def test_restored_custom_endpoint_requires_allowlist(name, model, monkeypatch):
|
|
registry = get_registry()
|
|
monkeypatch.setitem(registry._variables, "cohere-test-key", "test-cohere-key")
|
|
|
|
func = restore(name, model)
|
|
with pytest.raises(UntrustedEmbeddingConfigError, match="attacker.example"):
|
|
func.compute_query_embeddings("hello")
|
|
|
|
registry.allow_endpoint(ATTACKER_URL)
|
|
assert isinstance(restore(name, model), registry.get(name))
|
|
|
|
|
|
def test_default_endpoints_need_no_allowlist():
|
|
assert isinstance(restore("openai", {}), OpenAIEmbeddings)
|
|
assert isinstance(
|
|
restore("ollama", {"host": "http://localhost:11434"}), OllamaEmbeddings
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"model,endpoint",
|
|
[
|
|
({"service_endpoint": ATTACKER_URL}, ATTACKER_URL),
|
|
({"region": "eu-frankfurt-1"}, OCI_REGION_ENDPOINT),
|
|
],
|
|
)
|
|
def test_restored_oci_custom_endpoint_requires_allowlist(model, endpoint):
|
|
func = restore("oci-genai", model)
|
|
assert isinstance(func, UntrustedEmbeddingFunction)
|
|
with pytest.raises(UntrustedEmbeddingConfigError, match="allow_endpoint"):
|
|
func.compute_query_embeddings("hello")
|
|
|
|
get_registry().allow_endpoint(endpoint)
|
|
restored = restore("oci-genai", model)
|
|
assert isinstance(restored, OCIGenAIEmbeddings)
|
|
assert restored.endpoints() == [endpoint]
|
|
|
|
|
|
def test_restored_oci_default_endpoint_needs_no_allowlist():
|
|
func = restore("oci-genai", {})
|
|
assert isinstance(func, OCIGenAIEmbeddings)
|
|
assert func.endpoints() == []
|
|
|
|
|
|
def test_endpoint_allowlist_ignores_trailing_slash():
|
|
get_registry().allow_endpoint("http://my-host:11434/")
|
|
assert isinstance(
|
|
restore("ollama", {"host": "http://my-host:11434"}), OllamaEmbeddings
|
|
)
|
|
|
|
|
|
def test_create_trusts_its_own_endpoint():
|
|
OpenAIEmbeddings.create(base_url="http://my-proxy/v1")
|
|
assert isinstance(
|
|
restore("openai", {"base_url": "http://my-proxy/v1"}), OpenAIEmbeddings
|
|
)
|
|
|
|
|
|
def test_blocked_function_round_trips_metadata():
|
|
model = {"name": "attacker/model", "trust_remote_code": True}
|
|
func = restore("sentence-transformers", model)
|
|
conf = EmbeddingFunctionConfig(
|
|
source_column="text", vector_column="vector", function=func
|
|
)
|
|
entry = get_registry().function_to_metadata(conf)
|
|
assert entry["name"] == "sentence-transformers"
|
|
assert entry["model"] == model
|
|
|
|
|
|
def test_table_with_blocked_function_still_opens(tmp_path):
|
|
db = lancedb.connect(tmp_path)
|
|
schema = pa.schema(
|
|
[pa.field("text", pa.string()), pa.field("vector", pa.list_(pa.float32(), 2))],
|
|
metadata=metadata_for(
|
|
"sentence-transformers",
|
|
{"name": "attacker/model", "trust_remote_code": True},
|
|
),
|
|
)
|
|
db.create_table("t", schema=schema)
|
|
tbl = db.open_table("t")
|
|
|
|
tbl.add([{"text": "hi", "vector": [1.0, 2.0]}])
|
|
assert tbl.search([1.0, 2.0]).limit(1).to_list()[0]["text"] == "hi"
|
|
|
|
with pytest.raises(UntrustedEmbeddingConfigError, match="allow_remote_code"):
|
|
tbl.search("hi").limit(1).to_list()
|