From 58f5fc267e73c392e50b6f6f6bbc175a242aff3e Mon Sep 17 00:00:00 2001 From: "haitaohua@163.com" Date: Wed, 28 Oct 2026 10:24:19 +0800 Subject: [PATCH 1/2] feat(houyidb): add HouyiDB client HouyiDB is a memory-first vector database with an HNSW index. It exposes a PostgreSQL-compatible pgwire endpoint with a compact BYTEA batch format for unfiltered upserts and searches, plus an HTTP benchmark API for scalar labels, id filters, optimize and index status. The client uses pgwire for unfiltered workloads and switches to HTTP for filtered cases. NumGE is translated to a strict filter_gt_id so that the benchmark's >= semantics are preserved. Scalar labels are sent with the insert batch because only the HTTP data plane stores them. Register DB.HouyiDB (client/config/case config), add the `houyidb` optional dependency extra, the CLI command and README usage notes. Offline unit tests cover payload encoding, registration, filter routing and label-aware insert routing. --- README.md | 38 ++ pyproject.toml | 1 + tests/test_houyidb.py | 178 ++++++++ vectordb_bench/backend/clients/__init__.py | 16 + vectordb_bench/backend/clients/houyidb/cli.py | 147 +++++++ .../backend/clients/houyidb/config.py | 49 +++ .../backend/clients/houyidb/houyidb.py | 388 ++++++++++++++++++ vectordb_bench/cli/vectordbbench.py | 2 + 8 files changed, 819 insertions(+) create mode 100644 tests/test_houyidb.py create mode 100644 vectordb_bench/backend/clients/houyidb/cli.py create mode 100644 vectordb_bench/backend/clients/houyidb/config.py create mode 100644 vectordb_bench/backend/clients/houyidb/houyidb.py diff --git a/README.md b/README.md index be91a801f..1c135d9e3 100644 --- a/README.md +++ b/README.md @@ -845,6 +845,44 @@ To list the options for VolcMySQL, execute `vectordbbench volcmysqlhnsw --help`. > Note: vectors are loaded and queried over the raw-binary `VECTOR` path by default; the client auto-probes server support and falls back to `to_vector()` text when unavailable. Set `VDB_BINARY_VEC=0` to force the text path or `1` to force binary. +### Run HouyiDB from command line + +HouyiDB is a memory-first vector database with an HNSW index, a PostgreSQL-compatible pgwire endpoint and an HTTP benchmark API. Install the optional client dependencies with `pip install vectordb-bench[houyidb]`. The client loads and searches over pgwire by default and switches to the HTTP API for filtered cases or when `--transport http` is selected. Start HouyiDB from an empty data directory for a cold run. + +```shell +vectordbbench houyidb \ + --case-type Performance1536D50K \ + --host \ + --port 15432 \ + --http-port 17000 \ + --transport pgwire \ + --m 24 \ + --ef-construction 400 \ + --ef-search 256 \ + --num-concurrency '10,20,40,60,80' \ + --concurrency-duration 30 \ + --task-label \ + --db-label +``` + +To list the options for HouyiDB, execute `vectordbbench houyidb --help`. The following are some HouyiDB-specific command-line options. + +```text + --host TEXT HouyiDB host [required] + --port INTEGER HouyiDB pgwire port [default: 15432] + --http-port INTEGER Benchmark HTTP port [default: 17000] + --transport [pgwire|http] Data plane [default: pgwire] + --use-tls / --no-use-tls Use HTTPS for HTTP requests [default: no-use-tls] + --api-key TEXT Optional token: HTTP Bearer or pgwire password + --timeout-sec INTEGER Per-request timeout in seconds [default: 600] + --metric-type [L2|COSINE|IP] Distance metric [default: COSINE] + --m INTEGER HNSW m [default: 24] + --ef-construction INTEGER HNSW ef_construction [default: 400] + --ef-search INTEGER HNSW ef_search [default: 256] +``` + +Filtered cases use the HTTP data plane because that is where HouyiDB accepts scalar labels and id filters. + #### Using a configuration file. The vectordbbench command can optionally read some or all the options from a yaml formatted configuration file. diff --git a/pyproject.toml b/pyproject.toml index 98ace9b85..e6f172569 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -95,6 +95,7 @@ seekdb = [ "mysql-connector-python" ] volc_mysql = [ "mysql-connector-python" ] pinot = [ "requests" ] adbpg = [ "psycopg", "psycopg-binary", "pgvector" ] +houyidb = [ "requests", "psycopg[binary]>=3.1" ] [project.urls] Repository = "https://github.com/zilliztech/VectorDBBench" diff --git a/tests/test_houyidb.py b/tests/test_houyidb.py new file mode 100644 index 000000000..515ae5444 --- /dev/null +++ b/tests/test_houyidb.py @@ -0,0 +1,178 @@ +"""Unit tests for the HouyiDB client. + +These tests do not require a live server. They cover: + - HouyiDBConfig / HouyiDBIndexConfig defaults and param assembly + - AUB1 upsert and AVB1 query payload layout + - DB registration (init_cls / config_cls / case_config_cls) + - Filter routing: NumGE -> strict filter_gt_id, StrEqual -> filter_label + - Scalar labels route inserts through the HTTP data plane +""" + +from __future__ import annotations + +import struct + +import pytest + +from vectordb_bench.backend.clients import DB +from vectordb_bench.backend.clients.api import MetricType +from vectordb_bench.backend.clients.houyidb.config import HouyiDBConfig, HouyiDBIndexConfig +from vectordb_bench.backend.clients.houyidb.houyidb import ( + HouyiDB, + _encode_query_vector, + _encode_upsert_batch, +) +from vectordb_bench.backend.filter import IntFilter, LabelFilter + + +def make_db(dim: int = 4, **overrides) -> HouyiDB: + db_config = { + "host": "127.0.0.1", + "port": 15432, + "http_port": 17000, + "transport": "pgwire", + } + db_config.update(overrides) + return HouyiDB( + dim=dim, + db_config=db_config, + db_case_config=HouyiDBIndexConfig(metric_type=MetricType.COSINE), + ) + + +class _FakeResponse: + def __init__(self, ids: list[int]) -> None: + self._ids = ids + + def raise_for_status(self) -> None: + return + + def json(self) -> dict: + return {"ids": self._ids} + + +class _FakeSession: + def __init__(self, ids: list[int] | None = None) -> None: + self.captured: dict = {} + self._ids = ids or [] + + def post(self, url: str, json: dict, timeout: int) -> _FakeResponse: + self.captured.update(url=url, json=json, timeout=timeout) + return _FakeResponse(self._ids) + + +class TestHouyiDBConfig: + def test_defaults_and_to_dict(self): + cfg = HouyiDBConfig(host="db.local") + assert cfg.port == 15432 + assert cfg.http_port == 17000 + assert cfg.transport == "pgwire" + assert cfg.timeout_sec == 600 + assert cfg.to_dict() == { + "host": "db.local", + "port": 15432, + "use_tls": False, + "transport": "pgwire", + "api_key": None, + "timeout_sec": 600, + "http_port": 17000, + } + + def test_index_and_search_param(self): + cfg = HouyiDBIndexConfig( + metric_type=MetricType.L2, + m=16, + ef_construction=200, + ef_search=64, + ) + assert cfg.index_param() == { + "metric_type": "L2", + "m": 16, + "ef_construction": 200, + } + assert cfg.search_param() == {"ef_search": 64} + + +class TestEncoders: + def test_upsert_batch_layout(self): + payload = _encode_upsert_batch(3, [(7, [1.0, 2.0, 3.0])]) + assert payload[:4] == b"AUB1" + dim, count = struct.unpack(" tuple[int, None]: + captured.update(vectors=vectors, metadata=metadata, labels=labels) + return len(vectors), None + + monkeypatch.setattr(db, "_insert_http", fake_insert_http) + inserted, err = db.insert_embeddings( + [[0.0, 0.0, 0.0, 0.0]], + [42], + labels_data=["label_1p"], + ) + + assert err is None + assert inserted == 1 + assert captured["metadata"] == [42] + assert captured["labels"] == ["label_1p"] diff --git a/vectordb_bench/backend/clients/__init__.py b/vectordb_bench/backend/clients/__init__.py index d13ac9927..734d5dc4f 100644 --- a/vectordb_bench/backend/clients/__init__.py +++ b/vectordb_bench/backend/clients/__init__.py @@ -69,6 +69,7 @@ class DB(Enum): SeekDB = "SeekDB" VolcMySQL = "VolcMySQL" Adbpg = "AnalyticDB for PostgreSQL" + HouyiDB = "HouyiDB" @property def init_cls(self) -> type[VectorDB]: # noqa: PLR0911, PLR0912, C901, PLR0915 @@ -305,6 +306,11 @@ def init_cls(self) -> type[VectorDB]: # noqa: PLR0911, PLR0912, C901, PLR0915 return Adbpg + if self == DB.HouyiDB: + from .houyidb.houyidb import HouyiDB + + return HouyiDB + msg = f"Unknown DB: {self.name}" raise ValueError(msg) @@ -543,6 +549,11 @@ def config_cls(self) -> type[DBConfig]: # noqa: PLR0911, PLR0912, C901, PLR0915 return AdbpgConfig + if self == DB.HouyiDB: + from .houyidb.config import HouyiDBConfig + + return HouyiDBConfig + msg = f"Unknown DB: {self.name}" raise ValueError(msg) @@ -783,6 +794,11 @@ def case_config_cls( # noqa: C901, PLR0911, PLR0912, PLR0915 return _kividb_case_config.get(index_type, KiviDBHNSWConfig) + if self == DB.HouyiDB: + from .houyidb.config import HouyiDBIndexConfig + + return HouyiDBIndexConfig + # DB.Pinecone, DB.Redis return EmptyDBCaseConfig diff --git a/vectordb_bench/backend/clients/houyidb/cli.py b/vectordb_bench/backend/clients/houyidb/cli.py new file mode 100644 index 000000000..b50f839b9 --- /dev/null +++ b/vectordb_bench/backend/clients/houyidb/cli.py @@ -0,0 +1,147 @@ +"""HouyiDB command-line entry point for VectorDBBench.""" + +from typing import Annotated, Unpack + +import click +from pydantic import SecretStr + +from ....cli.cli import ( + CommonTypedDict, + cli, + click_parameter_decorators_from_typed_dict, + run, +) +from .. import DB +from ..api import MetricType + + +class HouyiDBTypedDict(CommonTypedDict): + host: Annotated[ + str, + click.option("--host", type=str, required=True, help="HouyiDB host"), + ] + port: Annotated[ + int, + click.option( + "--port", + type=int, + default=15432, + show_default=True, + help="HouyiDB pgwire port", + ), + ] + http_port: Annotated[ + int | None, + click.option( + "--http-port", + type=int, + default=17000, + show_default=True, + help=("Benchmark HTTP port for health, optimize, index status and the HTTP data plane"), + ), + ] + transport: Annotated[ + str, + click.option( + "--transport", + type=click.Choice(["pgwire", "http"], case_sensitive=False), + default="pgwire", + show_default=True, + help="Data plane: pgwire or the HTTP benchmark API", + ), + ] + use_tls: Annotated[ + bool, + click.option( + "--use-tls/--no-use-tls", + default=False, + show_default=True, + help="Use HTTPS for HTTP requests", + ), + ] + api_key: Annotated[ + str, + click.option( + "--api-key", + envvar="HOUYI_API_KEY", + default="", + show_default=False, + help="Optional token: HTTP Bearer or pgwire password", + ), + ] + timeout_sec: Annotated[ + int, + click.option( + "--timeout-sec", + type=int, + default=600, + show_default=True, + help="Per-request timeout in seconds", + ), + ] + metric_type: Annotated[ + str, + click.option( + "--metric-type", + type=click.Choice( + [metric.name for metric in (MetricType.L2, MetricType.COSINE, MetricType.IP)], + case_sensitive=True, + ), + default=MetricType.COSINE.name, + show_default=True, + help="Distance metric", + ), + ] + m: Annotated[ + int, + click.option("--m", type=int, default=24, show_default=True, help="HNSW m"), + ] + ef_construction: Annotated[ + int, + click.option( + "--ef-construction", + type=int, + default=400, + show_default=True, + help="HNSW ef_construction", + ), + ] + ef_search: Annotated[ + int, + click.option( + "--ef-search", + type=int, + default=256, + show_default=True, + help="HNSW ef_search", + ), + ] + + +@cli.command() +@click_parameter_decorators_from_typed_dict(HouyiDBTypedDict) +def HouyiDB(**parameters: Unpack[HouyiDBTypedDict]): + """Run a VectorDBBench case against HouyiDB.""" + from .config import HouyiDBConfig, HouyiDBIndexConfig + + run( + db=DB.HouyiDB, + db_config=HouyiDBConfig( + db_label=parameters["db_label"], + note=parameters["note"], + host=parameters["host"], + port=parameters["port"], + http_port=parameters["http_port"], + use_tls=parameters["use_tls"], + transport=parameters["transport"].lower(), + api_key=SecretStr(parameters["api_key"]) if parameters["api_key"] else None, + timeout_sec=parameters["timeout_sec"], + ), + db_case_config=HouyiDBIndexConfig( + metric_type=MetricType[parameters["metric_type"]], + m=parameters["m"], + ef_construction=parameters["ef_construction"], + ef_search=parameters["ef_search"], + ), + **parameters, + ) diff --git a/vectordb_bench/backend/clients/houyidb/config.py b/vectordb_bench/backend/clients/houyidb/config.py new file mode 100644 index 000000000..01f9e2017 --- /dev/null +++ b/vectordb_bench/backend/clients/houyidb/config.py @@ -0,0 +1,49 @@ +"""HouyiDB connection and index settings for VectorDBBench.""" + +from __future__ import annotations + +from pydantic import BaseModel, SecretStr + +from ..api import DBCaseConfig, DBConfig, MetricType + + +class HouyiDBConfig(DBConfig): + """Connection settings for a HouyiDB node.""" + + host: str + port: int = 15432 + http_port: int | None = 17000 + use_tls: bool = False + transport: str = "pgwire" + api_key: SecretStr | None = None + timeout_sec: int = 600 + + def to_dict(self) -> dict: + return { + "host": self.host, + "port": self.port, + "use_tls": self.use_tls, + "transport": self.transport, + "api_key": self.api_key.get_secret_value() if self.api_key else None, + "timeout_sec": self.timeout_sec, + "http_port": self.http_port, + } + + +class HouyiDBIndexConfig(BaseModel, DBCaseConfig): + """HNSW build and search settings.""" + + metric_type: MetricType | None = MetricType.COSINE + m: int = 24 + ef_construction: int = 400 + ef_search: int = 256 + + def index_param(self) -> dict: + return { + "metric_type": self.metric_type.name if self.metric_type else MetricType.COSINE.name, + "m": self.m, + "ef_construction": self.ef_construction, + } + + def search_param(self) -> dict: + return {"ef_search": self.ef_search} diff --git a/vectordb_bench/backend/clients/houyidb/houyidb.py b/vectordb_bench/backend/clients/houyidb/houyidb.py new file mode 100644 index 000000000..97ba4f874 --- /dev/null +++ b/vectordb_bench/backend/clients/houyidb/houyidb.py @@ -0,0 +1,388 @@ +"""HouyiDB client for VectorDBBench. + +HouyiDB exposes two data planes: + +* pgwire (PostgreSQL protocol) with a compact BYTEA batch format for vector + upserts and queries; +* an HTTP benchmark API for bulk upserts, filtered search, health checks, + optimize and index status. + +This client uses pgwire for unfiltered workloads and the HTTP API when scalar +labels or id filters are required. Both paths target the same server-side +index. A fresh server (empty WAL) is required for a cold run because the +server has no client-side "drop collection" operation for the main index. +""" + +from __future__ import annotations + +import logging +import struct +import threading +import time +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any + +import requests + +from vectordb_bench.backend.filter import Filter, FilterOp, non_filter +from vectordb_bench.backend.payload import PayloadProfile + +from ..api import MetricType, VectorDB + +if TYPE_CHECKING: + from collections.abc import Generator, Iterable + + from .config import HouyiDBIndexConfig + +log = logging.getLogger(__name__) + + +def _encode_upsert_batch(dim: int, items: list[tuple[int, list[float]]]) -> bytes: + """Encode the AUB1 BYTEA payload understood by the pgwire upsert directive.""" + out = bytearray(b"AUB1") + out.extend(int(dim).to_bytes(4, "little")) + out.extend(len(items).to_bytes(4, "little")) + for vector_id, vector in items: + if len(vector) != dim: + msg = f"AUB1 dim mismatch: expected {dim}, got {len(vector)}" + raise ValueError(msg) + out.extend(int(vector_id).to_bytes(8, "little")) + for value in vector: + out.extend(struct.pack(" bytes: + """Encode the AVB1 BYTEA payload understood by the pgwire query directive.""" + out = bytearray(b"AVB1") + out.extend(len(values).to_bytes(4, "little")) + for value in values: + out.extend(struct.pack(" None: + self.name = "HouyiDB" + self.dim = dim + self.db_config = db_config + self.case_config = db_case_config + self.collection_name = collection_name + self.with_scalar_labels = with_scalar_labels + self.transport = str(db_config.get("transport", "pgwire")).lower() + if self.transport not in ("http", "pgwire"): + msg = f"unsupported HouyiDB transport={self.transport!r}; expected 'pgwire' or 'http'" + raise ValueError(msg) + self.metric = self.case_config.metric_type or MetricType.COSINE + self.timeout_sec = int(db_config.get("timeout_sec", 600)) + raw_api_key = db_config.get("api_key") + self.api_key = raw_api_key.get_secret_value() if hasattr(raw_api_key, "get_secret_value") else raw_api_key + scheme = "https" if db_config.get("use_tls", False) else "http" + http_port = db_config.get("http_port") + self._http_port = int(http_port) if http_port is not None else int(db_config["port"]) + host = str(db_config["host"]) + if ":" in host and not host.startswith("["): + host = f"[{host}]" + self.base_url = f"{scheme}://{host}:{self._http_port}" + + self._thread_local = threading.local() + self._http_sessions_lock = threading.Lock() + self._http_sessions: list[requests.Session] = [] + self._pgwire_sessions_lock = threading.Lock() + self._pgwire_sessions: list[Any] = [] + self._filter: Filter = non_filter + self._connected = False + + if drop_old: + log.warning( + "HouyiDB has no client-side drop for the main index; start a fresh " + "server with an empty WAL for a cold run." + ) + log.info( + "HouyiDB initialized transport=%s dim=%s index=%s", + self.transport, + self.dim, + self.case_config.index_param(), + ) + log.info("HouyiDB search params=%s", self.case_config.search_param()) + + def __getstate__(self) -> dict[str, Any]: + state = dict(self.__dict__) + for key in ( + "_thread_local", + "_http_sessions_lock", + "_http_sessions", + "_pgwire_sessions_lock", + "_pgwire_sessions", + ): + state.pop(key, None) + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__.update(state) + self._thread_local = threading.local() + self._http_sessions_lock = threading.Lock() + self._http_sessions = [] + self._pgwire_sessions_lock = threading.Lock() + self._pgwire_sessions = [] + + def _http_session(self) -> requests.Session: + if not hasattr(self._thread_local, "session"): + session = requests.Session() + if self.api_key: + session.headers.update({"Authorization": f"Bearer {self.api_key}"}) + with self._http_sessions_lock: + self._http_sessions.append(session) + try: + response = session.get(f"{self.base_url}/v1/health", timeout=self.timeout_sec) + response.raise_for_status() + except Exception as exc: + with self._http_sessions_lock: + if session in self._http_sessions: + self._http_sessions.remove(session) + session.close() + msg = f"failed to connect HouyiDB HTTP endpoint {self.base_url}: {exc}" + raise RuntimeError(msg) from exc + self._thread_local.session = session + return self._thread_local.session + + def _pgwire_conn(self) -> Any: + if not hasattr(self._thread_local, "pg_conn"): + try: + import psycopg + from psycopg.conninfo import make_conninfo + except ImportError as exc: + msg = "transport=pgwire requires psycopg; install 'psycopg[binary]>=3.1'" + raise RuntimeError(msg) from exc + params: dict[str, Any] = { + "host": str(self.db_config["host"]), + "port": str(self.db_config["port"]), + "user": self._PGWIRE_USER, + "dbname": self._PGWIRE_DATABASE, + "connect_timeout": str(self.timeout_sec), + } + if self.api_key: + params["password"] = str(self.api_key) + try: + conn = psycopg.connect(make_conninfo(**params), autocommit=True) + conn.execute("SELECT 1") + except Exception as exc: + msg = f"failed to connect HouyiDB pgwire {self.db_config['host']}:{self.db_config['port']}: {exc}" + raise RuntimeError(msg) from exc + with self._pgwire_sessions_lock: + self._pgwire_sessions.append(conn) + self._thread_local.pg_conn = conn + self._thread_local.pg_binary = psycopg.Binary + return self._thread_local.pg_conn + + @contextmanager + def init(self) -> Generator[None, None, None]: + self._connected = True + try: + if self.transport == "http": + self._http_session() + else: + self._pgwire_conn() + yield + finally: + self._connected = False + with self._http_sessions_lock: + for session in self._http_sessions: + try: + session.close() + except Exception: + log.warning("failed to close HouyiDB HTTP session", exc_info=True) + self._http_sessions.clear() + if hasattr(self._thread_local, "session"): + del self._thread_local.session + if self.transport == "pgwire": + with self._pgwire_sessions_lock: + for conn in self._pgwire_sessions: + try: + conn.close() + except Exception: + log.warning("failed to close HouyiDB pgwire connection", exc_info=True) + self._pgwire_sessions.clear() + for attr in ("pg_conn", "pg_binary"): + if hasattr(self._thread_local, attr): + delattr(self._thread_local, attr) + + def optimize(self, data_size: int | None = None) -> None: + """Trigger a server-side optimize and wait until the build backlog drains.""" + del data_size + if not self._connected: + msg = "Please call init() before optimize" + raise RuntimeError(msg) + session = self._http_session() + response = session.post( + f"{self.base_url}/v1/optimize", + timeout=(30, max(7200, self.timeout_sec)), + ) + response.raise_for_status() + poll_seconds = 0.05 + while True: + response = session.get(f"{self.base_url}/v1/index/status", timeout=self.timeout_sec) + response.raise_for_status() + if int(response.json().get("pending_count", 0)) <= 0: + return + time.sleep(poll_seconds) + + def prepare_filter(self, filters: Filter) -> None: + """Store the case filter; search_embedding applies it on the matching path.""" + if filters.type not in self.supported_filter_types: + msg = f"unsupported HouyiDB filter: {filters}" + raise ValueError(msg) + self._filter = filters + + def insert_embeddings( + self, + embeddings: Iterable[list[float]], + metadata: list[int], + labels_data: list[str] | None = None, + tenant_labels_data: list[str] | None = None, + **kwargs: Any, + ) -> tuple[int, Exception | None]: + del kwargs + if not self._connected: + return 0, RuntimeError("Please call init() before insert") + if tenant_labels_data is not None: + return 0, ValueError("HouyiDB does not support multitenant datasets") + vectors = list(embeddings) + if len(vectors) != len(metadata): + return 0, ValueError("embeddings and metadata length mismatch") + + has_labels = labels_data is not None and len(labels_data) == len(vectors) + if self.transport == "http" or has_labels: + return self._insert_http(vectors, metadata, labels_data if has_labels else None) + return self._insert_pgwire(vectors, metadata) + + def _insert_http( + self, + vectors: list[list[float]], + metadata: list[int], + labels: list[str] | None, + ) -> tuple[int, Exception | None]: + inserted = 0 + try: + session = self._http_session() + for start in range(0, len(vectors), self._HTTP_UPSERT_CHUNK_SIZE): + end = start + self._HTTP_UPSERT_CHUNK_SIZE + payload_vectors = [] + for idx, vector in enumerate(vectors[start:end], start=start): + item: dict[str, Any] = {"id": int(metadata[idx]), "values": vector} + if labels is not None: + item["label"] = labels[idx] + payload_vectors.append(item) + payload = { + "vectors": payload_vectors, + "index": { + "m": int(self.case_config.m), + "ef_construction": int(self.case_config.ef_construction), + }, + } + response = session.post( + f"{self.base_url}/v1/vectors/upsert", + json=payload, + timeout=self.timeout_sec, + ) + response.raise_for_status() + inserted += int(response.json().get("inserted", 0)) + except Exception as exc: + return inserted, exc + return inserted, None + + def _insert_pgwire( + self, + vectors: list[list[float]], + metadata: list[int], + ) -> tuple[int, Exception | None]: + inserted = 0 + try: + conn = self._pgwire_conn() + pg_binary = self._thread_local.pg_binary + for start in range(0, len(vectors), self._HTTP_UPSERT_CHUNK_SIZE): + end = min(start + self._HTTP_UPSERT_CHUNK_SIZE, len(vectors)) + chunk = [] + for idx in range(start, end): + vector = vectors[idx] + if len(vector) != self.dim: + return inserted, ValueError(f"dim mismatch, expected {self.dim}, got {len(vector)}") + chunk.append((int(metadata[idx]), vector)) + payload = _encode_upsert_batch(self.dim, chunk) + row = conn.execute( + "/* houyi:upsert_batch=%s */ SELECT 1", + (pg_binary(payload),), + ).fetchone() + inserted += int(row[0]) if row else 0 + except Exception as exc: + return inserted, exc + return inserted, None + + def _search_http(self, query: list[float], k: int) -> list[int]: + payload: dict[str, Any] = { + "vector": query, + "k": int(k), + "ef_search": int(self.case_config.ef_search), + } + if self._filter.type == FilterOp.NumGE and self._filter.int_value > 0: + # HouyiDB's filter_gt_id is strict (>); VectorDBBench NumGE is >=. + payload["filter_gt_id"] = int(self._filter.int_value) - 1 + elif self._filter.type == FilterOp.StrEqual: + payload["filter_label"] = self._filter.label_value + try: + session = self._http_session() + response = session.post( + f"{self.base_url}/v1/vectors/search", + json=payload, + timeout=self.timeout_sec, + ) + response.raise_for_status() + return [int(item) for item in response.json().get("ids", [])] + except Exception as exc: + log.warning("HouyiDB HTTP search failed: %s", exc, exc_info=True) + return [] + + def search_embedding( + self, + query: list[float], + k: int = 100, + payload_profile: PayloadProfile = PayloadProfile.IDS_ONLY, + tenant: str | None = None, + **kwargs: Any, + ) -> list[int]: + del payload_profile, tenant, kwargs + if not self._connected or len(query) != self.dim: + return [] + if self._filter.type != FilterOp.NonFilter: + return self._search_http(query, k) + if self.transport == "http": + return self._search_http(query, k) + try: + conn = self._pgwire_conn() + pg_binary = self._thread_local.pg_binary + vector_payload = _encode_query_vector(query) + ef_search = int(self.case_config.ef_search) + sql = f"/* houyi:ef_search={ef_search} */ /* houyi:vector=%s */ SELECT id FROM docs LIMIT {int(k)}" + rows = conn.execute(sql, (pg_binary(vector_payload),)).fetchall() + return [int(row[0]) for row in rows] + except Exception as exc: + log.warning("HouyiDB pgwire search failed: %s", exc, exc_info=True) + return [] diff --git a/vectordb_bench/cli/vectordbbench.py b/vectordb_bench/cli/vectordbbench.py index a3649ae84..9ed3a2ae8 100644 --- a/vectordb_bench/cli/vectordbbench.py +++ b/vectordb_bench/cli/vectordbbench.py @@ -17,6 +17,7 @@ ) from ..backend.clients.endee.cli import Endee from ..backend.clients.hologres.cli import HologresHGraph +from ..backend.clients.houyidb.cli import HouyiDB from ..backend.clients.lancedb.cli import ( LanceDB, LanceDBAutoIndex, @@ -123,6 +124,7 @@ cli.add_command(PolarDBHNSWSQ) cli.add_command(SeekDBHNSW) cli.add_command(VolcMySQLHNSW) +cli.add_command(HouyiDB) if __name__ == "__main__": From e209a4945cd5c48e09a916fff9fbd04c7c3a9b3c Mon Sep 17 00:00:00 2001 From: "haitaohua@163.com" Date: Thu, 29 Oct 2026 18:50:15 +0800 Subject: [PATCH 2/2] fix(houyidb): address review feedback on errors, isolation, params, timeout - Propagate HTTP/pgwire search failures instead of returning an empty list, so failed requests are counted as failures rather than ultra-fast successes. - Reject datasets whose metric is not COSINE: the server builds a cosine index, so L2/IP ground truth would be measured against a different distance. - Enforce drop_old by rejecting a non-empty main index at construction time; the server has no remote drop, and silently loading on top of old rows contaminates the benchmark. - Verify the server's effective hnsw_m/hnsw_ef_construction from /v1/index/status after load and before search; pgwire applies build parameters only from server startup flags, so a mismatched label aborts. - Bound pgwire statement execution with a per-client watchdog that cancels (then closes) queries exceeding timeout_sec; connect_timeout alone did not limit query execution. --- README.md | 10 +- tests/test_houyidb.py | 226 +++++++++++- vectordb_bench/backend/clients/houyidb/cli.py | 22 +- .../backend/clients/houyidb/config.py | 13 +- .../backend/clients/houyidb/houyidb.py | 330 ++++++++++++++++-- 5 files changed, 549 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 1c135d9e3..3bb5dfb34 100644 --- a/README.md +++ b/README.md @@ -847,7 +847,9 @@ To list the options for VolcMySQL, execute `vectordbbench volcmysqlhnsw --help`. ### Run HouyiDB from command line -HouyiDB is a memory-first vector database with an HNSW index, a PostgreSQL-compatible pgwire endpoint and an HTTP benchmark API. Install the optional client dependencies with `pip install vectordb-bench[houyidb]`. The client loads and searches over pgwire by default and switches to the HTTP API for filtered cases or when `--transport http` is selected. Start HouyiDB from an empty data directory for a cold run. +HouyiDB is a memory-first vector database with an HNSW index, a PostgreSQL-compatible pgwire endpoint and an HTTP benchmark API. Install the optional client dependencies with `pip install vectordb-bench[houyidb]`. The client loads and searches over pgwire by default and switches to the HTTP API for filtered cases or when `--transport http` is selected. + +HouyiDB builds a cosine index, so the client rejects datasets whose distance metric is not `COSINE`. Because the server has no remote drop for the main index, a `drop_old=True` case is rejected when the index is not empty: start HouyiDB from an empty data directory (and empty WAL) before a fresh load. Before measuring, the client reads the effective `hnsw_m`, `hnsw_ef_construction` and `distance_metric` from `/v1/index/status` and aborts the run if they do not match the case configuration. With `--transport pgwire`, start the server with matching build parameters, e.g. `--pgwire-hnsw-m 24 --pgwire-hnsw-efc 400`; `--no-verify-build-params` is available only for older servers that do not report these fields. ```shell vectordbbench houyidb \ @@ -874,8 +876,10 @@ To list the options for HouyiDB, execute `vectordbbench houyidb --help`. The fol --transport [pgwire|http] Data plane [default: pgwire] --use-tls / --no-use-tls Use HTTPS for HTTP requests [default: no-use-tls] --api-key TEXT Optional token: HTTP Bearer or pgwire password - --timeout-sec INTEGER Per-request timeout in seconds [default: 600] - --metric-type [L2|COSINE|IP] Distance metric [default: COSINE] + --timeout-sec INTEGER Per-request timeout in seconds, including pgwire statement execution [default: 600] + --verify-build-params / --no-verify-build-params + Verify the server's effective HNSW build parameters before measuring [default: verify] + --metric-type [COSINE] Distance metric (HouyiDB builds a cosine index) [default: COSINE] --m INTEGER HNSW m [default: 24] --ef-construction INTEGER HNSW ef_construction [default: 400] --ef-search INTEGER HNSW ef_search [default: 256] diff --git a/tests/test_houyidb.py b/tests/test_houyidb.py index 515ae5444..612412976 100644 --- a/tests/test_houyidb.py +++ b/tests/test_houyidb.py @@ -6,11 +6,18 @@ - DB registration (init_cls / config_cls / case_config_cls) - Filter routing: NumGE -> strict filter_gt_id, StrEqual -> filter_label - Scalar labels route inserts through the HTTP data plane + - Rejection of non-cosine datasets + - drop_old enforcement against an occupied index + - Effective HNSW build-parameter verification + - Search failure propagation on both transports + - pgwire statement timeout """ from __future__ import annotations import struct +import threading +import time import pytest @@ -25,7 +32,13 @@ from vectordb_bench.backend.filter import IntFilter, LabelFilter -def make_db(dim: int = 4, **overrides) -> HouyiDB: +def make_db( + dim: int = 4, + *, + case_config: HouyiDBIndexConfig | None = None, + drop_old: bool = False, + **overrides, +) -> HouyiDB: db_config = { "host": "127.0.0.1", "port": 15432, @@ -36,29 +49,105 @@ def make_db(dim: int = 4, **overrides) -> HouyiDB: return HouyiDB( dim=dim, db_config=db_config, - db_case_config=HouyiDBIndexConfig(metric_type=MetricType.COSINE), + db_case_config=case_config or HouyiDBIndexConfig(metric_type=MetricType.COSINE), + drop_old=drop_old, ) class _FakeResponse: - def __init__(self, ids: list[int]) -> None: - self._ids = ids + def __init__(self, payload: dict | None = None, status_code: int = 200) -> None: + self._payload = payload if payload is not None else {} + self.status_code = status_code def raise_for_status(self) -> None: - return + if self.status_code >= 400: + msg = f"HTTP {self.status_code}" + raise RuntimeError(msg) def json(self) -> dict: - return {"ids": self._ids} + return self._payload class _FakeSession: - def __init__(self, ids: list[int] | None = None) -> None: + def __init__( + self, + ids: list[int] | None = None, + status: dict | None = None, + post_error: Exception | None = None, + get_error: Exception | None = None, + ) -> None: self.captured: dict = {} + self.posts: list[dict] = [] + self.gets: list[str] = [] self._ids = ids or [] - - def post(self, url: str, json: dict, timeout: int) -> _FakeResponse: + self._status = status if status is not None else self.default_status() + self._post_error = post_error + self._get_error = get_error + + @staticmethod + def default_status(**overrides) -> dict: + status = { + "hot_count": 0, + "indexed_count": 0, + "pending_count": 0, + "hnsw_m": 24, + "hnsw_ef_construction": 400, + "distance_metric": "cosine", + } + status.update(overrides) + return status + + def get(self, url: str, timeout: int | None = None) -> _FakeResponse: + self.gets.append(url) + if self._get_error is not None: + raise self._get_error + if url.endswith("/v1/index/status"): + return _FakeResponse(self._status) + if url.endswith("/v1/health"): + return _FakeResponse({"status": "ok"}) + return _FakeResponse({}) + + def post(self, url: str, json: dict | None = None, timeout: int | None = None) -> _FakeResponse: + if self._post_error is not None: + raise self._post_error self.captured.update(url=url, json=json, timeout=timeout) - return _FakeResponse(self._ids) + self.posts.append({"url": url, "json": json}) + if url.endswith("/v1/vectors/search"): + return _FakeResponse({"ids": self._ids}) + if url.endswith("/v1/optimize"): + return _FakeResponse({"pending_items": 0}) + return _FakeResponse({"inserted": len((json or {}).get("vectors", []))}) + + +class _BrokenConn: + def execute(self, sql: str, params: object) -> None: + raise RuntimeError("server exploded") + + def close(self) -> None: + pass + + +class _BlockingConn: + def __init__(self) -> None: + self.cancelled = threading.Event() + self.closed = False + + def execute(self, sql: str, params: object) -> None: + self.cancelled.wait(timeout=5) + raise RuntimeError("query cancelled") + + def cancel_safe(self, timeout: float = 5) -> None: + self.cancelled.set() + + def close(self) -> None: + self.closed = True + self.cancelled.set() + + +def _patch_http(monkeypatch: pytest.MonkeyPatch, db: HouyiDB, session: _FakeSession) -> _FakeSession: + db._connected = True + monkeypatch.setattr(db, "_http_session", lambda: session) + return session class TestHouyiDBConfig: @@ -68,6 +157,7 @@ def test_defaults_and_to_dict(self): assert cfg.http_port == 17000 assert cfg.transport == "pgwire" assert cfg.timeout_sec == 600 + assert cfg.verify_build_params is True assert cfg.to_dict() == { "host": "db.local", "port": 15432, @@ -76,6 +166,7 @@ def test_defaults_and_to_dict(self): "api_key": None, "timeout_sec": 600, "http_port": 17000, + "verify_build_params": True, } def test_index_and_search_param(self): @@ -126,6 +217,121 @@ def test_http_port_falls_back_to_pgwire_port(self): assert db.base_url == "http://127.0.0.1:15432" +class TestMetricSupport: + @pytest.mark.parametrize("metric", [MetricType.L2, MetricType.IP]) + def test_rejects_non_cosine_datasets(self, metric: MetricType): + with pytest.raises(ValueError, match="cosine index"): + make_db(case_config=HouyiDBIndexConfig(metric_type=metric)) + + +class TestDropOld: + def test_occupied_index_is_rejected(self, monkeypatch: pytest.MonkeyPatch): + session = _FakeSession(status=_FakeSession.default_status(hot_count=1, indexed_count=2)) + monkeypatch.setattr(HouyiDB, "_http_session", lambda *_: session) + with pytest.raises(RuntimeError, match="not empty"): + make_db(drop_old=True) + + def test_empty_index_is_accepted(self, monkeypatch: pytest.MonkeyPatch): + session = _FakeSession() + monkeypatch.setattr(HouyiDB, "_http_session", lambda *_: session) + db = make_db(drop_old=True) + assert db.metric is MetricType.COSINE + assert any(url.endswith("/v1/index/status") for url in session.gets) + + +class TestBuildParamVerification: + def test_mismatch_is_rejected_before_optimize(self, monkeypatch: pytest.MonkeyPatch): + db = make_db() + session = _patch_http( + monkeypatch, + db, + _FakeSession(status=_FakeSession.default_status(hnsw_m=16)), + ) + with pytest.raises(RuntimeError, match="do not match"): + db.optimize() + assert not any(post["url"].endswith("/v1/optimize") for post in session.posts) + + def test_pgwire_mismatch_mentions_startup_flags(self, monkeypatch: pytest.MonkeyPatch): + db = make_db() + _patch_http( + monkeypatch, + db, + _FakeSession(status=_FakeSession.default_status(hnsw_ef_construction=128)), + ) + with pytest.raises(RuntimeError, match="--pgwire-hnsw-efc 400"): + db.optimize() + + def test_missing_fields_are_rejected(self, monkeypatch: pytest.MonkeyPatch): + status = _FakeSession.default_status() + status.pop("hnsw_m") + db = make_db() + _patch_http(monkeypatch, db, _FakeSession(status=status)) + with pytest.raises(RuntimeError, match="does not report"): + db.optimize() + + def test_verification_can_be_disabled_for_older_servers(self, monkeypatch: pytest.MonkeyPatch): + status = _FakeSession.default_status() + status.pop("hnsw_m") + db = make_db(verify_build_params=False) + session = _patch_http(monkeypatch, db, _FakeSession(status=status)) + db.optimize() + assert any(post["url"].endswith("/v1/optimize") for post in session.posts) + + def test_matching_params_allow_optimize(self, monkeypatch: pytest.MonkeyPatch): + db = make_db() + session = _patch_http(monkeypatch, db, _FakeSession()) + db.optimize() + assert any(post["url"].endswith("/v1/optimize") for post in session.posts) + + +class TestSearchFailures: + def test_http_failure_propagates(self, monkeypatch: pytest.MonkeyPatch): + db = make_db(transport="http") + _patch_http(monkeypatch, db, _FakeSession(post_error=RuntimeError("connection reset"))) + with pytest.raises(RuntimeError, match="connection reset"): + db.search_embedding([0.0, 0.0, 0.0, 0.0], k=2) + + def test_pgwire_failure_propagates(self, monkeypatch: pytest.MonkeyPatch): + db = make_db() + db._connected = True + db._build_params_verified = True + db._thread_local.pg_binary = lambda payload: payload + monkeypatch.setattr(db, "_pgwire_conn", _BrokenConn) + with pytest.raises(RuntimeError, match="server exploded"): + db.search_embedding([0.0, 0.0, 0.0, 0.0], k=2) + + def test_successful_zero_hits_return_empty(self, monkeypatch: pytest.MonkeyPatch): + db = make_db(transport="http") + _patch_http(monkeypatch, db, _FakeSession(ids=[])) + assert db.search_embedding([0.0, 0.0, 0.0, 0.0], k=2) == [] + + def test_search_before_init_raises(self): + db = make_db() + with pytest.raises(RuntimeError, match="init"): + db.search_embedding([0.0, 0.0, 0.0, 0.0], k=2) + + def test_query_dim_mismatch_raises(self): + db = make_db() + db._connected = True + with pytest.raises(ValueError, match="dim mismatch"): + db.search_embedding([0.0, 0.0], k=2) + + +class TestPgwireTimeout: + def test_blocked_statement_times_out_and_closes(self): + db = make_db() + db.timeout_sec = 1 + conn = _BlockingConn() + started = time.monotonic() + try: + with pytest.raises(TimeoutError, match="timeout_sec=1"): + db._execute_bounded(conn, "SELECT 1", None) + finally: + db._pgwire_watchdog.stop() + assert time.monotonic() - started < 3.0 + assert conn.closed + + class TestFilterRouting: def test_num_ge_uses_strict_gt_id(self, monkeypatch: pytest.MonkeyPatch): db = make_db() diff --git a/vectordb_bench/backend/clients/houyidb/cli.py b/vectordb_bench/backend/clients/houyidb/cli.py index b50f839b9..04ce7063b 100644 --- a/vectordb_bench/backend/clients/houyidb/cli.py +++ b/vectordb_bench/backend/clients/houyidb/cli.py @@ -76,20 +76,29 @@ class HouyiDBTypedDict(CommonTypedDict): type=int, default=600, show_default=True, - help="Per-request timeout in seconds", + help="Per-request timeout in seconds (also bounds pgwire statement execution)", + ), + ] + verify_build_params: Annotated[ + bool, + click.option( + "--verify-build-params/--no-verify-build-params", + default=True, + show_default=True, + help=( + "Verify the server's effective HNSW m/ef_construction match the case config " + "before measuring; disable only for servers that do not report them" + ), ), ] metric_type: Annotated[ str, click.option( "--metric-type", - type=click.Choice( - [metric.name for metric in (MetricType.L2, MetricType.COSINE, MetricType.IP)], - case_sensitive=True, - ), + type=click.Choice([MetricType.COSINE.name], case_sensitive=True), default=MetricType.COSINE.name, show_default=True, - help="Distance metric", + help="Distance metric (HouyiDB builds a cosine index)", ), ] m: Annotated[ @@ -136,6 +145,7 @@ def HouyiDB(**parameters: Unpack[HouyiDBTypedDict]): transport=parameters["transport"].lower(), api_key=SecretStr(parameters["api_key"]) if parameters["api_key"] else None, timeout_sec=parameters["timeout_sec"], + verify_build_params=parameters["verify_build_params"], ), db_case_config=HouyiDBIndexConfig( metric_type=MetricType[parameters["metric_type"]], diff --git a/vectordb_bench/backend/clients/houyidb/config.py b/vectordb_bench/backend/clients/houyidb/config.py index 01f9e2017..8f2a296d4 100644 --- a/vectordb_bench/backend/clients/houyidb/config.py +++ b/vectordb_bench/backend/clients/houyidb/config.py @@ -17,6 +17,11 @@ class HouyiDBConfig(DBConfig): transport: str = "pgwire" api_key: SecretStr | None = None timeout_sec: int = 600 + # Reject a run when the server does not report, or reports values other + # than, the requested HNSW build parameters. Disable only for servers + # older than the /v1/index/status build-parameter fields; doing so means + # the recorded m/ef_construction may differ from the effective graph. + verify_build_params: bool = True def to_dict(self) -> dict: return { @@ -27,11 +32,17 @@ def to_dict(self) -> dict: "api_key": self.api_key.get_secret_value() if self.api_key else None, "timeout_sec": self.timeout_sec, "http_port": self.http_port, + "verify_build_params": self.verify_build_params, } class HouyiDBIndexConfig(BaseModel, DBCaseConfig): - """HNSW build and search settings.""" + """HNSW build and search settings. + + HouyiDB's main index is built with cosine distance; the client rejects + datasets that ask for any other metric instead of benchmarking a + different distance than the dataset ground truth uses. + """ metric_type: MetricType | None = MetricType.COSINE m: int = 24 diff --git a/vectordb_bench/backend/clients/houyidb/houyidb.py b/vectordb_bench/backend/clients/houyidb/houyidb.py index 97ba4f874..2aa328cb1 100644 --- a/vectordb_bench/backend/clients/houyidb/houyidb.py +++ b/vectordb_bench/backend/clients/houyidb/houyidb.py @@ -10,11 +10,19 @@ This client uses pgwire for unfiltered workloads and the HTTP API when scalar labels or id filters are required. Both paths target the same server-side index. A fresh server (empty WAL) is required for a cold run because the -server has no client-side "drop collection" operation for the main index. +server has no client-side "drop collection" operation for the main index: +``drop_old=True`` is enforced by rejecting an occupied index instead of +silently loading on top of stale data. + +Search failures are propagated to VectorDBBench's runner so a failed request +is never counted as a successful (and extremely fast) query. HouyiDB builds a +cosine index, so datasets using another distance metric are rejected instead +of being benchmarked against incompatible ground truth. """ from __future__ import annotations +import contextlib import logging import struct import threading @@ -61,6 +69,119 @@ def _encode_query_vector(values: list[float]) -> bytes: return bytes(out) +class _InflightPgwireQuery: + """One pgwire statement under a hard client-side deadline.""" + + __slots__ = ("cancel_called", "close_called", "close_deadline", "conn", "deadline", "timed_out") + + def __init__(self, conn: Any, deadline: float, close_deadline: float) -> None: + self.conn = conn + self.deadline = deadline + self.close_deadline = close_deadline + self.timed_out = threading.Event() + self.cancel_called = False + self.close_called = False + + def abort(self, now: float) -> None: + if now >= self.deadline and not self.cancel_called: + self.cancel_called = True + self.timed_out.set() + self._cancel() + # A cancellation that does not unblock libpq (dead peer, half-open + # socket) is followed by closing the connection: the only remaining + # way to bound the call. + if now >= self.close_deadline and not self.close_called: + self.close_called = True + with contextlib.suppress(Exception): + # Best-effort unblock; close is the last resort. + self.conn.close() + + def _cancel(self) -> None: + cancel_safe = getattr(self.conn, "cancel_safe", None) + if callable(cancel_safe): + try: + cancel_safe(timeout=5) + except TypeError: + try: + cancel_safe() + except Exception: + log.debug("HouyiDB pgwire cancel_safe() failed", exc_info=True) + else: + return + except Exception: + log.debug("HouyiDB pgwire cancel_safe(timeout=5) failed", exc_info=True) + else: + return + cancel = getattr(self.conn, "cancel", None) + if callable(cancel): + with contextlib.suppress(Exception): + # Legacy psycopg 3.1 fallback; abort() closes the connection + # after the grace period if cancellation does not unblock. + cancel() + + +class _PgwireWatchdog: + """Cancel pgwire statements that outlive ``timeout_sec``. + + psycopg's ``connect_timeout`` only bounds connection establishment, so a + blocked statement would otherwise never expire. One daemon thread per + client instance scans the in-flight statements, which is much cheaper + than creating a timer thread per query at benchmark rates. + """ + + _POLL_SECONDS = 0.05 + _CLOSE_GRACE_SECONDS = 5.0 + + def __init__(self) -> None: + self._lock = threading.Lock() + self._inflight: dict[int, _InflightPgwireQuery] = {} + self._stop = threading.Event() + self._thread: threading.Thread | None = None + + def start(self) -> None: + with self._lock: + if self._thread is not None and self._thread.is_alive(): + return + self._stop.clear() + self._thread = threading.Thread( + target=self._run, + name="houyidb-pgwire-watchdog", + daemon=True, + ) + self._thread.start() + + def stop(self) -> None: + self._stop.set() + thread = self._thread + if thread is not None and thread is not threading.current_thread(): + thread.join(timeout=1.0) + self._thread = None + + def register(self, conn: Any, timeout_sec: float) -> _InflightPgwireQuery: + now = time.monotonic() + token = _InflightPgwireQuery( + conn, + now + timeout_sec, + now + timeout_sec + self._CLOSE_GRACE_SECONDS, + ) + with self._lock: + self._inflight[id(token)] = token + return token + + def unregister(self, token: _InflightPgwireQuery) -> None: + with self._lock: + self._inflight.pop(id(token), None) + + def _run(self) -> None: + while not self._stop.wait(self._POLL_SECONDS): + now = time.monotonic() + with self._lock: + tokens = list(self._inflight.values()) + for token in tokens: + if now >= token.deadline: + token.abort(now) + + class HouyiDB(VectorDB): """VectorDBBench client for HouyiDB.""" @@ -92,7 +213,15 @@ def __init__( msg = f"unsupported HouyiDB transport={self.transport!r}; expected 'pgwire' or 'http'" raise ValueError(msg) self.metric = self.case_config.metric_type or MetricType.COSINE + if self.metric is not MetricType.COSINE: + msg = ( + f"HouyiDB builds a cosine index; dataset metric {self.metric.name} is not supported. " + "VectorDBBench would otherwise measure cosine search against " + f"{self.metric.name} ground truth." + ) + raise ValueError(msg) self.timeout_sec = int(db_config.get("timeout_sec", 600)) + self.verify_build_params = bool(db_config.get("verify_build_params", True)) raw_api_key = db_config.get("api_key") self.api_key = raw_api_key.get_secret_value() if hasattr(raw_api_key, "get_secret_value") else raw_api_key scheme = "https" if db_config.get("use_tls", False) else "http" @@ -108,14 +237,18 @@ def __init__( self._http_sessions: list[requests.Session] = [] self._pgwire_sessions_lock = threading.Lock() self._pgwire_sessions: list[Any] = [] + self._pgwire_watchdog = _PgwireWatchdog() self._filter: Filter = non_filter self._connected = False + self._build_params_verified = False + self._build_params_warned = False + # VectorDBBench constructs the client once per fresh load and pickles + # it into search workers afterwards, so the emptiness check belongs + # here: `init()` also runs inside those workers, where the index is + # legitimately populated. if drop_old: - log.warning( - "HouyiDB has no client-side drop for the main index; start a fresh " - "server with an empty WAL for a cold run." - ) + self._ensure_empty_index() log.info( "HouyiDB initialized transport=%s dim=%s index=%s", self.transport, @@ -132,6 +265,7 @@ def __getstate__(self) -> dict[str, Any]: "_http_sessions", "_pgwire_sessions_lock", "_pgwire_sessions", + "_pgwire_watchdog", ): state.pop(key, None) return state @@ -143,6 +277,11 @@ def __setstate__(self, state: dict[str, Any]) -> None: self._http_sessions = [] self._pgwire_sessions_lock = threading.Lock() self._pgwire_sessions = [] + self._pgwire_watchdog = _PgwireWatchdog() + # Each worker process must observe the server's effective parameters + # itself; a parent-process success is not a proof for this process. + self._build_params_verified = False + self._build_params_warned = False def _http_session(self) -> requests.Session: if not hasattr(self._thread_local, "session"): @@ -164,6 +303,127 @@ def _http_session(self) -> requests.Session: self._thread_local.session = session return self._thread_local.session + def _index_status(self) -> dict[str, Any]: + """Fetch the main-index status (hot/indexed/pending plus HNSW config).""" + session = self._http_session() + response = session.get(f"{self.base_url}/v1/index/status", timeout=self.timeout_sec) + response.raise_for_status() + payload = response.json() + if not isinstance(payload, dict): + msg = f"unexpected HouyiDB index status payload: {payload!r}" + raise TypeError(msg) + return payload + + def _ensure_empty_index(self) -> None: + """Enforce ``drop_old``: refuse a populated index instead of contaminating a run. + + HouyiDB has no remote drop operation for the main index. A fresh load + on an occupied index would keep stale rows from an earlier case and + silently mix two datasets, so the client fails loudly and tells the + operator how to obtain a clean server. + """ + status = self._index_status() + occupied = sum(int(status.get(key, 0)) for key in ("hot_count", "indexed_count", "pending_count")) + if occupied: + msg = ( + "drop_old=True but the HouyiDB main index is not empty " + f"(hot={status.get('hot_count')}, indexed={status.get('indexed_count')}, " + f"pending={status.get('pending_count')}, collection={self.collection_name!r}). " + "HouyiDB has no remote drop: stop the server, remove its WAL/data directory, " + "restart it, and rerun the case." + ) + raise RuntimeError(msg) + + def _verify_build_params(self) -> None: + """Verify that the server's effective HNSW parameters match the case config. + + pgwire applies build parameters only from the server's startup flags + (``--pgwire-hnsw-m`` / ``--pgwire-hnsw-efc``); the HTTP path applies the + per-request hints. Either way, recording ``m``/``ef_construction`` from + the case config without checking the server would mislabel the run, so + this probes ``/v1/index/status`` after the load and before search. + """ + if self._build_params_verified: + return + if not self.verify_build_params: + if not self._build_params_warned: + log.warning( + "HouyiDB build-parameter verification is disabled; recorded m=%s " + "ef_construction=%s may differ from the server's effective graph", + self.case_config.m, + self.case_config.ef_construction, + ) + self._build_params_warned = True + self._build_params_verified = True + return + + status = self._index_status() + missing = [key for key in ("hnsw_m", "hnsw_ef_construction") if key not in status] + if missing: + msg = ( + "HouyiDB server does not report the effective HNSW build parameters " + f"({', '.join(missing)} missing from /v1/index/status); cannot verify that " + f"m={self.case_config.m} and ef_construction={self.case_config.ef_construction} " + "were applied. Upgrade HouyiDB, or set verify_build_params=False to accept " + "the unverified configuration." + ) + raise RuntimeError(msg) + + expected_m = int(self.case_config.m) + expected_efc = int(self.case_config.ef_construction) + actual_m = int(status["hnsw_m"]) + actual_efc = int(status["hnsw_ef_construction"]) + if actual_m != expected_m or actual_efc != expected_efc: + hint = "" + if self.transport == "pgwire": + hint = f" Restart houyi-server with --pgwire-hnsw-m {expected_m} --pgwire-hnsw-efc {expected_efc}." + msg = ( + f"HouyiDB effective HNSW parameters m={actual_m}, ef_construction={actual_efc} " + f"do not match the case configuration m={expected_m}, ef_construction={expected_efc}." + f"{hint}" + ) + raise RuntimeError(msg) + + metric = status.get("distance_metric") + if metric is not None and str(metric).lower() not in ("cosine", "cos"): + msg = f"HouyiDB index metric is {metric!r}, expected cosine" + raise RuntimeError(msg) + + self._build_params_verified = True + + def _execute_bounded(self, conn: Any, sql: str, params: Any) -> Any: + """Run ``conn.execute`` under the client-side statement deadline.""" + self._pgwire_watchdog.start() + token = self._pgwire_watchdog.register(conn, float(self.timeout_sec)) + try: + result = conn.execute(sql, params) + except Exception as exc: + if token.timed_out.is_set(): + self._discard_pgwire_conn(conn) + msg = f"HouyiDB pgwire query exceeded timeout_sec={self.timeout_sec}" + raise TimeoutError(msg) from exc + raise + finally: + self._pgwire_watchdog.unregister(token) + if token.timed_out.is_set(): + self._discard_pgwire_conn(conn) + msg = f"HouyiDB pgwire query exceeded timeout_sec={self.timeout_sec}" + raise TimeoutError(msg) + return result + + def _discard_pgwire_conn(self, conn: Any) -> None: + """Drop a cancelled connection so the next call reconnects cleanly.""" + with self._pgwire_sessions_lock: + if conn in self._pgwire_sessions: + self._pgwire_sessions.remove(conn) + if getattr(self._thread_local, "pg_conn", None) is conn: + for attr in ("pg_conn", "pg_binary"): + if hasattr(self._thread_local, attr): + delattr(self._thread_local, attr) + with contextlib.suppress(Exception): + # The connection is already unusable; closing is best-effort. + conn.close() + def _pgwire_conn(self) -> Any: if not hasattr(self._thread_local, "pg_conn"): try: @@ -181,10 +441,14 @@ def _pgwire_conn(self) -> Any: } if self.api_key: params["password"] = str(self.api_key) + conn = None try: conn = psycopg.connect(make_conninfo(**params), autocommit=True) - conn.execute("SELECT 1") + self._execute_bounded(conn, "SELECT 1", None) except Exception as exc: + if conn is not None: + with contextlib.suppress(Exception): + conn.close() msg = f"failed to connect HouyiDB pgwire {self.db_config['host']}:{self.db_config['port']}: {exc}" raise RuntimeError(msg) from exc with self._pgwire_sessions_lock: @@ -196,6 +460,8 @@ def _pgwire_conn(self) -> Any: @contextmanager def init(self) -> Generator[None, None, None]: self._connected = True + if self.transport == "pgwire": + self._pgwire_watchdog.start() try: if self.transport == "http": self._http_session() @@ -204,6 +470,7 @@ def init(self) -> Generator[None, None, None]: yield finally: self._connected = False + self._pgwire_watchdog.stop() with self._http_sessions_lock: for session in self._http_sessions: try: @@ -231,6 +498,7 @@ def optimize(self, data_size: int | None = None) -> None: if not self._connected: msg = "Please call init() before optimize" raise RuntimeError(msg) + self._verify_build_params() session = self._http_session() response = session.post( f"{self.base_url}/v1/optimize", @@ -327,7 +595,8 @@ def _insert_pgwire( return inserted, ValueError(f"dim mismatch, expected {self.dim}, got {len(vector)}") chunk.append((int(metadata[idx]), vector)) payload = _encode_upsert_batch(self.dim, chunk) - row = conn.execute( + row = self._execute_bounded( + conn, "/* houyi:upsert_batch=%s */ SELECT 1", (pg_binary(payload),), ).fetchone() @@ -347,18 +616,14 @@ def _search_http(self, query: list[float], k: int) -> list[int]: payload["filter_gt_id"] = int(self._filter.int_value) - 1 elif self._filter.type == FilterOp.StrEqual: payload["filter_label"] = self._filter.label_value - try: - session = self._http_session() - response = session.post( - f"{self.base_url}/v1/vectors/search", - json=payload, - timeout=self.timeout_sec, - ) - response.raise_for_status() - return [int(item) for item in response.json().get("ids", [])] - except Exception as exc: - log.warning("HouyiDB HTTP search failed: %s", exc, exc_info=True) - return [] + session = self._http_session() + response = session.post( + f"{self.base_url}/v1/vectors/search", + json=payload, + timeout=self.timeout_sec, + ) + response.raise_for_status() + return [int(item) for item in response.json().get("ids", [])] def search_embedding( self, @@ -369,20 +634,21 @@ def search_embedding( **kwargs: Any, ) -> list[int]: del payload_profile, tenant, kwargs - if not self._connected or len(query) != self.dim: - return [] + if not self._connected: + msg = "Please call init() before search" + raise RuntimeError(msg) + if len(query) != self.dim: + msg = f"query dim mismatch, expected {self.dim}, got {len(query)}" + raise ValueError(msg) + self._verify_build_params() if self._filter.type != FilterOp.NonFilter: return self._search_http(query, k) if self.transport == "http": return self._search_http(query, k) - try: - conn = self._pgwire_conn() - pg_binary = self._thread_local.pg_binary - vector_payload = _encode_query_vector(query) - ef_search = int(self.case_config.ef_search) - sql = f"/* houyi:ef_search={ef_search} */ /* houyi:vector=%s */ SELECT id FROM docs LIMIT {int(k)}" - rows = conn.execute(sql, (pg_binary(vector_payload),)).fetchall() - return [int(row[0]) for row in rows] - except Exception as exc: - log.warning("HouyiDB pgwire search failed: %s", exc, exc_info=True) - return [] + conn = self._pgwire_conn() + pg_binary = self._thread_local.pg_binary + vector_payload = _encode_query_vector(query) + ef_search = int(self.case_config.ef_search) + sql = f"/* houyi:ef_search={ef_search} */ /* houyi:vector=%s */ SELECT id FROM docs LIMIT {int(k)}" + rows = self._execute_bounded(conn, sql, (pg_binary(vector_payload),)).fetchall() + return [int(row[0]) for row in rows]