Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

23.1 KB
Raw Blame
"""Tests for the zvec target connector."""

from __future__ import annotations

import datetime
import decimal
import tempfile
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Annotated, Any, Iterator

import numpy as np
import pytest
from numpy.typing import NDArray

import cocoindex as coco
from cocoindex._internal.context_keys import ContextProvider
from cocoindex.connectorkits import target
from cocoindex.resources.schema import VectorSchema

from tests import common

try:
    import zvec

    from cocoindex.connectors import zvec as zc

    HAS_ZVEC = True
except ImportError:
    HAS_ZVEC = False

requires_zvec = pytest.mark.skipif(not HAS_ZVEC, reason="zvec is not installed")

pytestmark = requires_zvec


ZVEC_DB = coco.ContextKey["zc.ManagedConnection"]("zvec_test_db")


# =============================================================================
# Fixtures and helpers
# =============================================================================


@pytest.fixture
def conn() -> Iterator[Any]:
    base = Path(tempfile.mkdtemp(prefix="zvec_test_"))
    connection = zc.connect(base)
    yield connection
    connection.close()


_counter = {"n": 0}


def make_test_env(connection: Any, env_name: str) -> coco.Environment:
    ctx = ContextProvider()
    ctx.provide(ZVEC_DB, connection)
    _counter["n"] += 1
    settings = coco.Settings.from_env(
        db_path=common.get_env_db_path(
            f"connectors__test_zvec_target__{env_name}__{_counter['n']}"
        )
    )
    return coco.Environment(settings, context_provider=ctx)


def fetch_doc(connection: Any, collection_name: str, doc_id: str) -> Any:
    col = connection.open_existing(collection_name)
    result = col.fetch(ids=doc_id)
    return result.get(doc_id)


# =============================================================================
# Row types
# =============================================================================


# zvec collections require at least one vector field, so every row type carries one.
_Embedding = Annotated[
    NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=4)
]

_EMB = np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32)


@dataclass
class SimpleDoc:
    id: str
    title: str
    year: int
    embedding: _Embedding


@dataclass
class TypedDoc:
    id: str
    name: str
    score: float
    active: bool
    tags: list[str]
    embedding: _Embedding


@dataclass
class VectorDoc:
    id: str
    title: str
    embedding: _Embedding


# `from __future__ import annotations` keeps these as strings, so the zc
# reference is only resolved (via from_class) in tests, which are skipped when
# zvec is absent.
@dataclass
class SparseDoc:
    id: str
    title: str
    sparse: Annotated[dict[int, float], zc.ZvecVectorDef(sparse=True)]


@dataclass
class MultiVectorDoc:
    id: str
    dense: _Embedding
    sparse: Annotated[dict[int, float], zc.ZvecVectorDef(sparse=True)]


_Embedding16 = Annotated[
    NDArray[np.float16], VectorSchema(dtype=np.dtype(np.float16), size=4)
]
_EMB16 = np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float16)


@dataclass
class Fp16Doc:
    id: str
    title: str
    embedding: _Embedding16


@dataclass
class QuantizedDoc:
    id: str
    title: str
    embedding: Annotated[
        NDArray[np.float32],
        VectorSchema(dtype=np.dtype(np.float32), size=4),
        zc.ZvecVectorDef(quantize="int8"),
    ]


@dataclass
class EncoderDoc:
    id: str
    uid: uuid.UUID
    price: decimal.Decimal
    created: datetime.datetime
    day: datetime.date
    moment: datetime.time
    elapsed: datetime.timedelta
    blob: bytes
    embedding: _Embedding


@dataclass
class ArrayDoc:
    id: str
    ints: list[int]
    floats: list[float]
    flags: list[bool]
    embedding: _Embedding


@dataclass
class JsonDoc:
    id: str
    meta: dict[str, int]
    embedding: _Embedding


@dataclass
class FilterDoc:
    id: str
    year: int
    embedding: _Embedding


@dataclass
class FtsDoc:
    id: str
    body: Annotated[str, zc.ZvecFtsType()]
    embedding: _Embedding


@dataclass
class FtsTunedDoc:
    id: str
    # Deliberately different FTS config from FtsDoc (different tokenizer + filters).
    body: Annotated[str, zc.ZvecFtsType(tokenizer_name="whitespace", filters=())]
    embedding: _Embedding


@dataclass
class BytesKeyDoc:
    id: bytes
    embedding: _Embedding


@dataclass
class BoolKeyDoc:
    id: bool
    embedding: _Embedding


@dataclass
class AnyKeyDoc:
    id: Any
    embedding: _Embedding


@dataclass
class ObjectKeyDoc:
    id: object
    embedding: _Embedding


@dataclass
class UnionKeyDoc:
    id: int | str
    embedding: _Embedding


@dataclass
class StrKeyDoc:
    id: str
    embedding: _Embedding


# =============================================================================
# Mutable per-test source state
# =============================================================================

_rows: list[Any] = []
_row_type: type = SimpleDoc
_collection: str = "test_collection"
_managed_by: target.ManagedBy = target.ManagedBy.SYSTEM
_declare_enabled: bool = True


async def _declare() -> None:
    if not _declare_enabled:
        return
    table = await coco.use_mount(
        coco.component_subpath("setup", "col"),
        zc.declare_collection_target,
        ZVEC_DB,
        _collection,
        await zc.CollectionSchema.from_class(_row_type, primary_key=["id"]),
        managed_by=_managed_by,
    )
    for row in _rows:
        table.declare_row(row=row)


def _make_app(connection: Any, env_name: str) -> coco.App[[], None]:
    env = make_test_env(connection, env_name)
    return coco.App(coco.AppConfig(name=env_name, environment=env), _declare)


def _reset(row_type: type, collection: str) -> None:
    global _row_type, _collection, _managed_by, _declare_enabled
    _row_type = row_type
    _collection = collection
    _managed_by = target.ManagedBy.SYSTEM
    _declare_enabled = True
    _rows.clear()


# =============================================================================
# Tests
# =============================================================================


def test_create_and_insert(conn: Any) -> None:
    _reset(SimpleDoc, "test_create")
    app = _make_app(conn, "test_create_and_insert")

    _rows.extend(
        [
            SimpleDoc(id="1", title="Alice", year=2020, embedding=_EMB),
            SimpleDoc(id="2", title="Bob", year=2021, embedding=_EMB),
        ]
    )
    app.update_blocking()

    assert conn.collection_path("test_create").exists()
    doc = fetch_doc(conn, "test_create", "1")
    assert doc is not None
    assert doc.fields == {"title": "Alice", "year": 2020}
    assert fetch_doc(conn, "test_create", "2").fields == {"title": "Bob", "year": 2021}


def test_update_row(conn: Any) -> None:
    _reset(SimpleDoc, "test_update")
    app = _make_app(conn, "test_update_row")

    _rows.append(SimpleDoc(id="1", title="Alice", year=2020, embedding=_EMB))
    app.update_blocking()
    assert fetch_doc(conn, "test_update", "1").fields["title"] == "Alice"

    _rows[0] = SimpleDoc(id="1", title="Alice v2", year=2099, embedding=_EMB)
    app.update_blocking()
    doc = fetch_doc(conn, "test_update", "1")
    assert doc.fields == {"title": "Alice v2", "year": 2099}


def test_delete_row(conn: Any) -> None:
    _reset(SimpleDoc, "test_delete")
    app = _make_app(conn, "test_delete_row")

    _rows.extend(
        [
            SimpleDoc(id="1", title="A", year=1, embedding=_EMB),
            SimpleDoc(id="2", title="B", year=2, embedding=_EMB),
        ]
    )
    app.update_blocking()
    assert fetch_doc(conn, "test_delete", "2") is not None

    _rows[:] = [_rows[0]]
    app.update_blocking()
    assert fetch_doc(conn, "test_delete", "1") is not None
    assert fetch_doc(conn, "test_delete", "2") is None


def test_multiple_scalar_types(conn: Any) -> None:
    _reset(TypedDoc, "test_types")
    app = _make_app(conn, "test_multiple_scalar_types")

    _rows.append(
        TypedDoc(
            id="1", name="x", score=3.5, active=True, tags=["a", "b"], embedding=_EMB
        )
    )
    app.update_blocking()

    doc = fetch_doc(conn, "test_types", "1")
    assert doc.fields["name"] == "x"
    assert doc.fields["score"] == pytest.approx(3.5)
    assert doc.fields["active"] is True
    assert list(doc.fields["tags"]) == ["a", "b"]


def test_drop_collection(conn: Any) -> None:
    global _declare_enabled
    _reset(SimpleDoc, "test_drop")
    # Reuse one app/env so CocoIndex retains tracking state across runs.
    app = _make_app(conn, "test_drop_collection")

    _rows.append(SimpleDoc(id="1", title="A", year=1, embedding=_EMB))
    app.update_blocking()
    assert conn.collection_path("test_drop").exists()

    # Stop declaring the collection: it should be destroyed on the next run.
    _declare_enabled = False
    app.update_blocking()
    assert not conn.collection_path("test_drop").exists()


def test_writes_more_documents_than_one_zvec_batch(conn: Any) -> None:
    """A run writes and deletes more documents than one zvec write takes (1024)."""
    _reset(SimpleDoc, "test_big_batch")
    app = _make_app(conn, "test_writes_more_documents_than_one_zvec_batch")

    _rows.extend(
        SimpleDoc(id=str(i), title="t", year=i, embedding=_EMB) for i in range(2500)
    )
    app.update_blocking()
    col = conn.open_existing("test_big_batch")
    assert col.stats.doc_count == 2500

    _rows[:] = _rows[:10]
    app.update_blocking()
    assert col.stats.doc_count == 10


def test_undeclaring_a_document_removed_out_of_band(conn: Any) -> None:
    """A document already gone from the collection is deleted without error."""
    _reset(SimpleDoc, "test_gone")
    app = _make_app(conn, "test_undeclaring_a_document_removed_out_of_band")

    _rows.extend(
        [
            SimpleDoc(id="1", title="A", year=1, embedding=_EMB),
            SimpleDoc(id="2", title="B", year=2, embedding=_EMB),
        ]
    )
    app.update_blocking()
    conn.open_existing("test_gone").delete(ids=["2"])

    _rows[:] = _rows[:1]
    app.update_blocking()
    assert fetch_doc(conn, "test_gone", "1") is not None
    assert fetch_doc(conn, "test_gone", "2") is None


def test_no_op_when_unchanged(conn: Any) -> None:
    _reset(SimpleDoc, "test_noop")
    app = _make_app(conn, "test_no_op_when_unchanged")

    _rows.append(SimpleDoc(id="1", title="A", year=1, embedding=_EMB))
    app.update_blocking()
    # Running again with identical data should be a no-op and not error.
    app.update_blocking()
    assert fetch_doc(conn, "test_noop", "1").fields == {"title": "A", "year": 1}


def test_dense_vector(conn: Any) -> None:
    _reset(VectorDoc, "test_dense")
    app = _make_app(conn, "test_dense_vector")

    _rows.append(
        VectorDoc(
            id="1",
            title="hello",
            embedding=np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32),
        )
    )
    app.update_blocking()

    col = conn.open_existing("test_dense")
    results = col.query(
        zvec.Query(field_name="embedding", vector=[0.1, 0.2, 0.3, 0.4]),
        topk=5,
    )
    assert [d.id for d in results] == ["1"]


def test_sparse_vector(conn: Any) -> None:
    _reset(SparseDoc, "test_sparse")
    app = _make_app(conn, "test_sparse_vector")

    _rows.append(SparseDoc(id="1", title="s", sparse={1: 0.5, 7: 0.9}))
    app.update_blocking()

    doc = fetch_doc(conn, "test_sparse", "1")
    assert doc is not None
    assert doc.fields["title"] == "s"

    col = conn.open_existing("test_sparse")
    results = col.query(
        zvec.Query(field_name="sparse", vector={1: 0.5, 7: 0.9}), topk=5
    )
    assert [d.id for d in results] == ["1"]


def test_fts_field(conn: Any) -> None:
    _reset(FtsDoc, "test_fts")
    app = _make_app(conn, "test_fts_field")

    _rows.extend(
        [
            FtsDoc(id="1", body="the quick brown fox", embedding=_EMB),
            FtsDoc(id="2", body="a slow green turtle", embedding=_EMB),
        ]
    )
    app.update_blocking()

    # The string value is stored as an ordinary field.
    assert fetch_doc(conn, "test_fts", "1").fields["body"] == "the quick brown fox"

    # The field is full-text indexed: an FTS match on a tokenized term hits only doc 1.
    col = conn.open_existing("test_fts")
    results = col.query(
        zvec.Query(field_name="body", fts=zvec.Fts(match_string="fox")), topk=5
    )
    assert [d.id for d in results] == ["1"]


@pytest.mark.asyncio
async def test_fts_requires_str(conn: Any) -> None:
    @dataclass
    class BadFtsDoc:
        id: str
        count: Annotated[int, zc.ZvecFtsType()]
        embedding: _Embedding

    with pytest.raises(ValueError, match="ZvecFtsType"):
        await zc.CollectionSchema.from_class(BadFtsDoc, primary_key=["id"])


@pytest.mark.asyncio
async def test_fts_config_change_differs_in_tracking(conn: Any) -> None:
    # A change to FTS config (tokenizer/filters) must change the tracking record,
    # so the collection is rebuilt rather than silently keeping the old index.
    from cocoindex.connectors.zvec import _target as _zt

    s_default = await zc.CollectionSchema.from_class(FtsDoc, primary_key=["id"])
    s_tuned = await zc.CollectionSchema.from_class(FtsTunedDoc, primary_key=["id"])

    default_col = s_default.columns["body"]
    tuned_col = s_tuned.columns["body"]
    assert default_col.kind == "fts" and tuned_col.kind == "fts"
    assert (default_col.tokenizer_name, default_col.filters) == (
        "standard",
        ("lowercase",),
    )
    assert (tuned_col.tokenizer_name, tuned_col.filters) == ("whitespace", ())

    # The tracking record (used for change detection) must reflect the difference.
    core_default = _zt._tracking_core_from_spec(_zt._CollectionSpec(schema=s_default))
    core_tuned = _zt._tracking_core_from_spec(_zt._CollectionSpec(schema=s_tuned))
    assert core_default != core_tuned


def test_multiple_vector_fields(conn: Any) -> None:
    _reset(MultiVectorDoc, "test_multivec")
    app = _make_app(conn, "test_multiple_vector_fields")

    _rows.append(
        MultiVectorDoc(
            id="1",
            dense=np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32),
            sparse={2: 0.3},
        )
    )
    app.update_blocking()

    col = conn.open_existing("test_multivec")
    results = col.query(
        zvec.Query(field_name="dense", vector=[0.1, 0.2, 0.3, 0.4]), topk=5
    )
    assert [d.id for d in results] == ["1"]


def test_multiple_collections(conn: Any) -> None:
    async def _declare_two() -> None:
        schema = await zc.CollectionSchema.from_class(SimpleDoc, primary_key=["id"])
        t1 = await coco.use_mount(
            coco.component_subpath("setup", "c1"),
            zc.declare_collection_target,
            ZVEC_DB,
            "collection_one",
            schema,
        )
        t2 = await coco.use_mount(
            coco.component_subpath("setup", "c2"),
            zc.declare_collection_target,
            ZVEC_DB,
            "collection_two",
            schema,
        )
        t1.declare_row(row=SimpleDoc(id="1", title="one", year=1, embedding=_EMB))
        t2.declare_row(row=SimpleDoc(id="1", title="two", year=2, embedding=_EMB))

    env = make_test_env(conn, "test_multiple_collections")
    app = coco.App(
        coco.AppConfig(name="test_multiple_collections", environment=env),
        _declare_two,
    )
    app.update_blocking()

    assert fetch_doc(conn, "collection_one", "1").fields["title"] == "one"
    assert fetch_doc(conn, "collection_two", "1").fields["title"] == "two"


def test_user_managed_collection(conn: Any) -> None:
    # Pre-create the collection outside CocoIndex.
    schema = zvec.CollectionSchema(
        name="user_col",
        fields=[
            zvec.FieldSchema(
                name="title", data_type=zvec.DataType.STRING, nullable=True
            ),
            zvec.FieldSchema(name="year", data_type=zvec.DataType.INT64, nullable=True),
        ],
        vectors=[
            zvec.VectorSchema(
                name="embedding",
                data_type=zvec.DataType.VECTOR_FP32,
                dimension=4,
                index_param=zvec.HnswIndexParam(metric_type=zvec.MetricType.COSINE),
            )
        ],
    )
    conn.open_or_create("user_col", schema)

    global _row_type, _collection, _managed_by
    _row_type = SimpleDoc
    _collection = "user_col"
    _managed_by = target.ManagedBy.USER
    _rows.clear()
    _rows.append(SimpleDoc(id="1", title="A", year=1, embedding=_EMB))

    global _declare_enabled
    app = _make_app(conn, "test_user_managed")
    app.update_blocking()
    assert fetch_doc(conn, "user_col", "1").fields["title"] == "A"

    # Stop declaring: a user-managed collection must NOT be destroyed.
    _declare_enabled = False
    app.update_blocking()
    assert conn.collection_path("user_col").exists()


@pytest.mark.asyncio
async def test_schema_validation(conn: Any) -> None:
    schema = await zc.CollectionSchema.from_class(SimpleDoc, primary_key=["id"])

    # zvec requires collection names of at least 3 characters.
    with pytest.raises(ValueError, match="at least 3 characters"):
        zc.collection_target(ZVEC_DB, "ab", schema)

    # Composite primary keys are unsupported (single string id only).
    with pytest.raises(ValueError, match="exactly one primary key"):
        await zc.CollectionSchema.from_class(SimpleDoc, primary_key=["id", "title"])

    # A collection must declare at least one vector field.
    @dataclass
    class NoVectorDoc:
        id: str
        title: str

    no_vec_schema = await zc.CollectionSchema.from_class(
        NoVectorDoc, primary_key=["id"]
    )
    with pytest.raises(ValueError, match="at least one vector field"):
        zc.collection_target(ZVEC_DB, "no_vec_collection", no_vec_schema)

    # zvec dense vectors must be float32 or float16.
    @dataclass
    class Float64Doc:
        id: str
        embedding: Annotated[
            NDArray[np.float64], VectorSchema(dtype=np.dtype(np.float64), size=4)
        ]

    with pytest.raises(ValueError, match="float32 or float16"):
        await zc.CollectionSchema.from_class(Float64Doc, primary_key=["id"])


def test_fp16_dense_vector(conn: Any) -> None:
    _reset(Fp16Doc, "test_fp16")
    app = _make_app(conn, "test_fp16_dense_vector")

    _rows.append(Fp16Doc(id="1", title="h", embedding=_EMB16))
    app.update_blocking()

    col = conn.open_existing("test_fp16")
    results = col.query(
        zvec.Query(field_name="embedding", vector=[0.1, 0.2, 0.3, 0.4]), topk=5
    )
    assert [d.id for d in results] == ["1"]


def test_int8_quantized_vector(conn: Any) -> None:
    _reset(QuantizedDoc, "test_quant")
    app = _make_app(conn, "test_int8_quantized_vector")

    _rows.append(QuantizedDoc(id="1", title="q", embedding=_EMB))
    app.update_blocking()

    assert fetch_doc(conn, "test_quant", "1") is not None


def test_scalar_encoders_round_trip(conn: Any) -> None:
    _reset(EncoderDoc, "test_enc")
    app = _make_app(conn, "test_scalar_encoders_round_trip")

    uid = uuid.UUID("12345678-1234-5678-1234-567812345678")
    created = datetime.datetime(2020, 1, 2, 3, 4, 5)
    day = datetime.date(2020, 1, 2)
    moment = datetime.time(3, 4, 5)
    _rows.append(
        EncoderDoc(
            id="1",
            uid=uid,
            price=decimal.Decimal("3.50"),
            created=created,
            day=day,
            moment=moment,
            elapsed=datetime.timedelta(hours=1),
            blob=b"hello",
            embedding=_EMB,
        )
    )
    app.update_blocking()

    fields = fetch_doc(conn, "test_enc", "1").fields
    assert fields["uid"] == str(uid)
    assert fields["price"] == "3.50"
    assert fields["created"] == created.isoformat()
    assert fields["day"] == day.isoformat()
    assert fields["moment"] == moment.isoformat()
    assert fields["elapsed"] == pytest.approx(3600.0)
    assert fields["blob"] == "aGVsbG8="  # base64 of b"hello"


def test_array_fields_round_trip(conn: Any) -> None:
    _reset(ArrayDoc, "test_arr")
    app = _make_app(conn, "test_array_fields_round_trip")

    _rows.append(
        ArrayDoc(
            id="1",
            ints=[1, 2, 3],
            floats=[1.5, 2.5],
            flags=[True, False],
            embedding=_EMB,
        )
    )
    app.update_blocking()

    fields = fetch_doc(conn, "test_arr", "1").fields
    assert list(fields["ints"]) == [1, 2, 3]
    assert list(fields["floats"]) == pytest.approx([1.5, 2.5])
    assert list(fields["flags"]) == [True, False]


def test_json_fallback_round_trip(conn: Any) -> None:
    _reset(JsonDoc, "test_json")
    app = _make_app(conn, "test_json_fallback_round_trip")

    _rows.append(JsonDoc(id="1", meta={"a": 1, "b": 2}, embedding=_EMB))
    app.update_blocking()

    import json

    raw = fetch_doc(conn, "test_json", "1").fields["meta"]
    assert json.loads(raw) == {"a": 1, "b": 2}


def test_filter_query(conn: Any) -> None:
    _reset(FilterDoc, "test_filter")
    app = _make_app(conn, "test_filter_query")

    _rows.extend(
        [
            FilterDoc(id="1", year=1990, embedding=_EMB),
            FilterDoc(id="2", year=2020, embedding=_EMB),
        ]
    )
    app.update_blocking()

    col = conn.open_existing("test_filter")
    results = col.query(
        zvec.Query(field_name="embedding", vector=[0.1, 0.2, 0.3, 0.4]),
        topk=5,
        filter="year > 2000",
    )
    assert [d.id for d in results] == ["2"]


@pytest.mark.parametrize(
    ("row_type", "key", "key_type"),
    [
        (BytesKeyDoc, b"1", "bytes"),
        (AnyKeyDoc, 1, "Any"),
        (ObjectKeyDoc, 1, "Any"),
        (UnionKeyDoc, 1, "a union"),
    ],
)
def test_new_collection_rejects_ambiguous_key_type(
    conn: Any, row_type: type, key: Any, key_type: str
) -> None:
    """str() of these key types can give two keys one document id."""
    collection = f"test_key_{row_type.__name__.lower()}"
    _reset(row_type, collection)
    app = _make_app(conn, f"test_new_collection_rejects_{row_type.__name__}")

    _rows.append(row_type(id=key, embedding=_EMB))
    with pytest.raises(Exception, match=f"is typed {key_type}"):
        app.update_blocking()
    assert not conn.collection_path(collection).exists()


def test_new_collection_accepts_bool_key(conn: Any) -> None:
    """str() keeps bool keys apart ("True", "False"), so a bool key column is accepted."""
    _reset(BoolKeyDoc, "test_key_bool")
    app = _make_app(conn, "test_new_collection_accepts_bool_key")
    _rows.extend(
        [BoolKeyDoc(id=True, embedding=_EMB), BoolKeyDoc(id=False, embedding=_EMB)]
    )
    app.update_blocking()
    assert fetch_doc(conn, "test_key_bool", "True") is not None
    assert fetch_doc(conn, "test_key_bool", "False") is not None


def test_existing_collection_keeps_ambiguous_key_type(conn: Any) -> None:
    """A collection that already exists keeps accepting rows: only new ones are checked."""
    global _row_type
    _reset(StrKeyDoc, "test_key_existing")
    app = _make_app(conn, "test_existing_collection_keeps_ambiguous_key_type")
    _rows.append(StrKeyDoc(id="a", embedding=_EMB))
    app.update_blocking()

    # The key type isn't part of the collection's tracking record, so the
    # collection stays as it is.
    _row_type = UnionKeyDoc
    _rows[:] = [UnionKeyDoc(id="a", embedding=_EMB), UnionKeyDoc(id=2, embedding=_EMB)]
    app.update_blocking()
    assert fetch_doc(conn, "test_key_existing", "a") is not None
    assert fetch_doc(conn, "test_key_existing", "2") is not None