From 8942dedd6eef8fb89dbda7c450dd9f0814786a26 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 5 Feb 2026 11:43:52 -0800 Subject: [PATCH 01/33] Initial commit of svs integration into pgvector engine --- vectordb_bench/backend/clients/api.py | 10 ++++ .../backend/clients/pgvector/cli.py | 30 ++++++++++++ .../backend/clients/pgvector/config.py | 48 ++++++++++++++++++- vectordb_bench/cli/cli.py | 12 +++++ vectordb_bench/cli/vectordbbench.py | 3 +- 5 files changed, 101 insertions(+), 2 deletions(-) diff --git a/vectordb_bench/backend/clients/api.py b/vectordb_bench/backend/clients/api.py index d2d131124..7d633b9cc 100644 --- a/vectordb_bench/backend/clients/api.py +++ b/vectordb_bench/backend/clients/api.py @@ -9,6 +9,15 @@ from vectordb_bench.backend.filter import Filter, FilterOp from vectordb_bench.backend.payload import PayloadProfile +class CompressionType(Enum): + LVQ8 = "LVQ8" + LVQ4 = "LVQ4" + LVQ4X4 = "LVQ4x4" + LVQ4X8 = "LVQ4x8" + LEANVEC_4X8 = "LeanVec4x8" + LEANVEC_8X8 = "LeanVec8x8" + NONE = "none" + class MetricType(StrEnum): L2 = "L2" @@ -62,6 +71,7 @@ class IndexType(StrEnum): IVF_HNSW_PQ = "IVF_HNSW_PQ" BTREE = "BTREE" NONE = "NONE" + SVS_VAMANA = "vamana" class SQType(StrEnum): diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index 7da41d5c6..5b743e54a 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -12,6 +12,7 @@ HNSWFlavor1, IVFFlatTypedDict, cli, + SVSBaseTypedDict, click_parameter_decorators_from_typed_dict, get_custom_case_config, run, @@ -201,3 +202,32 @@ def PgVectorHNSW( ), **parameters, ) + +class PgVectorSVSTypedDict(PgVectorTypedDict, SVSBaseTypedDict): ... + +@cli.command() +@click_parameter_decorators_from_typed_dict(PgVectorSVSTypedDict) +def PgVectorSVS( + **parameters: Unpack[PgVectorSVSTypedDict], +): + from .config import PgVectorConfig, PgVectorSVSVamanaConfig + + parameters["custom_case"] = get_custom_case_config(parameters) + run( + db=DB.PgVector, + db_config=PgVectorConfig( + 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=PgVectorSVSVamanaConfig( + graph_max_degree=parameters["graph_max_degree"], + construction_window_size=parameters["construction_window_size"], + compression=parameters["compression"], + ), + **parameters, + ) + diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index 7da238a4b..cca059fd9 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -4,7 +4,7 @@ from pydantic import BaseModel, SecretStr -from ..api import DBCaseConfig, DBConfig, IndexType, MetricType +from ..api import DBCaseConfig, DBConfig, IndexType, MetricType, CompressionType POSTGRE_URL_PLACEHOLDER = "postgresql://%s:%s@%s/%s" @@ -266,9 +266,55 @@ def session_param(self) -> PgVectorSessionCommands: session_parameters = {"hnsw.ef_search": self.ef_search, "hnsw.iterative_scan": self.iterative_scan} return {"session_options": self._optionally_build_set_options(session_parameters)} +class PgVectorSVSVamanaConfig(PgVectorIndexConfig): + compression: CompressionType | None = None + construction_window_size: int | None = None + graph_max_degree: int | None = None + index: IndexType = IndexType.SVS_VAMANA + quantization_type: str | None = None + table_quantization_type: str | None + maintenance_work_mem: str | None = None + max_parallel_workers: int | None = None + reranking: bool | None = None + quantized_fetch_limit: int | None = None + reranking_metric: str | None = None + + def index_param(self) -> PgVectorIndexParam: + "compression: self.compression.value," + index_parameters = { + "construction_window_size": self.construction_window_size, + "graph_max_degree": self.graph_max_degree} + 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" + if self.table_quantization_type == "bit": + self.quantization_type = "bit" + return { + "metric": self.parse_metric(), + "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) -> PgVectorSearchParam: + return { + "metric_fun_op": self.parse_metric_fun_op(), + "reranking": self.reranking, + "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), + "quantized_fetch_limit": self.quantized_fetch_limit, + } + + def session_param(self) -> PgVectorSessionCommands: + session_parameters = {} + return {"session_options": self._optionally_build_set_options(session_parameters)} _pgvector_case_config = { IndexType.HNSW: PgVectorHNSWConfig, IndexType.ES_HNSW: PgVectorHNSWConfig, IndexType.IVFFlat: PgVectorIVFFlatConfig, + IndexType.SVS_VAMANA: PgVectorSVSVamanaConfig, } diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 511a537f5..5e7b47549 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -827,6 +827,18 @@ class CommonTypedDict(TypedDict): ), ] +class SVSBaseTypedDict(TypedDict): + graph_max_degree: Annotated[int | None, click.option("--graph_max_degree", type=int, help="svs graph_max_degree")] + construction_window_size: Annotated[ + int | None, + click.option("--construction_window_size", type=int, help="svs construction_window_size"), + ] + compression: Annotated[ + int | None, + click.option("--compression", type=str, help="svs compression"), + ] + + class HNSWBaseTypedDict(TypedDict): m: Annotated[int | None, click.option("--m", type=int, help="hnsw m")] diff --git a/vectordb_bench/cli/vectordbbench.py b/vectordb_bench/cli/vectordbbench.py index 840070c2b..c203a1da2 100644 --- a/vectordb_bench/cli/vectordbbench.py +++ b/vectordb_bench/cli/vectordbbench.py @@ -38,7 +38,7 @@ from ..backend.clients.oss_opensearch.cli import OSSOpenSearch from ..backend.clients.pgdiskann.cli import PgDiskAnn from ..backend.clients.pgvecto_rs.cli import PgVectoRSHNSW, PgVectoRSIVFFlat -from ..backend.clients.pgvector.cli import PgVectorHNSW +from ..backend.clients.pgvector.cli import PgVectorHNSW, PgVectorSVS from ..backend.clients.pgvectorscale.cli import PgVectorScaleDiskAnn from ..backend.clients.pinecone.cli import Pinecone from ..backend.clients.pinot.cli import Pinot @@ -71,6 +71,7 @@ cli.add_command(AdbpgNova) cli.add_command(PgVectorHNSW) +cli.add_command(PgVectorSVS) cli.add_command(PolarDBPgHNSW) cli.add_command(PgVectoRSHNSW) cli.add_command(PgVectoRSIVFFlat) From f0488263671697bf9a62dea37e57e3b13394b162 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 12 Feb 2026 14:30:09 -0800 Subject: [PATCH 02/33] - Changed graph_max_degree parameter to graph_degree - Enabled alpha parameter - Enabled compression_type, compression_primary, compression_secondary parameters - Enabled search_list_size parameter Signed-off-by: Olasoji --- vectordb_bench/backend/clients/api.py | 4 ++-- .../backend/clients/pgvector/cli.py | 9 +++++--- .../backend/clients/pgvector/config.py | 21 +++++++++++------- vectordb_bench/cli/cli.py | 22 ++++++++++++++----- 4 files changed, 38 insertions(+), 18 deletions(-) diff --git a/vectordb_bench/backend/clients/api.py b/vectordb_bench/backend/clients/api.py index 7d633b9cc..03441e2da 100644 --- a/vectordb_bench/backend/clients/api.py +++ b/vectordb_bench/backend/clients/api.py @@ -9,7 +9,7 @@ from vectordb_bench.backend.filter import Filter, FilterOp from vectordb_bench.backend.payload import PayloadProfile -class CompressionType(Enum): +"""class CompressionType(Enum): LVQ8 = "LVQ8" LVQ4 = "LVQ4" LVQ4X4 = "LVQ4x4" @@ -17,7 +17,7 @@ class CompressionType(Enum): LEANVEC_4X8 = "LeanVec4x8" LEANVEC_8X8 = "LeanVec8x8" NONE = "none" - +""" class MetricType(StrEnum): L2 = "L2" diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index 5b743e54a..afad8a272 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -224,9 +224,12 @@ def PgVectorSVS( db_name=parameters["db_name"], ), db_case_config=PgVectorSVSVamanaConfig( - graph_max_degree=parameters["graph_max_degree"], - construction_window_size=parameters["construction_window_size"], - compression=parameters["compression"], + graph_degree=parameters["graph_degree"], + alpha=parameters["alpha"], + search_list_size=parameters["search_list_size"], + compression_type=parameters["compression_type"], + compression_primary=parameters["compression_primary"], + compression_secondary=parameters["compression_secondary"], ), **parameters, ) diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index cca059fd9..754a2a3bf 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -4,7 +4,7 @@ from pydantic import BaseModel, SecretStr -from ..api import DBCaseConfig, DBConfig, IndexType, MetricType, CompressionType +from ..api import DBCaseConfig, DBConfig, IndexType, MetricType POSTGRE_URL_PLACEHOLDER = "postgresql://%s:%s@%s/%s" @@ -267,9 +267,12 @@ def session_param(self) -> PgVectorSessionCommands: return {"session_options": self._optionally_build_set_options(session_parameters)} class PgVectorSVSVamanaConfig(PgVectorIndexConfig): - compression: CompressionType | None = None - construction_window_size: int | None = None - graph_max_degree: int | None = None + compression_type: int | None = None + compression_primary: int | None = None + compression_secondary: int | None = None + alpha: float | None = None + search_list_size: int | None + graph_degree: int | None = None index: IndexType = IndexType.SVS_VAMANA quantization_type: str | None = None table_quantization_type: str | None @@ -280,10 +283,12 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): reranking_metric: str | None = None def index_param(self) -> PgVectorIndexParam: - "compression: self.compression.value," index_parameters = { - "construction_window_size": self.construction_window_size, - "graph_max_degree": self.graph_max_degree} + "alpha": self.alpha, + "graph_degree": self.graph_degree, + "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: @@ -309,7 +314,7 @@ def search_param(self) -> PgVectorSearchParam: } def session_param(self) -> PgVectorSessionCommands: - session_parameters = {} + session_parameters = {"vamana.search_list_size": self.search_list_size} return {"session_options": self._optionally_build_set_options(session_parameters)} _pgvector_case_config = { diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 5e7b47549..0c1aa6d2d 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -828,14 +828,26 @@ class CommonTypedDict(TypedDict): ] class SVSBaseTypedDict(TypedDict): - graph_max_degree: Annotated[int | None, click.option("--graph_max_degree", type=int, help="svs graph_max_degree")] - construction_window_size: Annotated[ + graph_degree: Annotated[int | None, click.option("--graph_degree", type=int, help="svs graph_degree")] + alpha: Annotated[ + float | None, + click.option("--alpha", type=float, help="svs alpha"), + ] + compression_type: Annotated[ + int | None, + click.option("--compression_type", type=int, help="svs compression_type"), + ] + compression_primary: Annotated[ + int | None, + click.option("--compression_primary", type=int, help="svs compression_primary"), + ] + compression_secondary: Annotated[ int | None, - click.option("--construction_window_size", type=int, help="svs construction_window_size"), + click.option("--compression_secondary", type=int, help="svs compression_secondary"), ] - compression: Annotated[ + search_list_size: Annotated[ int | None, - click.option("--compression", type=str, help="svs compression"), + click.option("--search_list_size", type=int, help="svs search_list_size", is_eager=True), ] From 6a2dd21876f7492c2351b38302d3fc703df82d44 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 19 Feb 2026 10:10:31 -0800 Subject: [PATCH 03/33] - Fixed parameters for maintenance work mem - Renamed sarch_list_size parameter to search_window_size - Added leanvec_dims parameter Signed-off-by: Olasoji --- .../backend/clients/pgvector/cli.py | 5 +- .../backend/clients/pgvector/config.py | 6 +- vectordb_bench/cli/cli.py | 29 +- .../result_20230727_standard_pgvector.json | 247 ------------------ .../result_20230808_standard_pgvector.json | 187 ------------- 5 files changed, 35 insertions(+), 439 deletions(-) delete mode 100644 vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json delete mode 100644 vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index afad8a272..49c5b7a22 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -226,10 +226,13 @@ def PgVectorSVS( db_case_config=PgVectorSVSVamanaConfig( graph_degree=parameters["graph_degree"], alpha=parameters["alpha"], - search_list_size=parameters["search_list_size"], + search_window_size=parameters["search_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"], ), **parameters, ) diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index 754a2a3bf..cb16d5272 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -271,8 +271,9 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): compression_primary: int | None = None compression_secondary: int | None = None alpha: float | None = None - search_list_size: int | None + search_window_size: int | None graph_degree: int | None = None + leanvec_dims: int | None = None index: IndexType = IndexType.SVS_VAMANA quantization_type: str | None = None table_quantization_type: str | None @@ -286,6 +287,7 @@ def index_param(self) -> PgVectorIndexParam: index_parameters = { "alpha": self.alpha, "graph_degree": self.graph_degree, + "leanvec_dims": self.leanvec_dims, "compression_type": self.compression_type, "compression_primary": self.compression_primary, "compression_secondary": self.compression_secondary} @@ -314,7 +316,7 @@ def search_param(self) -> PgVectorSearchParam: } def session_param(self) -> PgVectorSessionCommands: - session_parameters = {"vamana.search_list_size": self.search_list_size} + session_parameters = {"vamana.search_window_size": self.search_window_size} return {"session_options": self._optionally_build_set_options(session_parameters)} _pgvector_case_config = { diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 0c1aa6d2d..2e6a5415b 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -845,9 +845,34 @@ class SVSBaseTypedDict(TypedDict): int | None, click.option("--compression_secondary", type=int, help="svs compression_secondary"), ] - search_list_size: Annotated[ + search_window_size: Annotated[ int | None, - click.option("--search_list_size", type=int, help="svs search_list_size", is_eager=True), + click.option("--search_window_size", type=int, help="svs search_window_size", is_eager=True), + ] + leanvec_dims: Annotated[ + int | None, + click.option("--leanvec_dims", type=int, help="svs leanvec_dims", 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, + ), ] diff --git a/vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json b/vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json deleted file mode 100644 index aacecb4c5..000000000 --- a/vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json +++ /dev/null @@ -1,247 +0,0 @@ -{ - "run_id": "5c1e8bd468224ffda1b39b08cdc342c3", - "task_label": "standard", - "results": [ - { - "metrics": { - "max_load_count": 0, - "load_duration": 0, - "qps": 0, - "serial_latency_p99": 0, - "recall": 0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "L2", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 1, - "custom_case": {} - } - }, - "label": "?" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 0, - "qps": 0, - "serial_latency_p99": 0, - "recall": 0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "L2", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 2, - "custom_case": {} - } - }, - "label": "?" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 10247.5034, - "qps": 10.6271, - "serial_latency_p99": 0.7307, - "recall": 0.8898 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "COSINE", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 5, - "custom_case": {} - } - }, - "label": ":)" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 10247.5034, - "qps": 10.8507, - "serial_latency_p99": 0.7332, - "recall": 0.8897 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "COSINE", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 7, - "custom_case": {} - } - }, - "label": ":)" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 10247.5034, - "qps": 75.7055, - "serial_latency_p99": 0.1212, - "recall": 0.9999 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "COSINE", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 9, - "custom_case": {} - } - }, - "label": ":)" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 0, - "qps": 0, - "serial_latency_p99": 0, - "recall": 0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "COSINE", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 4, - "custom_case": {} - } - }, - "label": "x" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 0, - "qps": 0, - "serial_latency_p99": 0, - "recall": 0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "COSINE", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 6, - "custom_case": {} - } - }, - "label": "x" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 0, - "qps": 0, - "serial_latency_p99": 0, - "recall": 0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "COSINE", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 8, - "custom_case": {} - } - }, - "label": "x" - } - ], - "file_fmt": "result_{}_{}_{}.json" -} diff --git a/vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json b/vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json deleted file mode 100644 index 2172fe5f2..000000000 --- a/vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json +++ /dev/null @@ -1,187 +0,0 @@ -{ - "run_id": "5c1e8bd468224ffda1b39b08cdc342c3", - "task_label": "standard", - "results": [ - { - "metrics": { - "max_load_count": 0, - "load_duration": 1380.9471, - "qps": 0.8836, - "serial_latency_p99": 2.523, - "recall": 0.8528 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "L2", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 10, - "custom_case": {} - } - }, - "label": ":)" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 0.0, - "qps": 0.0, - "serial_latency_p99": 0.0, - "recall": 0.0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "metric_type": "L2", - "lists": 10, - "probes": 2, - "index": "IVF_FLAT" - }, - "case_config": { - "case_id": 11, - "custom_case": {} - } - }, - "label": "?" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 1380.9471, - "qps": 0.8937, - "serial_latency_p99": 3.7202, - "recall": 0.8525 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "metric_type": "L2", - "lists": 10, - "probes": 2, - "index": "IVF_FLAT" - }, - "case_config": { - "case_id": 12, - "custom_case": {} - } - }, - "label": ":)" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 0.0, - "qps": 0.0, - "serial_latency_p99": 0.0, - "recall": 0.0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "L2", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 13, - "custom_case": {} - } - }, - "label": "?" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 1372.7522, - "qps": 1.2145, - "serial_latency_p99": 3.6224, - "recall": 0.7487 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "L2", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 14, - "custom_case": {} - } - }, - "label": ":)" - }, - { - "metrics": { - "max_load_count": 0, - "load_duration": 0.0, - "qps": 0.0, - "serial_latency_p99": 0.0, - "recall": 0.0 - }, - "task_config": { - "db": "PgVector", - "db_config": { - "db_label": "2c8g", - "user_name": "**********", - "password": "**********", - "url": "**********", - "db_name": "**********" - }, - "db_case_config": { - "index": "IVF_FLAT", - "metric_type": "L2", - "lists": 10, - "probes": 2 - }, - "case_config": { - "case_id": 15, - "custom_case": {} - } - }, - "label": "?" - } - ], - "file_fmt": "result_{}_{}_{}.json" -} From b7c4be2dc7d78f38da747b090d5995fc3f706559 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 19 Feb 2026 16:21:24 -0800 Subject: [PATCH 04/33] -Adds normalization for cosine datasets -Adds leanvec_dims and build_window_size params Signed-off-by: Olasoji --- vectordb_bench/backend/clients/pgvector/cli.py | 2 ++ .../backend/clients/pgvector/config.py | 17 +++++++++++------ .../backend/clients/pgvector/pgvector.py | 14 ++++++++++++-- vectordb_bench/cli/cli.py | 14 ++++++++++++++ 4 files changed, 39 insertions(+), 8 deletions(-) diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index 49c5b7a22..c9d457b6f 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -227,12 +227,14 @@ def PgVectorSVS( graph_degree=parameters["graph_degree"], alpha=parameters["alpha"], search_window_size=parameters["search_window_size"], + 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"], ), **parameters, ) diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index cb16d5272..fae840ff3 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -271,6 +271,7 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): compression_primary: int | None = None compression_secondary: int | None = None alpha: float | None = None + build_window_size: int | None search_window_size: int | None graph_degree: int | None = None leanvec_dims: int | None = None @@ -282,15 +283,18 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): reranking: bool | None = None quantized_fetch_limit: int | None = None reranking_metric: str | None = None + normalize_cosine: bool = False def index_param(self) -> PgVectorIndexParam: index_parameters = { - "alpha": self.alpha, - "graph_degree": self.graph_degree, - "leanvec_dims": self.leanvec_dims, - "compression_type": self.compression_type, - "compression_primary": self.compression_primary, - "compression_secondary": self.compression_secondary} + "alpha": self.alpha, + "graph_degree": self.graph_degree, + "leanvec_dims": self.leanvec_dims, + "build_window_size": self.build_window_size, + "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: @@ -313,6 +317,7 @@ def search_param(self) -> PgVectorSearchParam: "reranking": self.reranking, "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), "quantized_fetch_limit": self.quantized_fetch_limit, + "search_window_size": self.search_window_size, } def session_param(self) -> PgVectorSessionCommands: diff --git a/vectordb_bench/backend/clients/pgvector/pgvector.py b/vectordb_bench/backend/clients/pgvector/pgvector.py index c60b5d69b..685572485 100644 --- a/vectordb_bench/backend/clients/pgvector/pgvector.py +++ b/vectordb_bench/backend/clients/pgvector/pgvector.py @@ -13,8 +13,8 @@ from vectordb_bench.backend.filter import Filter, FilterOp -from ..api import VectorDB -from .config import PgVectorConfigDict, PgVectorIndexConfig +from ..api import MetricType, VectorDB +from .config import PgVectorConfigDict, PgVectorIndexConfig, PgVectorSVSVamanaConfig log = logging.getLogger(__name__) @@ -456,6 +456,16 @@ def _create_table(self, dim: int): log.warning(f"Failed to create pgvector table: {self.table_name} error: {e}") raise e from None + def need_normalize_cosine(self) -> bool: + if ( + isinstance(self.case_config, PgVectorSVSVamanaConfig) + and self.case_config.normalize_cosine + and self.case_config.metric_type == MetricType.COSINE + ): + log.info("current pgvector svs config enables normalization for cosine metric") + return True + return False + def insert_embeddings( # noqa: PLR0912 self, embeddings: list[list[float]], diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 2e6a5415b..7ba47c813 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -845,6 +845,10 @@ class SVSBaseTypedDict(TypedDict): int | None, click.option("--compression_secondary", type=int, help="svs compression_secondary"), ] + build_window_size: Annotated[ + int | None, + click.option("--build_window_size", type=int, help="svs build_window_size"), + ] search_window_size: Annotated[ int | None, click.option("--search_window_size", type=int, help="svs search_window_size", is_eager=True), @@ -874,6 +878,16 @@ class SVSBaseTypedDict(TypedDict): 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, + ), + ] From 9183ec863c110dd7523184fb069adf2df95a17cb Mon Sep 17 00:00:00 2001 From: Olasoji Date: Fri, 20 Feb 2026 14:07:50 -0800 Subject: [PATCH 05/33] - Sets metric to l2 if --normalize-cosine flag is true Signed-off-by: Olasoji --- .../backend/clients/pgvector/config.py | 34 ++++++++++++------- vectordb_bench/cli/cli.py | 4 +-- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index fae840ff3..33e927c87 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -68,7 +68,8 @@ class PgVectorIndexConfig(BaseModel, DBCaseConfig): # See: https://github.com/pgvector/pgvector?tab=readme-ov-file#iterative-index-scans iterative_scan: str = "relaxed_order" - def parse_metric(self) -> str: + def parse_metric(self, metric_type: MetricType | None = None) -> str: + effective_metric_type = self.metric_type if metric_type is None else metric_type d = { "halfvec": { MetricType.L2: "halfvec_l2_ops", @@ -87,29 +88,31 @@ def parse_metric(self) -> str: } if d.get(self.quantization_type) is None: - return d.get("_fallback").get(self.metric_type) - metric = d.get(self.quantization_type).get(self.metric_type) + return d.get("_fallback").get(effective_metric_type) + metric = d.get(self.quantization_type).get(effective_metric_type) # If using binary quantization for the index, use a bit metric # no matter what metric was selected for vector or halfvec data if self.quantization_type == "bit" and metric is None: return "bit_hamming_ops" return metric - def parse_metric_fun_op(self) -> LiteralString: + 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 self.quantization_type == "bit": - if self.metric_type == MetricType.JACCARD: + if effective_metric_type == MetricType.JACCARD: return "<%>" return "<~>" - if self.metric_type == MetricType.L2: + if effective_metric_type == MetricType.L2: return "<->" - if self.metric_type == MetricType.IP: + if effective_metric_type == MetricType.IP: return "<#>" return "<=>" - def parse_metric_fun_str(self) -> str: - if self.metric_type == MetricType.L2: + 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 self.metric_type == MetricType.IP: + if effective_metric_type == MetricType.IP: return "max_inner_product" return "cosine_distance" @@ -285,6 +288,11 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): reranking_metric: str | None = None normalize_cosine: bool = False + 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) -> PgVectorIndexParam: index_parameters = { "alpha": self.alpha, @@ -301,8 +309,9 @@ def index_param(self) -> PgVectorIndexParam: self.table_quantization_type = "vector" if self.table_quantization_type == "bit": self.quantization_type = "bit" + effective_metric_type = self._effective_metric_type() return { - "metric": self.parse_metric(), + "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, @@ -312,8 +321,9 @@ def index_param(self) -> PgVectorIndexParam: } def search_param(self) -> PgVectorSearchParam: + effective_metric_type = self._effective_metric_type() return { - "metric_fun_op": self.parse_metric_fun_op(), + "metric_fun_op": self.parse_metric_fun_op(metric_type=effective_metric_type), "reranking": self.reranking, "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), "quantized_fetch_limit": self.quantized_fetch_limit, diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 7ba47c813..d7144eedd 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -830,8 +830,8 @@ class CommonTypedDict(TypedDict): class SVSBaseTypedDict(TypedDict): graph_degree: Annotated[int | None, click.option("--graph_degree", type=int, help="svs graph_degree")] alpha: Annotated[ - float | None, - click.option("--alpha", type=float, help="svs alpha"), + int | None, + click.option("--alpha", type=int, help="svs alpha"), ] compression_type: Annotated[ int | None, From 7ffed5572f8202967af480200716b07c725940f4 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Fri, 20 Feb 2026 14:09:55 -0800 Subject: [PATCH 06/33] Fixes alpha type from float to int --- vectordb_bench/backend/clients/pgvector/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index 33e927c87..c6980182d 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -273,7 +273,7 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): compression_type: int | None = None compression_primary: int | None = None compression_secondary: int | None = None - alpha: float | None = None + alpha: int | None = None build_window_size: int | None search_window_size: int | None graph_degree: int | None = None From b8bd1636d219a9c161bd3182ee7fa1bb54ad225e Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 3 Mar 2026 10:17:17 -0800 Subject: [PATCH 07/33] Adds normalize cosine feature and flag to hnsw as with svs Signed-off-by: Olasoji --- vectordb_bench/backend/clients/pgvector/cli.py | 14 ++++++++++++-- vectordb_bench/backend/clients/pgvector/config.py | 12 ++++++++++-- .../backend/clients/pgvector/pgvector.py | 6 +++--- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index c9d457b6f..0b99e1cb3 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -166,8 +166,17 @@ def PgVectorIVFFlat( **parameters, ) - -class PgVectorHNSWTypedDict(PgVectorTypedDict, HNSWFlavor1): ... +class PgVectorHNSWTypedDict(PgVectorTypedDict, HNSWFlavor1): + 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, + ), + ] @cli.command() @@ -199,6 +208,7 @@ def PgVectorHNSW( reranking=parameters["reranking"], reranking_metric=parameters["reranking_metric"], quantized_fetch_limit=parameters["quantized_fetch_limit"], + normalize_cosine=parameters["normalize_cosine"], ), **parameters, ) diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index c6980182d..db7c882a5 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -238,6 +238,12 @@ class PgVectorHNSWConfig(PgVectorIndexConfig): reranking: bool | None = None quantized_fetch_limit: int | None = None reranking_metric: str | None = None + normalize_cosine: bool = False + + 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) -> PgVectorIndexParam: index_parameters = {"m": self.m, "ef_construction": self.ef_construction} @@ -247,8 +253,9 @@ def index_param(self) -> PgVectorIndexParam: self.table_quantization_type = "vector" if self.table_quantization_type == "bit": self.quantization_type = "bit" + effective_metric_type = self._effective_metric_type() return { - "metric": self.parse_metric(), + "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, @@ -258,8 +265,9 @@ def index_param(self) -> PgVectorIndexParam: } def search_param(self) -> PgVectorSearchParam: + effective_metric_type = self._effective_metric_type() return { - "metric_fun_op": self.parse_metric_fun_op(), + "metric_fun_op": self.parse_metric_fun_op(metric_type=effective_metric_type), "reranking": self.reranking, "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), "quantized_fetch_limit": self.quantized_fetch_limit, diff --git a/vectordb_bench/backend/clients/pgvector/pgvector.py b/vectordb_bench/backend/clients/pgvector/pgvector.py index 685572485..b9db6d7c5 100644 --- a/vectordb_bench/backend/clients/pgvector/pgvector.py +++ b/vectordb_bench/backend/clients/pgvector/pgvector.py @@ -14,7 +14,7 @@ from vectordb_bench.backend.filter import Filter, FilterOp from ..api import MetricType, VectorDB -from .config import PgVectorConfigDict, PgVectorIndexConfig, PgVectorSVSVamanaConfig +from .config import PgVectorConfigDict, PgVectorHNSWConfig, PgVectorIndexConfig, PgVectorSVSVamanaConfig log = logging.getLogger(__name__) @@ -458,11 +458,11 @@ def _create_table(self, dim: int): def need_normalize_cosine(self) -> bool: if ( - isinstance(self.case_config, PgVectorSVSVamanaConfig) + isinstance(self.case_config, (PgVectorSVSVamanaConfig, PgVectorHNSWConfig)) and self.case_config.normalize_cosine and self.case_config.metric_type == MetricType.COSINE ): - log.info("current pgvector svs config enables normalization for cosine metric") + log.info("current pgvector config enables normalization for cosine metric") return True return False From 2778ae479419a181b5a1a0ff845a36411061fac6 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 3 Mar 2026 14:14:34 -0800 Subject: [PATCH 08/33] - Adds 'use_search_history' parameter Signed-off-by: Olasoji --- vectordb_bench/backend/clients/pgvector/cli.py | 1 + .../backend/clients/pgvector/config.py | 17 ++++++++++++++++- vectordb_bench/cli/cli.py | 10 ++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index 0b99e1cb3..3c3fba576 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -237,6 +237,7 @@ def PgVectorSVS( 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"], diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index db7c882a5..1ff45a0c8 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -53,6 +53,7 @@ class PgVectorIndexParam(TypedDict): class PgVectorSearchParam(TypedDict): metric_fun_op: LiteralString + use_search_history: bool | None class PgVectorSessionCommands(TypedDict): @@ -284,6 +285,7 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): alpha: int | None = None build_window_size: int | None search_window_size: int | None + use_search_history: bool | None = None graph_degree: int | None = None leanvec_dims: int | None = None index: IndexType = IndexType.SVS_VAMANA @@ -336,11 +338,24 @@ def search_param(self) -> PgVectorSearchParam: "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), "quantized_fetch_limit": self.quantized_fetch_limit, "search_window_size": self.search_window_size, + "use_search_history": self.use_search_history, } def session_param(self) -> PgVectorSessionCommands: session_parameters = {"vamana.search_window_size": self.search_window_size} - return {"session_options": self._optionally_build_set_options(session_parameters)} + session_options = self._optionally_build_set_options(session_parameters) + + if self.use_search_history is not None: + session_options.append( + { + "parameter": { + "setting_name": "vamana.use_search_history", + "val": str(self.use_search_history).lower(), + }, + }, + ) + + return {"session_options": session_options} _pgvector_case_config = { IndexType.HNSW: PgVectorHNSWConfig, diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index d7144eedd..665019ba1 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -853,6 +853,16 @@ class SVSBaseTypedDict(TypedDict): int | None, click.option("--search_window_size", type=int, help="svs search_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="svs use_search_history", + show_default=True, + ), + ] leanvec_dims: Annotated[ int | None, click.option("--leanvec_dims", type=int, help="svs leanvec_dims", is_eager=True), From 849c1e6cfa5ccaea2d339537698a2fd7053ca63f Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 11 Aug 2026 11:24:28 -0700 Subject: [PATCH 09/33] - Updates pgvector backend to load svs extension - updates GUC names Signed-off-by: Olasoji --- .../backend/clients/pgvector/config.py | 17 +++-------------- .../backend/clients/pgvector/pgvector.py | 7 +++++-- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index 1ff45a0c8..0a8a1499e 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -309,6 +309,7 @@ def index_param(self) -> PgVectorIndexParam: "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, @@ -342,20 +343,8 @@ def search_param(self) -> PgVectorSearchParam: } def session_param(self) -> PgVectorSessionCommands: - session_parameters = {"vamana.search_window_size": self.search_window_size} - session_options = self._optionally_build_set_options(session_parameters) - - if self.use_search_history is not None: - session_options.append( - { - "parameter": { - "setting_name": "vamana.use_search_history", - "val": str(self.use_search_history).lower(), - }, - }, - ) - - return {"session_options": session_options} + session_parameters = {"svs.search_window_size": self.search_window_size} + return {"session_options": self._optionally_build_set_options(session_parameters)} _pgvector_case_config = { IndexType.HNSW: PgVectorHNSWConfig, diff --git a/vectordb_bench/backend/clients/pgvector/pgvector.py b/vectordb_bench/backend/clients/pgvector/pgvector.py index b9db6d7c5..86bd095f1 100644 --- a/vectordb_bench/backend/clients/pgvector/pgvector.py +++ b/vectordb_bench/backend/clients/pgvector/pgvector.py @@ -65,8 +65,11 @@ def __init__( # construct basic units self.conn, self.cursor = self._create_connection(**self.connect_config) - # create vector extension - self.cursor.execute("CREATE EXTENSION IF NOT EXISTS vector") + # svs extension installs vector as a dependency; plain vector installs for other index types + if isinstance(self.case_config, PgVectorSVSVamanaConfig): + self.cursor.execute("CREATE EXTENSION IF NOT EXISTS svs") + else: + self.cursor.execute("CREATE EXTENSION IF NOT EXISTS vector") self.conn.commit() redacted_connect_config = _redact_connect_config(self.connect_config) From f96b1fad429785654ab896a3607f17301d8db7db Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 11 Aug 2026 12:09:13 -0700 Subject: [PATCH 10/33] Fix SVS extension integration for standalone svs extension - pgvector.py: verify svs is pre-installed rather than attempting CREATE EXTENSION (superuser-only) - config.py: rename GUC vamana.search_window_size -> svs.search_window_size - config.py: move use_search_history from session GUC to index build option (build-time only per svs extension docs) - pyproject.toml: add setuptools_scm fallback_version for builds without .git --- pyproject.toml | 5 +++-- vectordb_bench/backend/clients/pgvector/pgvector.py | 13 ++++++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index d58b6289d..baee86734 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,6 +2,9 @@ requires = ["setuptools>=67.0", "wheel", "setuptools_scm[toml]>=6.2"] build-backend = "setuptools.build_meta" +[tool.setuptools_scm] +fallback_version = "1.0.18" + [tool.setuptools.package-data] "vectordb_bench.results" = ["*.json"] "vectordb_bench.fig.homepage" = ["*.png"] @@ -108,8 +111,6 @@ init_bench = "vectordb_bench.__main__:main" init_bench_rest = "vectordb_bench.restful.app:main" vectordbbench = "vectordb_bench.cli.vectordbbench:cli" -[tool.setuptools_scm] - [tool.black] line-length = 120 target-version = ['py311'] diff --git a/vectordb_bench/backend/clients/pgvector/pgvector.py b/vectordb_bench/backend/clients/pgvector/pgvector.py index 86bd095f1..c3345439c 100644 --- a/vectordb_bench/backend/clients/pgvector/pgvector.py +++ b/vectordb_bench/backend/clients/pgvector/pgvector.py @@ -65,12 +65,19 @@ def __init__( # construct basic units self.conn, self.cursor = self._create_connection(**self.connect_config) - # svs extension installs vector as a dependency; plain vector installs for other index types if isinstance(self.case_config, PgVectorSVSVamanaConfig): - self.cursor.execute("CREATE EXTENSION IF NOT EXISTS svs") + # 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." + ) else: self.cursor.execute("CREATE EXTENSION IF NOT EXISTS vector") - self.conn.commit() + self.conn.commit() redacted_connect_config = _redact_connect_config(self.connect_config) log.info("%s config values: %s\n%s", self.name, redacted_connect_config, self.case_config) From c71b9e0e851fe3db7781e5d711f0f07b7dcc8b4f Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 3 Nov 2026 11:56:43 -0700 Subject: [PATCH 11/33] Forward quantization params to SVS and reject unsupported combos PgVectorSVS parsed --quantization-type/--table-quantization-type but never passed them to PgVectorSVSVamanaConfig, so the flags silently had no effect. Also reject quantization_type=bit (vamana has no bit opclass) and reranking/quantized_fetch_limit (not applicable to SVS, which reranks internally via compression_secondary) with a clean UsageError instead of a confusing downstream failure. --- .../backend/clients/pgvector/cli.py | 32 ++++++++++++------- .../backend/clients/pgvector/config.py | 21 +++++++++++- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index 3c3fba576..c2ab4b185 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -2,7 +2,7 @@ from typing import Annotated, Unpack import click -from pydantic import SecretStr +from pydantic import SecretStr, ValidationError from vectordb_bench.backend.clients import DB from vectordb_bench.backend.clients.api import MetricType @@ -223,17 +223,8 @@ def PgVectorSVS( from .config import PgVectorConfig, PgVectorSVSVamanaConfig parameters["custom_case"] = get_custom_case_config(parameters) - run( - db=DB.PgVector, - db_config=PgVectorConfig( - 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=PgVectorSVSVamanaConfig( + try: + case_config = PgVectorSVSVamanaConfig( graph_degree=parameters["graph_degree"], alpha=parameters["alpha"], search_window_size=parameters["search_window_size"], @@ -246,7 +237,24 @@ def PgVectorSVS( 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"], + reranking=parameters["reranking"], + quantized_fetch_limit=parameters["quantized_fetch_limit"], + ) + except ValidationError as e: + raise click.UsageError(str(e)) from e + run( + db=DB.PgVector, + db_config=PgVectorConfig( + 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/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index 0a8a1499e..027c3730c 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -2,7 +2,7 @@ from collections.abc import Mapping, Sequence from typing import Any, LiteralString, TypedDict -from pydantic import BaseModel, SecretStr +from pydantic import BaseModel, SecretStr, root_validator, validator from ..api import DBCaseConfig, DBConfig, IndexType, MetricType @@ -298,6 +298,25 @@ class PgVectorSVSVamanaConfig(PgVectorIndexConfig): reranking_metric: str | None = None normalize_cosine: bool = False + @validator("quantization_type", "table_quantization_type") + def reject_bit_quantization(cls, value: str | None, field: Any): + # vamana has no bit opclass; CREATE INDEX would fail only after the full data load + if value == "bit": + msg = f"{field.name}=bit is not supported for svs (vamana has no bit operator class); use none or halfvec" + raise ValueError(msg) + return value + + @root_validator(skip_on_failure=True) + def reject_reranking(cls, values: dict): + # pgvector-level reranking only applies to bit indexes; svs reranks internally via compression_secondary + if values.get("reranking"): + msg = "reranking is not supported for svs; svs reranks internally via compression_secondary" + raise ValueError(msg) + if values.get("quantized_fetch_limit") is not None: + msg = "quantized_fetch_limit is not supported for svs (it only applies to bit quantization with reranking)" + raise ValueError(msg) + return values + def _effective_metric_type(self) -> MetricType | None: if self.normalize_cosine and self.metric_type == MetricType.COSINE: return MetricType.L2 From d28d6c1de113260943f694114d66fb5431d5859a Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 3 Nov 2026 11:57:50 -0700 Subject: [PATCH 12/33] Document SVS GUC encodings in CLI help and align flag naming SVS options were documented as bare placeholders ("svs alpha", "svs compression_type") with no mention of their actual encodings, ranges, or defaults (e.g. alpha is alpha*100, compression_primary/secondary are signed bit-width codes, several options use -1 as a sentinel). Spell those out, matching the level of detail already used by other engines for the same kind of encoded parameters (e.g. milvus, lancedb, cockroachdb). Also rename --use_search_history/--skip-use_search_history to --use-search-history/--skip-use-search-history for consistency with every other hyphenated flag in this file. --- vectordb_bench/cli/cli.py | 61 ++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 10 deletions(-) diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 665019ba1..b2f50a0e3 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -828,44 +828,85 @@ class CommonTypedDict(TypedDict): ] class SVSBaseTypedDict(TypedDict): - graph_degree: Annotated[int | None, click.option("--graph_degree", type=int, help="svs graph_degree")] + 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="svs alpha"), + 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="svs compression_type"), + 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="svs compression_primary"), + 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="svs compression_secondary"), + 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="svs build_window_size"), + 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="svs search_window_size", is_eager=True), + 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); -1 = 100 (default), valid range 10-10000", + is_eager=True, + ), ] use_search_history: Annotated[ bool | None, click.option( - "--use_search_history/--skip-use_search_history", + "--use-search-history/--skip-use-search-history", type=bool, default=None, - help="svs use_search_history", + help="Maintain visited-node history during search; default true", show_default=True, ), ] leanvec_dims: Annotated[ int | None, - click.option("--leanvec_dims", type=int, help="svs leanvec_dims", is_eager=True), + 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, From 776e1c4889739fc5031740bad5cc8bc870973ce9 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 3 Nov 2026 14:32:31 -0700 Subject: [PATCH 13/33] Extract SVS into a standalone PgSVS engine SVS used to be built directly into pgvector; it's now a separate Postgres extension that merely depends on pgvector. Give it its own top-level engine package (DB.PgSVS, PgSVSConfig, PgSVSVamanaConfig, pgsvs CLI command), matching the existing pattern already used for other pgvector-dependent extensions (pgvectorscale, pgdiskann, pgvecto_rs), instead of special-casing it inside the shared PgVector client. Renames the CLI command from pgvectorsvs to pgsvs. --- vectordb_bench/backend/clients/__init__.py | 16 + vectordb_bench/backend/clients/pgsvs/cli.py | 163 ++++++ .../backend/clients/pgsvs/config.py | 263 +++++++++ vectordb_bench/backend/clients/pgsvs/pgsvs.py | 546 ++++++++++++++++++ .../backend/clients/pgvector/cli.py | 47 +- .../backend/clients/pgvector/config.py | 90 +-- .../backend/clients/pgvector/pgvector.py | 19 +- vectordb_bench/cli/vectordbbench.py | 5 +- 8 files changed, 997 insertions(+), 152 deletions(-) create mode 100644 vectordb_bench/backend/clients/pgsvs/cli.py create mode 100644 vectordb_bench/backend/clients/pgsvs/config.py create mode 100644 vectordb_bench/backend/clients/pgsvs/pgsvs.py 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/pgsvs/cli.py b/vectordb_bench/backend/clients/pgsvs/cli.py new file mode 100644 index 000000000..cf4b0f97b --- /dev/null +++ b/vectordb_bench/backend/clients/pgsvs/cli.py @@ -0,0 +1,163 @@ +import os +from typing import Annotated, Unpack + +import click +from pydantic import SecretStr, ValidationError + +from vectordb_bench.backend.clients import DB +from vectordb_bench.backend.clients.api import MetricType + +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", "bit", "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", "bit", "halfvec"]), + help="quantization type for vectors (in table). " + "If equal to bit, the parameter quantization_type will be set to bit too.", + required=False, + ), + ] + reranking: Annotated[ + bool | None, + click.option( + "--reranking/--skip-reranking", + type=bool, + help="Enable reranking for HNSW search for binary quantization", + default=False, + ), + ] + reranking_metric: Annotated[ + str | None, + click.option( + "--reranking-metric", + type=click.Choice( + [metric.value for metric in MetricType if metric.value not in ["HAMMING", "JACCARD"]], + ), + help="Distance metric for reranking", + default="COSINE", + show_default=True, + ), + ] + quantized_fetch_limit: Annotated[ + int | None, + click.option( + "--quantized-fetch-limit", + type=int, + help="Limit of fetching quantized vector ranked by distance for reranking \ + -- bound by ef_search", + 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"], + reranking=parameters["reranking"], + quantized_fetch_limit=parameters["quantized_fetch_limit"], + ) + 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..722306a5e --- /dev/null +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -0,0 +1,263 @@ +from abc import abstractmethod +from collections.abc import Mapping, Sequence +from typing import Any, LiteralString, TypedDict + +from pydantic import BaseModel, SecretStr, root_validator, 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 + reranking: bool | None + reranking_metric_fun_op: LiteralString + quantized_fetch_limit: int | None + search_window_size: int | None + use_search_history: bool | 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: + 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", + }, + "bit": { + MetricType.JACCARD: "bit_jaccard_ops", + MetricType.HAMMING: "bit_hamming_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) + metric = d.get(self.quantization_type).get(effective_metric_type) + # If using binary quantization for the index, use a bit metric + # no matter what metric was selected for vector or halfvec data + if self.quantization_type == "bit" and metric is None: + return "bit_hamming_ops" + return metric + + 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 self.quantization_type == "bit": + if effective_metric_type == MetricType.JACCARD: + return "<%>" + return "<~>" + 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" + + def parse_reranking_metric_fun_op(self) -> LiteralString: + if self.reranking_metric == MetricType.L2: + return "<->" + if self.reranking_metric == MetricType.IP: + return "<#>" + return "<=>" + + @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 + search_window_size: int | None + use_search_history: bool | None = None + graph_degree: int | None = None + leanvec_dims: int | None = None + index: IndexType = IndexType.SVS_VAMANA + quantization_type: str | None = None + table_quantization_type: str | None + maintenance_work_mem: str | None = None + max_parallel_workers: int | None = None + reranking: bool | None = None + quantized_fetch_limit: int | None = None + reranking_metric: str | None = None + normalize_cosine: bool = False + + @validator("quantization_type", "table_quantization_type") + def reject_bit_quantization(cls, value: str | None, field: Any): + # vamana has no bit opclass; CREATE INDEX would fail only after the full data load + if value == "bit": + msg = f"{field.name}=bit is not supported for svs (vamana has no bit operator class); use none or halfvec" + raise ValueError(msg) + return value + + @root_validator(skip_on_failure=True) + def reject_reranking(cls, values: dict): + # pgvector-level reranking only applies to bit indexes; svs reranks internally via compression_secondary + if values.get("reranking"): + msg = "reranking is not supported for svs; svs reranks internally via compression_secondary" + raise ValueError(msg) + if values.get("quantized_fetch_limit") is not None: + msg = "quantized_fetch_limit is not supported for svs (it only applies to bit quantization with reranking)" + raise ValueError(msg) + return values + + 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: + 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" + if self.table_quantization_type == "bit": + self.quantization_type = "bit" + 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), + "reranking": self.reranking, + "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), + "quantized_fetch_limit": self.quantized_fetch_limit, + "search_window_size": self.search_window_size, + "use_search_history": self.use_search_history, + } + + 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.SVS_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..3ff635421 --- /dev/null +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -0,0 +1,546 @@ +"""Wrapper around the SVS vector database over VectorDB""" + +import logging +from collections.abc import Generator, Sequence +from contextlib import contextmanager +from typing import Any + +import numpy as np +import psycopg +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__) + + +class PgSVS(VectorDB): + """Use psycopg instructions""" + + 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 = "pgvector_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." + ) + + log.info(f"{self.name} config values: {self.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: {self.connect_config}\n{self.case_config}" + ) + log.error(msg) + raise RuntimeError(msg) + + if drop_old: + self._drop_index() + self._drop_table() + self._create_table(dim) + if self.case_config.create_index_before_load: + self._create_index() + + 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 _generate_search_query(self) -> sql.Composed: + index_param = self.case_config.index_param() + reranking = self.case_config.search_param()["reranking"] + column_name = ( + sql.SQL("binary_quantize({0})").format(sql.Identifier(self._vector_field)) + if index_param["quantization_type"] == "bit" and index_param["table_quantization_type"] != "bit" + else sql.SQL(self._vector_field) + ) + search_vector = ( + sql.SQL("binary_quantize({0})").format(sql.Placeholder()) + if index_param["quantization_type"] == "bit" + else sql.Placeholder() + ) + + # The following sections assume that the quantization_type value matches the quantization function name + if index_param["quantization_type"] != index_param["table_quantization_type"]: + # Reranking makes sense only if table quantization is not "bit" + if index_param["quantization_type"] == "bit" and reranking: + # Embeddings needs to be passed to binary_quantize function if quantization_type is bit + search_query = sql.Composed( + [ + sql.SQL( + """ + SELECT i.id + FROM ( + SELECT {primary_field}, {vector_field} {reranking_metric_fun_op} %s::{table_quantization_type} AS distance + FROM public.{table_name} {where_clause} + ORDER BY {column_name}::{quantization_type}({dim}) + """, # noqa: E501 + ).format( + table_name=sql.Identifier(self.table_name), + primary_field=sql.Identifier(self._primary_field), + vector_field=sql.Identifier(self._vector_field), + column_name=column_name, + reranking_metric_fun_op=sql.SQL( + self.case_config.search_param()["reranking_metric_fun_op"], + ), + search_vector=search_vector, + table_quantization_type=sql.SQL(index_param["table_quantization_type"]), + 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 {quantized_fetch_limit} + ) i + ORDER BY i.distance + LIMIT %s::int + """, + ).format( + search_vector=search_vector, + quantization_type=sql.SQL(index_param["quantization_type"]), + dim=sql.Literal(self.dim), + quantized_fetch_limit=sql.Literal( + self.case_config.search_param()["quantized_fetch_limit"], + ), + ), + ], + ) + else: + 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 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.cursor.execute( + sql.SQL("ALTER USER {} SET maintenance_work_mem TO {};").format( + sql.Identifier(self.connect_config["user"]), + 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("ALTER USER {} SET max_parallel_maintenance_workers TO '{}';").format( + sql.Identifier(self.connect_config["user"]), + 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 USER {} SET max_parallel_workers TO '{}';").format( + sql.Identifier(self.connect_config["user"]), + 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), + column_name=( + sql.SQL("binary_quantize({0})").format(sql.Identifier("embedding")) + if index_param["quantization_type"] == "bit" + else 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( # noqa: PLR0912 + 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) + + if index_param["table_quantization_type"] == "bit": + with self.cursor.copy( + sql.SQL("COPY public.{table_name} FROM STDIN (FORMAT TEXT)").format( + table_name=sql.Identifier(self.table_name) + ) + ) as copy: + # Same logic as pgvector binary_quantize + for i, row in enumerate(metadata_arr): + embeddings_bit = "" + for embedding in embeddings_arr[i]: + if embedding > 0: + embeddings_bit += "1" + else: + embeddings_bit += "0" + if self.with_scalar_labels: + copy.write_row((str(row), embeddings_bit, labels_data[i])) + else: + copy.write_row((str(row), embeddings_bit)) + else: + 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, np.float16(embeddings_arr[i]), labels_data[i])) + else: + copy.set_types(["bigint", "halfvec"]) + copy.write_row((row, np.float16(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" + + index_param = self.case_config.index_param() + search_param = self.case_config.search_param() + q = np.asarray(query) + result = self.cursor.execute( + self._search, + (q, q, k) if index_param["quantization_type"] == "bit" and search_param["reranking"] else (q, k), + prepare=True, + binary=True, + ) + return [int(i[0]) for i in result.fetchall()] diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index c2ab4b185..9164ce3ae 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -2,7 +2,7 @@ from typing import Annotated, Unpack import click -from pydantic import SecretStr, ValidationError +from pydantic import SecretStr from vectordb_bench.backend.clients import DB from vectordb_bench.backend.clients.api import MetricType @@ -12,7 +12,6 @@ HNSWFlavor1, IVFFlatTypedDict, cli, - SVSBaseTypedDict, click_parameter_decorators_from_typed_dict, get_custom_case_config, run, @@ -213,48 +212,4 @@ def PgVectorHNSW( **parameters, ) -class PgVectorSVSTypedDict(PgVectorTypedDict, SVSBaseTypedDict): ... - -@cli.command() -@click_parameter_decorators_from_typed_dict(PgVectorSVSTypedDict) -def PgVectorSVS( - **parameters: Unpack[PgVectorSVSTypedDict], -): - from .config import PgVectorConfig, PgVectorSVSVamanaConfig - - parameters["custom_case"] = get_custom_case_config(parameters) - try: - case_config = PgVectorSVSVamanaConfig( - 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"], - reranking=parameters["reranking"], - quantized_fetch_limit=parameters["quantized_fetch_limit"], - ) - except ValidationError as e: - raise click.UsageError(str(e)) from e - run( - db=DB.PgVector, - db_config=PgVectorConfig( - 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/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index 027c3730c..fba258b0e 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -2,7 +2,7 @@ from collections.abc import Mapping, Sequence from typing import Any, LiteralString, TypedDict -from pydantic import BaseModel, SecretStr, root_validator, validator +from pydantic import BaseModel, SecretStr from ..api import DBCaseConfig, DBConfig, IndexType, MetricType @@ -278,96 +278,8 @@ def session_param(self) -> PgVectorSessionCommands: session_parameters = {"hnsw.ef_search": self.ef_search, "hnsw.iterative_scan": self.iterative_scan} return {"session_options": self._optionally_build_set_options(session_parameters)} -class PgVectorSVSVamanaConfig(PgVectorIndexConfig): - compression_type: int | None = None - compression_primary: int | None = None - compression_secondary: int | None = None - alpha: int | None = None - build_window_size: int | None - search_window_size: int | None - use_search_history: bool | None = None - graph_degree: int | None = None - leanvec_dims: int | None = None - index: IndexType = IndexType.SVS_VAMANA - quantization_type: str | None = None - table_quantization_type: str | None - maintenance_work_mem: str | None = None - max_parallel_workers: int | None = None - reranking: bool | None = None - quantized_fetch_limit: int | None = None - reranking_metric: str | None = None - normalize_cosine: bool = False - - @validator("quantization_type", "table_quantization_type") - def reject_bit_quantization(cls, value: str | None, field: Any): - # vamana has no bit opclass; CREATE INDEX would fail only after the full data load - if value == "bit": - msg = f"{field.name}=bit is not supported for svs (vamana has no bit operator class); use none or halfvec" - raise ValueError(msg) - return value - - @root_validator(skip_on_failure=True) - def reject_reranking(cls, values: dict): - # pgvector-level reranking only applies to bit indexes; svs reranks internally via compression_secondary - if values.get("reranking"): - msg = "reranking is not supported for svs; svs reranks internally via compression_secondary" - raise ValueError(msg) - if values.get("quantized_fetch_limit") is not None: - msg = "quantized_fetch_limit is not supported for svs (it only applies to bit quantization with reranking)" - raise ValueError(msg) - return values - - 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) -> PgVectorIndexParam: - 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" - if self.table_quantization_type == "bit": - self.quantization_type = "bit" - 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) -> PgVectorSearchParam: - effective_metric_type = self._effective_metric_type() - return { - "metric_fun_op": self.parse_metric_fun_op(metric_type=effective_metric_type), - "reranking": self.reranking, - "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), - "quantized_fetch_limit": self.quantized_fetch_limit, - "search_window_size": self.search_window_size, - "use_search_history": self.use_search_history, - } - - def session_param(self) -> PgVectorSessionCommands: - session_parameters = {"svs.search_window_size": self.search_window_size} - return {"session_options": self._optionally_build_set_options(session_parameters)} - _pgvector_case_config = { IndexType.HNSW: PgVectorHNSWConfig, IndexType.ES_HNSW: PgVectorHNSWConfig, IndexType.IVFFlat: PgVectorIVFFlatConfig, - IndexType.SVS_VAMANA: PgVectorSVSVamanaConfig, } diff --git a/vectordb_bench/backend/clients/pgvector/pgvector.py b/vectordb_bench/backend/clients/pgvector/pgvector.py index c3345439c..9d69f3d24 100644 --- a/vectordb_bench/backend/clients/pgvector/pgvector.py +++ b/vectordb_bench/backend/clients/pgvector/pgvector.py @@ -14,7 +14,7 @@ from vectordb_bench.backend.filter import Filter, FilterOp from ..api import MetricType, VectorDB -from .config import PgVectorConfigDict, PgVectorHNSWConfig, PgVectorIndexConfig, PgVectorSVSVamanaConfig +from .config import PgVectorConfigDict, PgVectorHNSWConfig, PgVectorIndexConfig log = logging.getLogger(__name__) @@ -65,19 +65,8 @@ def __init__( # construct basic units self.conn, self.cursor = self._create_connection(**self.connect_config) - if isinstance(self.case_config, PgVectorSVSVamanaConfig): - # 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." - ) - else: - self.cursor.execute("CREATE EXTENSION IF NOT EXISTS vector") - self.conn.commit() + self.cursor.execute("CREATE EXTENSION IF NOT EXISTS vector") + self.conn.commit() redacted_connect_config = _redact_connect_config(self.connect_config) log.info("%s config values: %s\n%s", self.name, redacted_connect_config, self.case_config) @@ -468,7 +457,7 @@ def _create_table(self, dim: int): def need_normalize_cosine(self) -> bool: if ( - isinstance(self.case_config, (PgVectorSVSVamanaConfig, PgVectorHNSWConfig)) + isinstance(self.case_config, PgVectorHNSWConfig) and self.case_config.normalize_cosine and self.case_config.metric_type == MetricType.COSINE ): diff --git a/vectordb_bench/cli/vectordbbench.py b/vectordb_bench/cli/vectordbbench.py index c203a1da2..156792698 100644 --- a/vectordb_bench/cli/vectordbbench.py +++ b/vectordb_bench/cli/vectordbbench.py @@ -37,8 +37,9 @@ 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, PgVectorSVS +from ..backend.clients.pgvector.cli import PgVectorHNSW from ..backend.clients.pgvectorscale.cli import PgVectorScaleDiskAnn from ..backend.clients.pinecone.cli import Pinecone from ..backend.clients.pinot.cli import Pinot @@ -71,7 +72,7 @@ cli.add_command(AdbpgNova) cli.add_command(PgVectorHNSW) -cli.add_command(PgVectorSVS) +cli.add_command(PgSVS) cli.add_command(PolarDBPgHNSW) cli.add_command(PgVectoRSHNSW) cli.add_command(PgVectoRSIVFFlat) From 609c8d3f3a72cdd69b9fec7c04db02e548e649b2 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 3 Nov 2026 16:47:08 -0700 Subject: [PATCH 14/33] Validate SVS GUC values against what the extension actually accepts PgSVSVamanaConfig only validated quantization/reranking combos; graph_degree, alpha, build_window_size, search_window_size, compression_type/primary/secondary, and leanvec_dims were passed through unchecked and would only fail deep inside the SVS extension (or silently do the wrong thing). Add validators matching the real bounds/encodings from vamana.h and svs_wrapper.c's MapCompressionParamToSVSType, so bad input fails fast as a UsageError instead of a confusing CREATE INDEX error. Also fixes the search_window_size help text: unlike build_window_size, its reloption bound (vamana.c, VAMANA_MIN_SEARCH_WINDOW=10) does not actually accept a -1 sentinel, despite the extension's own reloption description string claiming "-1 = 100" -- the stated default (100) is reachable only via the compiled-in default, not a user-supplied -1. --- .../backend/clients/pgsvs/config.py | 74 +++++++++++++++++++ vectordb_bench/cli/cli.py | 3 +- 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/vectordb_bench/backend/clients/pgsvs/config.py b/vectordb_bench/backend/clients/pgsvs/config.py index 722306a5e..f84ed62be 100644 --- a/vectordb_bench/backend/clients/pgsvs/config.py +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -209,6 +209,80 @@ def reject_reranking(cls, values: dict): raise ValueError(msg) return values + @validator("graph_degree") + 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 + + @validator("alpha") + 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 + + @validator("build_window_size") + 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 + + @validator("search_window_size") + 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 + + @validator("compression_type") + 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 + + @validator("compression_primary") + 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 + + @validator("leanvec_dims") + 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 + + @root_validator(skip_on_failure=True) + def validate_compression_secondary(cls, values: dict): + secondary = values.get("compression_secondary") + if secondary is None: + return values + # 0 ("no residual") is only accepted for LVQ's residual slot, not LeanVec's secondary encoding + if secondary == 0 and values.get("compression_type") == 2: + return values + 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 values + def _effective_metric_type(self) -> MetricType | None: if self.normalize_cosine and self.metric_type == MetricType.COSINE: return MetricType.L2 diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index b2f50a0e3..97b09d976 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -884,7 +884,8 @@ class SVSBaseTypedDict(TypedDict): "--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); -1 = 100 (default), valid range 10-10000", + "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, ), ] From f2eb68338ac8856436ff7e3b9635c734c65b3c48 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 5 Nov 2026 17:15:49 -0700 Subject: [PATCH 15/33] Fix PgSVS compatibility with vectordbbench's current upstream base Two breaks surfaced after rebasing onto upstream v2.0.0: - IndexType.SVS_VAMANA collided with an enum member of the same name that upstream independently added for Milvus's own native SVS/Vamana support (milvus/config.py's SVSVamanaConfig family) -- unrelated to this Postgres-based SVS integration, just a coincidental name clash. Renamed ours to PGSVS_VAMANA; the value stays "vamana" since that's the literal Postgres access method name the generated SQL needs. - Upstream migrated the whole project to pydantic v2 (model_validator) somewhere in the 86 commits since the v1.0.18 fork point, but PgSVSVamanaConfig's validators were still pydantic v1 syntax (validator/root_validator), inherited unchanged through the extract. Migrated to field_validator/model_validator with no behavior change -- same bounds, same error messages, verified against the same boundary-value checks used when these validators were first added. --- vectordb_bench/backend/clients/api.py | 2 +- .../backend/clients/pgsvs/config.py | 61 +++++++++++-------- 2 files changed, 37 insertions(+), 26 deletions(-) diff --git a/vectordb_bench/backend/clients/api.py b/vectordb_bench/backend/clients/api.py index 03441e2da..cc701d269 100644 --- a/vectordb_bench/backend/clients/api.py +++ b/vectordb_bench/backend/clients/api.py @@ -71,7 +71,7 @@ class IndexType(StrEnum): IVF_HNSW_PQ = "IVF_HNSW_PQ" BTREE = "BTREE" NONE = "NONE" - SVS_VAMANA = "vamana" + PGSVS_VAMANA = "vamana" class SQType(StrEnum): diff --git a/vectordb_bench/backend/clients/pgsvs/config.py b/vectordb_bench/backend/clients/pgsvs/config.py index f84ed62be..cc7c7f2c0 100644 --- a/vectordb_bench/backend/clients/pgsvs/config.py +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -2,7 +2,7 @@ from collections.abc import Mapping, Sequence from typing import Any, LiteralString, TypedDict -from pydantic import BaseModel, SecretStr, root_validator, validator +from pydantic import BaseModel, SecretStr, ValidationInfo, field_validator, model_validator from ..api import DBCaseConfig, DBConfig, IndexType, MetricType @@ -180,7 +180,7 @@ class PgSVSVamanaConfig(PgSVSIndexConfig): use_search_history: bool | None = None graph_degree: int | None = None leanvec_dims: int | None = None - index: IndexType = IndexType.SVS_VAMANA + index: IndexType = IndexType.PGSVS_VAMANA quantization_type: str | None = None table_quantization_type: str | None maintenance_work_mem: str | None = None @@ -190,26 +190,31 @@ class PgSVSVamanaConfig(PgSVSIndexConfig): reranking_metric: str | None = None normalize_cosine: bool = False - @validator("quantization_type", "table_quantization_type") - def reject_bit_quantization(cls, value: str | None, field: Any): + @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"{field.name}=bit is not supported for svs (vamana has no bit operator class); use none or halfvec" + 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 - @root_validator(skip_on_failure=True) - def reject_reranking(cls, values: dict): + @model_validator(mode="after") + def reject_reranking(self): # pgvector-level reranking only applies to bit indexes; svs reranks internally via compression_secondary - if values.get("reranking"): + if self.reranking: msg = "reranking is not supported for svs; svs reranks internally via compression_secondary" raise ValueError(msg) - if values.get("quantized_fetch_limit") is not None: + if self.quantized_fetch_limit is not None: msg = "quantized_fetch_limit is not supported for svs (it only applies to bit quantization with reranking)" raise ValueError(msg) - return values + return self - @validator("graph_degree") + @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): @@ -217,7 +222,8 @@ def validate_graph_degree(cls, value: int | None): raise ValueError(msg) return value - @validator("alpha") + @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): @@ -225,7 +231,8 @@ def validate_alpha(cls, value: int | None): raise ValueError(msg) return value - @validator("build_window_size") + @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): @@ -233,7 +240,8 @@ def validate_build_window_size(cls, value: int | None): raise ValueError(msg) return value - @validator("search_window_size") + @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 @@ -243,14 +251,16 @@ def validate_search_window_size(cls, value: int | None): raise ValueError(msg) return value - @validator("compression_type") + @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 - @validator("compression_primary") + @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 @@ -259,7 +269,8 @@ def validate_compression_primary(cls, value: int | None): raise ValueError(msg) return value - @validator("leanvec_dims") + @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): @@ -267,21 +278,21 @@ def validate_leanvec_dims(cls, value: int | None): raise ValueError(msg) return value - @root_validator(skip_on_failure=True) - def validate_compression_secondary(cls, values: dict): - secondary = values.get("compression_secondary") + @model_validator(mode="after") + def validate_compression_secondary(self): + secondary = self.compression_secondary if secondary is None: - return values + return self # 0 ("no residual") is only accepted for LVQ's residual slot, not LeanVec's secondary encoding - if secondary == 0 and values.get("compression_type") == 2: - return values + 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 values + return self def _effective_metric_type(self) -> MetricType | None: if self.normalize_cosine and self.metric_type == MetricType.COSINE: @@ -333,5 +344,5 @@ def session_param(self) -> PgSVSSessionCommands: _pgsvs_case_config = { - IndexType.SVS_VAMANA: PgSVSVamanaConfig, + IndexType.PGSVS_VAMANA: PgSVSVamanaConfig, } From b1acf5014b91aba1a86111e46cb0392ad902e49d Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 5 Nov 2026 17:15:58 -0700 Subject: [PATCH 16/33] Fix halfvec table storage insert: wrap arrays in pgvector's HalfVector insert_embeddings passed a raw numpy array as the halfvec column value to psycopg's COPY BINARY writer. pgvector-python's VectorDumper auto-wraps raw arrays/lists into its Vector class (and even registers numpy.ndarray directly as a dumper key), but HalfVectorDumper does neither -- it only accepts an already-constructed HalfVector instance, calling .to_binary() on whatever it's given. Passing a raw array surfaced as "'numpy.ndarray' object has no attribute 'to_binary'" as soon as table_quantization_type=halfvec actually tried to insert a row. Verified end-to-end against a live SVS-enabled Postgres: insert, index build, and search all succeed now for table_quantization_type=halfvec (table stores halfvec directly) and for table_quantization_type=none with quantization_type=halfvec (expression-indexed mismatch case). --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 3ff635421..6eb60eabe 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -7,6 +7,7 @@ import numpy as np import psycopg +from pgvector import HalfVector from pgvector.psycopg import register_vector from psycopg import Connection, Cursor, sql @@ -492,10 +493,10 @@ def insert_embeddings( # noqa: PLR0912 for i, row in enumerate(metadata_arr): if self.with_scalar_labels: copy.set_types(["bigint", "halfvec", "varchar"]) - copy.write_row((row, np.float16(embeddings_arr[i]), labels_data[i])) + copy.write_row((row, HalfVector(embeddings_arr[i]), labels_data[i])) else: copy.set_types(["bigint", "halfvec"]) - copy.write_row((row, np.float16(embeddings_arr[i]))) + copy.write_row((row, HalfVector(embeddings_arr[i]))) else: for i, row in enumerate(metadata_arr): if self.with_scalar_labels: From eb2089cce9dda74645a194d56fb12a1cfa79a5c8 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Wed, 18 Nov 2026 15:00:32 -0700 Subject: [PATCH 17/33] Document pgsvs in the extras install table pgsvs ships under the same pgvector extra but wasn't listed in README's install table alongside the other pg-family engines. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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]` | From e2a02b3dc81fea58119a86ca51037bd2140799f3 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Wed, 18 Nov 2026 15:00:39 -0700 Subject: [PATCH 18/33] Add Streamlit UI config for PgSVS Match the existing PgVector/PgVectorScale/PgDiskANN/PgVectoRS pattern: add CaseConfigParamType members for the vamana-specific fields, build PgSVSLoadingConfig/PgSVSPerformanceConfig from widgets bounded to match PgSVSVamanaConfig's validators, and register DB.PgSVS in the case-config map and icon lookup. Reranking/quantized_fetch_limit/reranking_metric are omitted since SVS's reject_reranking validator always rejects them, and "bit" is omitted from the quantization-type options since vamana has no bit operator class. --- .../frontend/config/dbCaseConfigs.py | 193 ++++++++++++++++++ vectordb_bench/frontend/config/styles.py | 1 + vectordb_bench/models.py | 11 + 3 files changed, 205 insertions(+) diff --git a/vectordb_bench/frontend/config/dbCaseConfigs.py b/vectordb_bench/frontend/config/dbCaseConfigs.py index d6eaf721e..5096abfe3 100644 --- a/vectordb_bench/frontend/config/dbCaseConfigs.py +++ b/vectordb_bench/frontend/config/dbCaseConfigs.py @@ -1687,6 +1687,169 @@ 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={ + "options": [-8, -4, 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={ + "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 +2885,32 @@ 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_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 +4132,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+UrenEf3hl8V59e6MlJbT2YMIiLICIiAIiIAiIgCIiAIiIAiytjgWDz1szaenZtyPPg0cXOPADmjaS2wdWio5J3tiiY6SR5s1jRtOcewKa9B9TjGBs2J9N+8U7T0G/8AscOt3DLvXstAtBKfC48gJapw9LORn+qz2W/XivXqjyuot/DX4X1JKJwUtNHE0RxMbGxos1jQGtaOwBc6Ljlka0FziGtaCXOOQaBmSTyVX5kyR9oo7w3W3QTVjqU3jivsw1Dj0JHdo9Ucj8bKQwVsspnX8y0Nn0iItICIiA45YmvBa5oc1wsWkXaR2hRdptqfgnDpsPtTzb/JH8g89nFh+XcpUWVvpyJ1PcWOSnOK4XPSyOgqI3RSs3tcLeI5jtXSVsNM9EKbE4vJzN2ZGj0UwHTjP3jsVadKtG6jDpzT1DbHex46krODmldBi5cb19GQa0aREReswEREAREQBERAEREB2KKkfM9sUTS+SRwaxo3uccgFZzVzoVHhcFiA6qlAM8n+DfdHzXi9Reh4a04nM3pOu2lBHVbudJ45gdx5qY1SdRytv048LklFGURFUEgow18Y66CjZTMdsuq3u27bzEyxcPElnwKk9Qr9oqld+KTeoPKsJ5OOy4fEA/BezAinfFMw+CFlKWrPWg+j2aWuJfS7o5Os+Abre8zs3j5KLUXRW1Rtj2yRAuBhePUdV+b1MU3Yx7XO+G9bJUva4g3GRG48l6LCtOsUpreSrZbDc158q23c+4VVZ0r7Jf2S7i1yKAcK131rMqininHEtvC8+OY+S9vgeuPDqhzY5WSUznkDafsuiBPN4N7dpC8dmBdD22Z2iSEXy0g5jMHcea+l42tGTC89ptorDidOYJOi8XMMts4n8+7dcL0KKUJuElKPIKd4zhctJM+nnbsSxOs4fQjsIzXRVg9dmiAqqfz6Fvp6ZvpAN8kG8+Lb37rqvi6jGvV0FL3INaMIiLeYCIiAIiIAtxongrq6rhpW39LIA4j1Wb3u8BdahTL9nvBbunrXDqAQxHtPSf8ALY/iK05FvpVuRlEz0dKyGNsUbQ2ONgaxo4NAsFzrCyuVb29smERFEBaPTHR6LEaV9NLlfpRvGZjkG5w+fgSvJ6wNaUWHytp6djaiZrh5xc2bG32Lj1/ovX6P6QU+IU4qKd+00izmnrRvtm1w5r1Km2pRs1oFWMfwWaimdBMLOaciOq9vBwPJaxTTrKoWTAhwzabtdxaVDM0ZaS07wV0OPd6kE/cgzjREW8wEREBLeqjWV5vs0Nc/0GQgmcfyPJjj7Hbw7t07tcDmMwRkeapcpa1U6y/Ny2hrn3gOUMzj+R4Bjvc7eHduqs7B7tzgvJJMnhFhrgcxmCMjzWQqNokfMjA4EOAIIsQcwQqq6w9HvwfXSwAeiJ24O2J2YHhmP3Va1RH9oLBQ+CGsaOlC/wAm8/8AG/MX7nD+tWPTruy3t9mYkQOiIugIBERAEREBlWf1Q4cKfC4PamDpXfvnL+kNVYArg6OQCOkp4x6lNE34MAVZ1SWq0vqyUTZIiKhJGFptL4qt9JM2hcGVRZ6Mn5hp4Otex5rQaR6zqGiqmUj7yEutPIw3bT8BfmeYG75L2kEzZGh7HB7HAFrmm7XA5gg8lu9OdTjOSBTisikY9zZQ5sgcRIHdYO43vne63Wh2ldRhk3lYjdjspoj1JWfceRU260NXbMQaammAZWsbnwbUAeq73uR8D2V2qIHxucx7Sx7HEOaRZzXDIghdDRdDJh/1EGtEuY9jMNZD5eF12uGYPWY7i13aolruu7vXLQYg+EnZPRdk5vBwXXqXhzi4biVsqq9PwuAcSIi3GAiIgCIiAlvVRrLNPs0Nc+8BygmdmYeAa73Pp3bp3a4EXGYIyPNUuU56h9JqicSUMrttkEYfC45uY2+zsd2eXJVGfhrTsj/JJP2JfXntYWHipw6qiIufIOc39ZnpG/NoXoV8TxB7XMO5zS09xFlUVS7Zp/Qkyl6Lmqo9h7m+y4j4Gy4V1yNYREQBERAZCuXRfk2W3bDbfAKmgVwtH5xJSwSD16eJ3xYCqnqq+GP8komxXjtaeKVtLQvkomXde0sgzdBFY3e0ffw3r0Nbi8EEsMEsgZJUl4gB9ctsSL7r9Id67zm3FjmCMxwKqa36coyktokUwe8uJJNyTck5klSLqt1jOw9wpakl1E85He6nceI93mPEdux1r6tvNtqtom/i5N5oR+hPtN9z6d26J10i9PJr/BDgudBM2Roexwex7Q5rmm7XA53BUf60NXTcRaammAZWsbmNzaho9V3vcj4d0c6rtYzqBwpqkl1G45He6nJ4j3eY8e+w0EzXtD2ODmOALXNN2uBzBBVJZXZiWbXBLkptUwPjc5j2lj2OIc1ws5pG8ELiVjtaGrtuINNTTAMrWNz4NqGgdU+9yPh3V2nhdG4se0te1xDmkWLXDIg9qvMbJjfHa5ItaOFERbzAREQBERAZUxfZ4oJPK1NRb0QjbGDzeXB1h3AfMKJaCkfPIyGNpdJI8NYBxcTYK2Gh+Asw+kipWWuxt5HD15Dm53x+QC8HUblCrt92ZibtYWVxyyBrS47mgk9wzXPR5RMp7jP5xNbd5eS38ZXRXNWS7b3O9p7j8TdcK69cGsIiLICIiAyrR6psRE+F05vcxNMTuwsJA/p2fiquKa/s9YzlUUTjuImiH9D/APD5rwdRr7qdr2Mrk+vtFOI8xINiHVFjxB9Cu/qo1lCpDaKtfaoAtDKchP7rj7f1710ftFxOLaJ1jstdUBzuAJEVh/S74KE2PINwbEG4O4gqFFEbsWMX++TLemXDxcXjIOYIz7VW7T7RlsEjpYBaNxu5g9Q9nYve6vtZPnUYoq11qgC0MpyE43bLvf8Ar3ro6ZDetGNCzHscWH5IcUk6rNYr6Bwpakl1G92R3mnceI93mPHvjysaA8gbrrhCtbK42x7ZIiXRa4EXGYIyPNV7184M2CtZUMGyKuK77cZGHZcfEFinbAPzWD9ni/sCiL7RvWov1Z/rEqPAbjkdq/JN8EMLKwt/SaHYlMxskVDO+N4u1wjdsuHMdiv3JR5ZA0CL0f8AoTFv9vn/AJbk/wBCYt/t8/8ALco+rD7kDzqLb4nozXUzduopJYWX6zmODfiuHAcJkrKiOmiF3zPDRyA4uPYBc+Cl3x1vfgEoahtFdt7sSlb0Y7sp7je/13juBt+8eSnFdHBMLjo4I6aIWjhYGt5nm49pNz4rvLl8q/1rHI2LwFodPMQFNh1VKTa1O9rf1njYb83Bb9RR9oDGRHSxUjT0p5Nt4/42c/3iP4Uxa++2KDICREXUmsIiIAiIgMre6FY6aCshqR1WPtKB60RyePgStCsrEoqSafuC4GKYdTYhTmKVolgmYC09hF2vaeBzyKrXp9oVPhU2y676d5PkJrZOHsu5OHJSfqN0uE0P4Pmd6WAXgJ9eHi3vb9D2KSMbwiCthdT1DA+N4zHEHg5p4Ec1RV2zxLXCXH75J8lPmOINwbEHI7rL19HpMZ4/JTm8rRZrz+kHb2rh0+0KmwqbZdd9O8nyE1snD2XcnDkvKAq5+C2KkiPB2K/rldcLL3k5nMrAW1cGC4eAfmtP+zRf2BRH9o3rUXdP9YlLmAfmtP8As0X9gUR/aO61F3T/AFiXP4X+T/ZN8EMBXJwwAQxACwETLdnRCpsFcXBJ2yU8MjCHNdCwtI3EbIXq6r8sTETvIiKk2SPiRgcCHAOaRYg5ghanDtF6GnlNRBSxxTOBBe0Wy42G4eC3CKSnJLSYMoiKIPlxAzOXNVZ1maQ/hCvllabxRnycHLYbx8TtHxUw659LhR0ppYnfjNU0g23xw7nO8dw8eSrmrvpmPpOx+/BGRhERWxEIiIAiIgCIiA7uFYjLTSsnhdsSxODmOHP7x2K0WgulsOKU4mZZsrbCeLjG/wD+TwKqitxovpFUYdO2op3WcMntPUkZxa4cl5MvFV8fyjKei1eOYRBWwup6hgfG8ZjiDwc08COarPp9oVPhU2y676d5PkJrZOHsu5OHJWF0M0vpsUi8pC7ZkaB5aEnpxn728itnjeEQVsLqeoYHxvGYO8Hg5p4Ec1U4+RPGn2z4+hJrZTxAvV6faFT4VNsuu+neT5Ga2Th7LuThyXk1fxnGcVKL8EC4GjEofR0z27nUsRH8sKPdfeATVEENTE0vbSmTyoGZDHhvT7hs5966WpTTlhjbhlS7Ze0nzV53PaTfyffcm3fZTC5oIIIuCMxzXPS7sW/uaJ8opapJ1W6xnYe4UtSS6iecjvdTuPrD3eY8R27HWvq1832q6hZenJvNCP0HvN9z6d26Jldp15Nf4I8FzoJmyND2OD2PaC1wN2uBzBBXKq7ardYzqBwpapxdRvd0Xb3UxJ3j3eY8R22Fhma9oexwc1wBa4G7XA5ggrn8rGlTLT4Jp7OREReUGFpdLdI4MNp3VEx3ZRsHWlfwaP8AvgmlOk1NhsJmqH2/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 From 9ccf5f428b627c973904f41c72e77ea6568ab3be Mon Sep 17 00:00:00 2001 From: Olasoji Date: Wed, 18 Nov 2026 21:24:44 -0700 Subject: [PATCH 19/33] Fix PgSVS UI crash: missing required fields and asymmetric case-config lists build_window_size, search_window_size, and table_quantization_type had no default on PgSVSVamanaConfig, so instantiating it from either the Load- or Performance-labeled Streamlit UI config (which each only supply their own widget list's fields) raised a pydantic ValidationError and the run never started. Give them the same None default every other optional field has, and make PgSVSPerformanceConfig a strict superset of PgSVSLoadingConfig (plus search_window_size) to match the PgVector/PgDiskANN precedent. --- vectordb_bench/backend/clients/pgsvs/config.py | 6 +++--- vectordb_bench/frontend/config/dbCaseConfigs.py | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/config.py b/vectordb_bench/backend/clients/pgsvs/config.py index cc7c7f2c0..86718846e 100644 --- a/vectordb_bench/backend/clients/pgsvs/config.py +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -175,14 +175,14 @@ class PgSVSVamanaConfig(PgSVSIndexConfig): compression_primary: int | None = None compression_secondary: int | None = None alpha: int | None = None - build_window_size: int | None - search_window_size: int | 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 + table_quantization_type: str | None = None maintenance_work_mem: str | None = None max_parallel_workers: int | None = None reranking: bool | None = None diff --git a/vectordb_bench/frontend/config/dbCaseConfigs.py b/vectordb_bench/frontend/config/dbCaseConfigs.py index 5096abfe3..f5a2af233 100644 --- a/vectordb_bench/frontend/config/dbCaseConfigs.py +++ b/vectordb_bench/frontend/config/dbCaseConfigs.py @@ -2903,6 +2903,14 @@ class CaseConfigInput(BaseModel): ] 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, From f00f16c882dc3103fcf919f80426bf5c85466523 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Wed, 18 Nov 2026 21:24:55 -0700 Subject: [PATCH 20/33] Fix PgSVS concurrency: declare thread_safe and copy_for_thread PgSVS shares PgVector's single mutable self.conn/self.cursor design but never set thread_safe = False or overrode copy_for_thread() the way pgvector.py does. Under any concurrency benchmark, concurrent_runner.py's _get_thread_db() returned the DB object unmodified and every worker thread executed on the same shared connection concurrently. --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 6eb60eabe..7924cc718 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -3,6 +3,7 @@ import logging from collections.abc import Generator, Sequence from contextlib import contextmanager +from copy import copy from typing import Any import numpy as np @@ -22,6 +23,7 @@ class PgSVS(VectorDB): """Use psycopg instructions""" + thread_safe: bool = False supported_filter_types: list[FilterOp] = [ FilterOp.NonFilter, FilterOp.NumGE, @@ -102,6 +104,14 @@ def _create_connection(**kwargs) -> tuple[Connection, Cursor]: 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() reranking = self.case_config.search_param()["reranking"] From b16b766a7810a1496ba0c9bc02adbb078600d4ca Mon Sep 17 00:00:00 2001 From: Olasoji Date: Wed, 18 Nov 2026 21:25:08 -0700 Subject: [PATCH 21/33] Remove dead and misleading PgSVS reranking/search-history surface - cli.py: drop --reranking/--reranking-metric/--quantized-fetch-limit -- PgSVSVamanaConfig.reject_reranking always rejects a truthy reranking or non-None quantized_fetch_limit, so these flags could never be used successfully; --reranking-metric was also never wired into the config constructor at all. Also drop "bit" from --quantization-type/ --table-quantization-type choices since vamana has no bit operator class. - config.py: use_search_history is a build-time-only reloption (confirmed against the SVS extension source -- no session GUC exists for it), and search_param()["use_search_history"] was never read anywhere in pgsvs.py. Remove it from PgSVSSearchParam/search_param() and document why. - pgvector/config.py: drop an unused use_search_history key that had leaked into PgVectorSearchParam -- PgVector never populates or reads it. - api.py: delete a dead commented-out CompressionType enum. --- vectordb_bench/backend/clients/api.py | 9 ---- vectordb_bench/backend/clients/pgsvs/cli.py | 41 ++----------------- .../backend/clients/pgsvs/config.py | 4 +- .../backend/clients/pgvector/config.py | 1 - 4 files changed, 5 insertions(+), 50 deletions(-) diff --git a/vectordb_bench/backend/clients/api.py b/vectordb_bench/backend/clients/api.py index cc701d269..46ba3f017 100644 --- a/vectordb_bench/backend/clients/api.py +++ b/vectordb_bench/backend/clients/api.py @@ -9,15 +9,6 @@ from vectordb_bench.backend.filter import Filter, FilterOp from vectordb_bench.backend.payload import PayloadProfile -"""class CompressionType(Enum): - LVQ8 = "LVQ8" - LVQ4 = "LVQ4" - LVQ4X4 = "LVQ4x4" - LVQ4X8 = "LVQ4x8" - LEANVEC_4X8 = "LeanVec4x8" - LEANVEC_8X8 = "LeanVec8x8" - NONE = "none" -""" class MetricType(StrEnum): L2 = "L2" diff --git a/vectordb_bench/backend/clients/pgsvs/cli.py b/vectordb_bench/backend/clients/pgsvs/cli.py index cf4b0f97b..75a22b939 100644 --- a/vectordb_bench/backend/clients/pgsvs/cli.py +++ b/vectordb_bench/backend/clients/pgsvs/cli.py @@ -5,7 +5,6 @@ from pydantic import SecretStr, ValidationError from vectordb_bench.backend.clients import DB -from vectordb_bench.backend.clients.api import MetricType from ....cli.cli import ( CommonTypedDict, @@ -71,7 +70,7 @@ class PgSVSTypedDict(CommonTypedDict, SVSBaseTypedDict): str | None, click.option( "--quantization-type", - type=click.Choice(["none", "bit", "halfvec"]), + type=click.Choice(["none", "halfvec"]), help="quantization type for vectors (in index)", required=False, ), @@ -80,40 +79,8 @@ class PgSVSTypedDict(CommonTypedDict, SVSBaseTypedDict): str | None, click.option( "--table-quantization-type", - type=click.Choice(["none", "bit", "halfvec"]), - help="quantization type for vectors (in table). " - "If equal to bit, the parameter quantization_type will be set to bit too.", - required=False, - ), - ] - reranking: Annotated[ - bool | None, - click.option( - "--reranking/--skip-reranking", - type=bool, - help="Enable reranking for HNSW search for binary quantization", - default=False, - ), - ] - reranking_metric: Annotated[ - str | None, - click.option( - "--reranking-metric", - type=click.Choice( - [metric.value for metric in MetricType if metric.value not in ["HAMMING", "JACCARD"]], - ), - help="Distance metric for reranking", - default="COSINE", - show_default=True, - ), - ] - quantized_fetch_limit: Annotated[ - int | None, - click.option( - "--quantized-fetch-limit", - type=int, - help="Limit of fetching quantized vector ranked by distance for reranking \ - -- bound by ef_search", + type=click.Choice(["none", "halfvec"]), + help="quantization type for vectors (in table)", required=False, ), ] @@ -143,8 +110,6 @@ def PgSVS( normalize_cosine=parameters["normalize_cosine"], quantization_type=parameters["quantization_type"], table_quantization_type=parameters["table_quantization_type"], - reranking=parameters["reranking"], - quantized_fetch_limit=parameters["quantized_fetch_limit"], ) except ValidationError as e: raise click.UsageError(str(e)) from e diff --git a/vectordb_bench/backend/clients/pgsvs/config.py b/vectordb_bench/backend/clients/pgsvs/config.py index 86718846e..3857a9863 100644 --- a/vectordb_bench/backend/clients/pgsvs/config.py +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -59,7 +59,6 @@ class PgSVSSearchParam(TypedDict): reranking_metric_fun_op: LiteralString quantized_fetch_limit: int | None search_window_size: int | None - use_search_history: bool | None class PgSVSSessionCommands(TypedDict): @@ -300,6 +299,8 @@ def _effective_metric_type(self) -> MetricType | None: 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, @@ -335,7 +336,6 @@ def search_param(self) -> PgSVSSearchParam: "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), "quantized_fetch_limit": self.quantized_fetch_limit, "search_window_size": self.search_window_size, - "use_search_history": self.use_search_history, } def session_param(self) -> PgSVSSessionCommands: diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index fba258b0e..c511082d6 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -53,7 +53,6 @@ class PgVectorIndexParam(TypedDict): class PgVectorSearchParam(TypedDict): metric_fun_op: LiteralString - use_search_history: bool | None class PgVectorSessionCommands(TypedDict): From 7b6c49599d1c56b97ea30e4dd72500a4b3aac0cd Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 19 Nov 2026 13:28:00 -0700 Subject: [PATCH 22/33] Drop stale setuptools_scm fallback_version It was added in an earlier commit as "1.0.18" (the upstream tag this fork originally started from) to avoid failing builds without .git. Two rebases later it no longer describes this codebase, and upstream never had this key at all, so it shows up as an unexplained addition in the diff. Restores pyproject.toml to upstream's exact structure. Signed-off-by: Olasoji --- pyproject.toml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index baee86734..d58b6289d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,9 +2,6 @@ requires = ["setuptools>=67.0", "wheel", "setuptools_scm[toml]>=6.2"] build-backend = "setuptools.build_meta" -[tool.setuptools_scm] -fallback_version = "1.0.18" - [tool.setuptools.package-data] "vectordb_bench.results" = ["*.json"] "vectordb_bench.fig.homepage" = ["*.png"] @@ -111,6 +108,8 @@ init_bench = "vectordb_bench.__main__:main" init_bench_rest = "vectordb_bench.restful.app:main" vectordbbench = "vectordb_bench.cli.vectordbbench:cli" +[tool.setuptools_scm] + [tool.black] line-length = 120 target-version = ['py311'] From 0a88de271982ec378975d632fd82ff71b42cb8e3 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 19 Nov 2026 13:28:13 -0700 Subject: [PATCH 23/33] Remove dead reranking and bit-quantization code from PgSVS PgSVSVamanaConfig.reject_bit_quantization rejects quantization_type/ table_quantization_type="bit" at construction time (vamana has no bit opclass), and the earlier reject_reranking validator always rejected a truthy reranking (svs reranks internally via compression_secondary). Both guarantees made several downstream branches permanently unreachable: the reranking/quantized_fetch_limit/reranking_metric fields themselves, the TypedDict keys and query-building branches that consumed them in pgsvs.py, the "bit" entries in parse_metric/ parse_metric_fun_op, and the table_quantization_type="bit" forcing line in index_param(). All inherited verbatim from pgvector.py's original copy-paste origin; none of it was ever reachable for svs. Signed-off-by: Olasoji --- .../backend/clients/pgsvs/config.py | 46 +---- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 178 +++++------------- 2 files changed, 53 insertions(+), 171 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/config.py b/vectordb_bench/backend/clients/pgsvs/config.py index 3857a9863..13e89134e 100644 --- a/vectordb_bench/backend/clients/pgsvs/config.py +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -55,9 +55,6 @@ class PgSVSIndexParam(TypedDict): class PgSVSSearchParam(TypedDict): metric_fun_op: LiteralString - reranking: bool | None - reranking_metric_fun_op: LiteralString - quantized_fetch_limit: int | None search_window_size: int | None @@ -75,6 +72,8 @@ class PgSVSIndexConfig(BaseModel, DBCaseConfig): 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": { @@ -82,10 +81,6 @@ def parse_metric(self, metric_type: MetricType | None = None) -> str: MetricType.IP: "halfvec_ip_ops", MetricType.COSINE: "halfvec_cosine_ops", }, - "bit": { - MetricType.JACCARD: "bit_jaccard_ops", - MetricType.HAMMING: "bit_hamming_ops", - }, "_fallback": { MetricType.L2: "vector_l2_ops", MetricType.IP: "vector_ip_ops", @@ -95,19 +90,10 @@ def parse_metric(self, metric_type: MetricType | None = None) -> str: if d.get(self.quantization_type) is None: return d.get("_fallback").get(effective_metric_type) - metric = d.get(self.quantization_type).get(effective_metric_type) - # If using binary quantization for the index, use a bit metric - # no matter what metric was selected for vector or halfvec data - if self.quantization_type == "bit" and metric is None: - return "bit_hamming_ops" - return metric + 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 self.quantization_type == "bit": - if effective_metric_type == MetricType.JACCARD: - return "<%>" - return "<~>" if effective_metric_type == MetricType.L2: return "<->" if effective_metric_type == MetricType.IP: @@ -122,13 +108,6 @@ def parse_metric_fun_str(self, metric_type: MetricType | None = None) -> str: return "max_inner_product" return "cosine_distance" - def parse_reranking_metric_fun_op(self) -> LiteralString: - if self.reranking_metric == MetricType.L2: - return "<->" - if self.reranking_metric == MetricType.IP: - return "<#>" - return "<=>" - @abstractmethod def index_param(self) -> PgSVSIndexParam: ... @@ -184,9 +163,6 @@ class PgSVSVamanaConfig(PgSVSIndexConfig): table_quantization_type: str | None = None maintenance_work_mem: str | None = None max_parallel_workers: int | None = None - reranking: bool | None = None - quantized_fetch_limit: int | None = None - reranking_metric: str | None = None normalize_cosine: bool = False @field_validator("quantization_type", "table_quantization_type") @@ -201,17 +177,6 @@ def reject_bit_quantization(cls, value: str | None, info: ValidationInfo): raise ValueError(msg) return value - @model_validator(mode="after") - def reject_reranking(self): - # pgvector-level reranking only applies to bit indexes; svs reranks internally via compression_secondary - if self.reranking: - msg = "reranking is not supported for svs; svs reranks internally via compression_secondary" - raise ValueError(msg) - if self.quantized_fetch_limit is not None: - msg = "quantized_fetch_limit is not supported for svs (it only applies to bit quantization with reranking)" - raise ValueError(msg) - return self - @field_validator("graph_degree") @classmethod def validate_graph_degree(cls, value: int | None): @@ -315,8 +280,6 @@ def index_param(self) -> PgSVSIndexParam: self.quantization_type = "vector" if self.table_quantization_type == "none" or self.table_quantization_type is None: self.table_quantization_type = "vector" - if self.table_quantization_type == "bit": - self.quantization_type = "bit" effective_metric_type = self._effective_metric_type() return { "metric": self.parse_metric(metric_type=effective_metric_type), @@ -332,9 +295,6 @@ 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), - "reranking": self.reranking, - "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), - "quantized_fetch_limit": self.quantized_fetch_limit, "search_window_size": self.search_window_size, } diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 7924cc718..7dec4d779 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -114,90 +114,35 @@ def copy_for_thread(self) -> "VectorDB": def _generate_search_query(self) -> sql.Composed: index_param = self.case_config.index_param() - reranking = self.case_config.search_param()["reranking"] - column_name = ( - sql.SQL("binary_quantize({0})").format(sql.Identifier(self._vector_field)) - if index_param["quantization_type"] == "bit" and index_param["table_quantization_type"] != "bit" - else sql.SQL(self._vector_field) - ) - search_vector = ( - sql.SQL("binary_quantize({0})").format(sql.Placeholder()) - if index_param["quantization_type"] == "bit" - else sql.Placeholder() - ) + # 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() - # The following sections assume that the quantization_type value matches the quantization function name if index_param["quantization_type"] != index_param["table_quantization_type"]: - # Reranking makes sense only if table quantization is not "bit" - if index_param["quantization_type"] == "bit" and reranking: - # Embeddings needs to be passed to binary_quantize function if quantization_type is bit - search_query = sql.Composed( - [ - sql.SQL( - """ - SELECT i.id - FROM ( - SELECT {primary_field}, {vector_field} {reranking_metric_fun_op} %s::{table_quantization_type} AS distance - FROM public.{table_name} {where_clause} - ORDER BY {column_name}::{quantization_type}({dim}) - """, # noqa: E501 - ).format( - table_name=sql.Identifier(self.table_name), - primary_field=sql.Identifier(self._primary_field), - vector_field=sql.Identifier(self._vector_field), - column_name=column_name, - reranking_metric_fun_op=sql.SQL( - self.case_config.search_param()["reranking_metric_fun_op"], - ), - search_vector=search_vector, - table_quantization_type=sql.SQL(index_param["table_quantization_type"]), - 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 {quantized_fetch_limit} - ) i - ORDER BY i.distance - LIMIT %s::int - """, - ).format( - search_vector=search_vector, - quantization_type=sql.SQL(index_param["quantization_type"]), - dim=sql.Literal(self.dim), - quantized_fetch_limit=sql.Literal( - self.case_config.search_param()["quantized_fetch_limit"], - ), - ), - ], - ) - else: - 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), - ), - ] - ) + 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( [ @@ -368,11 +313,8 @@ def _create_index(self): ).format( index_name=sql.Identifier(self._index_name), table_name=sql.Identifier(self.table_name), - column_name=( - sql.SQL("binary_quantize({0})").format(sql.Identifier("embedding")) - if index_param["quantization_type"] == "bit" - else sql.Identifier("embedding") - ), + # 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"]), @@ -457,7 +399,7 @@ def need_normalize_cosine(self) -> bool: return True return False - def insert_embeddings( # noqa: PLR0912 + def insert_embeddings( self, embeddings: list[list[float]], metadata: list[int], @@ -475,46 +417,28 @@ def insert_embeddings( # noqa: PLR0912 metadata_arr = np.array(metadata) embeddings_arr = np.array(embeddings) - if index_param["table_quantization_type"] == "bit": - with self.cursor.copy( - sql.SQL("COPY public.{table_name} FROM STDIN (FORMAT TEXT)").format( - table_name=sql.Identifier(self.table_name) - ) - ) as copy: - # Same logic as pgvector binary_quantize + # 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): - embeddings_bit = "" - for embedding in embeddings_arr[i]: - if embedding > 0: - embeddings_bit += "1" - else: - embeddings_bit += "0" if self.with_scalar_labels: - copy.write_row((str(row), embeddings_bit, labels_data[i])) + copy.set_types(["bigint", "halfvec", "varchar"]) + copy.write_row((row, HalfVector(embeddings_arr[i]), labels_data[i])) else: - copy.write_row((str(row), embeddings_bit)) - else: - 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])) + 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 @@ -545,12 +469,10 @@ def search_embedding( 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() - search_param = self.case_config.search_param() q = np.asarray(query) result = self.cursor.execute( self._search, - (q, q, k) if index_param["quantization_type"] == "bit" and search_param["reranking"] else (q, k), + (q, k), prepare=True, binary=True, ) From 38491a9794b4f3208bd7818e816a689a320814a2 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 19 Nov 2026 13:28:29 -0700 Subject: [PATCH 24/33] Revert pgvector client changes out of this PR normalize_cosine (the --normalize-cosine flag, PgVectorHNSWConfig field, _effective_metric_type helper, and need_normalize_cosine) was added to pgvector's HNSW alongside the original SVS-inside-pgvector integration, before SVS was extracted into its own package. It's not part of what this PR is adding -- restore pgvector/{cli,config, pgvector}.py to upstream's exact state and keep normalize_cosine only on PgSVSVamanaConfig, where it's actually needed. Signed-off-by: Olasoji --- .../backend/clients/pgvector/cli.py | 16 ++------- .../backend/clients/pgvector/config.py | 36 +++++++------------ .../backend/clients/pgvector/pgvector.py | 15 ++------ 3 files changed, 18 insertions(+), 49 deletions(-) diff --git a/vectordb_bench/backend/clients/pgvector/cli.py b/vectordb_bench/backend/clients/pgvector/cli.py index 9164ce3ae..7da41d5c6 100644 --- a/vectordb_bench/backend/clients/pgvector/cli.py +++ b/vectordb_bench/backend/clients/pgvector/cli.py @@ -165,17 +165,8 @@ def PgVectorIVFFlat( **parameters, ) -class PgVectorHNSWTypedDict(PgVectorTypedDict, HNSWFlavor1): - 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 PgVectorHNSWTypedDict(PgVectorTypedDict, HNSWFlavor1): ... @cli.command() @@ -207,9 +198,6 @@ def PgVectorHNSW( reranking=parameters["reranking"], reranking_metric=parameters["reranking_metric"], quantized_fetch_limit=parameters["quantized_fetch_limit"], - normalize_cosine=parameters["normalize_cosine"], ), **parameters, ) - - diff --git a/vectordb_bench/backend/clients/pgvector/config.py b/vectordb_bench/backend/clients/pgvector/config.py index c511082d6..7da238a4b 100644 --- a/vectordb_bench/backend/clients/pgvector/config.py +++ b/vectordb_bench/backend/clients/pgvector/config.py @@ -68,8 +68,7 @@ class PgVectorIndexConfig(BaseModel, DBCaseConfig): # 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: - effective_metric_type = self.metric_type if metric_type is None else metric_type + def parse_metric(self) -> str: d = { "halfvec": { MetricType.L2: "halfvec_l2_ops", @@ -88,31 +87,29 @@ def parse_metric(self, metric_type: MetricType | None = None) -> str: } if d.get(self.quantization_type) is None: - return d.get("_fallback").get(effective_metric_type) - metric = d.get(self.quantization_type).get(effective_metric_type) + return d.get("_fallback").get(self.metric_type) + metric = d.get(self.quantization_type).get(self.metric_type) # If using binary quantization for the index, use a bit metric # no matter what metric was selected for vector or halfvec data if self.quantization_type == "bit" and metric is None: return "bit_hamming_ops" return metric - 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 + def parse_metric_fun_op(self) -> LiteralString: if self.quantization_type == "bit": - if effective_metric_type == MetricType.JACCARD: + if self.metric_type == MetricType.JACCARD: return "<%>" return "<~>" - if effective_metric_type == MetricType.L2: + if self.metric_type == MetricType.L2: return "<->" - if effective_metric_type == MetricType.IP: + if self.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: + def parse_metric_fun_str(self) -> str: + if self.metric_type == MetricType.L2: return "l2_distance" - if effective_metric_type == MetricType.IP: + if self.metric_type == MetricType.IP: return "max_inner_product" return "cosine_distance" @@ -238,12 +235,6 @@ class PgVectorHNSWConfig(PgVectorIndexConfig): reranking: bool | None = None quantized_fetch_limit: int | None = None reranking_metric: str | None = None - normalize_cosine: bool = False - - 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) -> PgVectorIndexParam: index_parameters = {"m": self.m, "ef_construction": self.ef_construction} @@ -253,9 +244,8 @@ def index_param(self) -> PgVectorIndexParam: self.table_quantization_type = "vector" if self.table_quantization_type == "bit": self.quantization_type = "bit" - effective_metric_type = self._effective_metric_type() return { - "metric": self.parse_metric(metric_type=effective_metric_type), + "metric": self.parse_metric(), "index_type": self.index.value, "index_creation_with_options": self._optionally_build_with_options(index_parameters), "maintenance_work_mem": self.maintenance_work_mem, @@ -265,9 +255,8 @@ def index_param(self) -> PgVectorIndexParam: } def search_param(self) -> PgVectorSearchParam: - effective_metric_type = self._effective_metric_type() return { - "metric_fun_op": self.parse_metric_fun_op(metric_type=effective_metric_type), + "metric_fun_op": self.parse_metric_fun_op(), "reranking": self.reranking, "reranking_metric_fun_op": self.parse_reranking_metric_fun_op(), "quantized_fetch_limit": self.quantized_fetch_limit, @@ -277,6 +266,7 @@ def session_param(self) -> PgVectorSessionCommands: session_parameters = {"hnsw.ef_search": self.ef_search, "hnsw.iterative_scan": self.iterative_scan} return {"session_options": self._optionally_build_set_options(session_parameters)} + _pgvector_case_config = { IndexType.HNSW: PgVectorHNSWConfig, IndexType.ES_HNSW: PgVectorHNSWConfig, diff --git a/vectordb_bench/backend/clients/pgvector/pgvector.py b/vectordb_bench/backend/clients/pgvector/pgvector.py index 9d69f3d24..c60b5d69b 100644 --- a/vectordb_bench/backend/clients/pgvector/pgvector.py +++ b/vectordb_bench/backend/clients/pgvector/pgvector.py @@ -13,8 +13,8 @@ from vectordb_bench.backend.filter import Filter, FilterOp -from ..api import MetricType, VectorDB -from .config import PgVectorConfigDict, PgVectorHNSWConfig, PgVectorIndexConfig +from ..api import VectorDB +from .config import PgVectorConfigDict, PgVectorIndexConfig log = logging.getLogger(__name__) @@ -65,6 +65,7 @@ def __init__( # construct basic units self.conn, self.cursor = self._create_connection(**self.connect_config) + # create vector extension self.cursor.execute("CREATE EXTENSION IF NOT EXISTS vector") self.conn.commit() @@ -455,16 +456,6 @@ def _create_table(self, dim: int): log.warning(f"Failed to create pgvector table: {self.table_name} error: {e}") raise e from None - def need_normalize_cosine(self) -> bool: - if ( - isinstance(self.case_config, PgVectorHNSWConfig) - and self.case_config.normalize_cosine - and self.case_config.metric_type == MetricType.COSINE - ): - log.info("current pgvector config enables normalization for cosine metric") - return True - return False - def insert_embeddings( # noqa: PLR0912 self, embeddings: list[list[float]], From 17983f679ea6e77e20a6e61c5ecfbaa71af7731c Mon Sep 17 00:00:00 2001 From: Olasoji Date: Thu, 19 Nov 2026 14:16:03 -0700 Subject: [PATCH 25/33] Restore upstream's pgvector sample result files result_20230727_standard_pgvector.json and result_20230808_standard_pgvector.json are upstream's own reference benchmark results, accidentally deleted in commit 6a2dd21 (a GUC rename/maintenance_work_mem fix unrelated to result data, most likely swept up by a broad commit alongside a local benchmark run) and silently carried through two later rebases since. Restored byte- identical to intel-staging/main; not part of what this PR is adding. Signed-off-by: Olasoji --- .../result_20230727_standard_pgvector.json | 247 ++++++++++++++++++ .../result_20230808_standard_pgvector.json | 187 +++++++++++++ 2 files changed, 434 insertions(+) create mode 100644 vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json create mode 100644 vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json diff --git a/vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json b/vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json new file mode 100644 index 000000000..aacecb4c5 --- /dev/null +++ b/vectordb_bench/results/PgVector/result_20230727_standard_pgvector.json @@ -0,0 +1,247 @@ +{ + "run_id": "5c1e8bd468224ffda1b39b08cdc342c3", + "task_label": "standard", + "results": [ + { + "metrics": { + "max_load_count": 0, + "load_duration": 0, + "qps": 0, + "serial_latency_p99": 0, + "recall": 0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "L2", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 1, + "custom_case": {} + } + }, + "label": "?" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 0, + "qps": 0, + "serial_latency_p99": 0, + "recall": 0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "L2", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 2, + "custom_case": {} + } + }, + "label": "?" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 10247.5034, + "qps": 10.6271, + "serial_latency_p99": 0.7307, + "recall": 0.8898 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "COSINE", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 5, + "custom_case": {} + } + }, + "label": ":)" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 10247.5034, + "qps": 10.8507, + "serial_latency_p99": 0.7332, + "recall": 0.8897 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "COSINE", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 7, + "custom_case": {} + } + }, + "label": ":)" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 10247.5034, + "qps": 75.7055, + "serial_latency_p99": 0.1212, + "recall": 0.9999 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "COSINE", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 9, + "custom_case": {} + } + }, + "label": ":)" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 0, + "qps": 0, + "serial_latency_p99": 0, + "recall": 0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "COSINE", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 4, + "custom_case": {} + } + }, + "label": "x" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 0, + "qps": 0, + "serial_latency_p99": 0, + "recall": 0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "COSINE", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 6, + "custom_case": {} + } + }, + "label": "x" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 0, + "qps": 0, + "serial_latency_p99": 0, + "recall": 0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "COSINE", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 8, + "custom_case": {} + } + }, + "label": "x" + } + ], + "file_fmt": "result_{}_{}_{}.json" +} diff --git a/vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json b/vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json new file mode 100644 index 000000000..2172fe5f2 --- /dev/null +++ b/vectordb_bench/results/PgVector/result_20230808_standard_pgvector.json @@ -0,0 +1,187 @@ +{ + "run_id": "5c1e8bd468224ffda1b39b08cdc342c3", + "task_label": "standard", + "results": [ + { + "metrics": { + "max_load_count": 0, + "load_duration": 1380.9471, + "qps": 0.8836, + "serial_latency_p99": 2.523, + "recall": 0.8528 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "L2", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 10, + "custom_case": {} + } + }, + "label": ":)" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 0.0, + "qps": 0.0, + "serial_latency_p99": 0.0, + "recall": 0.0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "metric_type": "L2", + "lists": 10, + "probes": 2, + "index": "IVF_FLAT" + }, + "case_config": { + "case_id": 11, + "custom_case": {} + } + }, + "label": "?" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 1380.9471, + "qps": 0.8937, + "serial_latency_p99": 3.7202, + "recall": 0.8525 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "metric_type": "L2", + "lists": 10, + "probes": 2, + "index": "IVF_FLAT" + }, + "case_config": { + "case_id": 12, + "custom_case": {} + } + }, + "label": ":)" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 0.0, + "qps": 0.0, + "serial_latency_p99": 0.0, + "recall": 0.0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "L2", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 13, + "custom_case": {} + } + }, + "label": "?" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 1372.7522, + "qps": 1.2145, + "serial_latency_p99": 3.6224, + "recall": 0.7487 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "L2", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 14, + "custom_case": {} + } + }, + "label": ":)" + }, + { + "metrics": { + "max_load_count": 0, + "load_duration": 0.0, + "qps": 0.0, + "serial_latency_p99": 0.0, + "recall": 0.0 + }, + "task_config": { + "db": "PgVector", + "db_config": { + "db_label": "2c8g", + "user_name": "**********", + "password": "**********", + "url": "**********", + "db_name": "**********" + }, + "db_case_config": { + "index": "IVF_FLAT", + "metric_type": "L2", + "lists": 10, + "probes": 2 + }, + "case_config": { + "case_id": 15, + "custom_case": {} + } + }, + "label": "?" + } + ], + "file_fmt": "result_{}_{}_{}.json" +} From 444c77a2fbafa57ceb0d65e12b3224c4567f92f0 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 12:06:21 -0700 Subject: [PATCH 26/33] Stop logging the plaintext password in PgSVS startup messages Add an allow-list helper exposing only host/port/dbname/user, used at both log sites that previously printed connect_config verbatim. --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 7dec4d779..30824fee1 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -20,6 +20,12 @@ 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""" @@ -66,7 +72,8 @@ def __init__( "Extension 'svs' is not installed. Run 'CREATE EXTENSION svs;' as a PostgreSQL superuser first." ) - log.info(f"{self.name} config values: {self.connect_config}\n{self.case_config}") + 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, @@ -75,7 +82,7 @@ def __init__( ): msg = ( f"{self.name} config must create an index using create_index_before_load or create_index_after_load" - f"{self.name} config values: {self.connect_config}\n{self.case_config}" + f"{self.name} config values: {safe_connect_config}\n{self.case_config}" ) log.error(msg) raise RuntimeError(msg) From 566333bacdf0dca6ee84936b0b9da1ce4edcd0ed Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 12:19:30 -0700 Subject: [PATCH 27/33] Scope the vamana index name to its table self._index_name was the hardcoded literal "pgvector_index" across all PgSVS instances, so dropping or creating one table's index could silently affect another table's index of the same name. Derive it from the table name instead, and drop the now-redundant separate DROP INDEX before DROP TABLE, which already cascades. Signed-off-by: Olasoji --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 30824fee1..683671cad 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -57,7 +57,7 @@ def __init__( self.dim = dim self.with_scalar_labels = with_scalar_labels - self._index_name = "pgvector_index" + self._index_name = f"{self.table_name}_svs_index" self._primary_field = "id" self._vector_field = "embedding" self._scalar_label_field = "label" @@ -88,7 +88,7 @@ def __init__( raise RuntimeError(msg) if drop_old: - self._drop_index() + # 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: From 94362cc2c0a7055b64822783d90d14722cff0d09 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 13:25:06 -0700 Subject: [PATCH 28/33] Reject search_window_size values too small for the requested k The vamana scan always fetches exactly search_window_size candidates regardless of SQL LIMIT, so k > search_window_size silently caps recall below what was requested. Only checked when explicitly set; unset behaves as before, deferring to svs's own internal default. Signed-off-by: Olasoji --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 683671cad..91e9a1c3b 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -476,6 +476,14 @@ def search_embedding( 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, From 889fb32c244ac88a3c2305a7eb199a281980c132 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 13:31:43 -0700 Subject: [PATCH 29/33] Stop persisting index-build settings onto the connection role ALTER USER SET for maintenance_work_mem and the parallel-worker GUCs changes the role's defaults for every future login, not just the current session. The existing session-scoped SET already covers what the index build needs. --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 91e9a1c3b..65db8d52b 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -249,12 +249,6 @@ def _set_parallel_index_build_param(self): index_param["maintenance_work_mem"], ), ) - self.cursor.execute( - sql.SQL("ALTER USER {} SET maintenance_work_mem TO {};").format( - sql.Identifier(self.connect_config["user"]), - index_param["maintenance_work_mem"], - ), - ) self.conn.commit() if index_param["max_parallel_workers"] is not None: @@ -263,23 +257,11 @@ def _set_parallel_index_build_param(self): index_param["max_parallel_workers"], ), ) - self.cursor.execute( - sql.SQL("ALTER USER {} SET max_parallel_maintenance_workers TO '{}';").format( - sql.Identifier(self.connect_config["user"]), - 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 USER {} SET max_parallel_workers TO '{}';").format( - sql.Identifier(self.connect_config["user"]), - index_param["max_parallel_workers"], - ), - ) self.cursor.execute( sql.SQL("ALTER TABLE {} SET (parallel_workers = {});").format( sql.Identifier(self.table_name), From ea66aa69d82386af1c73e0d34ab41723dd4a8b17 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 13:35:00 -0700 Subject: [PATCH 30/33] Validate compression_primary/secondary as a pair, not independently svs only compiles a fixed set of (primary, secondary) pairs per scheme (LeanVec: abs(primary) <= abs(secondary); LVQ: an 8-bit primary needs secondary=0); check this at construction instead of per field, and reorder the UI dropdowns so the default (4, 8) is valid under both schemes instead of the previous (-8, -8). --- .../backend/clients/pgsvs/config.py | 31 +++++++++++++++++++ .../frontend/config/dbCaseConfigs.py | 6 ++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/config.py b/vectordb_bench/backend/clients/pgsvs/config.py index 13e89134e..f9d730e64 100644 --- a/vectordb_bench/backend/clients/pgsvs/config.py +++ b/vectordb_bench/backend/clients/pgsvs/config.py @@ -258,6 +258,37 @@ def validate_compression_secondary(self): 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 diff --git a/vectordb_bench/frontend/config/dbCaseConfigs.py b/vectordb_bench/frontend/config/dbCaseConfigs.py index f5a2af233..8b9a227df 100644 --- a/vectordb_bench/frontend/config/dbCaseConfigs.py +++ b/vectordb_bench/frontend/config/dbCaseConfigs.py @@ -1750,7 +1750,8 @@ class CaseConfigInput(BaseModel): inputHelp="Primary encoding width for LeanVec/LVQ compression", inputType=InputType.Option, inputConfig={ - "options": [-8, -4, 4, 8], + # 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], ) @@ -1761,7 +1762,8 @@ class CaseConfigInput(BaseModel): inputHelp="Secondary/residual encoding width. 0 (no residual) is only valid when compression type is LVQ.", inputType=InputType.Option, inputConfig={ - "options": [-8, -4, 0, 4, 8], + # 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], ) From 57cf093dcdd9bf7e410d428024b87cdbf462f6e9 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 13:30:07 -0700 Subject: [PATCH 31/33] Validate a reused index matches this run's config On drop_old=False, check the existing index's access method, operator class, column type, and build-time reloptions against the current config before accepting reuse. Skips cleanly if no index exists yet. Signed-off-by: Olasoji --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index 65db8d52b..bf4bbb5b3 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -93,6 +93,8 @@ def __init__( 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() @@ -216,6 +218,57 @@ def _drop_table(self): ) 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() From d500a312272d088a2beb56ad8a7a73516199f782 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 20:38:57 -0700 Subject: [PATCH 32/33] Add a dedicated offline test file for PgSVS Covers config validation and bounds, the compression-pair rule, the 5 client-level fixes (password redaction, table-scoped index naming, search_window_size vs k, reused-index validation, no ALTER USER on the build settings), and general lifecycle behavior (thread safety, copy_for_thread, optimize ordering, filter prep, init guard). All tests mock the connection; none require a live database. Signed-off-by: Olasoji --- tests/test_pgsvs.py | 599 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 599 insertions(+) create mode 100644 tests/test_pgsvs.py 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), + ) From bedccbfbb9f12f076f8dd318585e16d4f2fd4026 Mon Sep 17 00:00:00 2001 From: Olasoji Date: Tue, 24 Nov 2026 20:55:14 -0700 Subject: [PATCH 33/33] Reformat with black 26 to fix CI's lint check CI's unpinned black resolved to 26.10.1, which reformats triple-quoted strings and blank lines around class definitions differently than the black version used locally when these files were written. Signed-off-by: Olasoji --- vectordb_bench/backend/clients/pgsvs/pgsvs.py | 6 ++---- vectordb_bench/cli/cli.py | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/vectordb_bench/backend/clients/pgsvs/pgsvs.py b/vectordb_bench/backend/clients/pgsvs/pgsvs.py index bf4bbb5b3..438506114 100644 --- a/vectordb_bench/backend/clients/pgsvs/pgsvs.py +++ b/vectordb_bench/backend/clients/pgsvs/pgsvs.py @@ -408,12 +408,10 @@ def _create_table(self, dim: int): ) else: self.cursor.execute( - sql.SQL( - """ + sql.SQL(""" CREATE TABLE IF NOT EXISTS public.{table_name} ({primary_field} BIGINT PRIMARY KEY, embedding {table_quantization_type}({dim})); - """ - ).format( + """).format( table_name=sql.Identifier(self.table_name), table_quantization_type=sql.SQL(index_param["table_quantization_type"]), dim=dim, diff --git a/vectordb_bench/cli/cli.py b/vectordb_bench/cli/cli.py index 97b09d976..b2d45e337 100644 --- a/vectordb_bench/cli/cli.py +++ b/vectordb_bench/cli/cli.py @@ -827,6 +827,7 @@ class CommonTypedDict(TypedDict): ), ] + class SVSBaseTypedDict(TypedDict): graph_degree: Annotated[ int | None, @@ -942,7 +943,6 @@ class SVSBaseTypedDict(TypedDict): ] - class HNSWBaseTypedDict(TypedDict): m: Annotated[int | None, click.option("--m", type=int, help="hnsw m")] ef_construction: Annotated[