diff --git a/README.md b/README.md index 49f78bbc8..022d2dba4 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ All the database client supported | pinecone | `pip install vectordb-bench[pinecone]` | | weaviate | `pip install vectordb-bench[weaviate]` | | elastic, aliyun_elasticsearch| `pip install vectordb-bench[elastic]` | -| pgvector, pgvectorscale, pgdiskann, alloydb, vectorchord, lakebase_vector | `pip install vectordb-bench[pgvector]` | +| pgvector, pgvectorscale, pgdiskann, alloydb, vectorchord, lakebase_vector, pgsvs | `pip install vectordb-bench[pgvector]` | | pgvecto.rs | `pip install vectordb-bench[pgvecto_rs]` | | redis | `pip install vectordb-bench[redis]` | | valkey | `pip install vectordb-bench[valkey]` | diff --git a/tests/test_pgsvs.py b/tests/test_pgsvs.py new file mode 100644 index 000000000..2c8c70b1f --- /dev/null +++ b/tests/test_pgsvs.py @@ -0,0 +1,599 @@ +"""Offline tests for the PgSVS config and client layer. + +These tests do not require a live database -- the connection is mocked out +entirely. For an end-to-end test against a real SVS-enabled Postgres, build +the extension per docs/build_guide/ in the SVS-Extension-for-PostgreSQL repo +(unlike plain pgvector, there is no prebuilt "svs" Docker image to run against). + +Usage: + pytest tests/test_pgsvs.py -v +""" + +from __future__ import annotations + +import importlib +import logging +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any +from unittest.mock import MagicMock, call + +import pytest +from pydantic import ValidationError + +from vectordb_bench.backend.clients import DB +from vectordb_bench.backend.clients.api import MetricType +from vectordb_bench.backend.clients.pgsvs.config import PgSVSVamanaConfig +from vectordb_bench.backend.filter import IntFilter, non_filter + +if TYPE_CHECKING: + from vectordb_bench.backend.clients.pgsvs.pgsvs import PgSVS + +DB_CONFIG = { + "connect_config": { + "host": "localhost", + "port": 5432, + "dbname": "vectordb", + "user": "vectordb", + "password": "super-secret-pw", + }, + "table_name": "test_pgsvs", +} + +DIM = 8 + + +# -- Helpers ------------------------------------------------------------------ + + +def make_config(**overrides) -> PgSVSVamanaConfig: + values = {"metric_type": MetricType.COSINE} + values.update(overrides) + return PgSVSVamanaConfig(**values) + + +def pgsvs_client_cls(): + pytest.importorskip("psycopg") + pytest.importorskip("pgvector") + from vectordb_bench.backend.clients.pgsvs.pgsvs import PgSVS # noqa: PLC0415 + + return PgSVS + + +def patch_sql_rendering(monkeypatch: pytest.MonkeyPatch): + """Let sql.Composed.as_string() work without a real psycopg connection.""" + client_cls = pgsvs_client_cls() + client_module = importlib.import_module(client_cls.__module__) + original_as_string = client_module.sql.Composed.as_string + monkeypatch.setattr( + client_module.sql.Composed, + "as_string", + lambda composed, _context=None: original_as_string(composed), + ) + return original_as_string + + +def make_db( + table_name: str = "test_pgsvs", + drop_old: bool = True, + *, + case_config: PgSVSVamanaConfig | None = None, + with_scalar_labels: bool = False, +) -> PgSVS: + config = dict(DB_CONFIG) + config["connect_config"] = dict(DB_CONFIG["connect_config"]) + config["table_name"] = table_name + return DB.PgSVS.init_cls( + dim=DIM, + db_config=config, + db_case_config=case_config or make_config(), + drop_old=drop_old, + with_scalar_labels=with_scalar_labels, + ) + + +def _default_execute_side_effect(query: Any, *_args: Any, **_kwargs: Any) -> MagicMock: + """pg_extension probe succeeds; anything else (e.g. the reuse-check query) + reports "nothing found" by default, so drop_old=False skips cleanly unless + a test overrides this to simulate a specific existing index.""" + result = MagicMock() + if isinstance(query, str) and "pg_extension" in query: + result.fetchone.return_value = (1,) + else: + result.fetchone.return_value = None + result.fetchall.return_value = [] + return result + + +def existing_index_side_effect(row: tuple[str, str, str, list[str]]): + """cursor.execute side_effect simulating a specific pre-existing index row + for _validate_existing_index's catalog query, while still passing the + pg_extension probe.""" + + def side_effect(query: Any, *_args: Any, **_kwargs: Any) -> MagicMock: + result = MagicMock() + if isinstance(query, str) and "pg_extension" in query: + result.fetchone.return_value = (1,) + else: + result.fetchone.return_value = row + return result + + return side_effect + + +@pytest.fixture +def mocked_db_connection(monkeypatch: pytest.MonkeyPatch) -> tuple[MagicMock, MagicMock]: + client_cls = pgsvs_client_cls() + conn = MagicMock(name="connection") + cursor = MagicMock(name="cursor") + cursor.execute.side_effect = _default_execute_side_effect + monkeypatch.setattr(client_cls, "_create_connection", staticmethod(lambda **_kwargs: (conn, cursor))) + return conn, cursor + + +@contextmanager +def capture_logger(name: str, caplog: pytest.LogCaptureFixture): + """caplog relies on propagation to the root logger, but importing + vectordb_bench runs log_util.init(), which sets propagate=False on the + "vectordb_bench" logger tree -- so attach caplog's handler directly.""" + logger = logging.getLogger(name) + logger.addHandler(caplog.handler) + previous_level = logger.level + logger.setLevel(logging.INFO) + try: + yield + finally: + logger.removeHandler(caplog.handler) + logger.setLevel(previous_level) + + +def rendered_executed_sql(cursor: MagicMock) -> list[str]: + """Render every statement passed to cursor.execute() as text, skipping + bare strings (e.g. the pg_extension probe) which render as-is.""" + rendered = [] + for execute_call in cursor.execute.call_args_list: + stmt = execute_call.args[0] + rendered.append(stmt if isinstance(stmt, str) else stmt.as_string()) + return rendered + + +# -- Config validation: bounds and discrete values --------------------------- + + +class TestPgSVSConfigBounds: + @pytest.mark.parametrize("value", ["bit"]) + @pytest.mark.parametrize("field", ["quantization_type", "table_quantization_type"]) + def test_rejects_bit_quantization(self, field: str, value: str) -> None: + with pytest.raises(ValidationError, match="is not supported for svs"): + make_config(**{field: value}) + + @pytest.mark.parametrize("value", ["none", "halfvec", None]) + @pytest.mark.parametrize("field", ["quantization_type", "table_quantization_type"]) + def test_accepts_non_bit_quantization(self, field: str, value: str | None) -> None: + make_config(**{field: value}) # must not raise + + @pytest.mark.parametrize("value", [16, 256, 100]) + def test_graph_degree_in_range(self, value: int) -> None: + make_config(graph_degree=value) + + @pytest.mark.parametrize("value", [15, 257, 0, -1]) + def test_graph_degree_out_of_range(self, value: int) -> None: + with pytest.raises(ValidationError, match="graph_degree"): + make_config(graph_degree=value) + + @pytest.mark.parametrize("value", [-1, 0, 200]) + def test_alpha_in_range(self, value: int) -> None: + make_config(alpha=value) + + @pytest.mark.parametrize("value", [-2, 201]) + def test_alpha_out_of_range(self, value: int) -> None: + with pytest.raises(ValidationError, match="alpha"): + make_config(alpha=value) + + @pytest.mark.parametrize("value", [-1, 0, 1000]) + def test_build_window_size_in_range(self, value: int) -> None: + make_config(build_window_size=value) + + @pytest.mark.parametrize("value", [-2, 1001]) + def test_build_window_size_out_of_range(self, value: int) -> None: + with pytest.raises(ValidationError, match="build_window_size"): + make_config(build_window_size=value) + + @pytest.mark.parametrize("value", [10, 10000]) + def test_search_window_size_in_range(self, value: int) -> None: + make_config(search_window_size=value) + + @pytest.mark.parametrize("value", [9, 10001, -1]) + def test_search_window_size_out_of_range(self, value: int) -> None: + with pytest.raises(ValidationError, match="search_window_size"): + make_config(search_window_size=value) + + @pytest.mark.parametrize("value", [-1, 0, 1, 2000]) + def test_leanvec_dims_in_range(self, value: int) -> None: + make_config(leanvec_dims=value) + + @pytest.mark.parametrize("value", [-2, 2001]) + def test_leanvec_dims_out_of_range(self, value: int) -> None: + with pytest.raises(ValidationError, match="leanvec_dims"): + make_config(leanvec_dims=value) + + @pytest.mark.parametrize("value", [0, 1, 2]) + def test_compression_type_valid(self, value: int) -> None: + make_config(compression_type=value) + + @pytest.mark.parametrize("value", [-1, 3]) + def test_compression_type_invalid(self, value: int) -> None: + with pytest.raises(ValidationError, match="compression_type"): + make_config(compression_type=value) + + @pytest.mark.parametrize("value", [-8, -4, 4, 8]) + def test_compression_primary_valid(self, value: int) -> None: + make_config(compression_primary=value) + + @pytest.mark.parametrize("value", [-6, 0, 6, 16]) + def test_compression_primary_invalid(self, value: int) -> None: + with pytest.raises(ValidationError, match="compression_primary"): + make_config(compression_primary=value) + + def test_compression_secondary_zero_requires_lvq(self): + with pytest.raises(ValidationError, match="compression_secondary"): + make_config(compression_type=1, compression_secondary=0) + + def test_compression_secondary_zero_allowed_for_lvq(self): + make_config(compression_type=2, compression_primary=8, compression_secondary=0) + + +# -- Config validation: the (primary, secondary) pair rule -- finding #6 ----- + + +class TestPgSVSCompressionPair: + @pytest.mark.parametrize(("primary", "secondary"), [(4, 4), (4, 8), (8, 8), (-8, -8), (-8, 8)]) + def test_leanvec_supported_pairs(self, primary: int, secondary: int) -> None: + make_config(compression_type=1, compression_primary=primary, compression_secondary=secondary) + + @pytest.mark.parametrize(("primary", "secondary"), [(8, 4), (8, -4)]) + def test_leanvec_unsupported_pairs(self, primary: int, secondary: int) -> None: + with pytest.raises(ValidationError, match="LeanVec pairing"): + make_config(compression_type=1, compression_primary=primary, compression_secondary=secondary) + + @pytest.mark.parametrize(("primary", "secondary"), [(4, 0), (8, 0), (4, 4), (4, 8), (-4, 0), (-8, 0)]) + def test_lvq_supported_pairs(self, primary: int, secondary: int) -> None: + make_config(compression_type=2, compression_primary=primary, compression_secondary=secondary) + + @pytest.mark.parametrize(("primary", "secondary"), [(8, 4), (8, 8), (-8, -8), (-8, 4)]) + def test_lvq_unsupported_pairs(self, primary: int, secondary: int) -> None: + with pytest.raises(ValidationError, match="LVQ pairing"): + make_config(compression_type=2, compression_primary=primary, compression_secondary=secondary) + + def test_pair_rule_skipped_when_compression_disabled(self): + # compression_type=0/None: primary=8/secondary=4 would be an invalid LeanVec + # pairing, but with compression off the pair rule shouldn't even apply. + make_config(compression_type=None, compression_primary=8, compression_secondary=4) + + def test_ui_default_pair_valid_under_both_schemes(self): + # The Streamlit widgets' first (default) option is (4, 8); must be valid + # for whichever scheme the user then picks. + make_config(compression_type=1, compression_primary=4, compression_secondary=8) + make_config(compression_type=2, compression_primary=4, compression_secondary=8) + + +# -- Config behavior: metric/quantization resolution ------------------------- + + +class TestPgSVSConfigBehavior: + @pytest.mark.parametrize( + ("metric_type", "quantization_type", "expected"), + [ + (MetricType.L2, None, "vector_l2_ops"), + (MetricType.IP, None, "vector_ip_ops"), + (MetricType.COSINE, None, "vector_cosine_ops"), + (MetricType.L2, "halfvec", "halfvec_l2_ops"), + (MetricType.IP, "halfvec", "halfvec_ip_ops"), + (MetricType.COSINE, "halfvec", "halfvec_cosine_ops"), + ], + ) + def test_index_param_metric_resolution( + self, + metric_type: MetricType, + quantization_type: str | None, + expected: str, + ) -> None: + cfg = make_config(metric_type=metric_type, quantization_type=quantization_type) + assert cfg.index_param()["metric"] == expected + + def test_index_param_normalizes_none_quantization_to_vector(self): + cfg = make_config(quantization_type=None, table_quantization_type=None) + params = cfg.index_param() + assert params["quantization_type"] == "vector" + assert params["table_quantization_type"] == "vector" + + def test_normalize_cosine_switches_effective_metric_to_l2(self): + normalized = make_config(metric_type=MetricType.COSINE, normalize_cosine=True) + plain = make_config(metric_type=MetricType.COSINE, normalize_cosine=False) + assert normalized.index_param()["metric"] == "vector_l2_ops" + assert plain.index_param()["metric"] == "vector_cosine_ops" + + def test_normalize_cosine_is_a_no_op_for_other_metrics(self): + cfg = make_config(metric_type=MetricType.L2, normalize_cosine=True) + assert cfg.index_param()["metric"] == "vector_l2_ops" + + def test_search_param_has_no_reranking_or_search_history_fields(self): + # Regression guard: reranking/quantized_fetch_limit/reranking_metric were + # removed as always-dead for svs, and use_search_history is build-time only. + cfg = make_config(search_window_size=200, use_search_history=True) + assert cfg.search_param() == {"metric_fun_op": "<=>", "search_window_size": 200} + + def test_session_param_emits_search_window_size(self): + cfg = make_config(search_window_size=150) + opts = cfg.session_param()["session_options"] + assert opts == [{"parameter": {"setting_name": "svs.search_window_size", "val": "150"}}] + + def test_session_param_empty_when_search_window_size_unset(self): + cfg = make_config(search_window_size=None) + assert cfg.session_param()["session_options"] == [] + + def test_index_param_includes_build_time_options(self): + cfg = make_config(graph_degree=32, alpha=-1, compression_type=1, compression_primary=4, compression_secondary=8) + names = {opt["option_name"]: opt["val"] for opt in cfg.index_param()["index_creation_with_options"]} + assert names["graph_degree"] == "32" + assert names["alpha"] == "-1" + assert names["compression_type"] == "1" + assert names["compression_primary"] == "4" + assert names["compression_secondary"] == "8" + # search_window_size is deliberately not a build-time option (session-only) + assert "search_window_size" not in names + + +# -- Client: password logging -- finding #1 ---------------------------------- + + +class TestPgSVSClientLogging: + def test_connection_password_is_redacted( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + caplog: pytest.LogCaptureFixture, + ): + with capture_logger("vectordb_bench.backend.clients.pgsvs.pgsvs", caplog): + make_db("test_redact", drop_old=False) + + assert DB_CONFIG["connect_config"]["password"] not in caplog.text + assert "localhost" in caplog.text # non-sensitive fields still get logged + + +# -- Client: index naming -- finding #2 --------------------------------------- + + +class TestPgSVSClientIndexName: + @pytest.mark.parametrize("table_name", ["table_a", "table_b"]) + def test_index_name_is_table_scoped( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + table_name: str, + ) -> None: + db = make_db(table_name, drop_old=False) + assert db._index_name == f"{table_name}_svs_index" + + def test_two_tables_get_distinct_index_names(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db_a = make_db("table_a", drop_old=False) + db_b = make_db("table_b", drop_old=False) + assert db_a._index_name != db_b._index_name + + def test_drop_old_does_not_issue_a_separate_drop_index( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + monkeypatch: pytest.MonkeyPatch, + ) -> None: + patch_sql_rendering(monkeypatch) + _conn, cursor = mocked_db_connection + + make_db("test_drop_old", drop_old=True) + + statements = rendered_executed_sql(cursor) + assert not any("DROP INDEX" in s for s in statements) + assert any("DROP TABLE" in s for s in statements) + + +# -- Client: search_window_size vs k -- finding #3 ---------------------------- + + +class TestPgSVSClientSearchWindow: + def _db_for_search( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + search_window_size: int | None, + ) -> PgSVS: + db = make_db( + "test_search_window", + drop_old=False, + case_config=make_config(search_window_size=search_window_size), + ) + db.conn, db.cursor = mocked_db_connection + db._search = "SELECT 1" + db.cursor.execute.return_value.fetchall.return_value = [] + return db + + def test_rejects_k_above_explicit_window(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db = self._db_for_search(mocked_db_connection, search_window_size=100) + with pytest.raises(ValueError, match="exceeds search_window_size"): + db.search_embedding(query=[0.1] * DIM, k=200) + + def test_allows_k_at_explicit_window_boundary(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db = self._db_for_search(mocked_db_connection, search_window_size=200) + db.search_embedding(query=[0.1] * DIM, k=200) # must not raise + + def test_allows_k_below_explicit_window(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db = self._db_for_search(mocked_db_connection, search_window_size=300) + db.search_embedding(query=[0.1] * DIM, k=200) # must not raise + + def test_never_rejects_when_window_unset(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db = self._db_for_search(mocked_db_connection, search_window_size=None) + db.search_embedding(query=[0.1] * DIM, k=10_000) # must not raise; left to svs's own default + + +# -- Client: reused-index validation -- finding #4 ---------------------------- + + +class TestPgSVSClientIndexReuseValidation: + def test_skips_when_no_index_exists_yet(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + make_db("fresh_table", drop_old=False) # default side_effect -> fetchone() is None; must not raise + + def test_passes_when_existing_index_matches(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + _conn, cursor = mocked_db_connection + cursor.execute.side_effect = existing_index_side_effect( + ("vamana", "vector_l2_ops", "vector(8)", ["graph_degree=32"]), + ) + make_db( + "matching_table", + drop_old=False, + case_config=make_config(metric_type=MetricType.L2, graph_degree=32), + ) # must not raise + + def test_rejects_wrong_access_method(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + _conn, cursor = mocked_db_connection + cursor.execute.side_effect = existing_index_side_effect( + ("hnsw", "vector_l2_ops", "vector(8)", []), + ) + with pytest.raises(RuntimeError, match="access_method=hnsw"): + make_db("wrong_am_table", drop_old=False, case_config=make_config(metric_type=MetricType.L2)) + + def test_rejects_wrong_operator_class(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + _conn, cursor = mocked_db_connection + cursor.execute.side_effect = existing_index_side_effect( + ("vamana", "vector_cosine_ops", "vector(8)", []), + ) + with pytest.raises(RuntimeError, match="operator_class=vector_cosine_ops"): + make_db("wrong_opc_table", drop_old=False, case_config=make_config(metric_type=MetricType.L2)) + + def test_rejects_wrong_column_type(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + _conn, cursor = mocked_db_connection + cursor.execute.side_effect = existing_index_side_effect( + ("vamana", "vector_l2_ops", "halfvec(8)", []), + ) + with pytest.raises(RuntimeError, match="column_type=halfvec"): + make_db( + "wrong_coltype_table", + drop_old=False, + case_config=make_config(metric_type=MetricType.L2, table_quantization_type=None), + ) + + def test_rejects_mismatched_reloption(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + _conn, cursor = mocked_db_connection + cursor.execute.side_effect = existing_index_side_effect( + ("vamana", "vector_l2_ops", "vector(8)", ["graph_degree=16"]), + ) + with pytest.raises(RuntimeError, match="graph_degree=16"): + make_db( + "mismatched_reloption_table", + drop_old=False, + case_config=make_config(metric_type=MetricType.L2, graph_degree=64), + ) + + +# -- Client: index-build settings stay session-scoped -- finding #5 ---------- + + +class TestPgSVSClientBuildSettings: + def test_build_settings_do_not_alter_the_role( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + monkeypatch: pytest.MonkeyPatch, + ): + patch_sql_rendering(monkeypatch) + conn, cursor = mocked_db_connection + cursor.execute.return_value.fetchall.return_value = [] + + db = make_db( + "test_build_settings", + drop_old=False, + case_config=make_config(maintenance_work_mem="512MB", max_parallel_workers=4), + ) + db.conn, db.cursor = conn, cursor + db._set_parallel_index_build_param() + + statements = rendered_executed_sql(cursor) + assert not any("ALTER USER" in s for s in statements) + assert any("SET maintenance_work_mem" in s for s in statements) + assert any("SET max_parallel_workers" in s for s in statements) + # the per-table storage parameter is legitimate and should remain + assert any("ALTER TABLE" in s and "parallel_workers" in s for s in statements) + + +# -- Client: general lifecycle coverage --------------------------------------- + + +class TestPgSVSClientLifecycle: + def test_db_is_not_thread_safe(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db = make_db("test_thread_safe", drop_old=False) + assert db.thread_safe is False + + def test_copy_for_thread_drops_the_live_connection(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + class NonDeepcopyableHandle: + def __deepcopy__(self, _memo: object) -> None: + raise TypeError("live handle cannot be deep-copied") + + db = make_db("test_copy_for_thread", drop_old=False) + live_conn = NonDeepcopyableHandle() + live_cursor = NonDeepcopyableHandle() + db.conn = live_conn + db.cursor = live_cursor + + db_copy = db.copy_for_thread() + + assert db_copy is not db + assert db_copy.conn is None + assert db_copy.cursor is None + assert db.conn is live_conn + assert db.cursor is live_cursor + assert db_copy.connect_config == db.connect_config + + def test_optimize_drops_then_recreates_the_index( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + monkeypatch: pytest.MonkeyPatch, + ) -> None: + db = make_db("test_optimize", drop_old=False) + lifecycle = MagicMock() + monkeypatch.setattr(db, "_drop_index", lifecycle.drop_index) + monkeypatch.setattr(db, "_create_index", lifecycle.create_index) + + db.optimize() + + assert lifecycle.mock_calls == [call.drop_index(), call.create_index()] + + def test_optimize_is_a_no_op_when_create_index_after_load_is_false( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + monkeypatch: pytest.MonkeyPatch, + ) -> None: + db = make_db( + "test_optimize_skip", + drop_old=False, + case_config=make_config(create_index_after_load=False, create_index_before_load=True), + ) + lifecycle = MagicMock() + monkeypatch.setattr(db, "_drop_index", lifecycle.drop_index) + monkeypatch.setattr(db, "_create_index", lifecycle.create_index) + + db.optimize() + + assert lifecycle.mock_calls == [] + + def test_prepare_filter_non_filter(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db = make_db("test_filter_none", drop_old=False) + db.prepare_filter(non_filter) + assert db.where_clause == "" + + def test_prepare_filter_num_ge(self, mocked_db_connection: tuple[MagicMock, MagicMock]) -> None: + db = make_db("test_filter_numge", drop_old=False) + db.prepare_filter(IntFilter(int_value=42, filter_rate=0.5)) + assert "id >= 42" in db.where_clause + + def test_init_raises_when_neither_create_index_flag_is_set( + self, + mocked_db_connection: tuple[MagicMock, MagicMock], + ) -> None: + with pytest.raises(RuntimeError, match="must create an index"): + make_db( + "test_no_index_flags", + drop_old=False, + case_config=make_config(create_index_before_load=False, create_index_after_load=False), + ) diff --git a/vectordb_bench/backend/clients/__init__.py b/vectordb_bench/backend/clients/__init__.py index 363490697..ba8b03657 100644 --- a/vectordb_bench/backend/clients/__init__.py +++ b/vectordb_bench/backend/clients/__init__.py @@ -38,6 +38,7 @@ class DB(Enum): PgVectoRS = "PgVectoRS" PgVectorScale = "PgVectorScale" PgDiskANN = "PgDiskANN" + PgSVS = "PgSVS" AlloyDB = "AlloyDB" LakebaseVector = "LakebaseVector" Redis = "Redis" @@ -145,6 +146,11 @@ def init_cls(self) -> type[VectorDB]: # noqa: PLR0911, PLR0912, C901, PLR0915 return PgDiskANN + if self == DB.PgSVS: + from .pgsvs.pgsvs import PgSVS + + return PgSVS + if self == DB.Redis: from .redis.redis import Redis @@ -398,6 +404,11 @@ def config_cls(self) -> type[DBConfig]: # noqa: PLR0911, PLR0912, C901, PLR0915 return PgDiskANNConfig + if self == DB.PgSVS: + from .pgsvs.config import PgSVSConfig + + return PgSVSConfig + if self == DB.Redis: from .redis.config import RedisConfig @@ -674,6 +685,11 @@ def case_config_cls( # noqa: C901, PLR0911, PLR0912, PLR0915 return _pgdiskann_case_config.get(index_type) + if self == DB.PgSVS: + from .pgsvs.config import _pgsvs_case_config + + return _pgsvs_case_config.get(index_type) + if self == DB.AlloyDB: from .alloydb.config import _alloydb_case_config diff --git a/vectordb_bench/backend/clients/api.py b/vectordb_bench/backend/clients/api.py index d2d131124..46ba3f017 100644 --- a/vectordb_bench/backend/clients/api.py +++ b/vectordb_bench/backend/clients/api.py @@ -62,6 +62,7 @@ class IndexType(StrEnum): IVF_HNSW_PQ = "IVF_HNSW_PQ" BTREE = "BTREE" NONE = "NONE" + PGSVS_VAMANA = "vamana" class SQType(StrEnum): diff --git a/vectordb_bench/backend/clients/pgsvs/cli.py b/vectordb_bench/backend/clients/pgsvs/cli.py new file mode 100644 index 000000000..75a22b939 --- /dev/null +++ b/vectordb_bench/backend/clients/pgsvs/cli.py @@ -0,0 +1,128 @@ +import os +from typing import Annotated, Unpack + +import click +from pydantic import SecretStr, ValidationError + +from vectordb_bench.backend.clients import DB + +from ....cli.cli import ( + CommonTypedDict, + SVSBaseTypedDict, + cli, + click_parameter_decorators_from_typed_dict, + get_custom_case_config, + run, +) + + +class PgSVSTypedDict(CommonTypedDict, SVSBaseTypedDict): + user_name: Annotated[ + str, + click.option("--user-name", type=str, help="Db username", required=True), + ] + password: Annotated[ + str, + click.option( + "--password", + type=str, + help="Postgres database password", + default=lambda: os.environ.get("POSTGRES_PASSWORD", ""), + show_default="$POSTGRES_PASSWORD", + ), + ] + + host: Annotated[str, click.option("--host", type=str, help="Db host", required=True)] + port: Annotated[ + int, + click.option( + "--port", + type=int, + help="Postgres database port", + default=5432, + show_default=True, + required=False, + ), + ] + db_name: Annotated[str, click.option("--db-name", type=str, help="Db name", required=True)] + maintenance_work_mem: Annotated[ + str | None, + click.option( + "--maintenance-work-mem", + type=str, + help="Sets the maximum memory to be used for maintenance operations (index creation). " + "Can be entered as string with unit like '64GB' or as an integer number of KB." + "This will set the parameters: max_parallel_maintenance_workers," + " max_parallel_workers & table(parallel_workers)", + required=False, + ), + ] + max_parallel_workers: Annotated[ + int | None, + click.option( + "--max-parallel-workers", + type=int, + help="Sets the maximum number of parallel processes per maintenance operation (index creation)", + required=False, + ), + ] + quantization_type: Annotated[ + str | None, + click.option( + "--quantization-type", + type=click.Choice(["none", "halfvec"]), + help="quantization type for vectors (in index)", + required=False, + ), + ] + table_quantization_type: Annotated[ + str | None, + click.option( + "--table-quantization-type", + type=click.Choice(["none", "halfvec"]), + help="quantization type for vectors (in table)", + required=False, + ), + ] + + +@cli.command() +@click_parameter_decorators_from_typed_dict(PgSVSTypedDict) +def PgSVS( + **parameters: Unpack[PgSVSTypedDict], +): + from .config import PgSVSConfig, PgSVSVamanaConfig + + parameters["custom_case"] = get_custom_case_config(parameters) + try: + case_config = PgSVSVamanaConfig( + graph_degree=parameters["graph_degree"], + alpha=parameters["alpha"], + search_window_size=parameters["search_window_size"], + use_search_history=parameters["use_search_history"], + build_window_size=parameters["build_window_size"], + leanvec_dims=parameters["leanvec_dims"], + compression_type=parameters["compression_type"], + compression_primary=parameters["compression_primary"], + compression_secondary=parameters["compression_secondary"], + maintenance_work_mem=parameters["maintenance_work_mem"], + max_parallel_workers=parameters["max_parallel_workers"], + normalize_cosine=parameters["normalize_cosine"], + quantization_type=parameters["quantization_type"], + table_quantization_type=parameters["table_quantization_type"], + ) + except ValidationError as e: + raise click.UsageError(str(e)) from e + run( + db=DB.PgSVS, + db_config=PgSVSConfig( + db_label=parameters["db_label"], + user_name=SecretStr(parameters["user_name"]), + password=SecretStr(parameters["password"]), + host=parameters["host"], + port=parameters["port"], + db_name=parameters["db_name"], + ), + db_case_config=case_config, + **parameters, + ) diff --git a/vectordb_bench/backend/clients/pgsvs/config.py b/vectordb_bench/backend/clients/pgsvs/config.py new file mode 100644 index 000000000..f9d730e64 --- /dev/null +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -0,0 +1,339 @@ +from abc import abstractmethod +from collections.abc import Mapping, Sequence +from typing import Any, LiteralString, TypedDict + +from pydantic import BaseModel, SecretStr, ValidationInfo, field_validator, model_validator + +from ..api import DBCaseConfig, DBConfig, IndexType, MetricType + +POSTGRE_URL_PLACEHOLDER = "postgresql://%s:%s@%s/%s" + + +class PgSVSConfigDict(TypedDict): + """These keys will be directly used as kwargs in psycopg connection string, + so the names must match exactly psycopg API""" + + user: str + password: str + host: str + port: int + dbname: str + + +class PgSVSConfig(DBConfig): + user_name: SecretStr = "postgres" + password: SecretStr + host: str = "localhost" + port: int = 5432 + db_name: str = "vectordb" + table_name: str = "vdbbench_table_test" + + def to_dict(self) -> PgSVSConfigDict: + user_str = self.user_name.get_secret_value() if isinstance(self.user_name, SecretStr) else self.user_name + pwd_str = self.password.get_secret_value() + return { + "connect_config": { + "host": self.host, + "port": self.port, + "dbname": self.db_name, + "user": user_str, + "password": pwd_str, + }, + "table_name": self.table_name, + } + + +class PgSVSIndexParam(TypedDict): + metric: str + index_type: str + index_creation_with_options: Sequence[dict[str, Any]] + maintenance_work_mem: str | None + max_parallel_workers: int | None + quantization_type: str | None + table_quantization_type: str | None + + +class PgSVSSearchParam(TypedDict): + metric_fun_op: LiteralString + search_window_size: int | None + + +class PgSVSSessionCommands(TypedDict): + session_options: Sequence[dict[str, Any]] + + +class PgSVSIndexConfig(BaseModel, DBCaseConfig): + metric_type: MetricType | None = None + create_index_before_load: bool = False + create_index_after_load: bool = True + # Scan more of the index to get enough results for filter-cases. + # Options: "strict_order" (order by distance), "relaxed_order" (slightly out of order but better recall) + # See: https://github.com/pgvector/pgvector?tab=readme-ov-file#iterative-index-scans + iterative_scan: str = "relaxed_order" + + def parse_metric(self, metric_type: MetricType | None = None) -> str: + # quantization_type can never be "bit" here (PgSVSVamanaConfig.reject_bit_quantization + # rejects it at construction time; vamana has no bit opclass). + effective_metric_type = self.metric_type if metric_type is None else metric_type + d = { + "halfvec": { + MetricType.L2: "halfvec_l2_ops", + MetricType.IP: "halfvec_ip_ops", + MetricType.COSINE: "halfvec_cosine_ops", + }, + "_fallback": { + MetricType.L2: "vector_l2_ops", + MetricType.IP: "vector_ip_ops", + MetricType.COSINE: "vector_cosine_ops", + }, + } + + if d.get(self.quantization_type) is None: + return d.get("_fallback").get(effective_metric_type) + return d.get(self.quantization_type).get(effective_metric_type) + + def parse_metric_fun_op(self, metric_type: MetricType | None = None) -> LiteralString: + effective_metric_type = self.metric_type if metric_type is None else metric_type + if effective_metric_type == MetricType.L2: + return "<->" + if effective_metric_type == MetricType.IP: + return "<#>" + return "<=>" + + def parse_metric_fun_str(self, metric_type: MetricType | None = None) -> str: + effective_metric_type = self.metric_type if metric_type is None else metric_type + if effective_metric_type == MetricType.L2: + return "l2_distance" + if effective_metric_type == MetricType.IP: + return "max_inner_product" + return "cosine_distance" + + @abstractmethod + def index_param(self) -> PgSVSIndexParam: ... + + @abstractmethod + def search_param(self) -> PgSVSSearchParam: ... + + @abstractmethod + def session_param(self) -> PgSVSSessionCommands: ... + + @staticmethod + def _optionally_build_with_options(with_options: Mapping[str, Any]) -> Sequence[dict[str, Any]]: + """Walk through mappings, creating a List of {key1 = value} pairs. That will be used to build a where clause""" + options = [] + for option_name, value in with_options.items(): + if value is not None: + options.append( + { + "option_name": option_name, + "val": str(value), + }, + ) + return options + + @staticmethod + def _optionally_build_set_options(set_mapping: Mapping[str, Any]) -> Sequence[dict[str, Any]]: + """Walk through options, creating 'SET 'key1 = "value1";' list""" + session_options = [] + for setting_name, value in set_mapping.items(): + if value: + session_options.append( + { + "parameter": { + "setting_name": setting_name, + "val": str(value), + }, + }, + ) + return session_options + + +class PgSVSVamanaConfig(PgSVSIndexConfig): + compression_type: int | None = None + compression_primary: int | None = None + compression_secondary: int | None = None + alpha: int | None = None + build_window_size: int | None = None + search_window_size: int | None = None + use_search_history: bool | None = None + graph_degree: int | None = None + leanvec_dims: int | None = None + index: IndexType = IndexType.PGSVS_VAMANA + quantization_type: str | None = None + table_quantization_type: str | None = None + maintenance_work_mem: str | None = None + max_parallel_workers: int | None = None + normalize_cosine: bool = False + + @field_validator("quantization_type", "table_quantization_type") + @classmethod + def reject_bit_quantization(cls, value: str | None, info: ValidationInfo): + # vamana has no bit opclass; CREATE INDEX would fail only after the full data load + if value == "bit": + msg = ( + f"{info.field_name}=bit is not supported for svs (vamana has no bit operator class); " + "use none or halfvec" + ) + raise ValueError(msg) + return value + + @field_validator("graph_degree") + @classmethod + def validate_graph_degree(cls, value: int | None): + # matches the vamana_relopt_kind "graph_degree" reloption bound (vamana.h VAMANA_MIN/MAX_GRAPH_DEGREE) + if value is not None and not (16 <= value <= 256): + msg = f"graph_degree={value} is out of range for svs; valid range is 16-256" + raise ValueError(msg) + return value + + @field_validator("alpha") + @classmethod + def validate_alpha(cls, value: int | None): + # matches the "alpha" reloption bound; -1 or 0 both mean "use the SVS library default" + if value is not None and not (-1 <= value <= 200): + msg = f"alpha={value} is out of range for svs; valid values are -1 (library default) or 0-200 (alpha*100)" + raise ValueError(msg) + return value + + @field_validator("build_window_size") + @classmethod + def validate_build_window_size(cls, value: int | None): + # matches the "build_window_size" reloption bound + if value is not None and not (-1 <= value <= 1000): + msg = f"build_window_size={value} is out of range for svs; valid values are -1 (2 * graph_degree) or 0-1000" + raise ValueError(msg) + return value + + @field_validator("search_window_size") + @classmethod + def validate_search_window_size(cls, value: int | None): + # matches the "search_window_size" reloption/GUC bound; unlike build_window_size there is no -1 + # sentinel here despite the reloption's description string claiming one -- Postgres's own bound + # check (VAMANA_MIN_SEARCH_WINDOW=10) would reject -1 before it ever reached that fallback. + if value is not None and not (10 <= value <= 10000): + msg = f"search_window_size={value} is out of range for svs; valid range is 10-10000" + raise ValueError(msg) + return value + + @field_validator("compression_type") + @classmethod + def validate_compression_type(cls, value: int | None): + if value is not None and value not in (0, 1, 2): + msg = f"compression_type={value} is invalid for svs; valid values are 0 (none), 1 (leanvec), 2 (lvq)" + raise ValueError(msg) + return value + + @field_validator("compression_primary") + @classmethod + def validate_compression_primary(cls, value: int | None): + # svs only accepts these four discrete codes (MapCompressionParamToSVSType in svs_wrapper.c); + # the reloption's numeric bound (-8 to 8) is wider than what's actually accepted + if value is not None and value not in (-8, -4, 4, 8): + msg = f"compression_primary={value} is invalid for svs; valid values are -8, -4, 4, 8" + raise ValueError(msg) + return value + + @field_validator("leanvec_dims") + @classmethod + def validate_leanvec_dims(cls, value: int | None): + # matches the "leanvec_dims" reloption bound + if value is not None and not (-1 <= value <= 2000): + msg = f"leanvec_dims={value} is out of range for svs; valid values are -1 (dimensions/2) or 0-2000" + raise ValueError(msg) + return value + + @model_validator(mode="after") + def validate_compression_secondary(self): + secondary = self.compression_secondary + if secondary is None: + return self + # 0 ("no residual") is only accepted for LVQ's residual slot, not LeanVec's secondary encoding + if secondary == 0 and self.compression_type == 2: + return self + if secondary not in (-8, -4, 4, 8): + msg = ( + f"compression_secondary={secondary} is invalid for svs; valid values are -8, -4, 4, 8" + " (or 0 for no residual, only when compression_type=2/lvq)" + ) + raise ValueError(msg) + return self + + @model_validator(mode="after") + def validate_compression_pair(self): + # svs compiles a fixed set of (primary, secondary) specializations per scheme; + # see docs/USER_GUIDE.md's compression table. Checked here, not just per-field, + # so an invalid pair fails before load rather than at CREATE INDEX after it. + if ( + self.compression_type not in (1, 2) + or self.compression_primary is None + or self.compression_secondary is None + ): + return self + primary = abs(self.compression_primary) + secondary = self.compression_secondary + + if self.compression_type == 1: + if primary > abs(secondary): + msg = ( + f"compression_primary={self.compression_primary}/compression_secondary={secondary} is not a " + "supported LeanVec pairing; LeanVec requires abs(compression_primary) <= " + "abs(compression_secondary) (supported: (4,4), (4,8), (8,8))" + ) + raise ValueError(msg) + elif primary == 8 and secondary != 0: + msg = ( + f"compression_primary={self.compression_primary}/compression_secondary={secondary} is not a " + "supported LVQ pairing; an 8-bit primary has no residual, so compression_secondary must be 0 " + "(supported: (4,0), (8,0), (4,4), (4,8))" + ) + raise ValueError(msg) + return self + + def _effective_metric_type(self) -> MetricType | None: + if self.normalize_cosine and self.metric_type == MetricType.COSINE: + return MetricType.L2 + return self.metric_type + + def index_param(self) -> PgSVSIndexParam: + # use_search_history is a build-time reloption only (baked into the index at CREATE INDEX); + # svs has no session-level GUC to override it at search time, unlike search_window_size. + index_parameters = { + "alpha": self.alpha, + "graph_degree": self.graph_degree, + "leanvec_dims": self.leanvec_dims, + "build_window_size": self.build_window_size, + "use_search_history": self.use_search_history, + "compression_type": self.compression_type, + "compression_primary": self.compression_primary, + "compression_secondary": self.compression_secondary, + } + if self.quantization_type == "none" or self.quantization_type is None: + self.quantization_type = "vector" + if self.table_quantization_type == "none" or self.table_quantization_type is None: + self.table_quantization_type = "vector" + effective_metric_type = self._effective_metric_type() + return { + "metric": self.parse_metric(metric_type=effective_metric_type), + "index_type": self.index.value, + "index_creation_with_options": self._optionally_build_with_options(index_parameters), + "maintenance_work_mem": self.maintenance_work_mem, + "max_parallel_workers": self.max_parallel_workers, + "quantization_type": self.quantization_type, + "table_quantization_type": self.table_quantization_type, + } + + def search_param(self) -> PgSVSSearchParam: + effective_metric_type = self._effective_metric_type() + return { + "metric_fun_op": self.parse_metric_fun_op(metric_type=effective_metric_type), + "search_window_size": self.search_window_size, + } + + def session_param(self) -> PgSVSSessionCommands: + session_parameters = {"svs.search_window_size": self.search_window_size} + return {"session_options": self._optionally_build_set_options(session_parameters)} + + +_pgsvs_case_config = { + IndexType.PGSVS_VAMANA: PgSVSVamanaConfig, +} diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py new file mode 100644 index 000000000..438506114 --- /dev/null +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -0,0 +1,527 @@ +"""Wrapper around the SVS vector database over VectorDB""" + +import logging +from collections.abc import Generator, Sequence +from contextlib import contextmanager +from copy import copy +from typing import Any + +import numpy as np +import psycopg +from pgvector import HalfVector +from pgvector.psycopg import register_vector +from psycopg import Connection, Cursor, sql + +from vectordb_bench.backend.filter import Filter, FilterOp + +from ..api import MetricType, VectorDB +from .config import PgSVSConfigDict, PgSVSIndexConfig, PgSVSVamanaConfig + +log = logging.getLogger(__name__) + + +def _safe_connect_config(connect_config: dict[str, Any]) -> dict[str, Any]: + # allow-list: only ever surfaces these named fields, so a future field added + # to connect_config can't leak into logs by default. + return {k: connect_config[k] for k in ("host", "port", "dbname", "user") if k in connect_config} + + +class PgSVS(VectorDB): + """Use psycopg instructions""" + + thread_safe: bool = False + supported_filter_types: list[FilterOp] = [ + FilterOp.NonFilter, + FilterOp.NumGE, + FilterOp.StrEqual, + ] + + conn: psycopg.Connection[Any] | None = None + cursor: psycopg.Cursor[Any] | None = None + + _search: sql.Composed + + def __init__( + self, + dim: int, + db_config: PgSVSConfigDict, + db_case_config: PgSVSIndexConfig, + drop_old: bool = False, + with_scalar_labels: bool = False, + **kwargs, + ): + self.name = "PgSVS" + self.case_config = db_case_config + self.table_name = db_config["table_name"] + self.connect_config = db_config["connect_config"] + self.dim = dim + self.with_scalar_labels = with_scalar_labels + + self._index_name = f"{self.table_name}_svs_index" + self._primary_field = "id" + self._vector_field = "embedding" + self._scalar_label_field = "label" + + # construct basic units + self.conn, self.cursor = self._create_connection(**self.connect_config) + + # svs is a superuser-only C extension; verify it's pre-installed rather than attempting CREATE + installed = self.cursor.execute("SELECT 1 FROM pg_extension WHERE extname = 'svs'").fetchone() + if not installed: + raise RuntimeError( + "Extension 'svs' is not installed. Run 'CREATE EXTENSION svs;' as a PostgreSQL superuser first." + ) + + safe_connect_config = _safe_connect_config(self.connect_config) + log.info(f"{self.name} config values: {safe_connect_config}\n{self.case_config}") + if not any( + ( + self.case_config.create_index_before_load, + self.case_config.create_index_after_load, + ), + ): + msg = ( + f"{self.name} config must create an index using create_index_before_load or create_index_after_load" + f"{self.name} config values: {safe_connect_config}\n{self.case_config}" + ) + log.error(msg) + raise RuntimeError(msg) + + if drop_old: + # DROP TABLE cascades and drops this table's own index too; no separate DROP INDEX needed. + self._drop_table() + self._create_table(dim) + if self.case_config.create_index_before_load: + self._create_index() + else: + self._validate_existing_index(dim) + + self.cursor.close() + self.conn.close() + self.cursor = None + self.conn = None + + @staticmethod + def _create_connection(**kwargs) -> tuple[Connection, Cursor]: + conn = psycopg.connect(**kwargs) + register_vector(conn) + conn.autocommit = False + cursor = conn.cursor() + + assert conn is not None, "Connection is not initialized" + assert cursor is not None, "Cursor is not initialized" + + return conn, cursor + + def copy_for_thread(self) -> "VectorDB": + # psycopg holds an open socket that can't be deep-copied; shallow-copy + # and drop the connection so init() reconnects inside the worker thread. + db_copy = copy(self) + db_copy.conn = None + db_copy.cursor = None + return db_copy + + def _generate_search_query(self) -> sql.Composed: + index_param = self.case_config.index_param() + # vamana has no bit opclass (rejected by PgSVSVamanaConfig.reject_bit_quantization), so + # quantization_type can never be "bit" here -- always the plain (non-binary_quantize) path. + column_name = sql.SQL(self._vector_field) + search_vector = sql.Placeholder() + + if index_param["quantization_type"] != index_param["table_quantization_type"]: + search_query = sql.Composed( + [ + sql.SQL( + """ + SELECT {primary_field} FROM public.{table_name} + {where_clause} ORDER BY {column_name}::{quantization_type}({dim}) + """, + ).format( + table_name=sql.Identifier(self.table_name), + primary_field=sql.Identifier(self._primary_field), + column_name=column_name, + quantization_type=sql.SQL(index_param["quantization_type"]), + dim=sql.Literal(self.dim), + where_clause=sql.SQL(self.where_clause), + ), + sql.SQL(self.case_config.search_param()["metric_fun_op"]), + sql.SQL(" {search_vector}::{quantization_type}({dim}) LIMIT %s::int").format( + search_vector=search_vector, + quantization_type=sql.SQL(index_param["quantization_type"]), + dim=sql.Literal(self.dim), + ), + ] + ) + else: + search_query = sql.Composed( + [ + sql.SQL( + "SELECT {primary_field} FROM public.{table_name} {where_clause} ORDER BY {vector_field}", + ).format( + table_name=sql.Identifier(self.table_name), + primary_field=sql.Identifier(self._primary_field), + vector_field=sql.Identifier(self._vector_field), + where_clause=sql.SQL(self.where_clause), + ), + sql.SQL(self.case_config.search_param()["metric_fun_op"]), + sql.SQL(" {search_vector}::{quantization_type}({dim}) LIMIT %s::int").format( + search_vector=search_vector, + quantization_type=sql.SQL(index_param["quantization_type"]), + dim=sql.Literal(self.dim), + ), + ] + ) + + return search_query + + @contextmanager + def init(self) -> Generator[None, None, None]: + """ + Examples: + >>> with self.init(): + >>> self.insert_embeddings() + >>> self.search_embedding() + """ + + self.conn, self.cursor = self._create_connection(**self.connect_config) + + # index configuration may have commands defined that we should set during each client session + session_options: Sequence[dict[str, Any]] = self.case_config.session_param()["session_options"] + + if len(session_options) > 0: + for setting in session_options: + command = sql.SQL("SET {setting_name} " + "= {val};").format( + setting_name=sql.Identifier(setting["parameter"]["setting_name"]), + val=sql.Identifier(str(setting["parameter"]["val"])), + ) + log.debug(command.as_string(self.cursor)) + self.cursor.execute(command) + self.conn.commit() + + try: + yield + finally: + self.cursor.close() + self.conn.close() + self.cursor = None + self.conn = None + + def _drop_table(self): + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + log.info(f"{self.name} client drop table : {self.table_name}") + + self.cursor.execute( + sql.SQL("DROP TABLE IF EXISTS public.{table_name}").format( + table_name=sql.Identifier(self.table_name), + ), + ) + self.conn.commit() + + def _validate_existing_index(self, dim: int): + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + + # to_regclass returns NULL (rather than erroring) if the table doesn't exist yet, + # which the join below then naturally turns into zero rows. + row = self.cursor.execute( + sql.SQL( + """ + SELECT am.amname, opc.opcname, format_type(att.atttypid, att.atttypmod) AS coltype, + idxc.reloptions + FROM pg_index i + JOIN pg_class idxc ON idxc.oid = i.indexrelid + JOIN pg_am am ON am.oid = idxc.relam + JOIN pg_opclass opc ON opc.oid = i.indclass[0] + JOIN pg_attribute att ON att.attrelid = i.indrelid AND att.attnum = i.indkey[0] + WHERE idxc.relname = {index_name} AND i.indrelid = to_regclass({table_name}) + """, + ).format( + index_name=sql.Literal(self._index_name), + table_name=sql.Literal(f"public.{self.table_name}"), + ), + ).fetchone() + if row is None: + # No existing index to reuse (table and/or index not created yet); it'll be + # built normally via create_index_before_load/create_index_after_load. + return + + actual_am, actual_opc, actual_coltype, actual_reloptions = row + reloptions = dict(opt.split("=", 1) for opt in (actual_reloptions or [])) + + index_param = self.case_config.index_param() + expected_coltype = f"{index_param['table_quantization_type']}({dim})" + expected_options = {opt["option_name"]: opt["val"] for opt in index_param["index_creation_with_options"]} + + mismatches = [] + if actual_am != "vamana": + mismatches.append(f"access_method={actual_am} (expected vamana)") + if actual_opc != index_param["metric"]: + mismatches.append(f"operator_class={actual_opc} (expected {index_param['metric']})") + if actual_coltype != expected_coltype: + mismatches.append(f"column_type={actual_coltype} (expected {expected_coltype})") + for option_name, expected_val in expected_options.items(): + actual_val = reloptions.get(option_name) + if actual_val != expected_val: + mismatches.append(f"{option_name}={actual_val} (expected {expected_val})") + + if mismatches: + msg = f"Existing index {self._index_name} doesn't match this run's config: {', '.join(mismatches)}" + raise RuntimeError(msg) + + def optimize(self, data_size: int | None = None): + self._post_insert() + + def _post_insert(self): + log.info(f"{self.name} post insert before optimize") + if self.case_config.create_index_after_load: + self._drop_index() + self._create_index() + + def _drop_index(self): + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + log.info(f"{self.name} client drop index : {self._index_name}") + + drop_index_sql = sql.SQL("DROP INDEX IF EXISTS {index_name}").format( + index_name=sql.Identifier(self._index_name), + ) + log.debug(drop_index_sql.as_string(self.cursor)) + self.cursor.execute(drop_index_sql) + self.conn.commit() + + def _set_parallel_index_build_param(self): + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + + index_param = self.case_config.index_param() + + if index_param["maintenance_work_mem"] is not None: + self.cursor.execute( + sql.SQL("SET maintenance_work_mem TO {};").format( + index_param["maintenance_work_mem"], + ), + ) + self.conn.commit() + + if index_param["max_parallel_workers"] is not None: + self.cursor.execute( + sql.SQL("SET max_parallel_maintenance_workers TO '{}';").format( + index_param["max_parallel_workers"], + ), + ) + self.cursor.execute( + sql.SQL("SET max_parallel_workers TO '{}';").format( + index_param["max_parallel_workers"], + ), + ) + self.cursor.execute( + sql.SQL("ALTER TABLE {} SET (parallel_workers = {});").format( + sql.Identifier(self.table_name), + index_param["max_parallel_workers"], + ), + ) + self.conn.commit() + + results = self.cursor.execute(sql.SQL("SHOW max_parallel_maintenance_workers;")).fetchall() + results.extend(self.cursor.execute(sql.SQL("SHOW max_parallel_workers;")).fetchall()) + results.extend(self.cursor.execute(sql.SQL("SHOW maintenance_work_mem;")).fetchall()) + log.info(f"{self.name} parallel index creation parameters: {results}") + + def _create_index(self): + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + log.info(f"{self.name} client create index : {self._index_name}") + + index_param = self.case_config.index_param() + self._set_parallel_index_build_param() + options = [] + for option in index_param["index_creation_with_options"]: + if option["val"] is not None: + options.append( + sql.SQL("{option_name} = {val}").format( + option_name=sql.Identifier(option["option_name"]), + val=sql.Identifier(str(option["val"])), + ), + ) + with_clause = sql.SQL("WITH ({});").format(sql.SQL(", ").join(options)) if any(options) else sql.Composed(()) + + if index_param["quantization_type"] != index_param["table_quantization_type"]: + index_create_sql = sql.SQL( + """ + CREATE INDEX IF NOT EXISTS {index_name} ON public.{table_name} + USING {index_type} (({column_name}::{quantization_type}({dim})) {embedding_metric}) + """, + ).format( + index_name=sql.Identifier(self._index_name), + table_name=sql.Identifier(self.table_name), + # vamana has no bit opclass, so quantization_type can never be "bit" here. + column_name=sql.Identifier("embedding"), + index_type=sql.Identifier(index_param["index_type"]), + # This assumes that the quantization_type value matches the quantization function name + quantization_type=sql.SQL(index_param["quantization_type"]), + dim=self.dim, + embedding_metric=sql.Identifier(index_param["metric"]), + ) + else: + index_create_sql = sql.SQL( + """ + CREATE INDEX IF NOT EXISTS {index_name} ON public.{table_name} + USING {index_type} (embedding {embedding_metric}) + """, + ).format( + index_name=sql.Identifier(self._index_name), + table_name=sql.Identifier(self.table_name), + index_type=sql.Identifier(index_param["index_type"]), + embedding_metric=sql.Identifier(index_param["metric"]), + ) + + index_create_sql_with_with_clause = (index_create_sql + with_clause).join(" ") + log.debug(index_create_sql_with_with_clause.as_string(self.cursor)) + self.cursor.execute(index_create_sql_with_with_clause) + self.conn.commit() + + def _create_table(self, dim: int): + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + + index_param = self.case_config.index_param() + + try: + log.info(f"{self.name} client create table : {self.table_name}") + + # create table + if self.with_scalar_labels: + self.cursor.execute( + sql.SQL( + """ + CREATE TABLE IF NOT EXISTS public.{table_name} + ({primary_field} BIGINT PRIMARY KEY, embedding {table_quantization_type}({dim}), {label_field} VARCHAR(64)); + """, # noqa: E501 + ).format( + table_name=sql.Identifier(self.table_name), + table_quantization_type=sql.SQL(index_param["table_quantization_type"]), + dim=dim, + primary_field=sql.Identifier(self._primary_field), + label_field=sql.Identifier(self._scalar_label_field), + ) + ) + else: + self.cursor.execute( + sql.SQL(""" + CREATE TABLE IF NOT EXISTS public.{table_name} + ({primary_field} BIGINT PRIMARY KEY, embedding {table_quantization_type}({dim})); + """).format( + table_name=sql.Identifier(self.table_name), + table_quantization_type=sql.SQL(index_param["table_quantization_type"]), + dim=dim, + primary_field=sql.Identifier(self._primary_field), + ) + ) + + self.cursor.execute( + sql.SQL( + "ALTER TABLE public.{table_name} ALTER COLUMN embedding SET STORAGE PLAIN;", + ).format(table_name=sql.Identifier(self.table_name)), + ) + self.conn.commit() + except Exception as e: + log.warning(f"Failed to create SVS table: {self.table_name} error: {e}") + raise e from None + + def need_normalize_cosine(self) -> bool: + if ( + isinstance(self.case_config, PgSVSVamanaConfig) + and self.case_config.normalize_cosine + and self.case_config.metric_type == MetricType.COSINE + ): + log.info("current SVS config enables normalization for cosine metric") + return True + return False + + def insert_embeddings( + self, + embeddings: list[list[float]], + metadata: list[int], + labels_data: list[str] | None = None, + **kwargs: Any, + ) -> tuple[int, Exception | None]: + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + if self.with_scalar_labels: + assert labels_data is not None, "labels_data should be provided if with_scalar_labels is set to True" + + index_param = self.case_config.index_param() + + try: + metadata_arr = np.array(metadata) + embeddings_arr = np.array(embeddings) + + # vamana has no bit opclass, so table_quantization_type can never be "bit" here. + with self.cursor.copy( + sql.SQL("COPY public.{table_name} FROM STDIN (FORMAT BINARY)").format( + table_name=sql.Identifier(self.table_name) + ) + ) as copy: + if index_param["table_quantization_type"] == "halfvec": + for i, row in enumerate(metadata_arr): + if self.with_scalar_labels: + copy.set_types(["bigint", "halfvec", "varchar"]) + copy.write_row((row, HalfVector(embeddings_arr[i]), labels_data[i])) + else: + copy.set_types(["bigint", "halfvec"]) + copy.write_row((row, HalfVector(embeddings_arr[i]))) + else: + for i, row in enumerate(metadata_arr): + if self.with_scalar_labels: + copy.set_types(["bigint", "vector", "varchar"]) + copy.write_row((row, embeddings_arr[i], labels_data[i])) + else: + copy.set_types(["bigint", "vector"]) + copy.write_row((row, embeddings_arr[i])) + self.conn.commit() + + return len(metadata), None + except Exception as e: + log.warning(f"Failed to insert data into SVS table ({self.table_name}), error: {e}") + return 0, e + + def prepare_filter(self, filters: Filter): + if filters.type == FilterOp.NonFilter: + self.where_clause = "" + elif filters.type == FilterOp.NumGE: + self.where_clause = f"WHERE {self._primary_field} >= {filters.int_value}" + elif filters.type == FilterOp.StrEqual: + self.where_clause = f"WHERE {self._scalar_label_field} = '{filters.label_value}'" + else: + msg = f"Not support Filter for PgSVS - {filters}" + raise ValueError(msg) + + self._search = self._generate_search_query() + + def search_embedding( + self, + query: list[float], + k: int = 100, + timeout: int | None = None, + **kwargs: Any, + ) -> list[int]: + assert self.conn is not None, "Connection is not initialized" + assert self.cursor is not None, "Cursor is not initialized" + + configured_window = self.case_config.search_window_size + if configured_window is not None and k > configured_window: + msg = ( + f"k={k} exceeds search_window_size={configured_window}; " + "search_window_size needs to be at least k for meaningful accuracy." + ) + raise ValueError(msg) + + q = np.asarray(query) + result = self.cursor.execute( + self._search, + (q, k), + prepare=True, + binary=True, + ) + return [int(i[0]) for i in result.fetchall()] diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 511a537f5..b2d45e337 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -828,6 +828,121 @@ class CommonTypedDict(TypedDict): ] +class SVSBaseTypedDict(TypedDict): + graph_degree: Annotated[ + int | None, + click.option( + "--graph_degree", + type=int, + help="Vamana graph degree (R parameter); valid range 16-256, default 64", + ), + ] + alpha: Annotated[ + int | None, + click.option( + "--alpha", + type=int, + help="Pruning alpha, encoded as alpha*100 (e.g. 120 = 1.2); " + "-1 = SVS library default; valid range -1 or 0-200", + ), + ] + compression_type: Annotated[ + int | None, + click.option( + "--compression_type", + type=int, + help="Internal vector compression: 0=none, 1=leanvec, 2=lvq; default 0", + ), + ] + compression_primary: Annotated[ + int | None, + click.option( + "--compression_primary", + type=int, + help="Primary quantization width: 4=UINT4, -4=INT4, 8=UINT8, -8=INT8", + ), + ] + compression_secondary: Annotated[ + int | None, + click.option( + "--compression_secondary", + type=int, + help="LeanVec secondary quantization / LVQ residual width: " + "4=UINT4, -4=INT4, 8=UINT8, -8=INT8, 0=no residual (LVQ only)", + ), + ] + build_window_size: Annotated[ + int | None, + click.option( + "--build_window_size", + type=int, + help="Build-time search window size; -1 = 2 * graph_degree (default)", + ), + ] + search_window_size: Annotated[ + int | None, + click.option( + "--search_window_size", + type=int, + help="Query-time search window size, applied via the svs.search_window_size session " + "setting (not forwarded to index build); valid range 10-10000, default 100 " + "(no -1-means-default sentinel here, unlike build_window_size)", + is_eager=True, + ), + ] + use_search_history: Annotated[ + bool | None, + click.option( + "--use-search-history/--skip-use-search-history", + type=bool, + default=None, + help="Maintain visited-node history during search; default true", + show_default=True, + ), + ] + leanvec_dims: Annotated[ + int | None, + click.option( + "--leanvec_dims", + type=int, + help="LeanVec reduced dimensions; -1 = dimensions/2 (default); " + "ignored unless compression_type=1 (leanvec)", + is_eager=True, + ), + ] + maintenance_work_mem: Annotated[ + str | None, + click.option( + "--maintenance-work-mem", + type=str, + help="Sets the maximum memory to be used for maintenance operations (index creation). " + "Can be entered as string with unit like '64GB' or as an integer number of KB." + "This will set the parameters: max_parallel_maintenance_workers," + " max_parallel_workers & table(parallel_workers)", + required=False, + ), + ] + max_parallel_workers: Annotated[ + int | None, + click.option( + "--max-parallel-workers", + type=int, + help="Sets the maximum number of parallel processes per maintenance operation (index creation)", + required=False, + ), + ] + normalize_cosine: Annotated[ + bool, + click.option( + "--normalize-cosine/--skip-normalize-cosine", + type=bool, + default=False, + help="Normalize vectors before insert/search when dataset metric is COSINE", + show_default=True, + ), + ] + + class HNSWBaseTypedDict(TypedDict): m: Annotated[int | None, click.option("--m", type=int, help="hnsw m")] ef_construction: Annotated[ diff --git a/vectordb_bench/cli/vectordbbench.py b/vectordb_bench/cli/vectordbbench.py index 840070c2b..156792698 100644 --- a/vectordb_bench/cli/vectordbbench.py +++ b/vectordb_bench/cli/vectordbbench.py @@ -37,6 +37,7 @@ from ..backend.clients.oceanbase.cli import OceanBaseHNSW, OceanBaseIVF from ..backend.clients.oss_opensearch.cli import OSSOpenSearch from ..backend.clients.pgdiskann.cli import PgDiskAnn +from ..backend.clients.pgsvs.cli import PgSVS from ..backend.clients.pgvecto_rs.cli import PgVectoRSHNSW, PgVectoRSIVFFlat from ..backend.clients.pgvector.cli import PgVectorHNSW from ..backend.clients.pgvectorscale.cli import PgVectorScaleDiskAnn @@ -71,6 +72,7 @@ cli.add_command(AdbpgNova) cli.add_command(PgVectorHNSW) +cli.add_command(PgSVS) cli.add_command(PolarDBPgHNSW) cli.add_command(PgVectoRSHNSW) cli.add_command(PgVectoRSIVFFlat) diff --git a/vectordb_bench/frontend/config/dbCaseConfigs.py b/vectordb_bench/frontend/config/dbCaseConfigs.py index d6eaf721e..8b9a227df 100644 --- a/vectordb_bench/frontend/config/dbCaseConfigs.py +++ b/vectordb_bench/frontend/config/dbCaseConfigs.py @@ -1687,6 +1687,171 @@ class CaseConfigInput(BaseModel): isDisplayed=lambda config: not config.get(CaseConfigParamType.graph_cache, True), ) +CaseConfigParamInput_IndexType_PgSVS = CaseConfigInput( + label=CaseConfigParamType.IndexType, + inputHelp="Select Index Type", + inputType=InputType.Option, + inputConfig={ + "options": [ + IndexType.PGSVS_VAMANA.value, + ], + }, +) + +CaseConfigParamInput_graph_degree_PgSVS = CaseConfigInput( + label=CaseConfigParamType.graph_degree, + displayLabel="Graph degree", + inputHelp="Maximum number of neighbors per graph node (reloption graph_degree)", + inputType=InputType.Number, + inputConfig={ + "min": 16, + "max": 256, + "value": 32, + }, +) + +CaseConfigParamInput_alpha_PgSVS = CaseConfigInput( + label=CaseConfigParamType.alpha, + displayLabel="Alpha", + inputHelp="Pruning alpha, encoded as alpha*100 (e.g. 120 = alpha 1.2). -1 uses the SVS library default.", + inputType=InputType.Number, + inputConfig={ + "min": -1, + "max": 200, + "value": -1, + }, +) + +CaseConfigParamInput_build_window_size_PgSVS = CaseConfigInput( + label=CaseConfigParamType.build_window_size, + displayLabel="Build window size", + inputHelp="Search window size used while building the graph. -1 uses 2 * graph_degree.", + inputType=InputType.Number, + inputConfig={ + "min": -1, + "max": 1000, + "value": -1, + }, +) + +CaseConfigParamInput_compression_type_PgSVS = CaseConfigInput( + label=CaseConfigParamType.compression_type, + displayLabel="Compression type", + inputHelp="0 = none, 1 = LeanVec, 2 = LVQ", + inputType=InputType.Option, + inputConfig={ + "options": [0, 1, 2], + }, +) + +CaseConfigParamInput_compression_primary_PgSVS = CaseConfigInput( + label=CaseConfigParamType.compression_primary, + displayLabel="Compression primary bits", + inputHelp="Primary encoding width for LeanVec/LVQ compression", + inputType=InputType.Option, + inputConfig={ + # 4 first: valid with every secondary option below, for both LeanVec and LVQ. + "options": [4, 8, -4, -8], + }, + isDisplayed=lambda config: config.get(CaseConfigParamType.compression_type, 0) in [1, 2], +) + +CaseConfigParamInput_compression_secondary_PgSVS = CaseConfigInput( + label=CaseConfigParamType.compression_secondary, + displayLabel="Compression secondary bits", + inputHelp="Secondary/residual encoding width. 0 (no residual) is only valid when compression type is LVQ.", + inputType=InputType.Option, + inputConfig={ + # 8 first: valid with the default primary=4, for both LeanVec and LVQ. + "options": [8, 4, 0, -4, -8], + }, + isDisplayed=lambda config: config.get(CaseConfigParamType.compression_type, 0) in [1, 2], +) + +CaseConfigParamInput_leanvec_dims_PgSVS = CaseConfigInput( + label=CaseConfigParamType.leanvec_dims, + displayLabel="LeanVec dimensions", + inputHelp="Reduced dimensionality for LeanVec compression. -1 uses dimensions/2.", + inputType=InputType.Number, + inputConfig={ + "min": -1, + "max": 2000, + "value": -1, + }, + isDisplayed=lambda config: config.get(CaseConfigParamType.compression_type, 0) == 1, +) + +CaseConfigParamInput_normalize_cosine_PgSVS = CaseConfigInput( + label=CaseConfigParamType.normalize_cosine, + displayLabel="Normalize for cosine", + inputType=InputType.Bool, + inputHelp="Normalize vectors and build an L2 index instead of relying on a cosine operator class", + inputConfig={ + "value": False, + }, +) + +CaseConfigParamInput_quantization_type_PgSVS = CaseConfigInput( + label=CaseConfigParamType.quantizationType, + inputType=InputType.Option, + inputConfig={ + "options": ["none", "halfvec"], + }, +) + +CaseConfigParamInput_table_quantization_type_PgSVS = CaseConfigInput( + label=CaseConfigParamType.tableQuantizationType, + inputType=InputType.Option, + inputConfig={ + "options": ["none", "halfvec"], + }, +) + +CaseConfigParamInput_use_search_history_PgSVS = CaseConfigInput( + label=CaseConfigParamType.use_search_history, + displayLabel="Use search history", + inputType=InputType.Bool, + inputHelp="Reuse visited-node history across searches; also set as the default at index build time", + inputConfig={ + "value": False, + }, +) + +CaseConfigParamInput_search_window_size_PgSVS = CaseConfigInput( + label=CaseConfigParamType.search_window_size, + displayLabel="Search window size", + inputHelp="svs.search_window_size -- search beam width; higher improves recall at the cost of latency", + inputType=InputType.Number, + inputConfig={ + "min": 10, + "max": 10000, + "value": 100, + }, +) + +CaseConfigParamInput_maintenance_work_mem_PgSVS = CaseConfigInput( + label=CaseConfigParamType.maintenance_work_mem, + inputHelp="Recommended value: 1.33x the index size, not to exceed the available free memory." + "Specify in gigabytes. e.g. 8GB", + inputType=InputType.Text, + inputConfig={ + "value": "8GB", + }, +) + +CaseConfigParamInput_max_parallel_workers_PgSVS = CaseConfigInput( + label=CaseConfigParamType.max_parallel_workers, + displayLabel="Max parallel workers", + inputHelp="Recommended value: (cpu cores - 1). This will set the parameters: max_parallel_maintenance_workers," + " max_parallel_workers & table(parallel_workers)", + inputType=InputType.Number, + inputConfig={ + "min": 0, + "max": 1024, + "value": 16, + }, +) + CaseConfigParamInput_IndexType_AlloyDB = CaseConfigInput( label=CaseConfigParamType.IndexType, @@ -2722,6 +2887,40 @@ class CaseConfigInput(BaseModel): CaseConfigParamInput_IterativeScan_PolarDBPG, ] +PgSVSLoadingConfig = [ + CaseConfigParamInput_IndexType_PgSVS, + CaseConfigParamInput_graph_degree_PgSVS, + CaseConfigParamInput_alpha_PgSVS, + CaseConfigParamInput_build_window_size_PgSVS, + CaseConfigParamInput_compression_type_PgSVS, + CaseConfigParamInput_compression_primary_PgSVS, + CaseConfigParamInput_compression_secondary_PgSVS, + CaseConfigParamInput_leanvec_dims_PgSVS, + CaseConfigParamInput_normalize_cosine_PgSVS, + CaseConfigParamInput_quantization_type_PgSVS, + CaseConfigParamInput_table_quantization_type_PgSVS, + CaseConfigParamInput_use_search_history_PgSVS, + CaseConfigParamInput_maintenance_work_mem_PgSVS, + CaseConfigParamInput_max_parallel_workers_PgSVS, +] +PgSVSPerformanceConfig = [ + CaseConfigParamInput_IndexType_PgSVS, + CaseConfigParamInput_graph_degree_PgSVS, + CaseConfigParamInput_alpha_PgSVS, + CaseConfigParamInput_build_window_size_PgSVS, + CaseConfigParamInput_compression_type_PgSVS, + CaseConfigParamInput_compression_primary_PgSVS, + CaseConfigParamInput_compression_secondary_PgSVS, + CaseConfigParamInput_leanvec_dims_PgSVS, + CaseConfigParamInput_normalize_cosine_PgSVS, + CaseConfigParamInput_quantization_type_PgSVS, + CaseConfigParamInput_table_quantization_type_PgSVS, + CaseConfigParamInput_use_search_history_PgSVS, + CaseConfigParamInput_search_window_size_PgSVS, + CaseConfigParamInput_maintenance_work_mem_PgSVS, + CaseConfigParamInput_max_parallel_workers_PgSVS, +] + PgVectoRSLoadingConfig = [ CaseConfigParamInput_IndexType_PgVectoRS, CaseConfigParamInput_m, @@ -3943,6 +4142,10 @@ class FilterType(Enum): CaseLabel.Load: PolarDBPgLoadingConfig, CaseLabel.Performance: PolarDBPgPerformanceConfig, }, + DB.PgSVS: { + CaseLabel.Load: PgSVSLoadingConfig, + CaseLabel.Performance: PgSVSPerformanceConfig, + }, DB.PgVectoRS: { CaseLabel.Load: PgVectoRSLoadingConfig, CaseLabel.Performance: PgVectoRSPerformanceConfig, diff --git a/vectordb_bench/frontend/config/styles.py b/vectordb_bench/frontend/config/styles.py index ee0e6022a..52fd731d0 100644 --- a/vectordb_bench/frontend/config/styles.py +++ b/vectordb_bench/frontend/config/styles.py @@ -49,6 +49,7 @@ def getPatternShape(i): DB.WeaviateCloud: "https://assets.zilliz.com/weaviate_4f6f171ebe.png", DB.PgVector: "https://assets.zilliz.com/PG_Vector_d464f2ef5f.png", DB.PolarDBPG: "https://assets.zilliz.com/PG_Vector_d464f2ef5f.png", + DB.PgSVS: "https://assets.zilliz.com/PG_Vector_d464f2ef5f.png", DB.PgVectoRS: "https://assets.zilliz.com/PG_Vector_d464f2ef5f.png", DB.PgVectorScale: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAQEhUQEBAWEBAQEBUXEBIVFxgRERASGhUYFhkXGBgaHiggHR0nHRYVLTEhJSkrLjouFx8/OTMsNyg5MS0BCgoKDg0OGBAQGC0eHx8wLS0tLS03KzEtNysrLS0tLSs3Ky03LSstLS0tKyswNi0rNy0tMC4tLSstLS0tLS0tLf/AABEIAMgAyAMBIgACEQEDEQH/xAAcAAEAAgIDAQAAAAAAAAAAAAAABwgBBQMEBgL/xABFEAABAwICBgUJAg0EAwAAAAABAAIDBBEFIQYHEjFBUSIyYXGBExQjQlJikaGxCMEVJDM0Q3J0gpKTorLCFlVj0VNz0v/EABoBAQACAwEAAAAAAAAAAAAAAAACBQEDBgT/xAAqEQACAgIBAwIGAgMAAAAAAAAAAQIDBBExBRIhE0EiMlFSYfCBkTShsf/aAAwDAQACEQMRAD8Ag1ERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREAWVutHtF62vds0sDpBexfbZjb3vOQUn4DqN3Oraq3OOAf5u/6Wi3Jrq+ZjRCqyrR4XqzwinGVI2V3tSkyk+By+S9FS4PTRC0VPFGPcja36BeKXVa18sdku0p3snksWVz/ACTfZHwXXqMLp5BaSnikHJzGu+oUF1aP2/7HaU4WFajE9XGE1A6VGxh9qK8JH8OS8Pjuo1hBdRVRaeEcw2m/xt3fAr0V9Spl4fgx2kIIvQaR6G1+Hk+cwOay+UrenEf3hl8V59e6MlJbT2YMIiLICIiAIiIA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zBBXKq7ardYzqBwpapxdRvd0Xb3UxJ3j3eY8R22Fhma9oexwc1wBa4G7XA5ggrn8rGlTLT4Jp7OREReUGFpdLdI4MNp3VEx3ZRsHWlfwaP8AvgmlOk1NhsJmqH2/8cY/KSu9lo+/gq0aZ6WVGKTmaY2Y24iiB6ETOQ5nmeKsMPDdr7n8phvR0dIcamrp31M7rySG/Y1vBo5ALWIsLokklpEAiIgCIiAIiIAiIgCIiA72EYpPSStnp5DFKw5Ob9DzHYVOug+t2nqQ2Gu2aafcJN0Eh7/UPfl2qvqLRfjQuWpIynouDjGFU9dA6Cdolhlb32yyc08+1Vp0+0KmwqbZdd9O8nyE1snD2XcnDkuHRnTnEMPsKecmMb4X+kiPgd3hZSGzWxQV8BpcVpHNbILOfH6RoPtgHpNI7Lrx003Y0vHxRM7TIZY8ggg2INwRvCnvVRrKFUG0Va8CoAAhlOQnGXRd7/171CuP0UMMpFNUNqYHZxSAFrtnk9rgC1wWuY8g3BsQciN4K9l9EL4aZhPRc9zQQQRcEWIO4hQPrX1amnLq2hZenNzNCP0B4ub7n07l6TVTrKFUG0Va+1SMoZTkJxu2Xe/9e9SlKW2O0Rs2zvut2qkg7cS3X6yXJTBSXqr1jOoXCkqnF1G49F291O48R7nMePfw62NGKKmk84oamEskd6SmbI1z4nHO7Wg9Ts4d26OldtQyK/K8MjwXOima5oe1wcxzbtcDdpbvuCo9021r0lGHRUpFXU2t0TeGM7uk4b+4fEKCTpHW+bik85kFM29og6zc87do7N29aleKrpkYy3N7M9xs8fxyorpTPUyGSQ7r9Vo9lo3Adi1iLCtEklpEQiIgCIiAIiIAiIgCIiAIiIAiIgCIiAIiID7Y4g3BsRuI3hck1VI/rvc7vJcuBE0gEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREB//2Q==", DB.PgDiskANN: "https://assets.zilliz.com/PG_Vector_d464f2ef5f.png", diff --git a/vectordb_bench/models.py b/vectordb_bench/models.py index a1788f5ec..bce0b126d 100644 --- a/vectordb_bench/models.py +++ b/vectordb_bench/models.py @@ -225,6 +225,17 @@ class CaseConfigParamType(Enum): scalar_index = "scalar_index" scalar_column = "scalar_column" + # PgSVS (vamana) parameters + alpha = "alpha" + compression_type = "compression_type" + compression_primary = "compression_primary" + compression_secondary = "compression_secondary" + build_window_size = "build_window_size" + search_window_size = "search_window_size" + use_search_history = "use_search_history" + leanvec_dims = "leanvec_dims" + normalize_cosine = "normalize_cosine" + class CustomizedCase(BaseModel): pass