Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(vectordb): add openGauss DataVec adapter (#4045)

LinQiang391d376bed9b323
diff --git a/Dockerfile b/Dockerfile
index e15c95c70..4c72c3060 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -82,13 +82,13 @@ RUN --mount=type=cache,target=/root/.cache/uv,id=uv-${TARGETPLATFORM} \
fi; \
case "${UV_LOCK_STRATEGY}" in \
locked) \
- uv sync --locked --no-editable --reinstall-package openviking --extra bot --extra gemini \
+ uv sync --locked --no-editable --reinstall-package openviking --extra bot --extra gemini --extra opengauss \
;; \
auto) \
if ! uv lock --check; then \
uv lock; \
fi; \
- uv sync --locked --no-editable --reinstall-package openviking --extra bot --extra gemini \
+ uv sync --locked --no-editable --reinstall-package openviking --extra bot --extra gemini --extra opengauss \
;; \
*) \
echo "Unsupported UV_LOCK_STRATEGY: ${UV_LOCK_STRATEGY}" >&2; \
diff --git a/openviking/storage/vectordb/collection/http_collection.py b/openviking/storage/vectordb/collection/http_collection.py
index 5388aa46c..ed0270aca 100644
--- a/openviking/storage/vectordb/collection/http_collection.py
+++ b/openviking/storage/vectordb/collection/http_collection.py
@@ -225,7 +225,7 @@ class HttpCollection(ICollection):
"CollectionName": self.collection_name,
"IndexName": index_name,
}
- if scalar_index:
+ if scalar_index is not None:
data["ScalarIndex"] = json.dumps(scalar_index)
if description is not None:
data["Description"] = description
diff --git a/openviking/storage/vectordb/collection/volcengine_collection.py b/openviking/storage/vectordb/collection/volcengine_collection.py
index 792757f91..8bf20beeb 100644
--- a/openviking/storage/vectordb/collection/volcengine_collection.py
+++ b/openviking/storage/vectordb/collection/volcengine_collection.py
@@ -376,7 +376,7 @@ class VolcengineCollection(ICollection):
"CollectionName": self.collection_name,
"IndexName": index_name,
}
- if scalar_index:
+ if scalar_index is not None:
data["ScalarIndex"] = scalar_index
if description is not None:
data["Description"] = description
diff --git a/openviking/storage/vectordb/index/local_index.py b/openviking/storage/vectordb/index/local_index.py
index 6b4c8adfa..81917e440 100644
--- a/openviking/storage/vectordb/index/local_index.py
+++ b/openviking/storage/vectordb/index/local_index.py
@@ -468,9 +468,9 @@ class LocalIndex(IIndex):
description: Optional[str],
):
meta_data: Dict[str, Any] = {}
- if scalar_index:
+ if scalar_index is not None:
meta_data["ScalarIndex"] = scalar_index
- if description:
+ if description is not None:
meta_data["Description"] = description
if not meta_data:
return
diff --git a/openviking/storage/vectordb/service/api_fastapi.py b/openviking/storage/vectordb/service/api_fastapi.py
index e7dbee4a7..95bddf9db 100644
--- a/openviking/storage/vectordb/service/api_fastapi.py
+++ b/openviking/storage/vectordb/service/api_fastapi.py
@@ -337,7 +337,15 @@ async def update_index(request: IndexUpdateRequest, req: Request):
if not index_name:
return error_response("index name is empty", ErrorCode.INVALID_PARAM.value, request=req)
- scalar_index = data_utils.convert_dict(request.ScalarIndex)
+ scalar_index = (
+ None
+ if request.ScalarIndex is None
+ else (
+ request.ScalarIndex
+ if isinstance(request.ScalarIndex, list)
+ else data_utils.convert_dict(request.ScalarIndex)
+ )
+ )
description = request.Description
collection.update_index(index_name, scalar_index, description)
diff --git a/openviking/storage/vectordb_adapters/__init__.py b/openviking/storage/vectordb_adapters/__init__.py
index 1d19e1bac..84fd1f455 100644
--- a/openviking/storage/vectordb_adapters/__init__.py
+++ b/openviking/storage/vectordb_adapters/__init__.py
@@ -6,6 +6,7 @@ from .base import CollectionAdapter
from .factory import create_collection_adapter
from .http_adapter import HttpCollectionAdapter
from .local_adapter import CuVSCollectionAdapter, LocalCollectionAdapter
+from .opengauss_adapter import OpenGaussCollectionAdapter
from .vikingdb_private_adapter import VikingDBPrivateCollectionAdapter
from .volcengine_adapter import VolcengineCollectionAdapter
@@ -16,5 +17,6 @@ __all__ = [
"HttpCollectionAdapter",
"VolcengineCollectionAdapter",
"VikingDBPrivateCollectionAdapter",
+ "OpenGaussCollectionAdapter",
"create_collection_adapter",
]
diff --git a/openviking/storage/vectordb_adapters/factory.py b/openviking/storage/vectordb_adapters/factory.py
index bc7ec0e12..bc3c13c31 100644
--- a/openviking/storage/vectordb_adapters/factory.py
+++ b/openviking/storage/vectordb_adapters/factory.py
@@ -9,6 +9,7 @@ import importlib
from .base import CollectionAdapter
from .http_adapter import HttpCollectionAdapter
from .local_adapter import CuVSCollectionAdapter, LocalCollectionAdapter
+from .opengauss_adapter import OpenGaussCollectionAdapter
from .vikingdb_private_adapter import VikingDBPrivateCollectionAdapter
from .volcengine_adapter import VolcengineCollectionAdapter
@@ -18,6 +19,7 @@ _ADAPTER_REGISTRY: dict[str, type[CollectionAdapter]] = {
"http": HttpCollectionAdapter,
"volcengine": VolcengineCollectionAdapter,
"vikingdb": VikingDBPrivateCollectionAdapter,
+ "opengauss": OpenGaussCollectionAdapter,
}
diff --git a/openviking/storage/vectordb_adapters/opengauss/__init__.py b/openviking/storage/vectordb_adapters/opengauss/__init__.py
new file mode 100644
index 000000000..ef0dfe9d3
--- /dev/null
+++ b/openviking/storage/vectordb_adapters/opengauss/__init__.py
@@ -0,0 +1,3 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Internal implementation modules for the openGauss adapter."""
diff --git a/openviking/storage/vectordb_adapters/opengauss/catalog.py b/openviking/storage/vectordb_adapters/opengauss/catalog.py
new file mode 100644
index 000000000..bc26d373e
--- /dev/null
+++ b/openviking/storage/vectordb_adapters/opengauss/catalog.py
@@ -0,0 +1,406 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""openGauss collection metadata and SPQ distribution operations."""
+
+from __future__ import annotations
+
+import json
+from typing import Any, Dict, List, Optional
+
+from openviking_cli.utils import get_logger
+
+from .sql import (
+ _META_TABLE,
+ _field_to_column_ddl,
+ _is_undefined_table_error,
+ _quote_identifier,
+ _validate_identifier,
+)
+
+logger = get_logger(__name__)
+
+
+def _validate_distributed_environment(conn) -> None:
+ cursor = conn.cursor()
+ try:
+ cursor.execute(
+ """
+ SELECT EXISTS (
+ SELECT 1 FROM pg_extension WHERE extname IN ('spq', 'spq_plugin_v2')
+ ),
+ EXISTS (
+ SELECT 1 FROM pg_proc WHERE proname = 'create_distributed_table'
+ ),
+ EXISTS (
+ SELECT 1 FROM pg_proc WHERE proname = 'create_reference_table'
+ )
+ """
+ )
+ extension_exists, distributed_function_exists, reference_function_exists = cursor.fetchone()
+ if not extension_exists:
+ raise RuntimeError(
+ "openGauss distributed mode requires the spq extension on the CN node"
+ )
+ if not distributed_function_exists:
+ raise RuntimeError(
+ "openGauss distributed mode requires create_distributed_table on the CN node"
+ )
+ if not reference_function_exists:
+ logger.info(
+ "opengauss_adapter: CN has no create_reference_table; metadata tables "
+ "will use spq hash distribution"
+ )
+
+ cursor.execute(
+ """
+ SELECT COUNT(*)
+ FROM pg_dist_node
+ WHERE isactive = true
+ AND (noderole IS NULL OR noderole = 'primary')
+ """
+ )
+ worker_count = int(cursor.fetchone()[0])
+ if worker_count < 1:
+ raise RuntimeError("openGauss distributed mode requires at least one active DN worker")
+
+ _probe_distributed_workers(cursor)
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ cursor.close()
+
+
+def _probe_distributed_workers(cursor) -> None:
+ """Verify that every node which will host shards accepts connections from the CN.
+
+ Shards only live on DN workers, so ``run_command_on_workers`` is the authoritative
+ probe. ``run_command_on_all_nodes`` also dials the CN itself when the coordinator is
+ registered in ``pg_dist_node``; many spq deployments never configure that loopback
+ authentication, so it is used only as a fallback when the worker variant is missing.
+ """
+ cursor.execute(
+ """
+ SELECT EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'run_command_on_workers'),
+ EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'run_command_on_all_nodes')
+ """
+ )
+ has_worker_probe, has_all_nodes_probe = cursor.fetchone()
+ if has_worker_probe:
+ probe_sql = (
+ "SELECT nodename || ':' || nodeport, success, result "
+ "FROM run_command_on_workers('SELECT 1')"
+ )
+ elif has_all_nodes_probe:
+ probe_sql = (
+ "SELECT nodeid, success, result FROM run_command_on_all_nodes('SELECT 1', true, false)"
+ )
+ else:
+ return
+ try:
+ cursor.execute(probe_sql)
+ rows = cursor.fetchall()
+ except Exception as exc:
+ # spq implements these helpers in PL/pgSQL and raises on the first unreachable
+ # node instead of reporting ``success = false`` rows.
+ raise RuntimeError(f"openGauss distributed workers are not reachable: {exc}") from exc
+ failed_nodes = [(node, result) for node, success, result in rows if not success]
+ if failed_nodes:
+ raise RuntimeError(f"openGauss distributed workers are not reachable: {failed_nodes}")
+
+
+def _distributed_table_kind(conn, table_name: str) -> Optional[str]:
+ _validate_identifier(table_name, kind="openGauss distributed table name")
+ cursor = conn.cursor()
+ try:
+ cursor.execute(
+ """
+ SELECT CASE partmethod
+ WHEN 'n' THEN 'reference'
+ ELSE 'distributed'
+ END
+ FROM pg_dist_partition
+ WHERE logicalrelid = %s::regclass
+ """,
+ (table_name,),
+ )
+ row = cursor.fetchone()
+ conn.commit()
+ return row[0] if row else None
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ cursor.close()
+
+
+def _verify_distributed_table_kind(conn, table_name: str, expected_kind: str) -> None:
+ actual_kind = _distributed_table_kind(conn, table_name)
+ if actual_kind != expected_kind:
+ raise RuntimeError(
+ f"openGauss table {table_name!r} expected {expected_kind} catalog state, "
+ f"got {actual_kind or 'local'}"
+ )
+
+
+def _is_table_already_distributed(conn, table_name: str) -> bool:
+ """Return True if *table_name* is registered in the distribution catalog.
+
+ Checks ``pg_dist_partition`` populated by spqplugin_v2 or a Citus-compatible
+ extension.
+ The function returns False gracefully when the extension is not installed
+ (undefined ``pg_dist_partition`` relation); any other backend failure
+ propagates to the caller.
+ """
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ """
+ SELECT 1 FROM pg_dist_partition
+ WHERE logicalrelid = %s::regclass
+ """,
+ (table_name,),
+ )
+ row = cur.fetchone()
+ conn.commit()
+ return row is not None
+ except Exception as error:
+ conn.rollback()
+ if _is_undefined_table_error(error):
+ return False
+ raise
+ finally:
+ cur.close()
+
+
+def _try_make_distributed_table(
+ conn,
+ table_name: str,
+ shard_count: int = 32,
+ distribution_column: str = "id",
+) -> None:
+ """Convert *table_name* to a distributed table via ``create_distributed_table``.
+
+ Distributes by *distribution_column* (hash partitioning) with the given
+ *shard_count*, using the openGauss spqplugin_v2 positional signature
+ ``create_distributed_table(name, column, 'hash', shard_count)``.
+ This is a no-op if the table is already distributed.
+ Failures are raised because distributed mode must not silently degrade
+ to a standalone table.
+ """
+ _validate_identifier(table_name, kind="openGauss distributed table name")
+ _validate_identifier(distribution_column, kind="openGauss distribution column name")
+ if _is_table_already_distributed(conn, table_name):
+ _verify_distributed_table_kind(conn, table_name, "distributed")
+ logger.info("opengauss_adapter: table '%s' is already distributed, skipping", table_name)
+ return
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ f"SELECT create_distributed_table(%s, %s, 'hash', {int(shard_count)})",
+ (table_name, distribution_column),
+ )
+ conn.commit()
+ _verify_distributed_table_kind(conn, table_name, "distributed")
+ logger.info(
+ "opengauss_adapter: distributed table '%s' created with %d shards",
+ table_name,
+ shard_count,
+ )
+ except Exception as error:
+ conn.rollback()
+ raise RuntimeError(
+ f"Failed to distribute openGauss table {table_name!r}; "
+ "ensure spq_plugin_v2 is installed on the CN node"
+ ) from error
+ finally:
+ cur.close()
+
+
+def _try_make_metadata_table_distributed(
+ conn,
+ table_name: str,
+ distribution_column: str,
+ shard_count: int = 32,
+) -> None:
+ """Distribute metadata according to the capabilities of the connected CN.
+
+ Citus-compatible deployments may expose ``create_reference_table``. The
+ official openGauss spqplugin_v2 API exposes hash-distributed tables only,
+ so metadata falls back to hash distribution by its primary key.
+ """
+ _validate_identifier(table_name, kind="openGauss metadata table name")
+ _validate_identifier(distribution_column, kind="openGauss metadata distribution column")
+ if _is_table_already_distributed(conn, table_name):
+ actual_kind = _distributed_table_kind(conn, table_name)
+ if actual_kind not in {"distributed", "reference"}:
+ raise RuntimeError(f"openGauss metadata table {table_name!r} has invalid catalog state")
+ return
+
+ cursor = conn.cursor()
+ try:
+ cursor.execute(
+ "SELECT EXISTS (SELECT 1 FROM pg_proc WHERE proname='create_reference_table')"
+ )
+ supports_reference_tables = bool(cursor.fetchone()[0])
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ cursor.close()
+
+ if supports_reference_tables:
+ cursor = conn.cursor()
+ try:
+ cursor.execute("SELECT create_reference_table(%s)", (table_name,))
+ conn.commit()
+ except Exception as error:
+ conn.rollback()
+ raise RuntimeError(
+ f"Failed to create openGauss reference metadata table {table_name!r}"
+ ) from error
+ finally:
+ cursor.close()
+ _verify_distributed_table_kind(conn, table_name, "reference")
+ return
+
+ _try_make_distributed_table(
+ conn,
+ table_name,
+ shard_count=shard_count,
+ distribution_column=distribution_column,
+ )
+
+
+def _create_collection_table(
+ conn,
+ name: str,
+ meta: Dict[str, Any],
+ dim: int,
+ distributed: bool = False,
+ shard_count: int = 32,
+ on_table_created=None,
+) -> None:
+ """Create the collection data table and optionally distribute it.
+
+ In distributed mode the table is converted to a distributed table keyed on
+ ``id`` after creation. The caller must have already created / ensured the
+ metadata tables so their distributed form is initialized first.
+ """
+ fields: List[Dict[str, Any]] = meta.get("Fields", [])
+ col_ddls = []
+ has_vector = False
+
+ for field in fields:
+ ftype = field.get("FieldType") or field.get("field_type") or field.get("type", "string")
+ if ftype == "vector":
+ has_vector = True
+ continue
+ field_name = field.get("FieldName") or field.get("field_name") or field.get("name", "")
+ if field_name == "content":
+ continue
+ ddl = _field_to_column_ddl(field)
+ if ddl:
+ col_ddls.append(ddl)
+
+ if has_vector and dim > 0:
+ col_ddls.append(f"vector vector({dim})")
+
+ col_defs = ", ".join(col_ddls) if col_ddls else ""
+ sep = ", " if col_defs else ""
+ quoted_name = _quote_identifier(name, kind="openGauss collection name")
+ sql = f"""
+ CREATE TABLE {quoted_name} (
+ id VARCHAR(256) PRIMARY KEY{sep}{col_defs}
+ )
+ """
+ cur = conn.cursor()
+ try:
+ cur.execute(sql)
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ cur.close()
+
+ if on_table_created is not None:
+ on_table_created()
+
+ if distributed:
+ _try_make_distributed_table(conn, name, shard_count)
+
+
+def _ensure_meta_table(conn, distributed: bool = False):
+ """Create the global collection metadata table if it doesn't exist.
+
+ In distributed mode the table becomes a reference table when supported;
+ standard spqplugin_v2 uses hash distribution by ``table_name``.
+ """
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ f"""
+ CREATE TABLE IF NOT EXISTS "{_META_TABLE}" (
+ table_name VARCHAR(256) PRIMARY KEY,
+ meta_json TEXT NOT NULL
+ )
+ """
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ cur.close()
+
+ if distributed:
+ _try_make_metadata_table_distributed(conn, _META_TABLE, "table_name")
+
+
+def _save_collection_meta(conn, name: str, meta: Dict[str, Any], distributed: bool = False):
+ _ensure_meta_table(conn, distributed=distributed)
+ cur = conn.cursor()
+ try:
+ # Use UPDATE -> INSERT for distributed compatibility
+ meta_json = json.dumps(meta)
+ cur.execute(
+ f'UPDATE "{_META_TABLE}" SET meta_json = %s WHERE table_name = %s',
+ (meta_json, name),
+ )
+ if cur.rowcount == 0:
+ cur.execute(
+ f'INSERT INTO "{_META_TABLE}" (table_name, meta_json) VALUES (%s, %s)',
+ (name, meta_json),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ cur.close()
+
+
+def _load_collection_meta(conn, name: str, distributed: bool = False) -> Optional[Dict[str, Any]]:
+ _ensure_meta_table(conn, distributed=distributed)
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ f'SELECT meta_json FROM "{_META_TABLE}" WHERE table_name = %s',
+ (name,),
+ )
+ row = cur.fetchone()
+ conn.commit()
+ except Exception:
+ # A backend failure (broken connection, missing SELECT privilege,
+ # catalog corruption, ...) must never masquerade as "collection does
+ # not exist": the caller could then enter the creation flow and
+ # rewrite metadata for a table that actually exists.
+ conn.rollback()
+ raise
+ finally:
+ cur.close()
+
+ return json.loads(row[0]) if row else None
diff --git a/openviking/storage/vectordb_adapters/opengauss/collection.py b/openviking/storage/vectordb_adapters/opengauss/collection.py
new file mode 100644
index 000000000..ba1bb64c7
--- /dev/null
+++ b/openviking/storage/vectordb_adapters/opengauss/collection.py
@@ -0,0 +1,1631 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""SQL-backed collection CRUD, search and index lifecycle."""
+
+from __future__ import annotations
+
+import json
+import re
+import threading
+from typing import Any, Dict, List, Optional
+
+from openviking.storage.vectordb.collection.collection import ICollection
+from openviking.storage.vectordb.collection.result import (
+ AggregateResult,
+ DataItem,
+ FetchDataInCollectionResult,
+ SearchItemResult,
+ SearchResult,
+)
+from openviking.storage.vectordb.index.index import IIndex
+from openviking_cli.utils import get_logger
+from openviking_cli.utils.config.vectordb_config import (
+ OpenGaussIndexConfig,
+)
+
+from .catalog import (
+ _try_make_metadata_table_distributed,
+)
+from .metadata import BUILD_KEYS, SEARCH_KEYS, migrate_persisted_index_meta
+from .sql import (
+ _DISTANCE_OP,
+ _META_TABLE,
+ _QUANTIZATION_OPTION_NAMES,
+ _UNSTORED_FIELDS,
+ _VECTOR_OPS,
+ _bounded_identifier,
+ _build_where_clause,
+ _coerce_sparse_vector,
+ _coerce_vector,
+ _date_time_to_epoch_ms,
+ _distance_to_similarity,
+ _index_access_method,
+ _index_meta_table_name,
+ _index_quantization,
+ _is_undefined_table_error,
+ _normalize_index_type,
+ _quote_identifier,
+ _resolve_build_params,
+ _resolve_search_params,
+ _validate_identifier,
+ _validate_vector,
+)
+
+logger = get_logger(__name__)
+
+
+class _PgIndex(IIndex):
+ """Dummy IIndex implementation for OpenGauss.
+
+ This class provides metadata-only index operations. The actual vector search
+ is performed directly via SQL queries in OpenGaussCollection.
+ """
+
+ def __init__(self, name: str, meta: Dict[str, Any]):
+ self._name = name
+ self._meta = meta
+
+ def get_name(self) -> str:
+ return self._name
+
+ def get_meta_data(self) -> Dict[str, Any]:
+ return dict(self._meta)
+
+ def upsert_data(self, delta_list):
+ """Not used - data operations handled by OpenGaussCollection."""
+ pass
+
+ def delete_data(self, delta_list):
+ """Not used - data operations handled by OpenGaussCollection."""
+ pass
+
+ def search(
+ self, query_vector=None, limit=10, filters=None, sparse_raw_terms=None, sparse_values=None
+ ):
+ """Not used - search handled by OpenGaussCollection."""
+ return [], []
+
+ def aggregate(self, filters=None):
+ """Not used - aggregation handled by OpenGaussCollection."""
+ return {}
+
+ def update(self, scalar_index=None, description=None):
+ """Not used - updates handled by OpenGaussCollection."""
+ pass
+
+ def rebuild_scalar_index(self, scalar_index, cands_fields):
+ """Not used - scalar indexes are SQL indexes managed by OpenGaussCollection.update_index."""
+ pass
+
+ def close(self):
+ """No-op for dummy index."""
+ pass
+
+ def drop(self):
+ """No-op for dummy index."""
+ pass
+
+
+class OpenGaussCollection(ICollection):
+ """A single OpenViking collection stored in an openGauss/PostgreSQL table.
+
+ Schema design:
+ - One table per collection: ``{collection_name}``
+ - Column ``id`` VARCHAR(256) PRIMARY KEY
+ - One column per non-vector field
+ - Column ``vector`` vector(dim) for dense vectors
+ - Metadata persisted in ``_ov_collection_meta`` table
+ - Index metadata persisted in ``_ov_index_{collection_name}`` table
+ """
+
+ def __init__(
+ self,
+ conn,
+ collection_name: str,
+ meta: Dict[str, Any],
+ dim: int,
+ distance: str = "cosine",
+ distributed: bool = False,
+ ):
+ super().__init__()
+ self._conn = conn
+ self._name = _validate_identifier(collection_name, kind="openGauss collection name")
+ self._meta = meta
+ self._dim = dim
+ self._distance = distance
+ self._distributed = distributed
+ self._lock = threading.RLock()
+ self._field_names = {
+ _validate_identifier(
+ field.get("FieldName") or field.get("field_name") or field.get("name", ""),
+ kind="openGauss field name",
+ )
+ for field in meta.get("Fields", [])
+ }
+ self._field_names.add("id")
+ if dim > 0:
+ self._field_names.add("vector")
+ self._array_fields = {
+ field.get("FieldName") or field.get("field_name") or field.get("name", "")
+ for field in meta.get("Fields", [])
+ if (field.get("FieldType") or field.get("field_type") or field.get("type"))
+ in {"list<string>", "list<int64>"}
+ }
+ self._date_time_fields = {
+ field.get("FieldName") or field.get("field_name") or field.get("name", "")
+ for field in meta.get("Fields", [])
+ if (field.get("FieldType") or field.get("field_type") or field.get("type"))
+ == "date_time"
+ }
+ # Verified physical indexes and requested indexes waiting for data.
+ self._indexes: Dict[str, Dict[str, Any]] = {}
+ self._pending_indexes: Dict[str, Dict[str, Any]] = {}
+ self._bulk_ingest_depth = 0
+ self._load_index_meta()
+ self._reconcile_index_metadata()
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _cursor(self):
+ return self._conn.cursor()
+
+ def _execute(self, sql: str, params=None, fetch: bool = False):
+ with self._lock:
+ cur = self._cursor()
+ try:
+ cur.execute(sql, params)
+ if fetch:
+ rows = cur.fetchall()
+ self._conn.commit()
+ return rows
+ self._conn.commit()
+ return cur
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cur.close()
+
+ def _index_catalog_table(self) -> str:
+ return _index_meta_table_name(self._name)
+
+ def _load_index_meta(self):
+ """Load persisted index metadata from the database.
+
+ Only the undefined-table error is tolerated (no index has been
+ created for this collection yet); any other backend failure must
+ surface instead of silently leaving the index registry empty, which
+ could trigger a spurious index rebuild.
+ """
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ try:
+ rows = self._execute(
+ f"SELECT index_name, meta_json FROM {idx_table}",
+ fetch=True,
+ )
+ except Exception as error:
+ if _is_undefined_table_error(error):
+ return
+ raise
+ for row in rows:
+ index_meta = self._normalized_index_meta(
+ row[0], migrate_persisted_index_meta(json.loads(row[1]))
+ )
+ if index_meta.get("_state") == "pending":
+ self._pending_indexes[row[0]] = index_meta
+ else:
+ self._indexes[row[0]] = index_meta
+
+ def _ensure_index_meta_table(self):
+ """Create the per-collection index metadata table if needed.
+
+ In distributed mode the table follows CN capabilities: a reference table
+ on Citus-compatible deployments or an spq hash-distributed metadata table.
+ """
+ idx_table = self._index_catalog_table()
+ quoted_idx_table = _quote_identifier(idx_table, kind="openGauss index metadata table")
+ self._execute(
+ f"""
+ CREATE TABLE IF NOT EXISTS {quoted_idx_table} (
+ index_name VARCHAR(256) PRIMARY KEY,
+ meta_json TEXT NOT NULL
+ )
+ """
+ )
+ if self._distributed:
+ _try_make_metadata_table_distributed(self._conn, idx_table, "index_name")
+
+ def _save_index_meta(self, index_name: str, meta: Dict[str, Any]):
+ self._ensure_index_meta_table()
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ meta_json = json.dumps(meta)
+ # Use UPDATE -> INSERT for distributed compatibility
+ with self._lock:
+ cur = self._cursor()
+ try:
+ cur.execute(
+ f"UPDATE {idx_table} SET meta_json = %s WHERE index_name = %s",
+ (meta_json, index_name),
+ )
+ if cur.rowcount == 0:
+ cur.execute(
+ f"INSERT INTO {idx_table} (index_name, meta_json) VALUES (%s, %s)",
+ (index_name, meta_json),
+ )
+ self._conn.commit()
+ except Exception as error:
+ self._conn.rollback()
+ if getattr(error, "pgcode", None) != "23505":
+ raise
+ retry_cursor = self._cursor()
+ try:
+ retry_cursor.execute(
+ f"UPDATE {idx_table} SET meta_json = %s WHERE index_name = %s",
+ (meta_json, index_name),
+ )
+ if retry_cursor.rowcount != 1:
+ raise RuntimeError(
+ f"openGauss index metadata race recovery failed for {index_name!r}"
+ ) from error
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ retry_cursor.close()
+ finally:
+ cur.close()
+
+ def _delete_index_meta(self, index_name: str):
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ try:
+ self._execute(
+ f"DELETE FROM {idx_table} WHERE index_name = %s",
+ (index_name,),
+ )
+ except Exception as error:
+ # Nothing to delete when the metadata table was never created.
+ if _is_undefined_table_error(error):
+ return
+ raise
+
+ def _get_all_columns(self) -> List[str]:
+ """Return all non-system column names of the collection table."""
+ rows = self._execute(
+ """
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name = %s
+ AND table_schema = current_schema()
+ ORDER BY ordinal_position
+ """,
+ (self._name,),
+ fetch=True,
+ )
+ return [row[0] for row in rows] if rows else []
+
+ def _get_column_types(self) -> Dict[str, str]:
+ """Return column name to data type mapping."""
+ rows = self._execute(
+ """
+ SELECT column_name, data_type
+ FROM information_schema.columns
+ WHERE table_name = %s
+ AND table_schema = current_schema()
+ """,
+ (self._name,),
+ fetch=True,
+ )
+ return {row[0]: row[1] for row in rows} if rows else {}
+
+ def _normalize_filter_date_times(
+ self, filters: Optional[Dict[str, Any]]
+ ) -> Optional[Dict[str, Any]]:
+ if not filters:
+ return filters
+ normalized = dict(filters)
+ conditions = normalized.get("conds")
+ if normalized.get("op") in {"and", "or"} and isinstance(conditions, list):
+ normalized["conds"] = [
+ self._normalize_filter_date_times(condition) for condition in conditions
+ ]
+ return normalized
+
+ field = normalized.get("field")
+ if field not in self._date_time_fields:
+ return normalized
+ if isinstance(conditions, list):
+ normalized["conds"] = [_date_time_to_epoch_ms(value) for value in conditions]
+ for bound in ("gt", "gte", "lt", "lte"):
+ if normalized.get(bound) is not None:
+ normalized[bound] = _date_time_to_epoch_ms(normalized[bound])
+ return normalized
+
+ def _select_output_columns(self, output_fields: Optional[List[str]]) -> str:
+ """Build the SELECT column list from output_fields."""
+ if not output_fields:
+ return "*"
+ allowed_fields = self._field_names | _UNSTORED_FIELDS
+ unknown_fields = sorted(set(output_fields) - allowed_fields)
+ if unknown_fields:
+ raise ValueError(f"Unknown openGauss output fields: {unknown_fields}")
+ cols = [_quote_identifier("id")]
+ for field in output_fields:
+ if field == "id":
+ continue
+ quoted = _quote_identifier(field, kind="openGauss output field")
+ if field in _UNSTORED_FIELDS:
+ # Schema/metadata still lists ``content``; the physical table
+ # does not. Project NULL so official URI rewrite/migration
+ # output_fields do not become a missing-column SQL error.
+ cols.append(f"NULL AS {quoted}")
+ else:
+ cols.append(quoted)
+ return ", ".join(cols)
+
+ def _row_to_dict(self, row, columns: List[str]) -> Dict[str, Any]:
+ record = {}
+ for column, value in zip(columns, row, strict=True):
+ if column == "vector":
+ record[column] = _coerce_vector(value)
+ elif column == "sparse_vector":
+ record[column] = _coerce_sparse_vector(value)
+ else:
+ record[column] = value
+ return record
+
+ # ------------------------------------------------------------------
+ # ICollection: collection lifecycle
+ # ------------------------------------------------------------------
+
+ def update(self, fields: Optional[Dict[str, Any]] = None, description: Optional[str] = None):
+ if fields:
+ self._meta.update(fields)
+ if description is not None:
+ self._meta["Description"] = description
+ # Persist updated meta
+ self._execute(
+ f"""
+ UPDATE "{_META_TABLE}"
+ SET meta_json = %s
+ WHERE table_name = %s
+ """,
+ (json.dumps(self._meta), self._name),
+ )
+
+ def get_meta_data(self) -> Dict[str, Any]:
+ return dict(self._meta)
+
+ def close(self):
+ pass # Connection lifecycle managed by adapter
+
+ def drop(self):
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ self._execute(f'DROP TABLE IF EXISTS "{self._name}" CASCADE')
+ self._execute(f"DROP TABLE IF EXISTS {idx_table} CASCADE")
+ self._execute(
+ f'DELETE FROM "{_META_TABLE}" WHERE table_name = %s',
+ (self._name,),
+ )
+ self._indexes.clear()
+
+ # ------------------------------------------------------------------
+ # ICollection: index management
+ # ------------------------------------------------------------------
+
+ def _physical_index_definition(self, physical_index_name: str) -> Optional[str]:
+ rows = self._execute(
+ """
+ SELECT indexdef
+ FROM pg_indexes
+ WHERE schemaname = current_schema()
+ AND tablename = %s
+ AND indexname = %s
+ """,
+ (self._name, physical_index_name),
+ fetch=True,
+ )
+ return rows[0][0] if rows else None
+
+ def _table_has_rows(self) -> bool:
+ rows = self._execute(
+ f"SELECT 1 FROM {_quote_identifier(self._name)} LIMIT 1",
+ fetch=True,
+ )
+ return bool(rows)
+
+ @staticmethod
+ def _index_requires_data(index_meta: Dict[str, Any]) -> bool:
+ if index_meta["_pg_index_type"] != "hnsw":
+ return True
+ return index_meta["_quantization"] is not None
+
+ @staticmethod
+ def _format_index_option(value: Any) -> str:
+ if isinstance(value, bool):
+ return "on" if value else "off"
+ if isinstance(value, str):
+ escaped = value.replace("'", "''")
+ return f"'{escaped}'"
+ return str(int(value))
+
+ def _normalized_index_meta(self, index_name: str, meta_data: Dict[str, Any]) -> Dict[str, Any]:
+ misplaced = (BUILD_KEYS | SEARCH_KEYS) & meta_data.keys()
+ if misplaced:
+ raise ValueError(f"openGauss index parameters must be nested: {sorted(misplaced)}")
+ vector_meta = dict(meta_data.get("VectorIndex") or {})
+ index_type = _normalize_index_type(vector_meta.get("IndexType", "hnsw"))
+ access_method = _index_access_method(index_type)
+ quantization = _index_quantization(index_type)
+ distance = vector_meta.get("Distance", self._distance)
+ operator_class = _VECTOR_OPS.get(distance, {}).get(access_method)
+ if not operator_class:
+ raise ValueError(
+ f"openGauss index_type={index_type!r} does not support distance={distance!r}"
+ )
+
+ options = OpenGaussIndexConfig(
+ index_type=index_type,
+ build_params=_resolve_build_params(index_type, meta_data),
+ search_params=_resolve_search_params(index_type, meta_data),
+ parallel_workers=meta_data.get("parallel_workers", 0),
+ maintenance_work_mem_mb=meta_data.get("maintenance_work_mem_mb", 64),
+ )
+ options.validate_capabilities(distributed=self._distributed, distance=distance)
+ index_type = options.index_type
+ quantization = options.quantization
+ build_params = options.build_params
+
+ physical_index_name = _bounded_identifier(
+ f"idx_{self._name}_{index_name}_vec",
+ kind="openGauss physical index name",
+ )
+ full_meta = dict(meta_data)
+ full_meta["IndexName"] = index_name
+ full_meta["build_params"] = build_params
+ full_meta["search_params"] = options.search_params
+ full_meta["parallel_workers"] = options.parallel_workers
+ full_meta["maintenance_work_mem_mb"] = int(
+ meta_data.get(
+ "maintenance_work_mem_mb",
+ getattr(self, "_maintenance_work_mem_mb", 64),
+ )
+ )
+ full_meta["_pg_index_name"] = physical_index_name
+ full_meta["_pg_index_type"] = access_method
+ full_meta["_logical_index_type"] = index_type
+ full_meta["_quantization"] = quantization
+ full_meta["_operator_class"] = operator_class
+ full_meta["_distance"] = distance
+ vector_meta["IndexType"] = index_type
+ vector_meta["Distance"] = distance
+ full_meta["VectorIndex"] = vector_meta
+ return full_meta
+
+ def _index_options(self, index_meta: Dict[str, Any]) -> list[tuple[str, Any]]:
+ access_method = index_meta["_pg_index_type"]
+ build_params = index_meta["build_params"]
+ if access_method == "hnsw":
+ options = [
+ ("m", build_params.get("m", 16)),
+ ("ef_construction", build_params.get("ef_construction", 64)),
+ ]
+ elif access_method == "ivfflat":
+ options = [("lists", build_params.get("lists", 100))]
+ else:
+ options = [("index_size", build_params.get("index_size", 100))]
+
+ if index_meta["_quantization"] == "pq":
+ options.extend(
+ [
+ ("enable_pq", True),
+ ("pq_m", build_params.get("pq_m", 8)),
+ ("pq_ksub", build_params.get("pq_ksub", 256)),
+ ]
+ )
+ if access_method == "ivfflat":
+ options.append(("by_residual", build_params.get("by_residual", False)))
+ if index_meta["_quantization"] == "rabitq":
+ options.extend(
+ [
+ ("enable_rabitq", True),
+ ("rabitq_refine_type", build_params.get("rabitq_refine_type", "none")),
+ ]
+ )
+ if "rabitq_fht" in build_params:
+ options.append(("rabitq_fht", build_params["rabitq_fht"]))
+ return options
+
+ def _create_index_sql(self, index_meta: Dict[str, Any]) -> str:
+ option_sql = ", ".join(
+ f"{name} = {self._format_index_option(value)}"
+ for name, value in self._index_options(index_meta)
+ )
+ return (
+ f"CREATE INDEX {_quote_identifier(index_meta['_pg_index_name'])} "
+ f"ON {_quote_identifier(self._name)} "
+ f"USING {index_meta['_pg_index_type']} "
+ f"({_quote_identifier('vector')} {index_meta['_operator_class']}) "
+ f"WITH ({option_sql})"
+ )
+
+ @staticmethod
+ def _normalized_indexdef(indexdef: str) -> str:
+ return " ".join(indexdef.lower().replace('"', "").replace("'", "").split())
+
+ def _index_identity_matches(self, index_meta: Dict[str, Any], indexdef: str) -> bool:
+ compact_definition = self._normalized_indexdef(indexdef).replace(" ", "")
+ return (
+ f"using{index_meta['_pg_index_type']}" in compact_definition
+ and index_meta["_operator_class"].lower().replace(" ", "") in compact_definition
+ )
+
+ def _catalog_index_options(self, indexdef: str) -> Optional[Dict[str, str]]:
+ match = re.search(r"\bwith\s*\((.*)\)", self._normalized_indexdef(indexdef))
+ if not match:
+ return None
+ options: Dict[str, str] = {}
+ for part in match.group(1).split(","):
+ if "=" not in part:
+ continue
+ name, value = part.split("=", 1)
+ options[name.strip()] = value.strip()
+ return options
+
+ @staticmethod
+ def _default_index_option_value(option_name: str) -> Any:
+ return {
+ "m": 16,
+ "ef_construction": 64,
+ "lists": 100,
+ "index_size": 100,
+ "pq_m": 8,
+ "pq_ksub": 256,
+ "by_residual": False,
+ "rabitq_refine_type": "none",
+ }.get(option_name)
+
+ def _option_is_omittable_default(self, option_name: str, option_value: Any) -> bool:
+ default = self._default_index_option_value(option_name)
+ if default is None:
+ return False
+ return (
+ self._format_index_option(option_value).strip("'").lower()
+ == self._format_index_option(default).strip("'").lower()
+ )
+
+ def _index_definition_matches(self, index_meta: Dict[str, Any], indexdef: str) -> bool:
+ if not self._index_identity_matches(index_meta, indexdef):
+ return False
+ catalog_options = self._catalog_index_options(indexdef) or {}
+ expected_pairs = list(self._index_options(index_meta))
+ expected_options = {
+ option_name: self._format_index_option(option_value).strip("'").lower()
+ for option_name, option_value in expected_pairs
+ }
+ for option_name, option_value in expected_pairs:
+ actual = catalog_options.get(option_name)
+ if actual is None:
+ # Catalog may omit default WITH options; non-defaults must appear.
+ if not self._option_is_omittable_default(option_name, option_value):
+ return False
+ continue
+ if actual != expected_options[option_name]:
+ return False
+ # Downgrades such as hnsw-pq -> hnsw leave enable_pq/pq_m in catalog.
+ # Those extras must force a rebuild; one-way expected-only checks miss them.
+ for option_name, actual in catalog_options.items():
+ if option_name in expected_options:
+ continue
+ if option_name in _QUANTIZATION_OPTION_NAMES:
+ if option_name in {"enable_pq", "enable_rabitq"} and actual in {
+ "off",
+ "false",
+ "0",
+ }:
+ continue
+ return False
+ default = self._default_index_option_value(option_name)
+ if default is None:
+ return False
+ if actual != self._format_index_option(default).strip("'").lower():
+ return False
+ return True
+
+ def _create_scalar_indexes(self, index_name: str, index_meta: Dict[str, Any]) -> None:
+ for scalar_field in index_meta.get("ScalarIndex", []):
+ if scalar_field not in self._field_names:
+ raise ValueError(f"Unknown openGauss scalar index field: {scalar_field!r}")
+ scalar_index_name = _bounded_identifier(
+ f"idx_{self._name}_{index_name}_{scalar_field}",
+ kind="openGauss scalar index name",
+ )
+ self._execute(
+ f"CREATE INDEX IF NOT EXISTS {_quote_identifier(scalar_index_name)} "
+ f"ON {_quote_identifier(self._name)} ({_quote_identifier(scalar_field)})"
+ )
+
+ def _persist_index_meta_and_scalar_indexes(
+ self,
+ index_name: str,
+ index_meta: Dict[str, Any],
+ ) -> None:
+ scalar_fields = list(index_meta.get("ScalarIndex", []))
+ unknown_fields = sorted(set(scalar_fields) - self._field_names)
+ if unknown_fields:
+ raise ValueError(f"Unknown openGauss scalar index field(s): {unknown_fields}")
+
+ self._ensure_index_meta_table()
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ meta_json = json.dumps(index_meta)
+
+ def execute_transaction(cursor, *, allow_insert: bool) -> None:
+ for scalar_field in scalar_fields:
+ scalar_index_name = _bounded_identifier(
+ f"idx_{self._name}_{index_name}_{scalar_field}",
+ kind="openGauss scalar index name",
+ )
+ cursor.execute(
+ f"CREATE INDEX IF NOT EXISTS "
+ f"{_quote_identifier(scalar_index_name)} "
+ f"ON {_quote_identifier(self._name)} "
+ f"({_quote_identifier(scalar_field)})"
+ )
+ cursor.execute(
+ f"UPDATE {idx_table} SET meta_json = %s WHERE index_name = %s",
+ (meta_json, index_name),
+ )
+ if cursor.rowcount == 0:
+ if not allow_insert:
+ raise RuntimeError(
+ f"openGauss index metadata race recovery failed for {index_name!r}"
+ )
+ cursor.execute(
+ f"INSERT INTO {idx_table} (index_name, meta_json) VALUES (%s, %s)",
+ (index_name, meta_json),
+ )
+
+ with self._lock:
+ cursor = self._cursor()
+ try:
+ execute_transaction(cursor, allow_insert=True)
+ self._conn.commit()
+ except Exception as error:
+ self._conn.rollback()
+ if getattr(error, "pgcode", None) != "23505":
+ raise
+ retry_cursor = self._cursor()
+ try:
+ execute_transaction(retry_cursor, allow_insert=False)
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ retry_cursor.close()
+ finally:
+ cursor.close()
+
+ def _materialize_index(self, index_name: str, index_meta: Dict[str, Any]) -> None:
+ index_meta = dict(index_meta)
+ index_meta.pop("_state", None)
+ physical_index_name = index_meta["_pg_index_name"]
+ existing_definition = self._physical_index_definition(physical_index_name)
+ if existing_definition and not self._index_definition_matches(
+ index_meta, existing_definition
+ ):
+ self._execute(f"DROP INDEX {_quote_identifier(physical_index_name)}")
+ existing_definition = None
+
+ self._apply_parallel_workers(index_meta)
+ if not existing_definition:
+ maintenance_work_mem_mb = int(index_meta["maintenance_work_mem_mb"])
+ with self._lock:
+ cursor = self._cursor()
+ try:
+ cursor.execute(
+ f"SET LOCAL maintenance_work_mem = '{maintenance_work_mem_mb}MB'"
+ )
+ cursor.execute(self._create_index_sql(index_meta))
+ self._conn.commit()
+ except Exception as error:
+ self._conn.rollback()
+ deployment_mode = "distributed" if self._distributed else "standalone"
+ raise RuntimeError(
+ "Failed to create openGauss ANN index "
+ f"{index_meta['_logical_index_type']!r} using "
+ f"{index_meta['_pg_index_type']!r} on collection {self._name!r} "
+ f"in {deployment_mode} mode with "
+ f"maintenance_work_mem={maintenance_work_mem_mb}MB: {error}"
+ ) from error
+ finally:
+ cursor.close()
+
+ verified_definition = self._physical_index_definition(physical_index_name)
+ if not verified_definition or not self._index_definition_matches(
+ index_meta, verified_definition
+ ):
+ raise RuntimeError(
+ f"openGauss created index {physical_index_name!r} but catalog verification failed"
+ )
+
+ self._persist_index_meta_and_scalar_indexes(index_name, index_meta)
+ self._indexes[index_name] = index_meta
+ self._pending_indexes.pop(index_name, None)
+
+ def _apply_parallel_workers(self, index_meta: Dict[str, Any]) -> None:
+ parallel_workers = index_meta.get("parallel_workers", 0)
+ quoted_table = _quote_identifier(self._name)
+ if parallel_workers > 0:
+ self._execute(f"ALTER TABLE {quoted_table} SET (parallel_workers = {parallel_workers})")
+ return
+ self._execute(f"ALTER TABLE {quoted_table} RESET (parallel_workers)")
+
+ def _materialize_pending_indexes(self) -> None:
+ if self._bulk_ingest_depth > 0 or not self._pending_indexes:
+ return
+ if not self._table_has_rows():
+ return
+ for index_name, index_meta in list(self._pending_indexes.items()):
+ self._materialize_index(index_name, index_meta)
+
+ def _materialize_pending_index(self, index_name: str) -> None:
+ if self._bulk_ingest_depth > 0:
+ return
+ index_meta = self._pending_indexes.get(index_name)
+ if index_meta is None or not self._table_has_rows():
+ return
+ self._materialize_index(index_name, index_meta)
+
+ def _reconcile_index_metadata(self) -> None:
+ for index_name, index_meta in list(self._indexes.items()):
+ physical_index_name = index_meta.get("_pg_index_name")
+ if not physical_index_name:
+ self._delete_index_meta_and_scalar_indexes(index_name, index_meta)
+ self._indexes.pop(index_name, None)
+ continue
+ index_definition = self._physical_index_definition(physical_index_name)
+ try:
+ normalized_meta = self._normalized_index_meta(index_name, index_meta)
+ except Exception:
+ self._delete_index_meta_and_scalar_indexes(index_name, index_meta)
+ self._indexes.pop(index_name, None)
+ continue
+ if not index_definition or not self._index_definition_matches(
+ normalized_meta, index_definition
+ ):
+ self._delete_index_meta_and_scalar_indexes(index_name, index_meta)
+ self._indexes.pop(index_name, None)
+
+ def _search_param_statements(self, index_name: str) -> list[str]:
+ index_meta = self._indexes.get(index_name) or self._pending_indexes.get(index_name)
+ if not index_meta:
+ raise RuntimeError(f"openGauss index {index_name!r} is not configured")
+ index_type = index_meta.get("_logical_index_type") or _normalize_index_type(
+ index_meta.get("VectorIndex", {}).get("IndexType", "hnsw")
+ )
+ access_method = _index_access_method(index_type)
+ params = _resolve_search_params(index_type, index_meta)
+ statements: list[str] = []
+ if access_method == "hnsw":
+ ef_search = params.get("ef_search", params.get("hnsw_ef_search"))
+ earlystop = params.get("earlystop_threshold", params.get("hnsw_earlystop_threshold"))
+ if ef_search is not None:
+ statements.append(f"SET LOCAL hnsw_ef_search = {int(ef_search)}")
+ if earlystop is not None:
+ statements.append(f"SET LOCAL hnsw_earlystop_threshold = {int(earlystop)}")
+ elif access_method == "ivfflat":
+ probes = params.get("probes", params.get("ivfflat_probes"))
+ if probes is not None:
+ statements.append(f"SET LOCAL ivfflat_probes = {int(probes)}")
+ if params.get("ivfpq_kreorder") is not None:
+ statements.append(f"SET LOCAL ivfpq_kreorder = {int(params['ivfpq_kreorder'])}")
+ else:
+ probes = params.get("probes", params.get("diskann_probes"))
+ if probes is not None:
+ statements.append(f"SET LOCAL diskann_probes = {int(probes)}")
+ if params.get("rbq_query_bits") is not None:
+ statements.append(f"SET LOCAL rbq_query_bits = {int(params['rbq_query_bits'])}")
+ if params.get("rbq_refinek") is not None:
+ statements.append(f"SET LOCAL rbq_refinek = {int(params['rbq_refinek'])}")
+ if statements and self._distributed:
+ # spq defaults to propagate_set_commands='none', so plain SET LOCAL
+ # would only change the CN session while DN shard scans keep server
+ # defaults. Propagation makes the parameters reach the DN scans.
+ statements.insert(0, "SET LOCAL spq.propagate_set_commands = 'local'")
+ return statements
+
+ def _apply_search_params_on_cursor(self, cursor, index_name: str) -> None:
+ for statement in self._search_param_statements(index_name):
+ cursor.execute(statement)
+
+ def create_index(self, index_name: str, meta_data: Dict[str, Any]) -> IIndex:
+ _validate_identifier(index_name, kind="openGauss index name")
+ index_meta = self._normalized_index_meta(index_name, meta_data)
+ if self._index_requires_data(index_meta) and not self._table_has_rows():
+ existing_definition = self._physical_index_definition(index_meta["_pg_index_name"])
+ if existing_definition and not self._index_definition_matches(
+ index_meta, existing_definition
+ ):
+ self._execute(
+ f"DROP INDEX IF EXISTS {_quote_identifier(index_meta['_pg_index_name'])}"
+ )
+ index_meta["_state"] = "pending"
+ self._persist_index_meta_and_scalar_indexes(index_name, index_meta)
+ self._pending_indexes[index_name] = index_meta
+ self._indexes.pop(index_name, None)
+ return _PgIndex(index_name, index_meta)
+ self._materialize_index(index_name, index_meta)
+ return _PgIndex(index_name, index_meta)
+
+ def has_index(self, index_name: str) -> bool:
+ index_meta = self._indexes.get(index_name)
+ if index_meta is None:
+ return False
+ index_definition = self._physical_index_definition(index_meta["_pg_index_name"])
+ return bool(
+ index_definition and self._index_definition_matches(index_meta, index_definition)
+ )
+
+ def get_index(self, index_name: str) -> Optional[IIndex]:
+ index_meta = self._indexes.get(index_name) or self._pending_indexes.get(index_name)
+ return _PgIndex(index_name, index_meta) if index_meta else None
+
+ def list_indexes(self) -> List[str]:
+ return sorted(set(self._indexes) | set(self._pending_indexes))
+
+ def drop_index(self, index_name: str):
+ index_meta = self._indexes.get(index_name) or self._pending_indexes.get(index_name)
+ if not index_meta:
+ return
+ physical_index_name = index_meta.get("_pg_index_name")
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ with self._lock:
+ cursor = self._cursor()
+ try:
+ if physical_index_name:
+ cursor.execute(f"DROP INDEX IF EXISTS {_quote_identifier(physical_index_name)}")
+ for scalar_field in index_meta.get("ScalarIndex", []):
+ scalar_index_name = _bounded_identifier(
+ f"idx_{self._name}_{index_name}_{scalar_field}",
+ kind="openGauss scalar index name",
+ )
+ cursor.execute(f"DROP INDEX IF EXISTS {_quote_identifier(scalar_index_name)}")
+ cursor.execute(
+ f"DELETE FROM {idx_table} WHERE index_name = %s",
+ (index_name,),
+ )
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cursor.close()
+ self._indexes.pop(index_name, None)
+ self._pending_indexes.pop(index_name, None)
+
+ def _delete_index_meta_and_scalar_indexes(
+ self,
+ index_name: str,
+ index_meta: Dict[str, Any],
+ ) -> None:
+ self._ensure_index_meta_table()
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ with self._lock:
+ cursor = self._cursor()
+ try:
+ for scalar_field in index_meta.get("ScalarIndex", []):
+ scalar_index_name = _bounded_identifier(
+ f"idx_{self._name}_{index_name}_{scalar_field}",
+ kind="openGauss scalar index name",
+ )
+ cursor.execute(f"DROP INDEX IF EXISTS {_quote_identifier(scalar_index_name)}")
+ cursor.execute(
+ f"DELETE FROM {idx_table} WHERE index_name = %s",
+ (index_name,),
+ )
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cursor.close()
+
+ def update_index(
+ self,
+ index_name: str,
+ scalar_index: Optional[List[str]] = None,
+ description: Optional[str] = None,
+ ):
+ index_meta = self._indexes.get(index_name) or self._pending_indexes.get(index_name)
+ if not index_meta:
+ return
+ if scalar_index is not None:
+ if not isinstance(scalar_index, list) or not all(
+ isinstance(field, str) for field in scalar_index
+ ):
+ raise ValueError("openGauss ScalarIndex must be a list of field names")
+ new_scalar_fields = list(dict.fromkeys(scalar_index))
+ unknown_fields = sorted(set(new_scalar_fields) - self._field_names)
+ if unknown_fields:
+ raise ValueError(f"Unknown openGauss scalar index field(s): {unknown_fields}")
+ self._ensure_index_meta_table()
+ idx_table = _quote_identifier(
+ self._index_catalog_table(), kind="openGauss index metadata table"
+ )
+ with self._lock:
+ cursor = self._cursor()
+ try:
+ cursor.execute(
+ f"SELECT meta_json FROM {idx_table} WHERE index_name = %s FOR UPDATE",
+ (index_name,),
+ )
+ metadata_row = cursor.fetchone()
+ current_meta = json.loads(metadata_row[0]) if metadata_row else dict(index_meta)
+ updated_meta = dict(current_meta)
+ old_scalar_fields = list(current_meta.get("ScalarIndex", []))
+ new_scalar_fields = old_scalar_fields
+ if scalar_index is not None:
+ new_scalar_fields = list(dict.fromkeys(scalar_index))
+ updated_meta["ScalarIndex"] = new_scalar_fields
+ if description is not None:
+ updated_meta["Description"] = description
+
+ removed_fields = sorted(set(old_scalar_fields) - set(new_scalar_fields))
+ added_fields = sorted(set(new_scalar_fields) - set(old_scalar_fields))
+ for scalar_field in removed_fields:
+ scalar_index_name = _bounded_identifier(
+ f"idx_{self._name}_{index_name}_{scalar_field}",
+ kind="openGauss scalar index name",
+ )
+ cursor.execute(f"DROP INDEX IF EXISTS {_quote_identifier(scalar_index_name)}")
+ for scalar_field in added_fields:
+ scalar_index_name = _bounded_identifier(
+ f"idx_{self._name}_{index_name}_{scalar_field}",
+ kind="openGauss scalar index name",
+ )
+ cursor.execute(
+ f"CREATE INDEX {_quote_identifier(scalar_index_name)} "
+ f"ON {_quote_identifier(self._name)} "
+ f"({_quote_identifier(scalar_field)})"
+ )
+ cursor.execute(
+ f"UPDATE {idx_table} SET meta_json = %s WHERE index_name = %s",
+ (json.dumps(updated_meta), index_name),
+ )
+ if cursor.rowcount == 0:
+ cursor.execute(
+ f"INSERT INTO {idx_table} (index_name, meta_json) VALUES (%s, %s)",
+ (index_name, json.dumps(updated_meta)),
+ )
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cursor.close()
+
+ if index_name in self._indexes:
+ self._indexes[index_name] = updated_meta
+ else:
+ self._pending_indexes[index_name] = updated_meta
+
+ def get_index_meta_data(self, index_name: str) -> Dict[str, Any]:
+ index_meta = self._indexes.get(index_name) or self._pending_indexes.get(index_name)
+ return dict(index_meta or {})
+
+ def begin_bulk_ingest(self) -> None:
+ with self._lock:
+ self._bulk_ingest_depth += 1
+
+ def end_bulk_ingest(self) -> None:
+ with self._lock:
+ if self._bulk_ingest_depth <= 0:
+ raise RuntimeError("openGauss end_bulk_ingest called without matching begin")
+ self._bulk_ingest_depth -= 1
+ if self._bulk_ingest_depth == 0:
+ self._materialize_pending_indexes()
+
+ # ------------------------------------------------------------------
+ # ICollection: search
+ # ------------------------------------------------------------------
+
+ def _resolve_distance_and_op(self, index_name: str) -> tuple[str, str]:
+ idx_meta = self._indexes.get(index_name) or self._pending_indexes.get(index_name, {})
+ distance = idx_meta.get("_distance") or idx_meta.get("Distance", self._distance)
+ op = _DISTANCE_OP.get(distance, "<=>")
+ return distance, op
+
+ def search_by_vector(
+ self,
+ index_name: str,
+ dense_vector: Optional[List[float]] = None,
+ limit: int = 10,
+ offset: int = 0,
+ filters: Optional[Dict[str, Any]] = None,
+ sparse_vector: Optional[Dict[str, float]] = None,
+ output_fields: Optional[List[str]] = None,
+ ) -> SearchResult:
+ # Sparse support is checked before the dense emptiness short-circuit:
+ # a pure sparse query must fail loudly instead of returning an empty
+ # result set that looks like "no recall".
+ if sparse_vector:
+ raise NotImplementedError(
+ "openGauss backend does not support sparse or hybrid vector search"
+ )
+
+ if not dense_vector:
+ return SearchResult(data=[])
+
+ self._materialize_pending_index(index_name)
+ if index_name in self._pending_indexes and not self._table_has_rows():
+ return SearchResult(data=[])
+ if not self.has_index(index_name):
+ raise RuntimeError(f"openGauss physical ANN index {index_name!r} is missing or invalid")
+ distance_metric, op = self._resolve_distance_and_op(index_name)
+ select_cols = self._select_output_columns(output_fields)
+
+ where_frag, where_params = _build_where_clause(
+ self._normalize_filter_date_times(filters), self._array_fields
+ )
+ where_clause = f"WHERE {where_frag}" if where_frag else ""
+
+ normalized_vector = _validate_vector(dense_vector, self._dim, field_name="query vector")
+ vector_str = "[" + ",".join(str(value) for value in normalized_vector) + "]"
+ sql = f"""
+ SELECT {select_cols}, vector {op} %s::vector AS _distance
+ FROM "{self._name}"
+ {where_clause}
+ ORDER BY _distance, id
+ LIMIT %s OFFSET %s
+ """
+ params = [vector_str] + where_params + [limit, offset]
+
+ try:
+ with self._lock:
+ cur = self._cursor()
+ try:
+ self._apply_search_params_on_cursor(cur, index_name)
+ cur.execute(sql, params)
+ col_names = [desc[0] for desc in cur.description]
+ rows = cur.fetchall()
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cur.close()
+ except Exception as error:
+ logger.error("opengauss_adapter: search_by_vector failed: %s", error)
+ raise
+
+ if not rows:
+ return SearchResult(data=[])
+
+ items = []
+ for row in rows:
+ record = self._row_to_dict(row, col_names)
+ distance = record.pop("_distance", 0.0)
+ record_id = record.pop("id", None)
+ similarity = _distance_to_similarity(distance_metric, distance)
+ items.append(SearchItemResult(id=record_id, fields=record, score=similarity))
+ return SearchResult(data=items)
+
+ def search_by_scalar(
+ self,
+ index_name: str,
+ field: str,
+ order: Optional[str] = "desc",
+ limit: int = 10,
+ offset: int = 0,
+ filters: Optional[Dict[str, Any]] = None,
+ output_fields: Optional[List[str]] = None,
+ ) -> SearchResult:
+ select_cols = self._select_output_columns(output_fields)
+ quoted_field = _quote_identifier(field, kind="openGauss scalar sort field")
+ where_frag, where_params = _build_where_clause(
+ self._normalize_filter_date_times(filters), self._array_fields
+ )
+ where_clause = f"WHERE {where_frag}" if where_frag else ""
+ sort_dir = "DESC" if (order or "desc").lower() == "desc" else "ASC"
+
+ sql = f"""
+ SELECT {select_cols}, {quoted_field} AS _scalar_val
+ FROM "{self._name}"
+ {where_clause}
+ ORDER BY {quoted_field} {sort_dir}, id {sort_dir}
+ LIMIT %s OFFSET %s
+ """
+ params = where_params + [limit, offset]
+
+ try:
+ with self._lock:
+ cur = self._cursor()
+ try:
+ cur.execute(sql, params)
+ col_names = [desc[0] for desc in cur.description]
+ rows = cur.fetchall()
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cur.close()
+ except Exception as error:
+ logger.error("opengauss_adapter: search_by_scalar failed: %s", error)
+ raise
+
+ items = []
+ for row in rows:
+ record = self._row_to_dict(row, col_names)
+ score = record.pop("_scalar_val", 0.0)
+ record_id = record.pop("id", None)
+ try:
+ score_float = float(score) if score is not None else 0.0
+ except (TypeError, ValueError):
+ score_float = 0.0
+ items.append(SearchItemResult(id=record_id, fields=record, score=score_float))
+ return SearchResult(data=items)
+
+ def search_by_random(
+ self,
+ index_name: str,
+ limit: int = 10,
+ offset: int = 0,
+ filters: Optional[Dict[str, Any]] = None,
+ output_fields: Optional[List[str]] = None,
+ ) -> SearchResult:
+ select_cols = self._select_output_columns(output_fields)
+ where_frag, where_params = _build_where_clause(
+ self._normalize_filter_date_times(filters), self._array_fields
+ )
+ where_clause = f"WHERE {where_frag}" if where_frag else ""
+
+ sql = f"""
+ SELECT {select_cols}
+ FROM "{self._name}"
+ {where_clause}
+ ORDER BY RANDOM()
+ LIMIT %s OFFSET %s
+ """
+ params = where_params + [limit, offset]
+
+ try:
+ with self._lock:
+ cur = self._cursor()
+ try:
+ cur.execute(sql, params)
+ col_names = [desc[0] for desc in cur.description]
+ rows = cur.fetchall()
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cur.close()
+ except Exception as error:
+ logger.error("opengauss_adapter: search_by_random failed: %s", error)
+ raise
+
+ items = []
+ for row in rows:
+ record = self._row_to_dict(row, col_names)
+ record_id = record.pop("id", None)
+ items.append(SearchItemResult(id=record_id, fields=record, score=0.0))
+ return SearchResult(data=items)
+
+ def search_by_keywords(
+ self,
+ index_name: str,
+ keywords: Optional[List[str]] = None,
+ query: Optional[str] = None,
+ limit: int = 10,
+ offset: int = 0,
+ filters: Optional[Dict[str, Any]] = None,
+ output_fields: Optional[List[str]] = None,
+ ) -> SearchResult:
+ raise NotImplementedError(
+ "openGauss backend does not provide OpenViking keyword/full-text search"
+ )
+
+ def search_by_id(
+ self,
+ index_name: str,
+ id: Any,
+ limit: int = 10,
+ offset: int = 0,
+ filters: Optional[Dict[str, Any]] = None,
+ output_fields: Optional[List[str]] = None,
+ ) -> SearchResult:
+ # Fetch the source vector and use it for similarity search. Backend
+ # failures propagate; only a genuinely missing id yields empty data.
+ try:
+ rows = self._execute(
+ f'SELECT vector FROM "{self._name}" WHERE id = %s',
+ (str(id),),
+ fetch=True,
+ )
+ except Exception as error:
+ logger.error(
+ "opengauss_adapter: search_by_id failed to fetch source vector: %s",
+ error,
+ )
+ raise
+
+ if not rows or rows[0][0] is None:
+ return SearchResult(data=[])
+
+ vec = _coerce_vector(rows[0][0])
+ if not isinstance(vec, list) or not vec:
+ return SearchResult(data=[])
+
+ result = self.search_by_vector(
+ index_name,
+ dense_vector=vec,
+ limit=limit + offset + 1,
+ offset=0,
+ filters=filters,
+ output_fields=output_fields,
+ )
+ candidates = [item for item in result.data if str(item.id) != str(id)]
+ result.data = candidates[offset : offset + limit]
+ return result
+
+ def search_by_multimodal(
+ self,
+ index_name: str,
+ text: Optional[str],
+ image: Optional[Any],
+ video: Optional[Any],
+ limit: int = 10,
+ offset: int = 0,
+ filters: Optional[Dict[str, Any]] = None,
+ output_fields: Optional[List[str]] = None,
+ ) -> SearchResult:
+ raise NotImplementedError(
+ "openGauss backend requires upstream multimodal embedding before vector search"
+ )
+
+ # ------------------------------------------------------------------
+ # ICollection: data operations
+ # ------------------------------------------------------------------
+
+ def upsert_data(self, data_list: List[Dict[str, Any]], ttl: int = 0):
+ if not data_list:
+ return
+
+ import uuid
+
+ all_columns = set(self._get_all_columns())
+ column_types = self._get_column_types()
+ prepared_records: list[tuple[str, list[str], list[str], list[Any]]] = []
+
+ for record_index, record in enumerate(data_list):
+ record_id = record.get("id") or record.get("_id") or str(uuid.uuid4())
+ unknown_fields = sorted(
+ set(record) - {"id", "_id", "vector"} - all_columns - _UNSTORED_FIELDS
+ )
+ if unknown_fields:
+ raise ValueError(
+ f"openGauss record at index {record_index} contains unknown fields: "
+ f"{unknown_fields}"
+ )
+
+ extra_fields = {
+ field_name: field_value
+ for field_name, field_value in record.items()
+ if field_name not in {"id", "_id", "vector"} | _UNSTORED_FIELDS
+ }
+ column_names = ["id"]
+ placeholders = ["%s"]
+ values: list[Any] = [str(record_id)]
+
+ for field_name, field_value in extra_fields.items():
+ _validate_identifier(field_name, kind="openGauss field name")
+ column_names.append(field_name)
+ column_type = column_types.get(field_name, "").lower()
+ if field_name in self._date_time_fields:
+ field_value = _date_time_to_epoch_ms(field_value)
+ if column_type == "jsonb":
+ placeholders.append("%s::jsonb")
+ field_value = json.dumps(field_value, ensure_ascii=False)
+ else:
+ placeholders.append("%s")
+ values.append(field_value)
+
+ vector_value = record.get("vector")
+ if vector_value is not None:
+ if "vector" not in all_columns:
+ raise ValueError("openGauss collection does not define a vector column")
+ normalized_vector = _validate_vector(
+ vector_value,
+ self._dim,
+ field_name=f"record[{record_index}].vector",
+ )
+ column_names.append("vector")
+ placeholders.append("%s::vector")
+ values.append("[" + ",".join(str(value) for value in normalized_vector) + "]")
+
+ prepared_records.append((str(record_id), column_names, placeholders, values))
+
+ table_identifier = _quote_identifier(self._name, kind="openGauss collection name")
+ with self._lock:
+ cursor = self._cursor()
+ try:
+ for record_id, column_names, placeholders, values in prepared_records:
+ update_columns = [
+ column_name for column_name in column_names if column_name != "id"
+ ]
+ update_placeholders = [
+ placeholder
+ for column_name, placeholder in zip(column_names, placeholders, strict=True)
+ if column_name != "id"
+ ]
+ update_set = ", ".join(
+ f"{_quote_identifier(column_name)} = {placeholder}"
+ for column_name, placeholder in zip(
+ update_columns, update_placeholders, strict=True
+ )
+ )
+ update_values = [
+ value
+ for column_name, value in zip(column_names, values, strict=True)
+ if column_name != "id"
+ ] + [record_id]
+
+ updated = 0
+ if update_set:
+ cursor.execute(
+ f"UPDATE {table_identifier} SET {update_set} "
+ f"WHERE {_quote_identifier('id')} = %s",
+ update_values,
+ )
+ updated = cursor.rowcount
+ if updated == 0:
+ columns_sql = ", ".join(
+ _quote_identifier(column_name) for column_name in column_names
+ )
+ insert_placeholders = ", ".join(placeholders)
+ cursor.execute("SAVEPOINT ov_upsert_insert")
+ try:
+ cursor.execute(
+ f"INSERT INTO {table_identifier} ({columns_sql}) "
+ f"VALUES ({insert_placeholders})",
+ values,
+ )
+ except Exception as error:
+ cursor.execute("ROLLBACK TO SAVEPOINT ov_upsert_insert")
+ if getattr(error, "pgcode", None) != "23505":
+ raise
+ if update_set:
+ cursor.execute(
+ f"UPDATE {table_identifier} SET {update_set} "
+ f"WHERE {_quote_identifier('id')} = %s",
+ update_values,
+ )
+ if cursor.rowcount != 1:
+ raise RuntimeError(
+ f"openGauss concurrent upsert recovery failed for {record_id!r}"
+ ) from error
+ finally:
+ cursor.execute("RELEASE SAVEPOINT ov_upsert_insert")
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cursor.close()
+ try:
+ self._materialize_pending_indexes()
+ except Exception:
+ logger.exception(
+ "opengauss_adapter: data committed but pending ANN index materialization failed"
+ )
+
+ def update_data(self, data_list: List[Dict[str, Any]]):
+ """Update existing records while preserving unspecified fields."""
+ if not data_list:
+ return []
+ for record in data_list:
+ if "id" not in record:
+ raise ValueError("primary key 'id' is required for update")
+
+ all_columns = set(self._get_all_columns())
+ column_types = self._get_column_types()
+ prepared_updates: list[tuple[str, list[str], list[Any]]] = []
+
+ for record_index, record in enumerate(data_list):
+ primary_key = str(record["id"])
+ unknown_fields = sorted(
+ set(record) - {"id", "_id", "vector"} - all_columns - _UNSTORED_FIELDS
+ )
+ if unknown_fields:
+ raise ValueError(
+ f"openGauss record at index {record_index} contains unknown fields: "
+ f"{unknown_fields}"
+ )
+
+ assignments: list[str] = []
+ values: list[Any] = []
+ for field_name, field_value in record.items():
+ if field_name in {"id", "_id"} | _UNSTORED_FIELDS:
+ continue
+ _validate_identifier(field_name, kind="openGauss field name")
+ if field_name == "vector":
+ if "vector" not in all_columns:
+ raise ValueError("openGauss collection does not define a vector column")
+ normalized_vector = _validate_vector(
+ field_value,
+ self._dim,
+ field_name=f"record[{record_index}].vector",
+ )
+ assignments.append(f"{_quote_identifier(field_name)} = %s::vector")
+ values.append("[" + ",".join(str(value) for value in normalized_vector) + "]")
+ continue
+ if field_name in self._date_time_fields:
+ field_value = _date_time_to_epoch_ms(field_value)
+ if column_types.get(field_name, "").lower() == "jsonb":
+ assignments.append(f"{_quote_identifier(field_name)} = %s::jsonb")
+ field_value = json.dumps(field_value, ensure_ascii=False)
+ else:
+ assignments.append(f"{_quote_identifier(field_name)} = %s")
+ values.append(field_value)
+ prepared_updates.append((primary_key, assignments, values))
+
+ table_identifier = _quote_identifier(
+ self._name,
+ kind="openGauss collection name",
+ )
+ with self._lock:
+ cursor = self._cursor()
+ try:
+ missing_ids: list[str] = []
+ for primary_key, assignments, values in prepared_updates:
+ if assignments:
+ cursor.execute(
+ f"UPDATE {table_identifier} SET {', '.join(assignments)} "
+ f"WHERE {_quote_identifier('id')} = %s",
+ values + [primary_key],
+ )
+ else:
+ cursor.execute(
+ f"UPDATE {table_identifier} "
+ f"SET {_quote_identifier('id')} = {_quote_identifier('id')} "
+ f"WHERE {_quote_identifier('id')} = %s",
+ (primary_key,),
+ )
+ if cursor.rowcount == 0:
+ missing_ids.append(primary_key)
+ if missing_ids:
+ raise ValueError(f"record not found for primary key(s): {missing_ids}")
+ self._conn.commit()
+ return [primary_key for primary_key, _, _ in prepared_updates]
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cursor.close()
+
+ def fetch_data(self, primary_keys: List[Any]) -> FetchDataInCollectionResult:
+ if not primary_keys:
+ return FetchDataInCollectionResult(items=[], ids_not_exist=[])
+
+ str_keys = [str(k) for k in primary_keys]
+ placeholders = ", ".join(["%s"] * len(str_keys))
+ sql = f'SELECT * FROM "{self._name}" WHERE id IN ({placeholders})'
+
+ try:
+ with self._lock:
+ cur = self._cursor()
+ try:
+ cur.execute(sql, str_keys)
+ col_names = [desc[0] for desc in cur.description]
+ rows = cur.fetchall()
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cur.close()
+ except Exception as error:
+ logger.error("opengauss_adapter: fetch_data failed: %s", error)
+ raise
+
+ found_ids = set()
+ items = []
+ for row in rows:
+ record = self._row_to_dict(row, col_names)
+ record_id = record.pop("id", None)
+ found_ids.add(str(record_id))
+ items.append(DataItem(id=record_id, fields=record))
+
+ ids_not_exist = [k for k in str_keys if k not in found_ids]
+ return FetchDataInCollectionResult(items=items, ids_not_exist=ids_not_exist)
+
+ def delete_data(self, primary_keys: List[Any]):
+ if not primary_keys:
+ return
+ str_keys = [str(k) for k in primary_keys]
+ placeholders = ", ".join(["%s"] * len(str_keys))
+ self._execute(
+ f'DELETE FROM "{self._name}" WHERE id IN ({placeholders})',
+ str_keys,
+ )
+
+ def delete_all_data(self):
+ self._execute(f'TRUNCATE TABLE "{self._name}"')
+
+ def aggregate_data(
+ self,
+ index_name: str,
+ op: str = "count",
+ field: Optional[str] = None,
+ filters: Optional[Dict[str, Any]] = None,
+ cond: Optional[Dict[str, Any]] = None,
+ ) -> AggregateResult:
+ where_frag, where_params = _build_where_clause(
+ self._normalize_filter_date_times(filters), self._array_fields
+ )
+ where_clause = f"WHERE {where_frag}" if where_frag else ""
+
+ if op == "count":
+ if field:
+ quoted_field = _quote_identifier(field, kind="openGauss aggregate field")
+ sql = f"""
+ SELECT {quoted_field}, COUNT(*) AS cnt
+ FROM "{self._name}"
+ {where_clause}
+ GROUP BY {quoted_field}
+ """
+ try:
+ rows = self._execute(sql, where_params, fetch=True)
+ except Exception as error:
+ logger.error("opengauss_adapter: aggregate_data (grouped) failed: %s", error)
+ raise
+
+ agg: Dict[str, Any] = {}
+ for row in rows:
+ key, cnt = row[0], row[1]
+ if cond:
+ gt = cond.get("gt")
+ gte = cond.get("gte")
+ lt = cond.get("lt")
+ lte = cond.get("lte")
+ if gt is not None and cnt <= gt:
+ continue
+ if gte is not None and cnt < gte:
+ continue
+ if lt is not None and cnt >= lt:
+ continue
+ if lte is not None and cnt > lte:
+ continue
+ agg[str(key)] = cnt
+ return AggregateResult(agg=agg, op=op, field=field)
+ else:
+ sql = f'SELECT COUNT(*) FROM "{self._name}" {where_clause}'
+ try:
+ rows = self._execute(sql, where_params, fetch=True)
+ total = rows[0][0] if rows else 0
+ except Exception as error:
+ logger.error("opengauss_adapter: aggregate_data (count) failed: %s", error)
+ raise
+ return AggregateResult(agg={"_total": int(total)}, op=op, field=None)
+
+ logger.warning("opengauss_adapter: unsupported aggregate op=%r", op)
+ return AggregateResult(agg={"_total": 0}, op=op, field=field)
diff --git a/openviking/storage/vectordb_adapters/opengauss/connection.py b/openviking/storage/vectordb_adapters/opengauss/connection.py
new file mode 100644
index 000000000..d46441d36
--- /dev/null
+++ b/openviking/storage/vectordb_adapters/opengauss/connection.py
@@ -0,0 +1,145 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Thread-local transaction and pooled connection lifecycle."""
+
+from __future__ import annotations
+
+import threading
+
+from openviking_cli.utils import get_logger
+
+logger = get_logger(__name__)
+
+
+class _PooledCursor:
+ def __init__(self, connection_proxy: "_PooledConnectionProxy", connection, cursor):
+ self._connection_proxy = connection_proxy
+ self._connection = connection
+ self._cursor = cursor
+ self._closed = False
+
+ def __getattr__(self, name: str):
+ return getattr(self._cursor, name)
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ try:
+ self._cursor.close()
+ finally:
+ self._connection_proxy.release(self._connection)
+
+
+class _PooledConnectionProxy:
+ """Compatibility connection backed by a psycopg2 threaded connection pool."""
+
+ def __init__(self, pool):
+ self._pool = pool
+ self._local = threading.local()
+ self._closed = False
+
+ def _checkout(self):
+ if self._closed:
+ raise RuntimeError("openGauss connection pool is closed")
+ connection = getattr(self._local, "connection", None)
+ if connection is not None and getattr(connection, "closed", False):
+ self._local.connection = None
+ self._local.cursor_count = 0
+ self._pool.putconn(connection, close=True)
+ connection = None
+ if connection is None:
+ connection = self._pool.getconn()
+ try:
+ connection.autocommit = False
+ except Exception:
+ self._pool.putconn(connection, close=True)
+ raise
+ self._local.connection = connection
+ self._local.cursor_count = 0
+ return connection
+
+ def cursor(self, *args, **kwargs):
+ connection = self._checkout()
+ self._local.cursor_count = getattr(self._local, "cursor_count", 0) + 1
+ try:
+ cursor = connection.cursor(*args, **kwargs)
+ except Exception:
+ self.release(connection)
+ raise
+ return _PooledCursor(self, connection, cursor)
+
+ def commit(self) -> None:
+ self._checkout().commit()
+
+ def rollback(self) -> None:
+ connection = getattr(self._local, "connection", None)
+ if connection is not None and not getattr(connection, "closed", False):
+ connection.rollback()
+
+ def release(self, connection) -> None:
+ if connection is not getattr(self._local, "connection", None):
+ return
+ cursor_count = max(getattr(self._local, "cursor_count", 1) - 1, 0)
+ self._local.cursor_count = cursor_count
+ if cursor_count > 0:
+ return
+ self._local.connection = None
+ close_connection = bool(getattr(connection, "closed", False))
+ try:
+ if not close_connection:
+ connection.rollback()
+ except Exception:
+ close_connection = True
+ self._pool.putconn(connection, close=close_connection)
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ connection = getattr(self._local, "connection", None)
+ if connection is not None:
+ self._local.connection = None
+ self._local.cursor_count = 0
+ self._pool.putconn(connection, close=True)
+ self._pool.closeall()
+ self._closed = True
+
+
+def _create_connection_pool(
+ *,
+ host: str,
+ port: int,
+ user: str,
+ password: str,
+ db_name: str,
+ min_size: int,
+ max_size: int,
+):
+ psycopg2 = _import_psycopg2()
+ return psycopg2.pool.ThreadedConnectionPool(
+ minconn=min_size,
+ maxconn=max_size,
+ host=host,
+ port=port,
+ user=user,
+ password=password,
+ dbname=db_name,
+ options="-c client_encoding=UTF8 -c search_path=public",
+ connect_timeout=10,
+ )
+
+
+def _import_psycopg2():
+ """Import psycopg2 (openGauss connector)."""
+ try:
+ import psycopg2 # noqa: PLC0415
+ import psycopg2.pool # noqa: PLC0415
+
+ return psycopg2
+ except ImportError as e:
+ raise ImportError(
+ "psycopg2 is required for the openGauss backend. Install it via:\n"
+ ' pip install "openviking[opengauss]"\n'
+ "or install the openGauss-connector-python-psycopg2 package, "
+ "which exposes the same psycopg2 module interface."
+ ) from e
diff --git a/openviking/storage/vectordb_adapters/opengauss/metadata.py b/openviking/storage/vectordb_adapters/opengauss/metadata.py
new file mode 100644
index 000000000..95faccf7e
--- /dev/null
+++ b/openviking/storage/vectordb_adapters/opengauss/metadata.py
@@ -0,0 +1,34 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Normalize persisted pre-release metadata at the database read boundary only."""
+
+from typing import Any
+
+from openviking_cli.utils.config.vectordb_config import (
+ _OPENGAUSS_BUILD_PARAMS,
+ _OPENGAUSS_SEARCH_ALIASES,
+ _OPENGAUSS_SEARCH_PARAMS,
+)
+
+BUILD_KEYS = frozenset().union(*_OPENGAUSS_BUILD_PARAMS.values()) | {"enable_pq", "enable_rabitq"}
+SEARCH_KEYS = frozenset().union(*_OPENGAUSS_SEARCH_PARAMS.values()) | frozenset(
+ key for aliases in _OPENGAUSS_SEARCH_ALIASES.values() for key in aliases
+)
+
+
+def migrate_persisted_index_meta(meta: dict[str, Any]) -> dict[str, Any]:
+ """Consume old duplicate fields once; never emit them in new metadata."""
+ result = dict(meta)
+ for group, keys in (("build_params", BUILD_KEYS), ("search_params", SEARCH_KEYS)):
+ values = result.get(group, {})
+ if not isinstance(values, dict):
+ raise ValueError(f"openGauss {group} must be an object")
+ values = dict(values)
+ for key in keys:
+ if key in result:
+ values.setdefault(key, result.pop(key))
+ result[group] = values
+ build = result["build_params"]
+ if "parallel_workers" in build:
+ result.setdefault("parallel_workers", build.pop("parallel_workers"))
+ return result
diff --git a/openviking/storage/vectordb_adapters/opengauss/sql.py b/openviking/storage/vectordb_adapters/opengauss/sql.py
new file mode 100644
index 000000000..c9023ca2a
--- /dev/null
+++ b/openviking/storage/vectordb_adapters/opengauss/sql.py
@@ -0,0 +1,492 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""SQL identifiers, value conversion and filter compilation."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import re
+from datetime import datetime, timezone
+from typing import Any, Dict, Optional
+
+from openviking_cli.utils import get_logger
+from openviking_cli.utils.config.vectordb_config import (
+ normalize_opengauss_index_type,
+ resolve_opengauss_index_spec,
+)
+
+logger = get_logger(__name__)
+
+
+_SUPPORTED_INDEX_TYPES = frozenset(
+ {
+ "hnsw",
+ "hnsw-pq",
+ "hnsw-rabitq",
+ "ivfflat",
+ "ivf-pq",
+ "ivf-rabitq",
+ "diskann",
+ }
+)
+
+
+_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")
+
+
+_IDENTIFIER_CHAR_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+
+_PATH_SCOPE_DEPTH_PATTERN = re.compile(r"\s*-d=(-?\d+)\s*")
+
+
+_MAX_SQL_IDENTIFIER = 63
+
+
+_BOUNDED_IDENT_HASH_LEN = 12
+
+
+_UNSTORED_FIELDS = frozenset({"content"})
+
+
+_EMPTY_OR_FILTER: Dict[str, Any] = {"op": "or", "conds": []}
+
+
+_QUANTIZATION_OPTION_NAMES = frozenset(
+ {
+ "enable_pq",
+ "enable_rabitq",
+ "pq_m",
+ "pq_ksub",
+ "by_residual",
+ "rabitq_refine_type",
+ "rabitq_fht",
+ }
+)
+
+
+_META_TABLE = "_ov_collection_meta"
+
+
+_FIELD_TYPE_MAP: Dict[str, str] = {
+ "string": "TEXT",
+ "path": "TEXT",
+ "int64": "BIGINT",
+ "int32": "INTEGER",
+ "float": "DOUBLE PRECISION",
+ "float32": "DOUBLE PRECISION",
+ "bool": "BOOLEAN",
+ "date_time": "BIGINT",
+ "list<string>": "TEXT[]",
+ "list<int64>": "BIGINT[]",
+ "text": "TEXT",
+ "vector": None, # handled separately
+ "sparse_vector": "JSONB",
+}
+
+
+_DISTANCE_OP: Dict[str, str] = {
+ "l2": "<->",
+ "ip": "<#>",
+ "cosine": "<=>",
+ "l1": "<+>",
+}
+
+
+_VECTOR_OPS: Dict[str, Dict[str, str]] = {
+ "l2": {
+ "hnsw": "vector_l2_ops",
+ "ivfflat": "vector_l2_ops",
+ "diskann": "vector_l2_ops",
+ },
+ "ip": {
+ "hnsw": "vector_ip_ops",
+ "ivfflat": "vector_ip_ops",
+ "diskann": "vector_ip_ops",
+ },
+ "cosine": {
+ "hnsw": "vector_cosine_ops",
+ "ivfflat": "vector_cosine_ops",
+ "diskann": "vector_cosine_ops",
+ },
+ "l1": {
+ "hnsw": "vector_l1_ops",
+ },
+}
+
+
+def _normalize_index_type(index_type: str | None) -> str:
+ return normalize_opengauss_index_type(index_type)
+
+
+def _index_access_method(index_type: str) -> str:
+ return resolve_opengauss_index_spec(index_type)[0]
+
+
+def _index_quantization(index_type: str) -> Optional[str]:
+ return resolve_opengauss_index_spec(index_type)[1]
+
+
+def _validate_identifier(identifier: str, *, kind: str = "SQL identifier") -> str:
+ if not isinstance(identifier, str) or not _IDENTIFIER_PATTERN.fullmatch(identifier):
+ raise ValueError(
+ f"Invalid {kind}: {identifier!r}; use 1-63 ASCII letters, digits, or underscores"
+ )
+ return identifier
+
+
+def _bounded_identifier(identifier: str, *, kind: str = "SQL identifier") -> str:
+ """Fit a derived SQL name into NAMEDATALEN without silent truncation.
+
+ Collection/field names stay strictly 1-63 via ``_validate_identifier``.
+ Physical index and catalog table names are derived and can exceed 63
+ even when every input is legal; hash the tail so CREATE INDEX cannot
+ fail after the collection table already exists.
+ """
+ if not isinstance(identifier, str) or not _IDENTIFIER_CHAR_PATTERN.fullmatch(identifier):
+ raise ValueError(
+ f"Invalid {kind}: {identifier!r}; use ASCII letters, digits, or underscores"
+ )
+ if len(identifier) <= _MAX_SQL_IDENTIFIER:
+ return identifier
+ digest = hashlib.sha1(identifier.encode("utf-8")).hexdigest()[:_BOUNDED_IDENT_HASH_LEN]
+ keep = _MAX_SQL_IDENTIFIER - 1 - len(digest)
+ return f"{identifier[:keep]}_{digest}"
+
+
+def _index_meta_table_name(collection_name: str) -> str:
+ return _bounded_identifier(
+ f"_ov_index_{collection_name}",
+ kind="openGauss index metadata table",
+ )
+
+
+def _quote_identifier(identifier: str, *, kind: str = "SQL identifier") -> str:
+ return f'"{_validate_identifier(identifier, kind=kind)}"'
+
+
+def _escape_like_pattern(value: str) -> str:
+ r"""Escape `\`, `%`, and `_` for LIKE ... ESCAPE '\'."""
+ return str(value).replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
+def _normalize_scope_path(path: str) -> str:
+ stripped = str(path).strip() or "/"
+ if stripped != "/":
+ stripped = stripped.rstrip("/") or "/"
+ return stripped
+
+
+def _parse_path_scope_depth(para: Any) -> Optional[int]:
+ if not isinstance(para, str):
+ return None
+ match = _PATH_SCOPE_DEPTH_PATTERN.fullmatch(para)
+ if not match:
+ return None
+ return int(match.group(1))
+
+
+def _sql_normalized_path(quoted_field: str) -> str:
+ """SQL equivalent of stripping and rstrip('/') for stored path values."""
+ trimmed = f"btrim({quoted_field})"
+ stripped = f"rtrim({trimmed}, '/')"
+ return (
+ f"(CASE WHEN {quoted_field} IS NULL THEN NULL "
+ f"WHEN {trimmed} = '' OR {stripped} = '' THEN '/' "
+ f"ELSE {stripped} END)"
+ )
+
+
+def _build_path_scope_clause(quoted_field: str, prefix: str, depth: int) -> tuple[str, list]:
+ """Translate PathScope to SQL using the official relative-depth contract.
+
+ ``depth < 0`` is unbounded recursion. ``depth == 0`` is an exact match.
+ Positive depth includes the node itself and descendants whose relative
+ path has at most ``depth`` segments. Stored values are normalized the
+ same way as the query prefix so trailing slashes do not change depth.
+ """
+ normalized = _normalize_scope_path(prefix)
+ field_expr = _sql_normalized_path(quoted_field)
+ if depth == 0:
+ return f"{field_expr} = %s", [normalized]
+
+ child_pattern = "/%" if normalized == "/" else f"{_escape_like_pattern(normalized)}/%"
+ start_pos = 2 if normalized == "/" else len(normalized) + 2
+ suffix = f"substring({field_expr} from {int(start_pos)})"
+ relative_depth = f"(char_length({suffix}) - char_length(replace({suffix}, '/', '')) + 1)"
+ if depth < 0:
+ return (
+ f"({field_expr} = %s OR {field_expr} LIKE %s ESCAPE '\\')",
+ [normalized, child_pattern],
+ )
+ return (
+ f"({field_expr} = %s OR ({field_expr} LIKE %s ESCAPE '\\' AND {relative_depth} <= %s))",
+ [normalized, child_pattern, int(depth)],
+ )
+
+
+def _validate_vector(vector: Any, dimension: int, *, field_name: str = "vector") -> list[float]:
+ if not isinstance(vector, (list, tuple)):
+ raise ValueError(f"openGauss {field_name} must be a list or tuple")
+ if dimension > 0 and len(vector) != dimension:
+ raise ValueError(
+ f"openGauss {field_name} dimension mismatch: expected {dimension}, got {len(vector)}"
+ )
+ normalized: list[float] = []
+ for index, value in enumerate(vector):
+ if isinstance(value, bool):
+ raise ValueError(f"openGauss {field_name}[{index}] must be numeric")
+ try:
+ number = float(value)
+ except (TypeError, ValueError) as error:
+ raise ValueError(f"openGauss {field_name}[{index}] must be numeric") from error
+ if not math.isfinite(number):
+ raise ValueError(f"openGauss {field_name}[{index}] must be finite")
+ normalized.append(number)
+ return normalized
+
+
+def _coerce_vector(value: Any) -> Any:
+ """Normalize psycopg2/DataVec vector values to ``list[float]``.
+
+ Unregistered ``vector`` columns typically arrive as strings like
+ ``'[1,2,3]'``. Official migration treats non-list payloads as missing.
+ """
+ if value is None:
+ return None
+ if isinstance(value, (list, tuple)):
+ try:
+ return [float(component) for component in value]
+ except (TypeError, ValueError):
+ return value
+ if hasattr(value, "tolist"):
+ try:
+ coerced = value.tolist()
+ except Exception:
+ coerced = None
+ if isinstance(coerced, (list, tuple)):
+ try:
+ return [float(component) for component in coerced]
+ except (TypeError, ValueError):
+ return value
+ if isinstance(value, (bytes, bytearray)):
+ try:
+ value = value.decode("utf-8")
+ except UnicodeDecodeError:
+ return value
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return None
+ if text.startswith("[") and text.endswith("]"):
+ text = text[1:-1].strip()
+ if not text:
+ return []
+ try:
+ return [float(part.strip()) for part in text.split(",") if part.strip()]
+ except ValueError:
+ return value
+ return value
+
+
+def _is_undefined_table_error(error: Exception) -> bool:
+ """Return True when *error* is the driver's undefined-table error (SQLSTATE 42P01).
+
+ Distinguishes the legitimate "catalog/metadata table not created yet" case
+ from real backend failures, which must propagate to the caller instead of
+ being silently converted into an empty/absent result.
+ """
+ sqlstate = getattr(error, "pgcode", None) or getattr(error, "sqlstate", None)
+ return sqlstate == "42P01"
+
+
+def _coerce_sparse_vector(value: Any) -> Any:
+ if value is None or isinstance(value, dict):
+ return value
+ if isinstance(value, (bytes, bytearray)):
+ try:
+ value = value.decode("utf-8")
+ except UnicodeDecodeError:
+ return value
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return None
+ try:
+ parsed = json.loads(text)
+ except json.JSONDecodeError:
+ return value
+ return parsed if isinstance(parsed, dict) else value
+ return value
+
+
+def _resolve_build_params(index_type: str, meta_data: Dict[str, Any]) -> Dict[str, Any]:
+ params = meta_data.get("build_params", {})
+ if not isinstance(params, dict):
+ raise ValueError("openGauss build_params must be an object")
+ return dict(params)
+
+
+def _resolve_search_params(index_type: str, meta_data: Dict[str, Any]) -> Dict[str, Any]:
+ params = meta_data.get("search_params", {})
+ if not isinstance(params, dict):
+ raise ValueError("openGauss search_params must be an object")
+ return dict(params)
+
+
+def _field_to_column_ddl(field: Dict[str, Any]) -> Optional[str]:
+ """Convert an OpenViking field definition to a SQL column definition.
+
+ Returns None for vector fields (handled separately) and
+ for unrecognised types (skipped with a warning).
+ """
+ name = field.get("FieldName") or field.get("field_name") or field.get("name", "")
+ ftype = field.get("FieldType") or field.get("field_type") or field.get("type", "string")
+
+ if ftype == "vector":
+ return None
+
+ # Skip 'id' field as it's already defined as PRIMARY KEY in the table schema
+ if name == "id":
+ return None
+
+ col_type = _FIELD_TYPE_MAP.get(ftype, "TEXT")
+ quoted = _quote_identifier(name, kind="openGauss field name")
+ return f"{quoted} {col_type}"
+
+
+def _date_time_to_epoch_ms(value: Any) -> int:
+ """Normalize OpenViking date_time values to epoch milliseconds."""
+ if isinstance(value, bool):
+ raise ValueError("date_time value cannot be boolean")
+ if isinstance(value, (int, float)):
+ return int(value)
+ if not isinstance(value, str):
+ raise ValueError(f"date_time value must be string or number, got {type(value).__name__}")
+
+ stripped = value.strip()
+ if not stripped:
+ raise ValueError("date_time value cannot be empty")
+ try:
+ return int(stripped)
+ except ValueError:
+ pass
+
+ normalized = stripped[:-1] + "+00:00" if stripped.endswith("Z") else stripped
+ parsed = datetime.fromisoformat(normalized)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return int(parsed.timestamp() * 1000)
+
+
+def _distance_to_similarity(distance_metric: str, distance_value: Any) -> float:
+ """Convert a DataVec distance into OpenViking's higher-is-better score."""
+ try:
+ distance = float(distance_value)
+ except (TypeError, ValueError):
+ return 0.0
+ if not math.isfinite(distance):
+ return 0.0
+
+ if distance_metric == "cosine":
+ return 1.0 - distance
+ if distance_metric == "ip":
+ return -distance
+ return 1.0 / (1.0 + max(distance, 0.0))
+
+
+def _build_where_clause(
+ filters: Optional[Dict[str, Any]],
+ array_fields: Optional[set[str]] = None,
+) -> tuple[str, list]:
+ """Recursively convert OpenViking filter DSL to a SQL WHERE clause.
+
+ Returns (sql_fragment, params_list).
+ """
+ if not filters:
+ return "", []
+
+ op = filters.get("op", "")
+
+ if op == "and":
+ parts, params = [], []
+ for cond in filters.get("conds", []):
+ frag, p = _build_where_clause(cond, array_fields)
+ if frag:
+ parts.append(f"({frag})")
+ params.extend(p)
+ if not parts:
+ return "", []
+ return " AND ".join(parts), params
+
+ if op == "or":
+ parts, params = [], []
+ for cond in filters.get("conds", []):
+ frag, p = _build_where_clause(cond, array_fields)
+ if frag:
+ parts.append(f"({frag})")
+ params.extend(p)
+ if not parts:
+ return "FALSE", []
+ return " OR ".join(parts), params
+
+ field = filters.get("field", "")
+ quoted_field = _quote_identifier(field, kind="openGauss filter field")
+
+ if op == "must":
+ conds = filters.get("conds", [])
+ depth = _parse_path_scope_depth(filters.get("para", ""))
+ if depth is not None and len(conds) == 1:
+ return _build_path_scope_clause(quoted_field, str(conds[0]), depth)
+ if conds:
+ if field in (array_fields or set()):
+ comparisons = [f"%s = ANY({quoted_field})" for _ in conds]
+ return " OR ".join(comparisons), list(conds)
+ placeholders = ", ".join(["%s"] * len(conds))
+ return f"{quoted_field} IN ({placeholders})", list(conds)
+ # Empty In/Eq is a contradiction, not an unfiltered scan.
+ return "FALSE", []
+
+ if op == "must_not":
+ conds = filters.get("conds", [])
+ depth = _parse_path_scope_depth(filters.get("para", ""))
+ if depth is not None and len(conds) == 1:
+ clause, params = _build_path_scope_clause(quoted_field, str(conds[0]), depth)
+ return f"NOT ({clause})", params
+ if not conds:
+ return "", []
+ if field in (array_fields or set()):
+ comparisons = [f"NOT (%s = ANY({quoted_field}))" for _ in conds]
+ return " AND ".join(comparisons), list(conds)
+ placeholders = ", ".join(["%s"] * len(conds))
+ return f"{quoted_field} NOT IN ({placeholders})", list(conds)
+
+ if op == "prefix":
+ prefix = str(filters.get("prefix", ""))
+ escaped_prefix = _escape_like_pattern(prefix)
+ return f"{quoted_field} LIKE %s ESCAPE '\\'", [f"{escaped_prefix}%"]
+
+ if op == "range":
+ parts, params = [], []
+ if "gte" in filters:
+ parts.append(f"{quoted_field} >= %s")
+ params.append(filters["gte"])
+ if "gt" in filters:
+ parts.append(f"{quoted_field} > %s")
+ params.append(filters["gt"])
+ if "lte" in filters:
+ parts.append(f"{quoted_field} <= %s")
+ params.append(filters["lte"])
+ if "lt" in filters:
+ parts.append(f"{quoted_field} < %s")
+ params.append(filters["lt"])
+ return " AND ".join(parts), params
+
+ if op == "contains":
+ raw_substring = filters.get("substring", "")
+ substring = _escape_like_pattern("" if raw_substring is None else raw_substring)
+ return f"{quoted_field} LIKE %s ESCAPE '\\'", [f"%{substring}%"]
+
+ raise NotImplementedError(f"openGauss backend does not support filter op={op!r}")
diff --git a/openviking/storage/vectordb_adapters/opengauss_adapter.py b/openviking/storage/vectordb_adapters/opengauss_adapter.py
new file mode 100644
index 000000000..af6121b76
--- /dev/null
+++ b/openviking/storage/vectordb_adapters/opengauss_adapter.py
@@ -0,0 +1,520 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""openGauss vector database adapter using psycopg2.
+
+openGauss (DataVec) provides native vector types and HNSW / IVFFlat / DISKANN
+indexes. No separate pgvector extension is required on openGauss >= 6.0.3.
+
+Driver: any psycopg2-compatible driver.
+ Install: pip install "openviking[opengauss]" (installs psycopg2-binary)
+ The openGauss-connector-python-psycopg2 package exposes the same `psycopg2`
+ module interface and works as a drop-in alternative.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+from openviking.storage.expr import FilterExpr, Or
+from openviking.storage.vectordb.collection.collection import Collection
+from openviking.storage.vectordb_adapters.base import CollectionAdapter
+from openviking_cli.utils import get_logger
+from openviking_cli.utils.config.vectordb_config import (
+ OpenGaussConfig,
+ VectorDBBackendConfig,
+)
+
+from .opengauss.catalog import (
+ _create_collection_table,
+ _ensure_meta_table,
+ _load_collection_meta,
+ _save_collection_meta,
+ _validate_distributed_environment,
+)
+from .opengauss.collection import (
+ OpenGaussCollection,
+)
+from .opengauss.connection import (
+ _create_connection_pool,
+ _PooledConnectionProxy,
+)
+from .opengauss.sql import (
+ _EMPTY_OR_FILTER,
+ _META_TABLE,
+ _VECTOR_OPS,
+ _build_where_clause,
+ _date_time_to_epoch_ms,
+ _index_access_method,
+ _index_quantization,
+ _quote_identifier,
+ _validate_identifier,
+)
+
+logger = get_logger(__name__)
+
+
+class OpenGaussCollectionAdapter(CollectionAdapter):
+ """OpenViking CollectionAdapter backed by openGauss DataVec.
+
+ Supports two deployment modes controlled by ``opengauss.mode``:
+
+ * **standalone** (default): connects to a single-node openGauss instance.
+ * **distributed**: connects to the CN node of an openGauss cluster with
+ spq_plugin_v2. Collection and metadata tables use verified distributed
+ catalog entries; metadata uses reference tables only when the CN supports them.
+
+ Index knobs follow the cuVS-style config shape:
+ ``index_type`` + ``build_params`` + ``search_params``.
+ """
+
+ mode = "opengauss"
+ USE_CONTENT_FIELD = False
+
+ def __init__(
+ self,
+ collection_name: str,
+ config: OpenGaussConfig,
+ index_name: str = "default",
+ distance_metric: str = "cosine",
+ ):
+ super().__init__(
+ collection_name=_validate_identifier(collection_name, kind="openGauss collection name"),
+ index_name=index_name,
+ )
+ validated_config = config.model_copy(deep=True)
+ validated_config.validate_capabilities(
+ distributed=config.is_distributed, distance=distance_metric
+ )
+ self._host = validated_config.host
+ self._port = validated_config.port
+ self._user = validated_config.user
+ self._password = validated_config.password
+ self._db_name = validated_config.db_name
+ self._distributed = validated_config.is_distributed
+ self._shard_count = validated_config.shard_count
+ self._distance_metric = (distance_metric or "cosine").lower()
+ self._index_type = validated_config.index_type
+ self._build_params = dict(validated_config.build_params)
+ self._parallel_workers = validated_config.parallel_workers
+ self._search_params = dict(validated_config.search_params)
+ self._maintenance_work_mem_mb = validated_config.maintenance_work_mem_mb
+ self._connection_pool_min_size = validated_config.connection_pool_min_size
+ self._connection_pool_max_size = validated_config.connection_pool_max_size
+ self._pool = None
+ self._conn = None
+ self._connect()
+
+ # ------------------------------------------------------------------
+ # Connection management
+ # ------------------------------------------------------------------
+
+ def _connect(self):
+ self._pool = _create_connection_pool(
+ host=self._host,
+ port=self._port,
+ user=self._user,
+ password=self._password,
+ db_name=self._db_name,
+ min_size=self._connection_pool_min_size,
+ max_size=self._connection_pool_max_size,
+ )
+ self._conn = _PooledConnectionProxy(self._pool)
+ try:
+ if self._distributed:
+ _validate_distributed_environment(self._conn)
+ _ensure_meta_table(self._conn, distributed=self._distributed)
+ except Exception:
+ self._conn.close()
+ self._conn = None
+ self._pool = None
+ raise
+ logger.info(
+ "opengauss_adapter: connected to %s:%s db=%s (distributed=%s)",
+ self._host,
+ self._port,
+ self._db_name,
+ self._distributed,
+ )
+
+ # ------------------------------------------------------------------
+ # CollectionAdapter: required overrides
+ # ------------------------------------------------------------------
+
+ @classmethod
+ def from_config(cls, config: VectorDBBackendConfig) -> "OpenGaussCollectionAdapter":
+ if config.opengauss is None:
+ raise ValueError("VectorDB opengauss backend requires 'opengauss' config")
+ return cls(
+ collection_name=config.name or "context",
+ config=config.opengauss,
+ index_name=config.index_name or "default",
+ distance_metric=config.distance_metric,
+ )
+
+ def _compile_filter(self, expr: FilterExpr | Dict[str, Any] | None) -> Dict[str, Any]:
+ compiled = super()._compile_filter(expr)
+ # Base compile collapses empty Or to ``{}``, which this backend treats
+ # as an unfiltered scan. Vacuous OR is a contradiction; keep the DSL
+ # so ``_build_where_clause`` emits FALSE (including nested And/Or).
+ if isinstance(expr, Or) and not compiled:
+ return dict(_EMPTY_OR_FILTER)
+ return compiled
+
+ def _table_exists(self, table_name: str) -> bool:
+ """Return True if *table_name* exists in the current schema.
+
+ Backend failures propagate to the caller: reporting "does not exist"
+ on a transient error would let the creation flow reuse an existing
+ physical table with freshly rewritten metadata.
+ """
+ try:
+ cur = self._conn.cursor()
+ try:
+ cur.execute(
+ """
+ SELECT 1 FROM information_schema.tables
+ WHERE table_name = %s AND table_schema = current_schema()
+ """,
+ (table_name,),
+ )
+ row = cur.fetchone()
+ self._conn.commit()
+ return row is not None
+ finally:
+ cur.close()
+ except Exception:
+ self._conn.rollback()
+ raise
+
+ def _load_existing_collection_if_needed(self) -> None:
+ if self._collection is not None:
+ return
+
+ meta = _load_collection_meta(
+ self._conn, self._collection_name, distributed=self._distributed
+ )
+ if meta is None:
+ return
+
+ # Check the actual table exists
+ if not self._table_exists(self._collection_name):
+ return
+
+ dim = meta.get("_dim", 0)
+ distance = (self._distance_metric or "cosine").lower()
+ if meta.get("_distance") != distance:
+ meta["_distance"] = distance
+ _save_collection_meta(
+ self._conn,
+ self._collection_name,
+ meta,
+ distributed=self._distributed,
+ )
+ og_coll = OpenGaussCollection(
+ self._conn,
+ self._collection_name,
+ meta,
+ dim,
+ distance,
+ distributed=self._distributed,
+ )
+ og_coll._maintenance_work_mem_mb = self._maintenance_work_mem_mb
+ self._collection = Collection(og_coll)
+
+ # Auto-create vector index if missing
+ self._ensure_vector_index_exists(og_coll, distance)
+
+ def create_collection(
+ self,
+ name: str,
+ schema: Dict[str, Any],
+ *,
+ distance: str,
+ sparse_weight: float,
+ index_name: str,
+ ) -> bool:
+ name = _validate_identifier(name, kind="openGauss collection name")
+ if (
+ self._table_exists(name)
+ and _load_collection_meta(
+ self._conn,
+ name,
+ distributed=self._distributed,
+ )
+ is None
+ ):
+ raise RuntimeError(
+ f"openGauss table {name!r} exists without collection metadata; "
+ "refusing to adopt an unverified orphan table"
+ )
+ try:
+ return super().create_collection(
+ name,
+ schema,
+ distance=distance,
+ sparse_weight=sparse_weight,
+ index_name=index_name,
+ )
+ except Exception:
+ partial_collection = self._collection
+ self._collection = None
+ if partial_collection is not None:
+ try:
+ partial_collection.drop()
+ except Exception:
+ logger.exception(
+ "opengauss_adapter: failed to clean up partially created collection %s",
+ name,
+ )
+ raise
+
+ def delete(
+ self,
+ *,
+ ids: Optional[list[str]] = None,
+ filter: Optional[Dict[str, Any] | FilterExpr] = None,
+ limit: Optional[int] = None,
+ ) -> int:
+ if ids is not None or filter is None:
+ return super().delete(ids=ids, filter=filter)
+ if limit is not None and limit <= 0:
+ return 0
+
+ collection = self.get_collection()
+ compiled_filter = self._compile_filter(filter)
+ collection_meta = collection.get_meta_data()
+ array_fields = {
+ field.get("FieldName") or field.get("field_name") or field.get("name", "")
+ for field in collection_meta.get("Fields", [])
+ if (field.get("FieldType") or field.get("field_type") or field.get("type"))
+ in {"list<string>", "list<int64>"}
+ }
+ date_time_fields = {
+ field.get("FieldName") or field.get("field_name") or field.get("name", "")
+ for field in collection_meta.get("Fields", [])
+ if (field.get("FieldType") or field.get("field_type") or field.get("type"))
+ == "date_time"
+ }
+
+ def normalize_date_times(condition: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+ if not condition:
+ return condition
+ normalized = dict(condition)
+ conditions = normalized.get("conds")
+ if normalized.get("op") in {"and", "or"} and isinstance(conditions, list):
+ normalized["conds"] = [normalize_date_times(item) for item in conditions]
+ return normalized
+ if normalized.get("field") not in date_time_fields:
+ return normalized
+ if isinstance(conditions, list):
+ normalized["conds"] = [_date_time_to_epoch_ms(value) for value in conditions]
+ for bound in ("gt", "gte", "lt", "lte"):
+ if normalized.get(bound) is not None:
+ normalized[bound] = _date_time_to_epoch_ms(normalized[bound])
+ return normalized
+
+ normalized_filter = normalize_date_times(compiled_filter)
+ where_fragment, where_params = _build_where_clause(
+ normalized_filter,
+ array_fields,
+ )
+ if not where_fragment:
+ return 0
+
+ cursor = self._conn.cursor()
+ try:
+ cursor.execute(
+ f'DELETE FROM "{self._collection_name}" '
+ f"WHERE id IN ("
+ f'SELECT id FROM "{self._collection_name}" '
+ f"WHERE {where_fragment} ORDER BY id LIMIT %s"
+ f")",
+ where_params + [limit],
+ )
+ deleted_count = cursor.rowcount
+ self._conn.commit()
+ return deleted_count
+ except Exception:
+ self._conn.rollback()
+ raise
+ finally:
+ cursor.close()
+
+ def update_data(self, data_list: List[Dict[str, Any]]) -> list[str]:
+ normalized_records = [self._normalize_record_for_write(record) for record in data_list]
+ result = self.get_collection().update_data(normalized_records)
+ return list(result or [])
+
+ def _existing_scalar_index_fields(self, og_coll: "OpenGaussCollection") -> list[str]:
+ for source in (
+ getattr(og_coll, "_indexes", {}).get(self._index_name),
+ getattr(og_coll, "_pending_indexes", {}).get(self._index_name),
+ getattr(og_coll, "_meta", None),
+ ):
+ if not isinstance(source, dict):
+ continue
+ fields = source.get("ScalarIndex")
+ if isinstance(fields, list) and fields:
+ return [str(field) for field in fields]
+ return []
+
+ def _ensure_vector_index_exists(self, og_coll: "OpenGaussCollection", distance: str = "cosine"):
+ """Ensure the configured vector index exists and is registered.
+
+ Presence of an arbitrary ANN index is not enough: reconnect must
+ recover the configured name, operator class, and build options, and
+ persist metadata when the physical index survived a failed catalog
+ write. A matching physical index is registered in place; only a
+ missing or conflicting index goes through create_index().
+ """
+ requested_meta = self._build_default_index_meta(
+ index_name=self._index_name,
+ distance=distance,
+ use_sparse=False,
+ sparse_weight=0.0,
+ scalar_index_fields=self._existing_scalar_index_fields(og_coll),
+ )
+ normalized_meta = og_coll._normalized_index_meta(self._index_name, requested_meta)
+ existing_definition = og_coll._physical_index_definition(normalized_meta["_pg_index_name"])
+ if existing_definition and og_coll._index_definition_matches(
+ normalized_meta, existing_definition
+ ):
+ og_coll._apply_parallel_workers(normalized_meta)
+ og_coll._persist_index_meta_and_scalar_indexes(
+ self._index_name,
+ normalized_meta,
+ )
+ og_coll._indexes[self._index_name] = normalized_meta
+ og_coll._pending_indexes.pop(self._index_name, None)
+ logger.info(
+ "opengauss_adapter: recovered configured vector index %s",
+ normalized_meta["_pg_index_name"],
+ )
+ return
+ og_coll.create_index(self._index_name, requested_meta)
+ logger.info("opengauss_adapter: vector index ensured via create_index")
+
+ def _build_default_index_meta(
+ self,
+ *,
+ index_name: str,
+ distance: str,
+ use_sparse: bool,
+ sparse_weight: float,
+ scalar_index_fields: list[str],
+ ) -> Dict[str, Any]:
+ if use_sparse:
+ raise NotImplementedError(
+ "openGauss backend does not support sparse or hybrid vector indexes"
+ )
+ index_meta: Dict[str, Any] = {
+ "IndexName": index_name,
+ "VectorIndex": {
+ "IndexType": self._index_type,
+ "Distance": distance or self._distance_metric,
+ },
+ "ScalarIndex": scalar_index_fields,
+ "build_params": dict(self._build_params),
+ "search_params": dict(self._search_params),
+ "maintenance_work_mem_mb": self._maintenance_work_mem_mb,
+ "parallel_workers": self._parallel_workers,
+ }
+ return index_meta
+
+ def _create_backend_collection(self, meta: Dict[str, Any]) -> Collection:
+ fields = meta.get("Fields", [])
+ dim = 0
+ distance = self._distance_metric or "cosine"
+ for f in fields:
+ ftype = f.get("FieldType") or f.get("field_type") or f.get("type", "")
+ if ftype == "vector":
+ # Schema may use "Dim", "dimension", or "dim"
+ dim = f.get("Dimension") or f.get("dimension") or f.get("Dim") or f.get("dim", 0)
+ access_method = _index_access_method(self._index_type)
+ if not _VECTOR_OPS.get(distance, {}).get(access_method):
+ raise ValueError(
+ f"openGauss index_type={self._index_type!r} does not support distance={distance!r}"
+ )
+ if distance == "l1" and _index_quantization(self._index_type) is not None:
+ raise ValueError("openGauss distance='l1' requires plain hnsw without PQ or RabitQ")
+ meta["_dim"] = dim
+ meta["_distance"] = distance
+ meta["_index_type"] = self._index_type
+ self._collection_name = _validate_identifier(
+ self._collection_name, kind="openGauss collection name"
+ )
+
+ table_created = False
+
+ def mark_table_created() -> None:
+ nonlocal table_created
+ table_created = True
+
+ try:
+ _create_collection_table(
+ self._conn,
+ self._collection_name,
+ meta,
+ dim,
+ distributed=self._distributed,
+ shard_count=self._shard_count,
+ on_table_created=mark_table_created,
+ )
+ _save_collection_meta(
+ self._conn,
+ self._collection_name,
+ meta,
+ distributed=self._distributed,
+ )
+ except Exception:
+ if not table_created:
+ raise
+ quoted_collection_name = _quote_identifier(
+ self._collection_name,
+ kind="openGauss collection name",
+ )
+ try:
+ cursor = self._conn.cursor()
+ try:
+ cursor.execute(f"DROP TABLE IF EXISTS {quoted_collection_name} CASCADE")
+ cursor.execute(
+ f'DELETE FROM "{_META_TABLE}" WHERE table_name = %s',
+ (self._collection_name,),
+ )
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ logger.exception(
+ "opengauss_adapter: failed to clean up orphan collection %s",
+ self._collection_name,
+ )
+ finally:
+ cursor.close()
+ finally:
+ raise
+
+ og_coll = OpenGaussCollection(
+ self._conn,
+ self._collection_name,
+ meta,
+ dim,
+ distance,
+ distributed=self._distributed,
+ )
+ og_coll._maintenance_work_mem_mb = self._maintenance_work_mem_mb
+ return Collection(og_coll)
+
+ def begin_bulk_ingest(self) -> None:
+ self.get_collection().begin_bulk_ingest()
+
+ def end_bulk_ingest(self) -> None:
+ self.get_collection().end_bulk_ingest()
+
+ def close(self) -> None:
+ super().close()
+ if self._conn is not None:
+ try:
+ self._conn.close()
+ except Exception:
+ pass
+ self._conn = None
diff --git a/openviking_cli/utils/config/__init__.py b/openviking_cli/utils/config/__init__.py
index 0b2d8bf56..75b31354a 100644
--- a/openviking_cli/utils/config/__init__.py
+++ b/openviking_cli/utils/config/__init__.py
@@ -87,7 +87,7 @@ from .rerank_config import RerankConfig
from .retrieval_config import RetrievalConfig
from .storage_config import StorageConfig
from .telemetry_config import TelemetryConfig, TracerConfig
-from .vectordb_config import VectorDBBackendConfig
+from .vectordb_config import OpenGaussConfig, VectorDBBackendConfig
from .vlm_config import VLMConfig
__all__ = [
@@ -147,6 +147,7 @@ __all__ = [
"RerankConfig",
"RetrievalConfig",
"StorageConfig",
+ "OpenGaussConfig",
"VectorDBBackendConfig",
"VLMConfig",
"ParserConfig",
diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.py
index b418bc6fc..d71396b54 100644
--- a/openviking_cli/utils/config/open_viking_config.py
+++ b/openviking_cli/utils/config/open_viking_config.py
@@ -566,6 +566,7 @@ class OpenVikingConfig(BaseModel):
and getattr(instance.storage, "vectordb", None)
and getattr(instance, "embedding", None)
):
+ instance.storage.vectordb.apply_resolved_dimension(instance.embedding.dimension)
db_dim = instance.storage.vectordb.dimension
emb_dim = instance.embedding.dimension
if db_dim > 0 and emb_dim > 0 and db_dim != emb_dim:
@@ -804,9 +805,7 @@ def initialize_openviking_config(
config.storage.agfs.path = resolved
config.storage.vectordb.path = resolved
- # Ensure vector dimension is synced if not set in storage
- if config.storage.vectordb.dimension == 0:
- config.storage.vectordb.dimension = config.embedding.dimension
+ config.storage.vectordb.apply_resolved_dimension(config.embedding.dimension)
# Validate configuration
if not is_valid_openviking_config(config):
diff --git a/openviking_cli/utils/config/vectordb_config.py b/openviking_cli/utils/config/vectordb_config.py
index aff31a33b..7641e0b8b 100644
--- a/openviking_cli/utils/config/vectordb_config.py
+++ b/openviking_cli/utils/config/vectordb_config.py
@@ -2,7 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, Literal, Optional
-from pydantic import BaseModel, Field, model_validator
+from pydantic import BaseModel, Field, StrictInt, model_validator
from openviking_cli.utils.logger import get_logger
@@ -46,6 +46,216 @@ class VikingDBConfig(BaseModel):
)
+_OPENGAUSS_MODES = frozenset({"standalone", "distributed"})
+# Distance metrics with a DataVec operator class; l1 is plain-HNSW only.
+_OPENGAUSS_DISTANCE_METRICS = frozenset({"cosine", "l2", "ip", "l1"})
+_OPENGAUSS_INDEX_TYPES = frozenset(
+ {
+ "hnsw",
+ "hnsw-pq",
+ "hnsw-rabitq",
+ "ivfflat",
+ "ivf-pq",
+ "ivf-rabitq",
+ "diskann",
+ }
+)
+_OPENGAUSS_INDEX_TYPE_ALIASES = {
+ "hnsw_pq": "hnsw-pq",
+ "hnswpq": "hnsw-pq",
+ "hnsw_rabitq": "hnsw-rabitq",
+ "hnswrabitq": "hnsw-rabitq",
+ "ivf_flat": "ivfflat",
+ "ivfflat-pq": "ivf-pq",
+ "ivf_pq": "ivf-pq",
+ "ivfpq": "ivf-pq",
+ "ivfflat-rabitq": "ivf-rabitq",
+ "ivf_rabitq": "ivf-rabitq",
+ "ivfrabitq": "ivf-rabitq",
+}
+_OPENGAUSS_COMMON_QUANT_BUILD_PARAMS = frozenset(
+ {"pq_m", "pq_ksub", "rabitq_refine_type", "rabitq_fht"}
+)
+_OPENGAUSS_BUILD_PARAMS = {
+ "hnsw": frozenset({"m", "ef_construction"}) | _OPENGAUSS_COMMON_QUANT_BUILD_PARAMS,
+ "ivfflat": frozenset({"lists", "by_residual"}) | _OPENGAUSS_COMMON_QUANT_BUILD_PARAMS,
+ "diskann": frozenset({"index_size"}),
+}
+_OPENGAUSS_SEARCH_PARAMS = {
+ "hnsw": frozenset({"ef_search", "earlystop_threshold", "rbq_query_bits", "rbq_refinek"}),
+ "ivfflat": frozenset({"probes", "ivfpq_kreorder", "rbq_query_bits", "rbq_refinek"}),
+ "diskann": frozenset({"probes"}),
+}
+_OPENGAUSS_SEARCH_ALIASES = {
+ "hnsw": {"hnsw_ef_search": "ef_search", "hnsw_earlystop_threshold": "earlystop_threshold"},
+ "ivfflat": {"ivfflat_probes": "probes"},
+ "diskann": {"diskann_probes": "probes"},
+}
+
+
+def normalize_opengauss_index_type(index_type: str | None) -> str:
+ value = (index_type or "hnsw").strip().lower()
+ value = _OPENGAUSS_INDEX_TYPE_ALIASES.get(value, value)
+ if value not in _OPENGAUSS_INDEX_TYPES:
+ raise ValueError(
+ f"Invalid openGauss index_type: {value!r}. "
+ f"Must be one of: {sorted(_OPENGAUSS_INDEX_TYPES)}"
+ )
+ return value
+
+
+def resolve_opengauss_index_spec(index_type: str) -> tuple[str, Optional[str]]:
+ normalized = normalize_opengauss_index_type(index_type)
+ if normalized.startswith("hnsw"):
+ access_method = "hnsw"
+ elif normalized.startswith("ivf"):
+ access_method = "ivfflat"
+ else:
+ access_method = "diskann"
+
+ if normalized.endswith("-pq"):
+ quantization = "pq"
+ elif normalized.endswith("-rabitq"):
+ quantization = "rabitq"
+ else:
+ quantization = None
+ return access_method, quantization
+
+
+class OpenGaussIndexConfig(BaseModel):
+ """Canonical adapter options; database-specific numerical limits belong to DataVec."""
+
+ index_type: str = "hnsw"
+ build_params: Dict[str, Any] = Field(default_factory=dict)
+ search_params: Dict[str, Any] = Field(default_factory=dict)
+ parallel_workers: StrictInt = Field(default=0, ge=0)
+ maintenance_work_mem_mb: StrictInt = Field(default=64, gt=0)
+ model_config = {"extra": "forbid"}
+
+ @model_validator(mode="before")
+ @classmethod
+ def normalize_index_options(cls, value):
+ if not isinstance(value, dict):
+ return value
+ data = dict(value)
+ index_type = normalize_opengauss_index_type(data.get("index_type", "hnsw"))
+ method, quantization = resolve_opengauss_index_spec(index_type)
+ build = data.get("build_params", {})
+ search = data.get("search_params", {})
+ if not isinstance(build, dict) or not isinstance(search, dict):
+ raise ValueError("openGauss build_params and search_params must be objects")
+ build, search = dict(build), dict(search)
+ flags = {}
+ for name in ("enable_pq", "enable_rabitq"):
+ if name in build:
+ flags[name] = build.pop(name)
+ if type(flags[name]) is not bool:
+ raise ValueError(f"openGauss build_params.{name} must be a boolean")
+ for name, kind in (("enable_pq", "pq"), ("enable_rabitq", "rabitq")):
+ if flags.get(name) is False and quantization == kind:
+ raise ValueError(f"openGauss {name}=false conflicts with index_type={index_type}")
+ if flags.get(name):
+ if quantization and quantization != kind:
+ raise ValueError("openGauss PQ and RabitQ cannot be enabled together")
+ if method == "diskann":
+ raise ValueError("openGauss DiskANN does not support PQ or RabitQ")
+ quantization = kind
+ if quantization:
+ index_type = f"{'ivf' if method == 'ivfflat' else method}-{quantization}"
+ for alias, canonical in _OPENGAUSS_SEARCH_ALIASES[method].items():
+ if alias in search:
+ alias_value = search.pop(alias)
+ if canonical in search and search[canonical] != alias_value:
+ raise ValueError(f"Conflicting openGauss search_params {alias} and {canonical}")
+ search[canonical] = alias_value
+ for group, params, allowed in (
+ ("build_params", build, _OPENGAUSS_BUILD_PARAMS[method]),
+ ("search_params", search, _OPENGAUSS_SEARCH_PARAMS[method]),
+ ):
+ unknown = sorted(set(params) - allowed)
+ if unknown:
+ raise ValueError(f"Unsupported openGauss {index_type} {group}: {unknown}")
+ for name, parameter in params.items():
+ if name in {"by_residual", "rabitq_fht"}:
+ if type(parameter) is not bool:
+ raise ValueError(f"openGauss {group}.{name} must be a boolean")
+ elif name == "rabitq_refine_type":
+ if not isinstance(parameter, str):
+ raise ValueError(f"openGauss {group}.{name} must be a string")
+ params[name] = parameter.lower()
+ elif type(parameter) is not int:
+ raise ValueError(f"openGauss {group}.{name} must be an integer")
+ if quantization != "pq" and (
+ {"pq_m", "pq_ksub", "by_residual"} & build.keys() or "ivfpq_kreorder" in search
+ ):
+ raise ValueError("openGauss PQ parameters require a *-pq index_type")
+ if quantization != "rabitq" and (
+ {"rabitq_refine_type", "rabitq_fht"} & build.keys()
+ or {"rbq_query_bits", "rbq_refinek"} & search.keys()
+ ):
+ raise ValueError("openGauss RabitQ parameters require a *-rabitq index_type")
+ data.update(index_type=index_type, build_params=build, search_params=search)
+ return data
+
+ @property
+ def access_method(self) -> str:
+ return resolve_opengauss_index_spec(self.index_type)[0]
+
+ @property
+ def quantization(self) -> Optional[str]:
+ return resolve_opengauss_index_spec(self.index_type)[1]
+
+ def validate_capabilities(self, *, distributed: bool, distance: str = "cosine") -> None:
+ if distributed and self.index_type != "hnsw":
+ raise ValueError(
+ "openGauss SPQ distributed mode currently supports only plain HNSW; "
+ "use standalone mode for PQ, RabitQ, IVF, or DiskANN indexes"
+ )
+ if distance not in _OPENGAUSS_DISTANCE_METRICS:
+ raise ValueError("Unsupported openGauss distance_metric")
+ if distance == "l1" and self.index_type != "hnsw":
+ raise ValueError("openGauss distance='l1' requires plain hnsw without PQ or RabitQ")
+
+
+class OpenGaussConfig(OpenGaussIndexConfig):
+ """Configuration for openGauss DataVec vector database."""
+
+ host: str = Field(
+ default="127.0.0.1",
+ description="openGauss host address (CN node when mode=distributed)",
+ )
+ port: int = Field(default=5432, ge=1, le=65535, description="openGauss port")
+ user: str = Field(default="gaussdb", description="Database user")
+ password: str = Field(default="", description="Database password")
+ db_name: str = Field(default="openviking", description="Database name")
+ mode: Literal["standalone", "distributed"] = Field(
+ default="standalone",
+ description="Deployment mode; distributed connects to an spq CN node.",
+ )
+ shard_count: int = Field(
+ default=32,
+ ge=1,
+ description="Number of shards per distributed collection table.",
+ )
+ connection_pool_min_size: int = Field(default=1, ge=1, le=64)
+ connection_pool_max_size: int = Field(default=8, ge=1, le=128)
+
+ model_config = {"extra": "forbid"}
+
+ @property
+ def is_distributed(self) -> bool:
+ return self.mode == "distributed"
+
+ @model_validator(mode="after")
+ def validate_opengauss(self):
+ self.validate_capabilities(distributed=self.is_distributed)
+ if self.connection_pool_min_size > self.connection_pool_max_size:
+ raise ValueError(
+ "openGauss connection_pool_min_size cannot exceed connection_pool_max_size"
+ )
+ return self
+
+
class CuVSConfig(BaseModel):
"""Configuration for GPU dense-vector search through NVIDIA cuVS."""
@@ -195,7 +405,7 @@ class VectorDBBackendConfig(BaseModel):
description=(
"VectorDB backend type: 'local', 'cuvs', 'http', "
"'volcengine' (AK/SK signed or API key data-plane only), "
- "or 'vikingdb' (private deployment)"
+ "'vikingdb' (private deployment), or 'opengauss'"
),
)
@@ -254,6 +464,11 @@ class VectorDBBackendConfig(BaseModel):
description="NVIDIA cuVS dense-vector search configuration for the 'cuvs' backend",
)
+ opengauss: Optional[OpenGaussConfig] = Field(
+ default_factory=OpenGaussConfig,
+ description="openGauss DataVec configuration for the 'opengauss' backend",
+ )
+
custom_params: Dict[str, Any] = Field(
default_factory=dict,
description="Custom parameters for custom backend adapters",
@@ -268,6 +483,7 @@ class VectorDBBackendConfig(BaseModel):
"http",
"volcengine",
"vikingdb",
+ "opengauss",
]
# Allow custom backend classes (containing dot) without standard validation
@@ -317,4 +533,27 @@ class VectorDBBackendConfig(BaseModel):
if not self.vikingdb or not self.vikingdb.host:
raise ValueError("VectorDB vikingdb backend requires 'host' to be set")
+ elif self.backend == "opengauss":
+ if not self.opengauss:
+ raise ValueError("VectorDB opengauss backend requires 'opengauss' config")
+ if not self.opengauss.host:
+ raise ValueError("VectorDB opengauss backend requires 'opengauss.host' to be set")
+ if self.sparse_weight > 0.0:
+ raise ValueError("VectorDB opengauss backend does not support sparse_weight > 0")
+ distance = (self.distance_metric or "cosine").lower()
+ if distance not in _OPENGAUSS_DISTANCE_METRICS:
+ raise ValueError(
+ "VectorDB opengauss backend supports distance_metric values: "
+ + ", ".join(sorted(_OPENGAUSS_DISTANCE_METRICS))
+ )
+ self.distance_metric = distance
+ self.opengauss.validate_capabilities(
+ distributed=self.opengauss.is_distributed, distance=distance
+ )
+
return self
+
+ def apply_resolved_dimension(self, embedding_dimension: Any) -> None:
+ """Resolve an unspecified collection dimension from the embedding configuration."""
+ if int(self.dimension or 0) == 0 and embedding_dimension:
+ self.dimension = int(embedding_dimension)
diff --git a/pyproject.toml b/pyproject.toml
index 1bd649adb..722d91bac 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -189,6 +189,11 @@ local-embed = [
"llama-cpp-python>=0.3.0",
]
+opengauss = [
+ # PostgreSQL wire-compatible driver verified against openGauss DataVec 7.0.
+ "psycopg2-binary>=2.9,<3",
+]
+
[project.urls]
Homepage = "https://github.com/volcengine/openviking"
Documentation = "https://openviking.ai"
diff --git a/tests/misc/test_config_validation.py b/tests/misc/test_config_validation.py
index 939370b1f..76a73cbb7 100644
--- a/tests/misc/test_config_validation.py
+++ b/tests/misc/test_config_validation.py
@@ -895,7 +895,7 @@ def test_removed_volcengine_api_key_backend_name_is_rejected():
assert "volcengine_api_key" in str(e)
[email protected]("backend", ["qdrant", "opengauss"])
[email protected]("backend", ["qdrant"])
def test_removed_third_party_vectordb_backends_are_rejected(backend):
with pytest.raises(ValueError) as exc_info:
VectorDBBackendConfig(backend=backend)
@@ -907,6 +907,33 @@ def test_removed_third_party_vectordb_backends_are_rejected(backend):
assert "vikingdb" in message
+def test_opengauss_backend_is_accepted_with_defaults():
+ config = VectorDBBackendConfig(backend="opengauss")
+ assert config.backend == "opengauss"
+ assert config.opengauss is not None
+ assert config.opengauss.host == "127.0.0.1"
+ assert config.opengauss.index_type == "hnsw"
+ assert config.opengauss.mode == "standalone"
+
+
+def test_opengauss_backend_requires_host():
+ from openviking_cli.utils.config.vectordb_config import OpenGaussConfig
+
+ with pytest.raises(ValueError, match="opengauss.host"):
+ VectorDBBackendConfig(backend="opengauss", opengauss=OpenGaussConfig(host=""))
+
+
+def test_opengauss_l1_requires_hnsw():
+ from openviking_cli.utils.config.vectordb_config import OpenGaussConfig
+
+ with pytest.raises(ValueError, match="l1"):
+ VectorDBBackendConfig(
+ backend="opengauss",
+ distance_metric="l1",
+ opengauss=OpenGaussConfig(index_type="ivfflat", build_params={"lists": 100}),
+ )
+
+
def test_vectordb_volcengine_api_key_auth_requires_host_or_region():
try:
VectorDBBackendConfig(
diff --git a/tests/storage/test_volcengine_clients.py b/tests/storage/test_volcengine_clients.py
index ed84f357f..39d2f7b39 100644
--- a/tests/storage/test_volcengine_clients.py
+++ b/tests/storage/test_volcengine_clients.py
@@ -1119,3 +1119,34 @@ def test_http_adapter_strict_count_propagates_http_failure(monkeypatch):
with pytest.raises(requests.HTTPError, match="503 unavailable"):
adapter.strict_count()
+
+
+def test_http_collection_update_index_preserves_explicit_empty_scalar_index(monkeypatch):
+ captured = {}
+
+ class _Response:
+ status_code = 200
+ text = '{"data": {}}'
+
+ def _fake_post(url, headers=None, json=None, timeout=None):
+ captured["url"] = url
+ captured["json"] = json
+ return _Response()
+
+ monkeypatch.setattr(
+ "openviking.storage.vectordb.collection.http_collection.requests.post",
+ _fake_post,
+ )
+
+ from openviking.storage.vectordb.collection.http_collection import HttpCollection
+
+ collection = HttpCollection(
+ ip="127.0.0.1",
+ port=1933,
+ meta_data={"ProjectName": "default", "CollectionName": "context"},
+ )
+
+ collection.update_index("default", [])
+
+ assert captured["url"].endswith("UpdateVikingdbIndex")
+ assert captured["json"]["ScalarIndex"] == "[]"
diff --git a/tests/vectordb/test_cuvs_index.py b/tests/vectordb/test_cuvs_index.py
index 6c6c0a9f0..07b705ca4 100644
--- a/tests/vectordb/test_cuvs_index.py
+++ b/tests/vectordb/test_cuvs_index.py
@@ -6,6 +6,7 @@ import time
from array import array
from concurrent.futures import ThreadPoolExecutor
from contextlib import nullcontext
+from unittest.mock import Mock
import pytest
@@ -22,6 +23,7 @@ from openviking.storage.vectordb.index.cuvs_index import (
estimate_cuvs_memory,
matches_filter,
)
+from openviking.storage.vectordb.index.local_index import LocalIndex
from openviking.storage.vectordb.store.data import CandidateData, DeltaRecord
@@ -3400,3 +3402,17 @@ def test_missing_cuvs_runtime_has_actionable_error(monkeypatch):
field_types={},
config={},
)
+
+
+def test_local_index_update_preserves_explicit_empty_values():
+ index = LocalIndex.__new__(LocalIndex)
+ index.meta = Mock()
+
+ index.update([], "")
+
+ index.meta.update.assert_called_once_with(
+ {
+ "ScalarIndex": [],
+ "Description": "",
+ }
+ )
diff --git a/tests/vectordb/test_opengauss_adapter_complete.py b/tests/vectordb/test_opengauss_adapter_complete.py
new file mode 100644
index 000000000..0eddfb9a7
--- /dev/null
+++ b/tests/vectordb/test_opengauss_adapter_complete.py
@@ -0,0 +1,1661 @@
+import json
+import threading
+from unittest.mock import Mock, patch
+
+import pytest
+from pydantic import ValidationError
+
+from openviking.storage.expr import And, Eq, Or
+from openviking.storage.vectordb_adapters.opengauss.catalog import (
+ _is_table_already_distributed,
+ _load_collection_meta,
+ _probe_distributed_workers,
+)
+from openviking.storage.vectordb_adapters.opengauss.collection import OpenGaussCollection
+from openviking.storage.vectordb_adapters.opengauss.connection import _PooledConnectionProxy
+from openviking.storage.vectordb_adapters.opengauss.sql import (
+ _bounded_identifier,
+ _build_where_clause,
+ _coerce_sparse_vector,
+ _coerce_vector,
+ _index_meta_table_name,
+ _is_undefined_table_error,
+ _validate_identifier,
+ _validate_vector,
+)
+from openviking.storage.vectordb_adapters.opengauss_adapter import OpenGaussCollectionAdapter
+from openviking_cli.utils.config.vectordb_config import (
+ OpenGaussConfig,
+ VectorDBBackendConfig,
+ resolve_opengauss_index_spec,
+)
+
+INDEX_CASES = [
+ ("hnsw", {"m": 16, "ef_construction": 64}, {"ef_search": 100}, "hnsw"),
+ ("hnsw-pq", {"pq_m": 8, "pq_ksub": 256}, {}, "hnsw"),
+ (
+ "hnsw-rabitq",
+ {"rabitq_refine_type": "FP32", "rabitq_fht": True},
+ {"rbq_query_bits": 8, "rbq_refinek": 20},
+ "hnsw",
+ ),
+ ("ivfflat", {"lists": 100}, {"probes": 10}, "ivfflat"),
+ (
+ "ivf-pq",
+ {"lists": 100, "pq_m": 8, "pq_ksub": 256, "by_residual": True},
+ {"probes": 10, "ivfpq_kreorder": 100},
+ "ivfflat",
+ ),
+ (
+ "ivf-rabitq",
+ {"lists": 100, "rabitq_refine_type": "SQ8"},
+ {"probes": 10, "rbq_query_bits": 8},
+ "ivfflat",
+ ),
+ ("diskann", {"index_size": 50}, {"probes": 256}, "diskann"),
+]
+
+
+ ("index_type", "build_params", "search_params", "access_method"), INDEX_CASES
+)
+def test_complete_index_matrix_generates_official_access_methods(
+ index_type, build_params, search_params, access_method
+):
+ config = VectorDBBackendConfig(
+ backend="opengauss",
+ dimension=512,
+ opengauss=OpenGaussConfig(
+ index_type=index_type,
+ build_params=build_params,
+ search_params=search_params,
+ ),
+ )
+ assert resolve_opengauss_index_spec(config.opengauss.index_type)[0] == access_method
+
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distance = "cosine"
+ collection._distributed = False
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ index_meta = collection._normalized_index_meta(
+ "default",
+ {
+ "VectorIndex": {"IndexType": index_type, "Distance": "cosine"},
+ "build_params": config.opengauss.build_params,
+ "search_params": config.opengauss.search_params,
+ },
+ )
+ sql = collection._create_index_sql(index_meta)
+ assert f"USING {access_method}" in sql
+ assert "CREATE INDEX IF NOT EXISTS" not in sql
+ if index_type.endswith("-pq"):
+ assert "enable_pq = on" in sql
+ if index_type.endswith("-rabitq"):
+ assert "enable_rabitq = on" in sql
+
+ collection._indexes["default"] = index_meta
+ statements = collection._search_param_statements("default")
+ assert all(statement.startswith("SET LOCAL ") for statement in statements)
+
+
+def test_search_param_statements_propagate_to_dn_workers_in_distributed_mode():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distance = "cosine"
+ collection._distributed = False
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ index_meta = collection._normalized_index_meta(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"},
+ "search_params": {"ef_search": 100},
+ },
+ )
+ collection._indexes["default"] = index_meta
+
+ standalone_statements = collection._search_param_statements("default")
+ assert standalone_statements == ["SET LOCAL hnsw_ef_search = 100"]
+
+ # spq defaults to propagate_set_commands='none'; without propagation the
+ # search parameters would never reach the DN shard scans.
+ collection._distributed = True
+ distributed_statements = collection._search_param_statements("default")
+ assert distributed_statements == [
+ "SET LOCAL spq.propagate_set_commands = 'local'",
+ "SET LOCAL hnsw_ef_search = 100",
+ ]
+
+
+def test_runtime_create_index_rejects_diskann_pq():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distance = "cosine"
+ collection._distributed = False
+ collection._dim = 8
+
+ with pytest.raises(ValueError, match="Invalid openGauss index_type"):
+ collection.create_index(
+ "default",
+ {
+ "VectorIndex": {
+ "IndexType": "diskann-pq",
+ "Distance": "cosine",
+ },
+ "build_params": {"index_size": 50, "pq_m": 8},
+ },
+ )
+
+ with pytest.raises(ValueError, match="[Dd]iskann|DiskANN"):
+ collection.create_index(
+ "default",
+ {
+ "VectorIndex": {
+ "IndexType": "diskann",
+ "Distance": "cosine",
+ },
+ "build_params": {"index_size": 50, "enable_pq": True, "pq_m": 8},
+ },
+ )
+
+
+def test_config_rejects_unknown_and_incompatible_parameters():
+ with pytest.raises(ValidationError, match="Unsupported openGauss"):
+ OpenGaussConfig(index_type="hnsw", build_params={"lists": 100})
+ with pytest.raises(ValidationError, match="cannot be enabled together"):
+ OpenGaussConfig(
+ index_type="hnsw",
+ build_params={"enable_pq": True, "enable_rabitq": True},
+ )
+ config = VectorDBBackendConfig(
+ backend="opengauss",
+ dimension=513,
+ opengauss=OpenGaussConfig(index_type="hnsw-pq", build_params={"pq_m": 8}),
+ )
+ assert config.dimension == 513 # DataVec validates PQ divisibility when building the index.
+
+
+def test_identifiers_and_vectors_are_strictly_validated():
+ assert _validate_identifier("context_01") == "context_01"
+ with pytest.raises(ValueError, match="Invalid"):
+ _validate_identifier('context"; DROP TABLE context; --')
+ assert _validate_vector([1, 2.5, 3], 3) == [1.0, 2.5, 3.0]
+ with pytest.raises(ValueError, match="dimension mismatch"):
+ _validate_vector([1, 2], 3)
+ with pytest.raises(ValueError, match="finite"):
+ _validate_vector([1, float("nan"), 3], 3)
+
+
+def test_training_index_metadata_is_persisted_as_pending_before_data_exists():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 8
+ collection._distance = "cosine"
+ collection._field_names = {"id", "vector"}
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ collection._persist_index_meta_and_scalar_indexes = Mock()
+ collection._table_has_rows = Mock(return_value=False)
+ collection._physical_index_definition = Mock(return_value=None)
+ collection._execute = Mock()
+
+ result = collection.create_index(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "ivf-pq", "Distance": "cosine"},
+ "build_params": {"lists": 10, "pq_m": 8},
+ },
+ )
+
+ assert result.get_name() == "default"
+ assert "default" in collection._pending_indexes
+ assert "default" not in collection._indexes
+ pending_meta = collection._pending_indexes["default"]
+ assert pending_meta["_state"] == "pending"
+ collection._persist_index_meta_and_scalar_indexes.assert_called_once_with(
+ "default", pending_meta
+ )
+ collection._execute.assert_not_called()
+
+
+def test_pending_index_drops_conflicting_physical_definition():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 8
+ collection._distance = "l2"
+ collection._field_names = {"id", "vector"}
+ collection._indexes = {"default": {"stale": True}}
+ collection._pending_indexes = {}
+ collection._persist_index_meta_and_scalar_indexes = Mock()
+ collection._table_has_rows = Mock(return_value=False)
+ collection._physical_index_definition = Mock(
+ return_value="CREATE INDEX idx_context_default_vec ON context "
+ "USING ivfflat (vector vector_cosine_ops) WITH (lists=10)"
+ )
+ collection._execute = Mock()
+
+ collection.create_index(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "ivf-pq", "Distance": "l2"},
+ "build_params": {"lists": 10, "pq_m": 8},
+ },
+ )
+
+ collection._execute.assert_called_once()
+ assert "DROP INDEX" in collection._execute.call_args.args[0]
+ assert "default" in collection._pending_indexes
+ assert "default" not in collection._indexes
+ collection._persist_index_meta_and_scalar_indexes.assert_called_once()
+
+
+def test_catalog_verification_failure_never_saves_metadata():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distance = "cosine"
+ collection._distributed = False
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ collection._physical_index_definition = Mock(side_effect=[None, None])
+ collection._execute = Mock()
+ collection._save_index_meta = Mock()
+ collection._lock = threading.RLock()
+ collection._cursor = Mock(return_value=Mock())
+ collection._conn = Mock()
+ meta = collection._normalized_index_meta(
+ "default",
+ {"VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"}},
+ )
+
+ with pytest.raises(RuntimeError, match="catalog verification failed"):
+ collection._materialize_index("default", meta)
+ collection._save_index_meta.assert_not_called()
+
+
+def test_materialized_index_is_not_published_before_metadata_persists():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distance = "cosine"
+ collection._distributed = False
+ collection._maintenance_work_mem_mb = 64
+ collection._indexes = {}
+ collection._pending_indexes = {"default": {"_state": "pending"}}
+ collection._lock = threading.RLock()
+ collection._physical_index_definition = Mock(
+ return_value=(
+ "CREATE INDEX idx_context_default_vec ON context "
+ "USING hnsw (vector vector_cosine_ops) "
+ "WITH (m=16, ef_construction=64)"
+ )
+ )
+ collection._apply_parallel_workers = Mock()
+ collection._persist_index_meta_and_scalar_indexes = Mock(
+ side_effect=RuntimeError("metadata failed")
+ )
+ meta = collection._normalized_index_meta(
+ "default",
+ {"VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"}},
+ )
+
+ with pytest.raises(RuntimeError, match="metadata failed"):
+ collection._materialize_index("default", meta)
+
+ assert "default" not in collection._indexes
+ assert "default" in collection._pending_indexes
+ collection._persist_index_meta_and_scalar_indexes.assert_called_once_with("default", meta)
+
+
+def test_pending_index_search_returns_empty_for_empty_collection():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._pending_indexes = {"default": {}}
+ collection._bulk_ingest_depth = 0
+ collection._materialize_index = Mock()
+ collection._table_has_rows = Mock(return_value=False)
+ collection.has_index = Mock(return_value=False)
+
+ result = collection.search_by_vector("default", dense_vector=[1.0])
+
+ assert result.data == []
+ collection._materialize_index.assert_not_called()
+ collection.has_index.assert_not_called()
+
+
+def test_index_materialization_sets_transaction_local_build_memory():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distance = "cosine"
+ collection._distributed = False
+ collection._maintenance_work_mem_mb = 128
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ collection._lock = threading.RLock()
+ collection._physical_index_definition = Mock(
+ side_effect=[
+ None,
+ "CREATE INDEX idx_context_default_vec ON context "
+ "USING ivfflat (vector vector_cosine_ops) WITH (lists=1)",
+ ]
+ )
+ collection._persist_index_meta_and_scalar_indexes = Mock()
+ cursor = Mock()
+ collection._cursor = Mock(return_value=cursor)
+ collection._conn = Mock()
+ meta = collection._normalized_index_meta(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "ivfflat", "Distance": "cosine"},
+ "build_params": {"lists": 1},
+ },
+ )
+
+ collection._materialize_index("default", meta)
+
+ assert cursor.execute.call_args_list[0].args[0] == (
+ 'ALTER TABLE "context" RESET (parallel_workers)'
+ )
+ assert cursor.execute.call_args_list[1].args == ("SET LOCAL maintenance_work_mem = '128MB'",)
+ create_index_sql = cursor.execute.call_args_list[2].args[0]
+ assert create_index_sql.startswith("CREATE INDEX")
+ assert '"idx_context_default_vec"' in create_index_sql
+ assert collection._conn.commit.call_count == 2
+ collection._conn.rollback.assert_not_called()
+ assert cursor.close.call_count == 2
+ collection._persist_index_meta_and_scalar_indexes.assert_called_once_with("default", meta)
+
+
+def _adapter_without_connect(**overrides) -> OpenGaussCollectionAdapter:
+ kwargs = {
+ "collection_name": "context",
+ "host": "127.0.0.1",
+ "port": 5432,
+ "user": "gaussdb",
+ "password": "",
+ "db_name": "openviking",
+ "index_type": "hnsw",
+ "distance_metric": "cosine",
+ }
+ kwargs.update(overrides)
+ adapter_args = {key: kwargs.pop(key) for key in ("collection_name", "distance_metric")}
+ if "index_name" in kwargs:
+ adapter_args["index_name"] = kwargs.pop("index_name")
+ if "distributed" in kwargs:
+ kwargs["mode"] = "distributed" if kwargs.pop("distributed") else "standalone"
+ with patch.object(OpenGaussCollectionAdapter, "_connect", return_value=None):
+ return OpenGaussCollectionAdapter(**adapter_args, config=OpenGaussConfig(**kwargs))
+
+
+def test_create_collection_rejects_unsafe_name_before_backend_ddl():
+ adapter = _adapter_without_connect()
+ adapter._create_backend_collection = Mock()
+ with patch.object(adapter, "collection_exists", return_value=False):
+ with pytest.raises(ValueError, match="Invalid openGauss collection name"):
+ adapter.create_collection(
+ 'evil"; DROP TABLE t; --',
+ {"Fields": []},
+ distance="cosine",
+ sparse_weight=0.0,
+ index_name="default",
+ )
+ adapter._create_backend_collection.assert_not_called()
+
+
+def test_ensure_vector_index_always_materializes_configured_index():
+ adapter = _adapter_without_connect(index_type="hnsw")
+ og_coll = Mock()
+ og_coll._indexes = {"default": {"ScalarIndex": ["uri"]}}
+ og_coll._pending_indexes = {}
+ og_coll._meta = {"ScalarIndex": ["uri"]}
+ og_coll._normalized_index_meta = Mock(
+ return_value={"_pg_index_name": "idx_context_default_vec", "ScalarIndex": ["uri"]}
+ )
+ og_coll._physical_index_definition = Mock(return_value=None)
+
+ adapter._ensure_vector_index_exists(og_coll, "cosine")
+
+ og_coll.create_index.assert_called_once()
+ index_name, index_meta = og_coll.create_index.call_args.args
+ assert index_name == "default"
+ assert index_meta["VectorIndex"]["IndexType"] == "hnsw"
+ assert index_meta["VectorIndex"]["Distance"] == "cosine"
+ assert index_meta["ScalarIndex"] == ["uri"]
+
+
+def test_ensure_vector_index_registers_matching_physical_index_without_rebuild():
+ adapter = _adapter_without_connect(index_type="hnsw")
+ og_coll = Mock()
+ og_coll._indexes = {}
+ og_coll._pending_indexes = {"default": {"stale": True}}
+ og_coll._meta = {"ScalarIndex": ["uri"]}
+ recovered = {
+ "_pg_index_name": "idx_context_default_vec",
+ "ScalarIndex": ["uri"],
+ }
+ og_coll._normalized_index_meta = Mock(return_value=recovered)
+ og_coll._physical_index_definition = Mock(
+ return_value="CREATE INDEX idx_context_default_vec ON context USING hnsw (vector vector_cosine_ops)"
+ )
+ og_coll._index_definition_matches = Mock(return_value=True)
+
+ adapter._ensure_vector_index_exists(og_coll, "cosine")
+
+ og_coll.create_index.assert_not_called()
+ og_coll._persist_index_meta_and_scalar_indexes.assert_called_once_with("default", recovered)
+ assert og_coll._indexes["default"] == recovered
+ assert "default" not in og_coll._pending_indexes
+
+
+def test_index_definition_matches_tolerates_omitted_default_with_options():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distance = "cosine"
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ meta = collection._normalized_index_meta(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"},
+ "build_params": {"m": 16, "ef_construction": 64},
+ },
+ )
+ catalog_without_with = (
+ "CREATE INDEX idx_context_default_vec ON context USING hnsw (vector vector_cosine_ops)"
+ )
+ catalog_with_defaults = catalog_without_with + " WITH (m=16, ef_construction=64)"
+ catalog_with_conflict = catalog_without_with + " WITH (m=8, ef_construction=64)"
+ catalog_wrong_opclass = (
+ "CREATE INDEX idx_context_default_vec ON context USING hnsw (vector vector_l2_ops)"
+ )
+
+ assert collection._index_definition_matches(meta, catalog_without_with)
+ assert collection._index_definition_matches(meta, catalog_with_defaults)
+ assert not collection._index_definition_matches(meta, catalog_with_conflict)
+ assert not collection._index_definition_matches(meta, catalog_wrong_opclass)
+
+ custom_meta = collection._normalized_index_meta(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"},
+ "build_params": {"m": 32, "ef_construction": 128},
+ },
+ )
+ catalog_missing_non_default_m = catalog_without_with + " WITH (ef_construction=128)"
+ assert not collection._index_definition_matches(custom_meta, catalog_without_with)
+ assert not collection._index_definition_matches(custom_meta, catalog_missing_non_default_m)
+ assert collection._index_definition_matches(
+ custom_meta,
+ catalog_without_with + " WITH (m=32, ef_construction=128)",
+ )
+ assert collection._index_definition_matches(
+ meta,
+ catalog_without_with + " WITH (ef_construction=64)",
+ )
+
+ pq_meta = collection._normalized_index_meta(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "hnsw-pq", "Distance": "cosine"},
+ "build_params": {"m": 16, "ef_construction": 64, "pq_m": 8},
+ },
+ )
+ assert not collection._index_definition_matches(pq_meta, catalog_without_with)
+ assert not collection._index_definition_matches(pq_meta, catalog_with_defaults)
+ leftover_pq = (
+ catalog_without_with + " WITH (m=16, ef_construction=64, enable_pq=on, pq_m=8, pq_ksub=256)"
+ )
+ leftover_rabitq = (
+ catalog_without_with
+ + " WITH (m=16, ef_construction=64, enable_rabitq=on, rabitq_refine_type=fp32)"
+ )
+ assert not collection._index_definition_matches(meta, leftover_pq)
+ assert not collection._index_definition_matches(meta, leftover_rabitq)
+
+
+def test_public_api_empty_or_compiles_to_sql_contradiction():
+ adapter = _adapter_without_connect()
+
+ compiled = adapter._compile_filter(Or([]))
+ assert compiled == {"op": "or", "conds": []}
+ sql, params = _build_where_clause(compiled)
+ assert sql == "FALSE"
+ assert params == []
+
+ unfiltered = adapter._compile_filter(None)
+ assert unfiltered == {}
+ assert _build_where_clause(unfiltered) == ("", [])
+
+ nested = adapter._compile_filter(And([Eq("id", "keep"), Or([])]))
+ nested_sql, nested_params = _build_where_clause(nested)
+ assert "FALSE" in nested_sql
+ assert nested_params == ["keep"]
+
+
+def test_select_projects_unstored_content_as_null():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._field_names = {"id", "uri", "vector", "content", "account_id"}
+ sql = collection._select_output_columns(["id", "uri", "content", "vector", "account_id"])
+ assert sql == '"id", "uri", NULL AS "content", "vector", "account_id"'
+
+ collection._field_names = {"id", "uri", "vector"}
+ sql = collection._select_output_columns(["id", "uri", "content"])
+ assert sql == '"id", "uri", NULL AS "content"'
+
+
+def test_collection_update_uses_canonical_description_key():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._meta = {"Description": "old"}
+ collection._execute = Mock()
+
+ collection.update(description="new")
+
+ assert collection._meta["Description"] == "new"
+ assert "description" not in collection._meta
+ persisted_meta = json.loads(collection._execute.call_args.args[1][0])
+ assert persisted_meta["Description"] == "new"
+
+
+def test_row_to_dict_normalizes_psycopg_vector_payloads():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ record = collection._row_to_dict(
+ ("row-1", "[0.25, 0.5, 1]", '{"3": 0.75}'),
+ ["id", "vector", "sparse_vector"],
+ )
+ assert record["id"] == "row-1"
+ assert record["vector"] == [0.25, 0.5, 1.0]
+ assert record["sparse_vector"] == {"3": 0.75}
+ assert _coerce_vector(None) is None
+ assert _coerce_vector([1, 2]) == [1.0, 2.0]
+ assert _coerce_sparse_vector({"1": 1.0}) == {"1": 1.0}
+
+
+def test_long_collection_name_fits_physical_sql_identifiers():
+ raw_index = f"idx_{'c' * 50}_default_vec"
+ assert len(raw_index) > 63
+
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "c" * 50
+ collection._distance = "cosine"
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ meta = collection._normalized_index_meta(
+ "default",
+ {"VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"}},
+ )
+ physical = meta["_pg_index_name"]
+ assert len(physical) <= 63
+ assert _validate_identifier(physical) == physical
+ assert physical == _bounded_identifier(raw_index)
+ again = collection._normalized_index_meta(
+ "default",
+ {"VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"}},
+ )
+ assert again["_pg_index_name"] == physical
+
+ assert _bounded_identifier("idx_context_default_vec") == "idx_context_default_vec"
+ assert _index_meta_table_name("context") == "_ov_index_context"
+ long_collection = "n" * 54
+ assert len(f"_ov_index_{long_collection}") > 63
+ catalog = _index_meta_table_name(long_collection)
+ assert len(catalog) <= 63
+ assert _validate_identifier(catalog) == catalog
+
+
+def test_reconnect_prefers_configured_distance_over_persisted_meta():
+ adapter = _adapter_without_connect(distance_metric="l2")
+ adapter._collection = None
+ adapter._conn = Mock()
+ adapter._table_exists = Mock(return_value=True)
+ persisted = {"_dim": 8, "_distance": "cosine", "Fields": []}
+ og_coll = Mock()
+
+ with (
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._load_collection_meta",
+ return_value=persisted,
+ ),
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter.OpenGaussCollection",
+ return_value=og_coll,
+ ) as collection_cls,
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter.Collection",
+ side_effect=lambda impl: impl,
+ ),
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._save_collection_meta",
+ ) as save_meta,
+ patch.object(adapter, "_ensure_vector_index_exists") as ensure_index,
+ ):
+ adapter._load_existing_collection_if_needed()
+
+ assert persisted["_distance"] == "l2"
+ save_meta.assert_called_once()
+ assert collection_cls.call_args.args[4] == "l2"
+ ensure_index.assert_called_once_with(og_coll, "l2")
+
+
+def test_reconnect_does_not_rewrite_meta_when_distance_matches():
+ adapter = _adapter_without_connect(distance_metric="cosine")
+ adapter._collection = None
+ adapter._conn = Mock()
+ adapter._table_exists = Mock(return_value=True)
+ persisted = {"_dim": 8, "_distance": "cosine", "Fields": []}
+ og_coll = Mock()
+
+ with (
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._load_collection_meta",
+ return_value=persisted,
+ ),
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter.OpenGaussCollection",
+ return_value=og_coll,
+ ),
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter.Collection",
+ side_effect=lambda impl: impl,
+ ),
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._save_collection_meta",
+ ) as save_meta,
+ patch.object(adapter, "_ensure_vector_index_exists") as ensure_index,
+ ):
+ adapter._load_existing_collection_if_needed()
+
+ save_meta.assert_not_called()
+ ensure_index.assert_called_once_with(og_coll, "cosine")
+
+
+# ---------------------------------------------------------------------------
+# Backend failures must propagate instead of masquerading as absence
+# ---------------------------------------------------------------------------
+
+
+class _UndefinedTableError(Exception):
+ pgcode = "42P01"
+
+
+class _PermissionDeniedError(Exception):
+ pgcode = "42501"
+
+
+def test_is_undefined_table_error_classification():
+ assert _is_undefined_table_error(_UndefinedTableError("boom")) is True
+ # A real SQLSTATE wins over any message text.
+ assert _is_undefined_table_error(_PermissionDeniedError('relation "t" does not exist')) is False
+ # Message text is not reliable enough to classify backend failures.
+ assert _is_undefined_table_error(RuntimeError('relation "t" does not exist')) is False
+ assert _is_undefined_table_error(RuntimeError("network timeout")) is False
+
+
+def test_load_collection_meta_propagates_backend_errors():
+ conn = Mock()
+ cursor = Mock()
+ conn.cursor.return_value = cursor
+
+ def execute(sql, params=None):
+ if sql.lstrip().startswith("SELECT"):
+ raise RuntimeError("connection dropped")
+
+ cursor.execute.side_effect = execute
+ with pytest.raises(RuntimeError, match="connection dropped"):
+ _load_collection_meta(conn, "context")
+ conn.rollback.assert_called_once_with()
+
+
+def test_load_collection_meta_returns_none_only_without_row():
+ conn = Mock()
+ cursor = Mock()
+ conn.cursor.return_value = cursor
+ cursor.fetchone.return_value = None
+
+ assert _load_collection_meta(conn, "context") is None
+ conn.rollback.assert_not_called()
+
+
+def test_table_exists_propagates_backend_errors():
+ adapter = _adapter_without_connect()
+ conn = Mock()
+ cursor = Mock()
+ conn.cursor.return_value = cursor
+ cursor.execute.side_effect = RuntimeError("permission denied")
+ adapter._conn = conn
+
+ with pytest.raises(RuntimeError, match="permission denied"):
+ adapter._table_exists("context")
+ conn.rollback.assert_called_once_with()
+
+
+def test_pure_sparse_query_raises_not_implemented():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ with pytest.raises(NotImplementedError, match="sparse"):
+ collection.search_by_vector(
+ "default",
+ dense_vector=None,
+ sparse_vector={"term": 1.0},
+ )
+ # Empty dense query without sparse terms still short-circuits gracefully.
+ assert collection.search_by_vector("default", dense_vector=None).data == []
+
+
+def test_search_by_id_propagates_backend_errors():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._execute = Mock(side_effect=RuntimeError("connection dropped"))
+
+ with pytest.raises(RuntimeError, match="connection dropped"):
+ collection.search_by_id("default", "doc-1")
+
+
+def test_search_by_id_applies_offset_after_excluding_source_record():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._execute = Mock(return_value=[("[1,0]",)])
+ collection.search_by_vector = Mock(
+ return_value=Mock(
+ data=[
+ Mock(id="doc-1"),
+ Mock(id="neighbor-1"),
+ Mock(id="neighbor-2"),
+ Mock(id="neighbor-3"),
+ ]
+ )
+ )
+
+ result = collection.search_by_id("default", "doc-1", limit=2, offset=1)
+
+ collection.search_by_vector.assert_called_once_with(
+ "default",
+ dense_vector=[1.0, 0.0],
+ limit=4,
+ offset=0,
+ filters=None,
+ output_fields=None,
+ )
+ assert [item.id for item in result.data] == ["neighbor-2", "neighbor-3"]
+
+
+def test_drop_index_keeps_registry_when_database_drop_fails():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._indexes = {"default": {"_pg_index_name": "idx_context_default_vec"}}
+ collection._pending_indexes = {}
+ collection._lock = __import__("threading").RLock()
+ collection._conn = Mock()
+ cursor = Mock()
+ cursor.execute.side_effect = RuntimeError("permission denied")
+ collection._conn.cursor.return_value = cursor
+
+ with pytest.raises(RuntimeError, match="permission denied"):
+ collection.drop_index("default")
+
+ assert "default" in collection._indexes
+
+
+def test_drop_index_removes_ann_scalar_indexes_and_metadata_atomically():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._indexes = {
+ "default": {
+ "_pg_index_name": "idx_context_default_vec",
+ "ScalarIndex": ["uri", "level"],
+ }
+ }
+ collection._pending_indexes = {}
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ cursor = Mock()
+ collection._conn.cursor.return_value = cursor
+
+ collection.drop_index("default")
+
+ executed_sql = [item.args[0] for item in cursor.execute.call_args_list]
+ assert 'DROP INDEX IF EXISTS "idx_context_default_vec"' in executed_sql
+ assert 'DROP INDEX IF EXISTS "idx_context_default_uri"' in executed_sql
+ assert 'DROP INDEX IF EXISTS "idx_context_default_level"' in executed_sql
+ assert any(sql.startswith("DELETE FROM") for sql in executed_sql)
+ collection._conn.commit.assert_called_once_with()
+ assert "default" not in collection._indexes
+
+
+def test_reconcile_missing_ann_cleans_scalar_indexes_before_registry_removal():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ meta = {
+ "_pg_index_name": "idx_context_default_vec",
+ "ScalarIndex": ["uri"],
+ "VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"},
+ }
+ collection._indexes = {"default": meta}
+ collection._physical_index_definition = Mock(return_value=None)
+ collection._normalized_index_meta = Mock(return_value=meta)
+ collection._delete_index_meta_and_scalar_indexes = Mock()
+
+ collection._reconcile_index_metadata()
+
+ collection._delete_index_meta_and_scalar_indexes.assert_called_once_with("default", meta)
+ assert "default" not in collection._indexes
+
+
+def test_reconcile_keeps_registry_when_scalar_cleanup_fails():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ meta = {
+ "_pg_index_name": "idx_context_default_vec",
+ "ScalarIndex": ["uri"],
+ "VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"},
+ }
+ collection._indexes = {"default": meta}
+ collection._physical_index_definition = Mock(return_value=None)
+ collection._normalized_index_meta = Mock(return_value=meta)
+ collection._delete_index_meta_and_scalar_indexes = Mock(
+ side_effect=RuntimeError("cleanup failed")
+ )
+
+ with pytest.raises(RuntimeError, match="cleanup failed"):
+ collection._reconcile_index_metadata()
+
+ assert collection._indexes["default"] == meta
+
+
+def test_update_index_accepts_scalar_field_list_and_removes_stale_indexes():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._field_names = {"id", "vector", "uri", "level"}
+ collection._indexes = {
+ "default": {
+ "_pg_index_name": "idx_context_default_vec",
+ "ScalarIndex": ["uri"],
+ }
+ }
+ collection._pending_indexes = {}
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ collection._ensure_index_meta_table = Mock()
+ cursor = Mock()
+ cursor.rowcount = 1
+ cursor.fetchone.return_value = None
+ collection._conn.cursor.return_value = cursor
+
+ collection.update_index("default", ["level"], "updated")
+
+ executed_sql = [item.args[0] for item in cursor.execute.call_args_list]
+ assert 'DROP INDEX IF EXISTS "idx_context_default_uri"' in executed_sql
+ assert any(sql.startswith('CREATE INDEX "idx_context_default_level"') for sql in executed_sql)
+ assert collection._indexes["default"]["ScalarIndex"] == ["level"]
+ assert collection._indexes["default"]["Description"] == "updated"
+
+
+def test_update_index_empty_scalar_list_clears_indexes():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._field_names = {"id", "vector", "uri"}
+ collection._indexes = {
+ "default": {
+ "_pg_index_name": "idx_context_default_vec",
+ "ScalarIndex": ["uri"],
+ }
+ }
+ collection._pending_indexes = {}
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ collection._ensure_index_meta_table = Mock()
+ cursor = Mock()
+ cursor.rowcount = 1
+ cursor.fetchone.return_value = None
+ collection._conn.cursor.return_value = cursor
+
+ collection.update_index("default", [])
+
+ assert collection._indexes["default"]["ScalarIndex"] == []
+ assert 'DROP INDEX IF EXISTS "idx_context_default_uri"' in [
+ item.args[0] for item in cursor.execute.call_args_list
+ ]
+
+
+def test_create_collection_cleans_partial_collection_after_index_failure():
+ adapter = _adapter_without_connect()
+ adapter._collection = None
+ partial_collection = Mock()
+ partial_collection.create_index.side_effect = RuntimeError("index creation failed")
+ adapter._create_backend_collection = Mock(return_value=partial_collection)
+ adapter._table_exists = Mock(return_value=False)
+
+ with patch.object(adapter, "collection_exists", return_value=False):
+ with pytest.raises(RuntimeError, match="index creation failed"):
+ adapter.create_collection(
+ "context",
+ {"Fields": []},
+ distance="cosine",
+ sparse_weight=0.0,
+ index_name="default",
+ )
+
+ partial_collection.drop.assert_called_once_with()
+ assert adapter._collection is None
+
+
+def test_create_collection_rejects_unregistered_orphan_table():
+ adapter = _adapter_without_connect()
+ adapter._conn = Mock()
+ adapter._table_exists = Mock(return_value=True)
+
+ with patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._load_collection_meta",
+ return_value=None,
+ ):
+ with pytest.raises(RuntimeError, match="orphan table"):
+ adapter.create_collection(
+ "context",
+ {"Fields": []},
+ distance="cosine",
+ sparse_weight=0.0,
+ index_name="default",
+ )
+
+
+def test_distributed_conversion_failure_cleans_created_local_table():
+ adapter = _adapter_without_connect(distributed=True)
+ adapter._conn = Mock()
+ cleanup_cursor = Mock()
+ adapter._conn.cursor.return_value = cleanup_cursor
+ meta = {
+ "Fields": [
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 8},
+ ]
+ }
+
+ def fail_after_table_creation(*args, **kwargs):
+ kwargs["on_table_created"]()
+ raise RuntimeError("distribution failed")
+
+ with patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._create_collection_table",
+ side_effect=fail_after_table_creation,
+ ):
+ with pytest.raises(RuntimeError, match="distribution failed"):
+ adapter._create_backend_collection(meta)
+
+ executed_sql = [item.args[0] for item in cleanup_cursor.execute.call_args_list]
+ assert 'DROP TABLE IF EXISTS "context" CASCADE' in executed_sql
+ adapter._conn.commit.assert_called_once_with()
+
+
+def test_explicit_quantization_flags_require_training_data():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ for flag in ("enable_pq", "enable_rabitq"):
+ meta = collection._normalized_index_meta(
+ "default",
+ {"VectorIndex": {"IndexType": "hnsw"}, "build_params": {flag: True}},
+ )
+ assert collection._index_requires_data(meta)
+ assert flag not in meta["build_params"]
+ assert not collection._index_requires_data(
+ {
+ "_pg_index_type": "hnsw",
+ "_quantization": None,
+ "build_params": {},
+ }
+ )
+
+
+def test_update_data_rejects_missing_records_and_requires_primary_key():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ with pytest.raises(ValueError, match="primary key 'id'"):
+ collection.update_data([{"uri": "viking://resources/new"}])
+
+ collection._name = "context"
+ collection._dim = 2
+ collection._date_time_fields = set()
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ collection._get_all_columns = Mock(return_value=["id", "uri"])
+ collection._get_column_types = Mock(return_value={"id": "character varying", "uri": "text"})
+ cursor = Mock()
+ cursor.rowcount = 0
+ collection._conn.cursor.return_value = cursor
+ with pytest.raises(ValueError, match="record not found"):
+ collection.update_data([{"id": "missing", "uri": "viking://resources/new"}])
+ collection._conn.rollback.assert_called_once_with()
+
+
+def test_update_data_preserves_unspecified_fields():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 2
+ collection._date_time_fields = set()
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ collection._get_all_columns = Mock(return_value=["id", "uri", "level"])
+ collection._get_column_types = Mock(
+ return_value={"id": "character varying", "uri": "text", "level": "bigint"}
+ )
+ cursor = Mock()
+ cursor.rowcount = 1
+ collection._conn.cursor.return_value = cursor
+
+ updated_ids = collection.update_data([{"id": "doc-1", "level": 2}])
+
+ update_sql, update_params = cursor.execute.call_args.args
+ assert 'SET "level" = %s' in update_sql
+ assert '"uri"' not in update_sql
+ assert update_params == [2, "doc-1"]
+ assert updated_ids == ["doc-1"]
+ collection._conn.commit.assert_called_once_with()
+
+
+def test_adapter_exposes_transactional_update_data():
+ adapter = _adapter_without_connect()
+ adapter._collection = Mock()
+ adapter._collection.update_data.return_value = ["doc-1"]
+
+ assert adapter.update_data([{"id": "doc-1", "level": 2}]) == ["doc-1"]
+ adapter._collection.update_data.assert_called_once_with([{"id": "doc-1", "level": 2}])
+
+
+def test_adapter_update_normalizes_all_uri_fields_before_write():
+ adapter = _adapter_without_connect()
+ adapter._collection = Mock()
+ adapter._collection.update_data.return_value = ["doc-1"]
+ record = {
+ "id": "doc-1",
+ "uri": "viking://resources/demo",
+ "parent_uri": "viking://resources",
+ }
+
+ assert adapter.update_data([record]) == ["doc-1"]
+
+ adapter._collection.update_data.assert_called_once_with(
+ [
+ {
+ "id": "doc-1",
+ "uri": "/resources/demo",
+ "parent_uri": "/resources",
+ }
+ ]
+ )
+ assert record["uri"] == "viking://resources/demo"
+
+
+def test_runtime_index_creation_reuses_config_validation():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._dim = 8
+ collection._persist_index_meta_and_scalar_indexes = Mock()
+
+ with pytest.raises(ValueError, match="cannot be enabled together"):
+ collection.create_index(
+ "invalid",
+ {
+ "VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"},
+ "build_params": {"enable_pq": True, "enable_rabitq": True},
+ },
+ )
+ collection._persist_index_meta_and_scalar_indexes.assert_not_called()
+
+
+def test_runtime_index_validation_preserves_parallel_workers():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 8
+ collection._distance = "cosine"
+ collection._field_names = {"id", "vector"}
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ collection._persist_index_meta_and_scalar_indexes = Mock()
+ collection._table_has_rows = Mock(return_value=False)
+ collection._physical_index_definition = Mock(return_value=None)
+
+ collection.create_index(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "ivfflat", "Distance": "cosine"},
+ "build_params": {"lists": 10},
+ "parallel_workers": 4,
+ },
+ )
+
+ assert collection._pending_indexes["default"]["parallel_workers"] == 4
+
+
+def test_reconnect_reapplies_parallel_workers_for_matching_index():
+ adapter = _adapter_without_connect(parallel_workers=8)
+ collection = Mock()
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ collection._meta = {}
+ normalized_meta = {
+ "_pg_index_name": "idx_context_default_vec",
+ "build_params": {"parallel_workers": 8},
+ "ScalarIndex": [],
+ }
+ collection._normalized_index_meta.return_value = normalized_meta
+ collection._physical_index_definition.return_value = "matching index"
+ collection._index_definition_matches.return_value = True
+
+ adapter._ensure_vector_index_exists(collection, "cosine")
+
+ collection._apply_parallel_workers.assert_called_once_with(normalized_meta)
+
+
+def test_connection_proxy_returns_closed_connection_before_replacement():
+ pool = Mock()
+ closed_connection = Mock()
+ closed_connection.closed = True
+ replacement = Mock()
+ replacement.closed = False
+ pool.getconn.return_value = replacement
+ proxy = _PooledConnectionProxy(pool)
+ proxy._local.connection = closed_connection
+ proxy._local.cursor_count = 0
+
+ assert proxy._checkout() is replacement
+ pool.putconn.assert_called_once_with(closed_connection, close=True)
+
+
+def test_connection_proxy_releases_connection_when_cursor_creation_fails():
+ pool = Mock()
+ connection = Mock()
+ connection.closed = False
+ connection.cursor.side_effect = RuntimeError("cursor failed")
+ pool.getconn.return_value = connection
+ proxy = _PooledConnectionProxy(pool)
+
+ with pytest.raises(RuntimeError, match="cursor failed"):
+ proxy.cursor()
+
+ pool.putconn.assert_called_once_with(connection, close=False)
+ assert proxy._local.connection is None
+ assert proxy._local.cursor_count == 0
+
+
+def test_connection_proxy_returns_connection_when_checkout_initialization_fails():
+ pool = Mock()
+ connection = Mock()
+ type(connection).autocommit = property(fset=Mock(side_effect=RuntimeError("connection lost")))
+ pool.getconn.return_value = connection
+ proxy = _PooledConnectionProxy(pool)
+
+ with pytest.raises(RuntimeError, match="connection lost"):
+ proxy._checkout()
+
+ pool.putconn.assert_called_once_with(connection, close=True)
+ assert getattr(proxy._local, "connection", None) is None
+
+
+def test_adapter_connect_closes_pool_when_metadata_initialization_fails():
+ adapter = _adapter_without_connect()
+ pool = Mock()
+ with (
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._create_connection_pool",
+ return_value=pool,
+ ),
+ patch(
+ "openviking.storage.vectordb_adapters.opengauss_adapter._ensure_meta_table",
+ side_effect=RuntimeError("permission denied"),
+ ),
+ ):
+ with pytest.raises(RuntimeError, match="permission denied"):
+ adapter._connect()
+
+ pool.closeall.assert_called_once_with()
+ assert adapter._conn is None
+ assert adapter._pool is None
+
+
[email protected]("parallel_workers", [-1, 33, True, 1.5, "invalid"])
+def test_runtime_index_validation_rejects_invalid_parallel_workers(parallel_workers):
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._dim = 8
+ collection._distance = "cosine"
+ collection._create_scalar_indexes = Mock()
+
+ with pytest.raises((ValueError, ValidationError)):
+ collection.create_index(
+ "default",
+ {
+ "VectorIndex": {"IndexType": "hnsw", "Distance": "cosine"},
+ "build_params": {"parallel_workers": parallel_workers},
+ },
+ )
+ collection._create_scalar_indexes.assert_not_called()
+
+
[email protected]("index_type", ["hnsw-pq", "hnsw-rabitq"])
+def test_runtime_index_validation_rejects_quantized_l1(index_type):
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._dim = 8
+ collection._distance = "l1"
+ collection._create_scalar_indexes = Mock()
+
+ with pytest.raises(ValueError, match="plain hnsw"):
+ collection.create_index(
+ "default",
+ {
+ "VectorIndex": {"IndexType": index_type, "Distance": "l1"},
+ },
+ )
+ collection._create_scalar_indexes.assert_not_called()
+
+
+def test_pending_index_metadata_survives_reconnect():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._indexes = {}
+ collection._pending_indexes = {}
+ collection._execute = Mock(
+ return_value=[
+ (
+ "secondary",
+ json.dumps(
+ {
+ "_state": "pending",
+ "_pg_index_name": "idx_context_secondary_vec",
+ }
+ ),
+ )
+ ]
+ )
+
+ collection._load_index_meta()
+
+ assert "secondary" in collection._pending_indexes
+ assert "secondary" not in collection._indexes
+
+
+def test_filter_delete_executes_direct_sql_without_implicit_limit():
+ adapter = _adapter_without_connect()
+ adapter._collection = Mock()
+ adapter._collection.get_meta_data.return_value = {
+ "Fields": [{"FieldName": "account_id", "FieldType": "string"}]
+ }
+ adapter._conn = Mock()
+ cursor = Mock()
+ cursor.rowcount = 100001
+ adapter._conn.cursor.return_value = cursor
+
+ deleted_count = adapter.delete(filter=Eq("account_id", "acct-1"))
+
+ assert deleted_count == 100001
+ delete_sql, delete_params = cursor.execute.call_args.args
+ assert delete_sql.startswith('DELETE FROM "context" WHERE')
+ assert "ORDER BY id LIMIT %s" in delete_sql
+ assert delete_params == ["acct-1", None]
+
+
+def test_save_index_meta_recovers_cross_process_unique_race():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._distributed = False
+ collection._lock = threading.RLock()
+ collection._ensure_index_meta_table = Mock()
+ collection._conn = Mock()
+ first_cursor = Mock()
+ first_cursor.rowcount = 0
+ unique_error = RuntimeError("duplicate key")
+ unique_error.pgcode = "23505"
+ first_cursor.execute.side_effect = [None, unique_error]
+ retry_cursor = Mock()
+ retry_cursor.rowcount = 1
+ collection._conn.cursor.side_effect = [first_cursor, retry_cursor]
+
+ collection._save_index_meta("default", {"_state": "pending"})
+
+ collection._conn.rollback.assert_called_once_with()
+ collection._conn.commit.assert_called_once_with()
+ assert "UPDATE" in retry_cursor.execute.call_args.args[0]
+
+
+def test_atomic_scalar_metadata_persistence_recovers_unique_race():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._field_names = {"id", "vector", "uri"}
+ collection._lock = threading.RLock()
+ collection._ensure_index_meta_table = Mock()
+ collection._conn = Mock()
+ first_cursor = Mock()
+ retry_cursor = Mock()
+ unique_error = RuntimeError("duplicate key")
+ unique_error.pgcode = "23505"
+
+ def first_execute(sql, params=None):
+ if sql.startswith("UPDATE"):
+ first_cursor.rowcount = 0
+ elif sql.startswith("INSERT"):
+ raise unique_error
+
+ def retry_execute(sql, params=None):
+ if sql.startswith("UPDATE"):
+ retry_cursor.rowcount = 1
+
+ first_cursor.execute.side_effect = first_execute
+ retry_cursor.execute.side_effect = retry_execute
+ collection._conn.cursor.side_effect = [first_cursor, retry_cursor]
+
+ collection._persist_index_meta_and_scalar_indexes(
+ "default",
+ {"ScalarIndex": ["uri"], "_state": "pending"},
+ )
+
+ collection._conn.rollback.assert_called_once_with()
+ collection._conn.commit.assert_called_once_with()
+ assert any(
+ item.args[0].startswith("CREATE INDEX IF NOT EXISTS")
+ for item in retry_cursor.execute.call_args_list
+ )
+ assert any(item.args[0].startswith("UPDATE") for item in retry_cursor.execute.call_args_list)
+
+
+def test_search_sql_uses_stable_id_tiebreaker():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 2
+ collection._distance = "cosine"
+ collection._field_names = {"id", "vector", "level"}
+ collection._array_fields = set()
+ collection._date_time_fields = set()
+ collection._indexes = {"default": {"_distance": "cosine"}}
+ collection._pending_indexes = {}
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ cursor = Mock()
+ cursor.description = [("id",), ("vector",), ("_distance",)]
+ cursor.fetchall.return_value = []
+ collection._conn.cursor.return_value = cursor
+ collection._materialize_pending_index = Mock()
+ collection.has_index = Mock(return_value=True)
+ collection._apply_search_params_on_cursor = Mock()
+
+ collection.search_by_vector("default", dense_vector=[1.0, 0.0])
+ assert "ORDER BY _distance, id" in cursor.execute.call_args.args[0]
+
+ cursor.description = [("id",), ("level",), ("_scalar_val",)]
+ cursor.fetchall.return_value = []
+ collection.search_by_scalar("default", field="level", order="desc")
+ assert 'ORDER BY "level" DESC, id DESC' in cursor.execute.call_args.args[0]
+
+
+def test_healthy_index_query_ignores_unrelated_failing_pending_index():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 2
+ collection._distance = "cosine"
+ collection._field_names = {"id", "vector"}
+ collection._array_fields = set()
+ collection._date_time_fields = set()
+ collection._indexes = {"default": {"_distance": "cosine"}}
+ collection._pending_indexes = {"secondary": {"_distance": "cosine"}}
+ collection._bulk_ingest_depth = 0
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ cursor = Mock()
+ cursor.description = [("id",), ("vector",), ("_distance",)]
+ cursor.fetchall.return_value = []
+ collection._conn.cursor.return_value = cursor
+ collection._table_has_rows = Mock(return_value=True)
+ collection._materialize_index = Mock(side_effect=RuntimeError("secondary build failed"))
+ collection.has_index = Mock(return_value=True)
+ collection._apply_search_params_on_cursor = Mock()
+
+ result = collection.search_by_vector("default", dense_vector=[1.0, 0.0])
+
+ assert result.data == []
+ collection._materialize_index.assert_not_called()
+
+
+def test_query_materializes_only_requested_pending_index():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ requested_meta = {"_distance": "cosine"}
+ collection._pending_indexes = {
+ "requested": requested_meta,
+ "secondary": {"_distance": "cosine"},
+ }
+ collection._bulk_ingest_depth = 0
+ collection._table_has_rows = Mock(return_value=True)
+ collection._materialize_index = Mock()
+
+ collection._materialize_pending_index("requested")
+
+ collection._materialize_index.assert_called_once_with("requested", requested_meta)
+
+
+def test_upsert_does_not_report_committed_rows_as_failed_when_index_build_fails():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 2
+ collection._field_names = {"id", "vector"}
+ collection._date_time_fields = set()
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ cursor = Mock()
+ cursor.rowcount = 0
+ collection._conn.cursor.return_value = cursor
+ collection._get_all_columns = Mock(return_value=["id", "vector"])
+ collection._get_column_types = Mock(
+ return_value={"id": "character varying", "vector": "USER-DEFINED"}
+ )
+ collection._materialize_pending_indexes = Mock(
+ side_effect=RuntimeError("index creation failed")
+ )
+
+ collection.upsert_data([{"id": "doc-1", "vector": [1.0, 0.0]}])
+
+ collection._conn.commit.assert_called_once_with()
+ collection._materialize_pending_indexes.assert_called_once_with()
+
+
+def test_upsert_recovers_concurrent_insert_unique_race():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._dim = 2
+ collection._field_names = {"id", "vector"}
+ collection._date_time_fields = set()
+ collection._lock = threading.RLock()
+ collection._conn = Mock()
+ cursor = Mock()
+ unique_error = RuntimeError("duplicate key")
+ unique_error.pgcode = "23505"
+ rowcounts = iter([0, 1])
+
+ def execute(sql, params=None):
+ if sql.startswith("UPDATE"):
+ cursor.rowcount = next(rowcounts)
+ elif sql.startswith("INSERT"):
+ raise unique_error
+
+ cursor.execute.side_effect = execute
+ collection._conn.cursor.return_value = cursor
+ collection._get_all_columns = Mock(return_value=["id", "vector"])
+ collection._get_column_types = Mock(
+ return_value={"id": "character varying", "vector": "USER-DEFINED"}
+ )
+ collection._materialize_pending_indexes = Mock()
+
+ collection.upsert_data([{"id": "doc-1", "vector": [1.0, 0.0]}])
+
+ executed_sql = [call.args[0] for call in cursor.execute.call_args_list]
+ assert executed_sql == [
+ 'UPDATE "context" SET "vector" = %s::vector WHERE "id" = %s',
+ "SAVEPOINT ov_upsert_insert",
+ 'INSERT INTO "context" ("id", "vector") VALUES (%s, %s::vector)',
+ "ROLLBACK TO SAVEPOINT ov_upsert_insert",
+ 'UPDATE "context" SET "vector" = %s::vector WHERE "id" = %s',
+ "RELEASE SAVEPOINT ov_upsert_insert",
+ ]
+ collection._conn.commit.assert_called_once_with()
+
+
+def test_load_index_meta_tolerates_only_missing_catalog_table():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+ collection._indexes = {}
+
+ collection._execute = Mock(
+ side_effect=_UndefinedTableError('relation "_ov_index_context" does not exist')
+ )
+ collection._load_index_meta()
+ assert collection._indexes == {}
+
+ collection._execute = Mock(side_effect=_PermissionDeniedError("permission denied"))
+ with pytest.raises(_PermissionDeniedError):
+ collection._load_index_meta()
+
+
+def test_delete_index_meta_tolerates_only_missing_catalog_table():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ collection._name = "context"
+
+ collection._execute = Mock(
+ side_effect=_UndefinedTableError('relation "_ov_index_context" does not exist')
+ )
+ collection._delete_index_meta("default")
+
+ collection._execute = Mock(side_effect=RuntimeError("connection dropped"))
+ with pytest.raises(RuntimeError, match="connection dropped"):
+ collection._delete_index_meta("default")
+
+
+def test_is_table_already_distributed_propagates_non_catalog_errors():
+ conn = Mock()
+ cursor = Mock()
+ conn.cursor.return_value = cursor
+ cursor.execute.side_effect = _UndefinedTableError('relation "pg_dist_partition" does not exist')
+ assert _is_table_already_distributed(conn, "context") is False
+
+ broken_conn = Mock()
+ broken_cursor = Mock()
+ broken_conn.cursor.return_value = broken_cursor
+ broken_cursor.execute.side_effect = RuntimeError("node down")
+ with pytest.raises(RuntimeError, match="node down"):
+ _is_table_already_distributed(broken_conn, "context")
+ broken_conn.rollback.assert_called_once_with()
+
+
+def _probe_cursor(available, probe_rows=None, probe_error=None):
+ cursor = Mock()
+ executed = []
+
+ def _execute(sql, params=None):
+ executed.append(" ".join(sql.split()))
+ if "FROM run_command_on_" in sql and probe_error is not None:
+ raise probe_error
+
+ cursor.execute.side_effect = _execute
+ cursor.fetchone.return_value = available
+ cursor.fetchall.return_value = probe_rows or []
+ return cursor, executed
+
+
+def test_probe_distributed_workers_prefers_shard_hosting_workers():
+ cursor, executed = _probe_cursor(
+ (True, True), [("10.93.0.3:5432", True, "1"), ("10.93.0.4:5432", True, "1")]
+ )
+ _probe_distributed_workers(cursor)
+ assert any("FROM run_command_on_workers('SELECT 1')" in sql for sql in executed)
+ assert not any("FROM run_command_on_all_nodes(" in sql for sql in executed)
+
+
+def test_probe_distributed_workers_falls_back_to_all_nodes_probe():
+ cursor, executed = _probe_cursor((False, True), [(1, True, "1"), (2, True, "1")])
+ _probe_distributed_workers(cursor)
+ assert any("FROM run_command_on_all_nodes('SELECT 1', true, false)" in sql for sql in executed)
+
+ cursor, executed = _probe_cursor((False, False))
+ _probe_distributed_workers(cursor)
+ assert len(executed) == 1
+
+
+def test_probe_distributed_workers_reports_unreachable_nodes():
+ cursor, _ = _probe_cursor(
+ (True, True), [("10.93.0.3:5432", True, "1"), ("10.93.0.4:5432", False, "timeout")]
+ )
+ with pytest.raises(RuntimeError, match=r"not reachable.*10\.93\.0\.4:5432"):
+ _probe_distributed_workers(cursor)
+
+ cursor, _ = _probe_cursor(
+ (True, True),
+ probe_error=RuntimeError("connection establishment for node 10.93.0.4:5432 failed"),
+ )
+ with pytest.raises(RuntimeError, match=r"not reachable.*10\.93\.0\.4:5432 failed"):
+ _probe_distributed_workers(cursor)
diff --git a/tests/vectordb/test_opengauss_config.py b/tests/vectordb/test_opengauss_config.py
new file mode 100644
index 000000000..78eba0c97
--- /dev/null
+++ b/tests/vectordb/test_opengauss_config.py
@@ -0,0 +1,482 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from unittest.mock import Mock, patch
+
+import pytest
+from pydantic import ValidationError
+
+from openviking.storage.vectordb_adapters.factory import create_collection_adapter
+from openviking.storage.vectordb_adapters.opengauss.catalog import _create_collection_table
+from openviking.storage.vectordb_adapters.opengauss.collection import OpenGaussCollection
+from openviking.storage.vectordb_adapters.opengauss.sql import (
+ _build_path_scope_clause,
+ _build_where_clause,
+ _date_time_to_epoch_ms,
+ _distance_to_similarity,
+ _field_to_column_ddl,
+ _normalize_index_type,
+ _resolve_build_params,
+)
+from openviking.storage.vectordb_adapters.opengauss_adapter import OpenGaussCollectionAdapter
+from openviking_cli.utils.config.vectordb_config import (
+ OpenGaussConfig,
+ VectorDBBackendConfig,
+)
+
+
+def test_opengauss_index_type_defaults_and_variants():
+ assert OpenGaussConfig().index_type == "hnsw"
+ assert (
+ OpenGaussConfig(index_type="ivfflat", build_params={"lists": 128}).index_type == "ivfflat"
+ )
+ assert (
+ OpenGaussConfig(
+ index_type="diskann",
+ build_params={"index_size": 64},
+ search_params={"probes": 32},
+ ).index_type
+ == "diskann"
+ )
+
+
+def test_database_specific_ranges_are_deferred_but_types_are_checked():
+ for kind, params in [
+ ("hnsw", {"m": 32, "ef_construction": 40}),
+ ("ivfflat", {"lists": 0}),
+ ("diskann", {"index_size": 8}),
+ ]:
+ assert OpenGaussConfig(index_type=kind, build_params=params).build_params == params
+ for value in (True, "16", 1.5, None):
+ with pytest.raises(ValidationError, match="integer"):
+ OpenGaussConfig(build_params={"m": value})
+ with pytest.raises(ValidationError, match="maintenance_work_mem_mb"):
+ OpenGaussConfig(maintenance_work_mem_mb=0)
+
+
+ ("index_type", "build_params"),
+ [
+ ("hnsw-pq", {"pq_m": 8}),
+ ("hnsw-rabitq", {"rabitq_refine_type": "FP32"}),
+ ("ivfflat", {"lists": 1}),
+ ("ivf-pq", {"lists": 1, "pq_m": 8}),
+ ("ivf-rabitq", {"lists": 1}),
+ ("diskann", {"index_size": 50}),
+ ],
+)
+def test_opengauss_distributed_mode_rejects_non_plain_hnsw(index_type, build_params):
+ with pytest.raises(ValidationError, match="supports only plain HNSW"):
+ OpenGaussConfig(
+ mode="distributed",
+ index_type=index_type,
+ build_params=build_params,
+ )
+
+
[email protected]("index_type", ["diskann-pq", "diskann_pq", "diskannpq"])
+def test_opengauss_rejects_diskann_pq_index_types(index_type):
+ with pytest.raises(ValidationError, match="Invalid openGauss index_type"):
+ OpenGaussConfig(index_type=index_type)
+
+
+ "build_params",
+ [
+ {"index_size": 50, "enable_pq": True},
+ {"index_size": 50, "pq_m": 8},
+ {"index_size": 50, "enable_pq": True, "pq_m": 8},
+ ],
+)
+def test_opengauss_rejects_diskann_pq_build_parameters(build_params):
+ with pytest.raises(ValidationError, match="[Dd]iskann|DiskANN"):
+ OpenGaussConfig(index_type="diskann", build_params=build_params)
+
+
+def test_opengauss_index_build_memory_defaults_to_safe_transaction_value():
+ config = OpenGaussConfig()
+
+ assert config.maintenance_work_mem_mb == 64
+
+
+def test_normalize_and_resolve_index_helpers():
+ assert _normalize_index_type("HNSW") == "hnsw"
+ assert _normalize_index_type("ivf_flat") == "ivfflat"
+ with pytest.raises(ValueError, match="index_type"):
+ _normalize_index_type("diskann_v1")
+ assert _resolve_build_params("hnsw", {"build_params": {"m": 16}}) == {"m": 16}
+
+
+def test_build_where_clause_supports_common_filters():
+ sql, params = _build_where_clause(
+ {
+ "op": "and",
+ "conds": [
+ {"op": "must", "field": "uri", "conds": ["/a"], "para": "-d=1"},
+ {"op": "range", "field": "score", "gte": 1, "lt": 10},
+ {"op": "contains", "field": "abstract", "substring": "hello"},
+ ],
+ }
+ )
+ assert 'rtrim(btrim("uri"),' in sql
+ assert "LIKE %s ESCAPE" in sql
+ assert '"score" >= %s' in sql
+ assert '"abstract" LIKE %s ESCAPE' in sql
+ assert params == ["/a", "/a/%", 1, 1, 10, "%hello%"]
+
+
+def test_factory_routes_opengauss_backend():
+ config = VectorDBBackendConfig(
+ backend="opengauss",
+ opengauss=OpenGaussConfig(
+ host="127.0.0.1",
+ index_type="ivfflat",
+ build_params={"lists": 200},
+ search_params={"probes": 14},
+ ),
+ )
+ with patch.object(OpenGaussCollectionAdapter, "_connect", return_value=None):
+ adapter = create_collection_adapter(config)
+ assert isinstance(adapter, OpenGaussCollectionAdapter)
+ assert adapter.mode == "opengauss"
+ assert adapter._index_type == "ivfflat"
+ assert adapter._build_params["lists"] == 200
+ assert adapter._search_params["probes"] == 14
+
+
+def test_build_default_index_meta_uses_configured_index_knobs():
+ with patch.object(OpenGaussCollectionAdapter, "_connect", return_value=None):
+ adapter = OpenGaussCollectionAdapter(
+ collection_name="context",
+ distance_metric="cosine",
+ config=OpenGaussConfig(
+ host="127.0.0.1",
+ port=5432,
+ user="gaussdb",
+ password="",
+ db_name="openviking",
+ index_type="hnsw",
+ build_params={"m": 16, "ef_construction": 64},
+ search_params={"ef_search": 100},
+ maintenance_work_mem_mb=128,
+ ),
+ )
+ meta = adapter._build_default_index_meta(
+ index_name="default",
+ distance="cosine",
+ use_sparse=False,
+ sparse_weight=0.0,
+ scalar_index_fields=["uri"],
+ )
+ assert meta["VectorIndex"]["IndexType"] == "hnsw"
+ assert meta["build_params"]["m"] == 16
+ assert meta["search_params"]["ef_search"] == 100
+ assert meta["maintenance_work_mem_mb"] == 128
+ assert meta["ScalarIndex"] == ["uri"]
+
+
+def test_direct_adapter_constructor_validates_and_normalizes_all_config_fields():
+ with patch.object(OpenGaussCollectionAdapter, "_connect", return_value=None):
+ adapter = OpenGaussCollectionAdapter(
+ collection_name="context",
+ config=OpenGaussConfig(
+ host="host",
+ port="5432",
+ user="u",
+ password="p",
+ db_name="db",
+ mode="distributed" if False else "standalone",
+ shard_count="4",
+ index_type="hnsw",
+ maintenance_work_mem_mb=128,
+ connection_pool_min_size="2",
+ connection_pool_max_size="4",
+ ),
+ )
+
+ assert adapter._port == 5432
+ assert adapter._shard_count == 4
+ assert adapter._maintenance_work_mem_mb == 128
+ assert adapter._connection_pool_min_size == 2
+ assert adapter._connection_pool_max_size == 4
+
+
+ "invalid_fields",
+ [
+ {"port": 0},
+ {"shard_count": 0},
+ {"maintenance_work_mem_mb": 0},
+ {"connection_pool_min_size": 0},
+ {"connection_pool_min_size": 5, "connection_pool_max_size": 4},
+ ],
+)
+def test_direct_adapter_constructor_rejects_invalid_config_before_connect(invalid_fields):
+ kwargs = {
+ "collection_name": "context",
+ "host": "host",
+ "port": 5432,
+ "user": "u",
+ "password": "p",
+ "db_name": "db",
+ "index_type": "hnsw",
+ }
+ kwargs.update(invalid_fields)
+
+ with patch.object(OpenGaussCollectionAdapter, "_connect") as connect:
+ with pytest.raises(ValidationError):
+ OpenGaussCollectionAdapter(
+ collection_name=kwargs.pop("collection_name"), config=OpenGaussConfig(**kwargs)
+ )
+ connect.assert_not_called()
+
+
+ ("distance_metric", "distance", "expected_score"),
+ [
+ ("cosine", 0.0, 1.0),
+ ("cosine", 1.0, 0.0),
+ ("ip", -0.75, 0.75),
+ ("l2", 0.0, 1.0),
+ ("l2", 3.0, 0.25),
+ ("l1", 1.0, 0.5),
+ ],
+)
+def test_distance_to_similarity_uses_higher_is_better_scores(
+ distance_metric, distance, expected_score
+):
+ assert _distance_to_similarity(distance_metric, distance) == pytest.approx(expected_score)
+
+
+ ("value", "expected"),
+ [
+ (1767225600000, 1767225600000),
+ ("1767225600000", 1767225600000),
+ ("2026-01-01T00:00:00Z", 1767225600000),
+ ("2026-01-01T08:00:00+08:00", 1767225600000),
+ ],
+)
+def test_date_time_to_epoch_ms_accepts_epoch_and_iso_values(value, expected):
+ assert _date_time_to_epoch_ms(value) == expected
+
+
+def test_opengauss_field_types_match_openviking_storage_contract():
+ assert _field_to_column_ddl({"FieldName": "created_at", "FieldType": "date_time"}) == (
+ '"created_at" BIGINT'
+ )
+ assert _field_to_column_ddl({"FieldName": "search_tags", "FieldType": "list<string>"}) == (
+ '"search_tags" TEXT[]'
+ )
+ assert _field_to_column_ddl({"FieldName": "sparse_vector", "FieldType": "sparse_vector"}) == (
+ '"sparse_vector" JSONB'
+ )
+
+
+def test_build_where_clause_supports_array_membership_negation_and_prefix():
+ sql, params = _build_where_clause(
+ {
+ "op": "and",
+ "conds": [
+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},
+ {"op": "must_not", "field": "search_tags", "conds": ["hidden=true"]},
+ {"op": "prefix", "field": "uri", "prefix": "/resources/demo_"},
+ ],
+ },
+ {"search_tags"},
+ )
+ assert '%s = ANY("search_tags")' in sql
+ assert 'NOT (%s = ANY("search_tags"))' in sql
+ assert '"uri" LIKE %s ESCAPE' in sql
+ assert params == ["env=prod", "hidden=true", r"/resources/demo\_%"]
+
+
+def test_build_where_clause_rejects_unsupported_filter_operations():
+ with pytest.raises(NotImplementedError, match="regex"):
+ _build_where_clause({"op": "regex", "field": "name", "pattern": ".*"})
+
+
+def test_empty_in_and_or_are_contradictions_not_unfiltered_scans():
+ sql, params = _build_where_clause({"op": "must", "field": "id", "conds": []})
+ assert sql == "FALSE"
+ assert params == []
+
+ sql, params = _build_where_clause({"op": "or", "conds": []})
+ assert sql == "FALSE"
+ assert params == []
+
+ sql, params = _build_where_clause(
+ {"op": "and", "conds": [{"op": "must", "field": "id", "conds": []}]}
+ )
+ assert sql == "(FALSE)"
+ assert params == []
+
+ sql, params = _build_where_clause({"op": "must_not", "field": "id", "conds": []})
+ assert sql == ""
+ assert params == []
+
+
+def test_contains_and_prefix_escape_sql_wildcards():
+ sql, params = _build_where_clause(
+ {"op": "contains", "field": "abstract", "substring": "100%_off"}
+ )
+ assert "ESCAPE '\\'" in sql
+ assert params == [r"%100\%\_off%"]
+
+ sql, params = _build_where_clause({"op": "prefix", "field": "uri", "prefix": r"foo\bar%"})
+ assert "ESCAPE '\\'" in sql
+ assert params == [r"foo\\bar\%%"]
+
+
+def test_path_scope_limits_relative_depth_and_avoids_sibling_prefix_match():
+ exact_sql, exact_params = _build_path_scope_clause('"uri"', "/a", 0)
+ assert exact_sql.endswith("= %s")
+ assert "rtrim(btrim(\"uri\"), '/')" in exact_sql
+ assert exact_params == ["/a"]
+
+ one_sql, one_params = _build_path_scope_clause('"uri"', "/a", 1)
+ assert "rtrim" in one_sql
+ assert "LIKE %s ESCAPE" in one_sql
+ assert "substring" in one_sql
+ assert "char_length" in one_sql
+ assert one_params == ["/a", "/a/%", 1]
+ assert "/a%" not in one_params
+ assert _build_path_scope_clause('"uri"', "/a/", 0)[1] == ["/a"]
+
+ unbounded_sql, unbounded_params = _build_path_scope_clause('"uri"', "/a", -1)
+ assert "substring" not in unbounded_sql
+ assert unbounded_params == ["/a", "/a/%"]
+
+ root_sql, root_params = _build_path_scope_clause('"uri"', "/", 1)
+ assert root_params == ["/", "/%", 1]
+ assert "from 2" in root_sql
+
+ exclude_sql, exclude_params = _build_where_clause(
+ {"op": "must_not", "field": "uri", "conds": ["/tmp"], "para": "-d=-1"}
+ )
+ assert exclude_sql.startswith("NOT (")
+ assert exclude_params == ["/tmp", "/tmp/%"]
+
+
+def test_create_collection_table_validates_name_before_ddl():
+ conn = Mock()
+ with pytest.raises(ValueError, match="Invalid openGauss collection name"):
+ _create_collection_table(conn, 'evil"; DROP TABLE t; --', {"Fields": []}, 0)
+ conn.cursor.assert_not_called()
+
+
+def test_resolved_dimension_defers_database_specific_limits():
+ for kind, params, dim in [("diskann", {}, 3072), ("hnsw-pq", {"pq_m": 7}, 1030)]:
+ config = VectorDBBackendConfig(
+ backend="opengauss", opengauss=OpenGaussConfig(index_type=kind, build_params=params)
+ )
+ config.apply_resolved_dimension(dim)
+ assert config.dimension == dim
+
+
+def test_explicit_quantization_flags_have_one_canonical_representation():
+ for flag, kind in [("enable_pq", "hnsw-pq"), ("enable_rabitq", "hnsw-rabitq")]:
+ cfg = OpenGaussConfig(build_params={flag: True})
+ assert cfg.index_type == kind
+ assert flag not in cfg.build_params
+ assert OpenGaussConfig(**cfg.model_dump()).model_dump() == cfg.model_dump()
+ with pytest.raises(ValidationError, match="plain HNSW"):
+ OpenGaussConfig(mode="distributed", build_params={flag: True})
+ with pytest.raises(ValidationError, match="conflicts"):
+ OpenGaussConfig(index_type=kind, build_params={flag: False})
+
+
+def test_l1_distance_rejects_explicit_quantization_flags():
+ for build_params in (
+ {"enable_pq": True, "pq_m": 8, "pq_ksub": 256},
+ {"enable_rabitq": True},
+ ):
+ with pytest.raises(ValidationError, match="PQ or RabitQ"):
+ VectorDBBackendConfig(
+ backend="opengauss",
+ distance_metric="l1",
+ dimension=1024,
+ opengauss=OpenGaussConfig(
+ host="127.0.0.1",
+ index_type="hnsw",
+ build_params=build_params,
+ ),
+ )
+ plain = VectorDBBackendConfig(
+ backend="opengauss",
+ distance_metric="l1",
+ dimension=1024,
+ opengauss=OpenGaussConfig(host="127.0.0.1", index_type="hnsw"),
+ )
+ assert plain.distance_metric == "l1"
+
+
+def test_opengauss_distance_metric_whitelist_and_normalization():
+ with pytest.raises(ValidationError, match="distance_metric"):
+ VectorDBBackendConfig(
+ backend="opengauss",
+ distance_metric="bogus",
+ dimension=1024,
+ opengauss=OpenGaussConfig(host="127.0.0.1"),
+ )
+ normalized = VectorDBBackendConfig(
+ backend="opengauss",
+ distance_metric="COSINE",
+ dimension=1024,
+ opengauss=OpenGaussConfig(host="127.0.0.1"),
+ )
+ assert normalized.distance_metric == "cosine"
+
+
+def test_adapter_rejects_unsupported_distance_before_connect():
+ with patch.object(OpenGaussCollectionAdapter, "_connect") as connect:
+ with pytest.raises(ValueError, match="distance"):
+ OpenGaussCollectionAdapter(
+ collection_name="context", config=OpenGaussConfig(), distance_metric="bogus"
+ )
+ connect.assert_not_called()
+
+
+def test_from_config_ignores_unvalidated_custom_params():
+ config = VectorDBBackendConfig(
+ backend="opengauss",
+ opengauss=OpenGaussConfig(
+ host="127.0.0.1",
+ index_type="hnsw",
+ build_params={"m": 16, "ef_construction": 64},
+ search_params={"ef_search": 40},
+ ),
+ custom_params={
+ "index_type": "hnsw-pq",
+ "build_params": {"enable_pq": True, "pq_m": 0},
+ "search_params": {"ef_search": 999999},
+ "pq_m": 0,
+ },
+ )
+ with patch.object(OpenGaussCollectionAdapter, "_connect", return_value=None):
+ adapter = OpenGaussCollectionAdapter.from_config(config)
+ assert adapter._index_type == "hnsw"
+ assert adapter._build_params.get("enable_pq") is not True
+ assert adapter._build_params.get("pq_m") is None
+ assert adapter._search_params.get("ef_search") == 40
+
+
+def test_opengauss_rejects_sparse_weight_configuration():
+ with pytest.raises(ValidationError, match="sparse_weight"):
+ VectorDBBackendConfig(backend="opengauss", sparse_weight=0.5)
+
+
+def test_opengauss_collection_rejects_unsupported_search_modes():
+ collection = OpenGaussCollection.__new__(OpenGaussCollection)
+ collection._distributed = False
+ collection._distance = "cosine"
+ with pytest.raises(NotImplementedError, match="keyword"):
+ collection.search_by_keywords("default", query="hello")
+ with pytest.raises(NotImplementedError, match="multimodal"):
+ collection.search_by_multimodal("default", text="hello", image=None, video=None)
+
+
[email protected]("parallel_workers", [True, False, "4", 1.5])
+def test_parallel_workers_requires_strict_integer(parallel_workers):
+ with pytest.raises(ValidationError, match="parallel_workers"):
+ OpenGaussConfig(parallel_workers=parallel_workers)
diff --git a/tests/vectordb/test_opengauss_database_integration.py b/tests/vectordb/test_opengauss_database_integration.py
new file mode 100644
index 000000000..08d27acbf
--- /dev/null
+++ b/tests/vectordb/test_opengauss_database_integration.py
@@ -0,0 +1,239 @@
+import os
+import uuid
+from urllib.parse import unquote, urlparse
+
+import psycopg2
+import pytest
+
+from openviking.storage.vectordb_adapters.opengauss_adapter import OpenGaussCollectionAdapter
+from openviking_cli.utils.config.vectordb_config import OpenGaussConfig
+
+pytestmark = pytest.mark.integration
+
+
+def _adapter_from_dsn(index_type: str, mode: str) -> OpenGaussCollectionAdapter:
+ environment_name = (
+ "OPENVIKING_OPENGAUSS_DISTRIBUTED_DSN"
+ if mode == "distributed"
+ else "OPENVIKING_OPENGAUSS_STANDALONE_DSN"
+ )
+ raw_dsn = os.getenv(environment_name)
+ if not raw_dsn:
+ pytest.skip(f"{environment_name} is not configured")
+ parsed = urlparse(raw_dsn)
+ build_params = {
+ "hnsw": {"m": 16, "ef_construction": 64},
+ "hnsw-pq": {"m": 16, "ef_construction": 64, "pq_m": 8},
+ "hnsw-rabitq": {"m": 16, "ef_construction": 64, "rabitq_refine_type": "FP32"},
+ "ivfflat": {"lists": 1},
+ "ivf-pq": {"lists": 1, "pq_m": 8},
+ "ivf-rabitq": {"lists": 1},
+ "diskann": {"index_size": 50},
+ }[index_type]
+ return OpenGaussCollectionAdapter(
+ collection_name=f"ov_validation_{uuid.uuid4().hex[:8]}",
+ config=OpenGaussConfig(
+ host=parsed.hostname or "127.0.0.1",
+ port=parsed.port or 5432,
+ user=unquote(parsed.username or "gaussdb"),
+ password=unquote(parsed.password or ""),
+ db_name=parsed.path.lstrip("/") or "omm",
+ mode="distributed" if mode == "distributed" else "standalone",
+ shard_count=4,
+ index_type=index_type,
+ build_params=build_params,
+ search_params={"ef_search": 40} if index_type.startswith("hnsw") else {"probes": 8},
+ ),
+ )
+
+
+ "index_type",
+ ["hnsw", "hnsw-pq", "hnsw-rabitq", "ivfflat", "ivf-pq", "ivf-rabitq", "diskann"],
+)
+def test_standalone_real_index_and_ann_plan(index_type):
+ adapter = _adapter_from_dsn(index_type, "standalone")
+ collection_name = adapter._collection_name
+ try:
+ schema = {
+ "CollectionName": collection_name,
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "uri", "FieldType": "path"},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 8},
+ ],
+ "ScalarIndex": ["uri"],
+ }
+ assert adapter.create_collection(
+ collection_name,
+ schema,
+ distance="cosine",
+ sparse_weight=0,
+ index_name="default",
+ )
+ adapter.begin_bulk_ingest()
+ adapter.upsert(
+ [
+ {
+ "id": f"item-{number}",
+ "uri": f"viking://resources/{number}",
+ "vector": [float(number == position) for position in range(8)],
+ }
+ for number in range(8)
+ ]
+ )
+ adapter.end_bulk_ingest()
+ collection = adapter.get_collection()
+ assert collection.has_index("default")
+ fetched = adapter.get(["item-0"])
+ assert isinstance(fetched[0]["vector"], list)
+ assert len(fetched[0]["vector"]) == 8
+
+ cursor = adapter._conn.cursor()
+ cursor.execute(
+ "SELECT indexdef FROM pg_indexes WHERE schemaname=current_schema() AND tablename=%s AND indexname=%s",
+ (collection_name, f"idx_{collection_name}_default_vec"),
+ )
+ index_definition = cursor.fetchone()[0]
+ assert "USING " in index_definition
+ cursor.execute("SET enable_seqscan=off")
+ cursor.execute(
+ f'EXPLAIN SELECT id FROM "{collection_name}" ORDER BY vector <=> %s::vector LIMIT 3',
+ ("[1,0,0,0,0,0,0,0]",),
+ )
+ plan = "\n".join(row[0] for row in cursor.fetchall())
+ adapter._conn.commit()
+ cursor.close()
+ assert f"Ann Index Scan using idx_{collection_name}_default_vec" in plan
+ finally:
+ adapter.drop_collection()
+ adapter.close()
+
+
+def test_database_constraint_error_preserves_driver_cause():
+ adapter = _adapter_from_dsn("hnsw", "standalone")
+ name = adapter._collection_name
+ adapter._build_params = {"m": 1, "ef_construction": 64}
+ try:
+ with pytest.raises(RuntimeError, match="Failed to create openGauss ANN index") as caught:
+ adapter.create_collection(
+ name,
+ {
+ "CollectionName": name,
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 8},
+ ],
+ },
+ distance="cosine",
+ sparse_weight=0,
+ index_name="default",
+ )
+ cause = caught.value.__cause__
+ assert isinstance(cause, psycopg2.Error)
+ assert cause.pgcode
+ assert str(cause).strip() in str(caught.value)
+ finally:
+ adapter.close()
+
+
+def test_distributed_hnsw_real_catalog_and_plan():
+ adapter = _adapter_from_dsn("hnsw", "distributed")
+ collection_name = adapter._collection_name
+ try:
+ schema = {
+ "CollectionName": collection_name,
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 8},
+ ],
+ }
+ assert adapter.create_collection(
+ collection_name,
+ schema,
+ distance="cosine",
+ sparse_weight=0,
+ index_name="default",
+ )
+ adapter.upsert(
+ [
+ {
+ "id": f"item-{number}",
+ "vector": [float(number == position) for position in range(8)],
+ }
+ for number in range(8)
+ ]
+ )
+ cursor = adapter._conn.cursor()
+ cursor.execute(
+ "SELECT partmethod FROM pg_dist_partition WHERE logicalrelid=%s::regclass",
+ (collection_name,),
+ )
+ assert cursor.fetchone() is not None
+ cursor.execute("SET enable_seqscan=off")
+ cursor.execute(
+ f'EXPLAIN SELECT id FROM "{collection_name}" ORDER BY vector <=> %s::vector LIMIT 3',
+ ("[1,0,0,0,0,0,0,0]",),
+ )
+ plan = "\n".join(row[0] for row in cursor.fetchall())
+ adapter._conn.commit()
+ cursor.close()
+ assert "Ann Index Scan" in plan
+ finally:
+ adapter.drop_collection()
+ adapter.close()
+
+
+ ("index_type", "build_params"),
+ [
+ ("hnsw", {"enable_pq": True}),
+ ("hnsw", {"enable_rabitq": True}),
+ ("hnsw-pq", {"pq_m": 8}),
+ ("hnsw-rabitq", {"rabitq_refine_type": "FP32"}),
+ ("ivfflat", {"lists": 1}),
+ ("ivf-pq", {"lists": 1, "pq_m": 8}),
+ ("ivf-rabitq", {"lists": 1}),
+ ("diskann", {"index_size": 50}),
+ ],
+)
+def test_distributed_non_plain_hnsw_is_rejected_without_orphan_table(
+ index_type,
+ build_params,
+):
+ raw_dsn = os.getenv("OPENVIKING_OPENGAUSS_DISTRIBUTED_DSN")
+ if not raw_dsn:
+ pytest.skip("OPENVIKING_OPENGAUSS_DISTRIBUTED_DSN is not configured")
+ parsed = urlparse(raw_dsn)
+ collection_name = f"ov_validation_{uuid.uuid4().hex[:8]}"
+
+ with pytest.raises(
+ ValueError,
+ match="supports only plain HNSW",
+ ):
+ OpenGaussCollectionAdapter(
+ collection_name=collection_name,
+ config=OpenGaussConfig(
+ host=parsed.hostname or "127.0.0.1",
+ port=parsed.port or 5432,
+ user=unquote(parsed.username or "gaussdb"),
+ password=unquote(parsed.password or ""),
+ db_name=parsed.path.lstrip("/") or "postgres",
+ mode="distributed" if True else "standalone",
+ shard_count=4,
+ index_type=index_type,
+ build_params=build_params,
+ ),
+ )
+
+ connection = psycopg2.connect(raw_dsn)
+ cursor = connection.cursor()
+ cursor.execute(
+ "SELECT COUNT(*) FROM information_schema.tables "
+ "WHERE table_schema=current_schema() AND table_name=%s",
+ (collection_name,),
+ )
+ assert cursor.fetchone()[0] == 0
+ connection.commit()
+ cursor.close()
+ connection.close()
diff --git a/tests/vectordb/test_opengauss_integration.py b/tests/vectordb/test_opengauss_integration.py
new file mode 100644
index 000000000..e9af39f27
--- /dev/null
+++ b/tests/vectordb/test_opengauss_integration.py
@@ -0,0 +1,294 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import os
+import uuid
+from unittest.mock import patch
+from urllib.parse import unquote, urlparse
+
+import pytest
+
+from openviking.storage.expr import Or
+from openviking.storage.vectordb_adapters.opengauss_adapter import OpenGaussCollectionAdapter
+from openviking_cli.utils.config.vectordb_config import OpenGaussConfig
+
+pytestmark = pytest.mark.integration
+
+
+def _build_adapter(collection_name: str, **overrides) -> OpenGaussCollectionAdapter:
+ raw_dsn = os.getenv("OPENVIKING_OPENGAUSS_TEST_DSN") or os.getenv(
+ "OPENVIKING_OPENGAUSS_STANDALONE_DSN"
+ )
+ if not raw_dsn:
+ pytest.skip("OPENVIKING_OPENGAUSS_TEST_DSN is not configured")
+
+ parsed = urlparse(raw_dsn)
+ kwargs = {
+ "collection_name": collection_name,
+ "host": parsed.hostname or "127.0.0.1",
+ "port": parsed.port or 5432,
+ "user": unquote(parsed.username or "gaussdb"),
+ "password": unquote(parsed.password or ""),
+ "db_name": parsed.path.lstrip("/") or "postgres",
+ "index_name": "default",
+ "distance_metric": "cosine",
+ "index_type": "hnsw",
+ "build_params": {"m": 16, "ef_construction": 64},
+ "search_params": {"ef_search": 40},
+ }
+ kwargs.update(overrides)
+ adapter_args = {
+ key: kwargs.pop(key) for key in ("collection_name", "index_name", "distance_metric")
+ }
+ return OpenGaussCollectionAdapter(**adapter_args, config=OpenGaussConfig(**kwargs))
+
+
+def _context_schema(collection_name: str, dim: int = 3) -> dict:
+ return {
+ "CollectionName": collection_name,
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "uri", "FieldType": "path"},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": dim},
+ {"FieldName": "sparse_vector", "FieldType": "sparse_vector"},
+ {"FieldName": "created_at", "FieldType": "date_time"},
+ {"FieldName": "updated_at", "FieldType": "date_time"},
+ {"FieldName": "level", "FieldType": "int64"},
+ {"FieldName": "search_tags", "FieldType": "list<string>"},
+ {"FieldName": "abstract", "FieldType": "string"},
+ {"FieldName": "content", "FieldType": "text"},
+ {"FieldName": "account_id", "FieldType": "string"},
+ ],
+ "ScalarIndex": ["uri", "created_at", "level", "search_tags"],
+ }
+
+
+def _drop_quietly(adapter: OpenGaussCollectionAdapter | None) -> None:
+ if adapter is None:
+ return
+ try:
+ adapter.drop_collection()
+ except Exception:
+ pass
+ try:
+ adapter.close()
+ except Exception:
+ pass
+
+
+def test_opengauss_context_contract_and_dense_retrieval():
+ collection_name = f"ov_it_{uuid.uuid4().hex[:12]}"
+ adapter = _build_adapter(collection_name)
+ try:
+ schema = _context_schema(collection_name)
+ assert adapter.create_collection(
+ collection_name,
+ schema,
+ distance="cosine",
+ sparse_weight=0.0,
+ index_name="default",
+ )
+ # ``content`` is dropped above the adapter by the storage backend when
+ # ``USE_CONTENT_FIELD`` is False, so it never reaches ``adapter.upsert``.
+ adapter.upsert(
+ [
+ {
+ "id": "closest",
+ "uri": "viking://resources/demo/closest",
+ "vector": [1.0, 0.0, 0.0],
+ "sparse_vector": {"alpha": 0.8},
+ "created_at": "2026-01-01T00:00:00Z",
+ "updated_at": "2026-01-01T00:00:01Z",
+ "level": 1,
+ "search_tags": ["env=prod", "team=search"],
+ "abstract": "closest",
+ "account_id": "acct-1",
+ },
+ {
+ "id": "farther",
+ "uri": "viking://resources/demo/farther",
+ "vector": [0.0, 1.0, 0.0],
+ "sparse_vector": {"beta": 0.4},
+ "created_at": 1767225602000,
+ "updated_at": 1767225603000,
+ "level": 2,
+ "search_tags": ["env=dev"],
+ "abstract": "farther",
+ "account_id": "acct-1",
+ },
+ ]
+ )
+
+ fetched = adapter.get(["closest"])
+ assert fetched[0]["created_at"] == 1767225600000
+ assert fetched[0]["search_tags"] == ["env=prod", "team=search"]
+ assert fetched[0]["sparse_vector"] == {"alpha": 0.8}
+ assert "content" not in fetched[0]
+ assert isinstance(fetched[0]["vector"], list)
+ assert fetched[0]["vector"] == [1.0, 0.0, 0.0]
+
+ projected = adapter.query(
+ query_vector=[1.0, 0.0, 0.0],
+ limit=1,
+ output_fields=["id", "uri", "content", "vector", "account_id"],
+ )
+ assert projected[0]["id"] == "closest"
+ assert projected[0]["content"] is None
+ assert isinstance(projected[0]["vector"], list)
+ assert projected[0]["vector"] == [1.0, 0.0, 0.0]
+
+ results = adapter.query(
+ query_vector=[1.0, 0.0, 0.0],
+ limit=2,
+ output_fields=["uri", "level", "search_tags"],
+ )
+ assert [record["id"] for record in results] == ["closest", "farther"]
+ assert results[0]["_score"] > results[1]["_score"]
+ assert results[0]["_score"] == pytest.approx(1.0)
+
+ filtered = adapter.query(
+ query_vector=[1.0, 0.0, 0.0],
+ filter={
+ "op": "and",
+ "conds": [
+ {
+ "op": "must",
+ "field": "uri",
+ "conds": ["viking://resources/demo"],
+ "para": "-d=1",
+ },
+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},
+ {
+ "op": "range",
+ "field": "created_at",
+ "gte": "2026-01-01T00:00:00Z",
+ },
+ ],
+ },
+ limit=10,
+ output_fields=["uri", "search_tags"],
+ )
+ assert [record["id"] for record in filtered] == ["closest"]
+ assert adapter.count() == 2
+ assert (
+ adapter.query(
+ query_vector=[1.0, 0.0, 0.0],
+ filter=Or([]),
+ limit=100000,
+ output_fields=["id"],
+ )
+ == []
+ )
+
+ class _Embedding:
+ dimension = 3
+
+ class _Cfg:
+ embedding = _Embedding()
+
+ with patch(
+ "openviking.storage.vectordb_adapters.base.get_openviking_config",
+ return_value=_Cfg(),
+ ):
+ assert adapter.delete(filter=Or([])) == 0
+ assert adapter.count() == 2
+
+ cursor = adapter._conn.cursor()
+ cursor.execute(
+ "SELECT indexdef FROM pg_indexes WHERE tablename = %s AND indexdef ILIKE '%%USING hnsw%%'",
+ (collection_name,),
+ )
+ assert cursor.fetchone() is not None
+ cursor.close()
+
+ assert adapter.delete(ids=["farther"]) == 1
+ assert adapter.count() == 1
+ finally:
+ _drop_quietly(adapter)
+
+
+def test_opengauss_reconnect_rebuilds_distance_operator_class():
+ collection_name = f"ov_it_{uuid.uuid4().hex[:12]}"
+ original = _build_adapter(collection_name, distance_metric="cosine")
+ rebuilt = None
+ try:
+ assert original.create_collection(
+ collection_name,
+ _context_schema(collection_name),
+ distance="cosine",
+ sparse_weight=0.0,
+ index_name="default",
+ )
+ original.upsert(
+ [
+ {
+ "id": "item",
+ "uri": "viking://resources/demo/item",
+ "vector": [1.0, 0.0, 0.0],
+ "account_id": "acct-1",
+ }
+ ]
+ )
+ cursor = original._conn.cursor()
+ cursor.execute(
+ "SELECT indexdef FROM pg_indexes WHERE tablename=%s AND indexname=%s",
+ (collection_name, f"idx_{collection_name}_default_vec"),
+ )
+ assert "vector_cosine_ops" in cursor.fetchone()[0]
+ cursor.close()
+ original.close()
+ original = None
+
+ rebuilt = _build_adapter(collection_name, distance_metric="l2")
+ rebuilt.get_collection()
+ cursor = rebuilt._conn.cursor()
+ cursor.execute(
+ "SELECT indexdef FROM pg_indexes WHERE tablename=%s AND indexname=%s",
+ (collection_name, f"idx_{collection_name}_default_vec"),
+ )
+ definition = cursor.fetchone()[0]
+ cursor.close()
+ assert "vector_l2_ops" in definition
+ records = rebuilt.get(["item"])
+ assert isinstance(records[0]["vector"], list)
+ assert records[0]["vector"] == [1.0, 0.0, 0.0]
+ finally:
+ _drop_quietly(rebuilt)
+ _drop_quietly(original)
+
+
+def test_opengauss_long_collection_name_creates_bounded_index():
+ collection_name = ("c" + uuid.uuid4().hex + "x" * 20)[:50]
+ assert len(collection_name) == 50
+ adapter = _build_adapter(collection_name)
+ try:
+ assert adapter.create_collection(
+ collection_name,
+ _context_schema(collection_name),
+ distance="cosine",
+ sparse_weight=0.0,
+ index_name="default",
+ )
+ adapter.upsert(
+ [
+ {
+ "id": "item",
+ "uri": "viking://resources/demo/item",
+ "vector": [1.0, 0.0, 0.0],
+ }
+ ]
+ )
+ cursor = adapter._conn.cursor()
+ cursor.execute(
+ "SELECT indexname FROM pg_indexes WHERE schemaname=current_schema() AND tablename=%s",
+ (collection_name,),
+ )
+ index_names = [row[0] for row in cursor.fetchall()]
+ cursor.close()
+ assert index_names
+ assert all(len(name) <= 63 for name in index_names)
+ raw_vector_index = f"idx_{collection_name}_default_vec"
+ assert len(raw_vector_index) > 63
+ assert raw_vector_index not in index_names
+ finally:
+ _drop_quietly(adapter)
diff --git a/tests/vectordb/test_opengauss_review_regressions.py b/tests/vectordb/test_opengauss_review_regressions.py
new file mode 100644
index 000000000..876e546a0
--- /dev/null
+++ b/tests/vectordb/test_opengauss_review_regressions.py
@@ -0,0 +1,153 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Regression coverage for canonical options and distributed capability enforcement."""
+
+from unittest.mock import Mock, patch
+
+import pytest
+from pydantic import ValidationError
+
+from openviking.storage.vectordb_adapters.opengauss.collection import OpenGaussCollection
+from openviking.storage.vectordb_adapters.opengauss.metadata import migrate_persisted_index_meta
+from openviking.storage.vectordb_adapters.opengauss_adapter import OpenGaussCollectionAdapter
+from openviking_cli.utils.config.vectordb_config import OpenGaussConfig, VectorDBBackendConfig
+
+
[email protected]("flag", ["enable_pq", "enable_rabitq"])
+def test_distributed_flags_rejected_before_connection_or_ddl(flag):
+ with patch.object(OpenGaussCollectionAdapter, "_connect") as connect:
+ with pytest.raises(ValidationError, match="plain HNSW"):
+ VectorDBBackendConfig(
+ backend="opengauss",
+ dimension=512,
+ opengauss={
+ "mode": "distributed",
+ "index_type": "hnsw",
+ "build_params": {flag: True},
+ },
+ )
+ connect.assert_not_called()
+ coll = OpenGaussCollection.__new__(OpenGaussCollection)
+ coll._distributed = True
+ coll._distance = "cosine"
+ coll._name = "context"
+ coll._execute = Mock()
+ coll._materialize_index = Mock()
+ with pytest.raises(ValueError, match="plain HNSW"):
+ coll.create_index(
+ "default", {"VectorIndex": {"IndexType": "hnsw"}, "build_params": {flag: True}}
+ )
+ coll._execute.assert_not_called()
+ coll._materialize_index.assert_not_called()
+
+
+ "flag,expected", [("enable_pq", "hnsw-pq"), ("enable_rabitq", "hnsw-rabitq")]
+)
+def test_canonical_metadata_has_no_duplicate_options(flag, expected):
+ cfg = VectorDBBackendConfig(
+ backend="opengauss", opengauss={"build_params": {flag: True, "m": 16}}
+ )
+ with patch.object(OpenGaussCollectionAdapter, "_connect"):
+ adapter = OpenGaussCollectionAdapter.from_config(cfg)
+ meta = adapter._build_default_index_meta(
+ index_name="default",
+ distance="cosine",
+ use_sparse=False,
+ sparse_weight=0,
+ scalar_index_fields=[],
+ )
+ assert meta["VectorIndex"]["IndexType"] == expected
+ assert meta["build_params"] == {"m": 16}
+ assert "m" not in meta and flag not in meta
+ coll = OpenGaussCollection.__new__(OpenGaussCollection)
+ coll._name, coll._distance, coll._distributed = "context", "cosine", False
+ normalized = coll._normalized_index_meta("default", meta)
+ assert flag not in normalized["build_params"]
+ assert f"{flag} = on" in coll._create_index_sql(normalized)
+
+
+def test_alias_conflicts_are_rejected_and_aliases_normalized():
+ cfg = OpenGaussConfig(search_params={"hnsw_ef_search": 40})
+ assert cfg.search_params == {"ef_search": 40}
+ with pytest.raises(ValueError, match="Conflicting"):
+ OpenGaussConfig(search_params={"hnsw_ef_search": 40, "ef_search": 80})
+
+
+def test_persisted_aliases_are_consumed_only_at_read_boundary():
+ old = {
+ "VectorIndex": {"IndexType": "hnsw-pq"},
+ "m": 16,
+ "enable_pq": True,
+ "build_params": {"m": 32, "enable_pq": True, "parallel_workers": 4},
+ "ef_search": 40,
+ }
+ converted = migrate_persisted_index_meta(old)
+ assert converted["build_params"]["m"] == 32
+ assert converted["parallel_workers"] == 4
+ assert "m" not in converted and "enable_pq" not in converted
+ assert "parallel_workers" not in converted["build_params"]
+ coll = OpenGaussCollection.__new__(OpenGaussCollection)
+ coll._name, coll._distance, coll._distributed = "context", "cosine", False
+ with pytest.raises(ValueError, match="must be nested"):
+ coll.create_index("default", old)
+ normalized = coll._normalized_index_meta("default", converted)
+ assert normalized["build_params"] == {"m": 32}
+ assert normalized["search_params"] == {"ef_search": 40}
+ assert old["m"] == 16
+
+
+def test_adapter_copies_validated_config_without_reconstructing_it():
+ config = VectorDBBackendConfig(backend="opengauss", opengauss={"build_params": {"m": 16}})
+ with (
+ patch.object(OpenGaussCollectionAdapter, "_connect"),
+ patch.object(
+ OpenGaussConfig,
+ "__init__",
+ side_effect=AssertionError("must not revalidate complete config"),
+ ),
+ ):
+ adapter = OpenGaussCollectionAdapter.from_config(config)
+ config.opengauss.build_params["m"] = 32
+ assert adapter._build_params["m"] == 16
+
+
+ "params", [{"m": "16; DROP TABLE context"}, {"m": True}, {"m": float("nan")}, {"untrusted": 1}]
+)
+def test_raw_index_options_remain_validated(params):
+ with pytest.raises(ValueError):
+ OpenGaussConfig(build_params=params)
+
+
[email protected]("ids", [[], ["one", "two"]])
+def test_delete_ids_matches_upstream_contract(ids):
+ with patch.object(OpenGaussCollectionAdapter, "_connect"):
+ adapter = OpenGaussCollectionAdapter("context", OpenGaussConfig())
+ collection = Mock()
+ adapter.get_collection = Mock(return_value=collection)
+ adapter._conn = Mock()
+ assert adapter.delete(ids=ids, filter={"op": "must", "field": "id", "conds": ["other"]}) == len(
+ ids
+ )
+ adapter._conn.cursor.assert_not_called()
+ if ids:
+ collection.delete_data.assert_called_once_with(ids)
+ else:
+ collection.delete_data.assert_not_called()
+
+
+def test_filter_delete_has_no_implicit_row_limit():
+ with patch.object(OpenGaussCollectionAdapter, "_connect"):
+ adapter = OpenGaussCollectionAdapter("context", OpenGaussConfig())
+ collection = Mock()
+ collection.get_meta_data.return_value = {"Fields": []}
+ adapter.get_collection = Mock(return_value=collection)
+ adapter._conn = Mock()
+ cursor = adapter._conn.cursor.return_value
+ cursor.rowcount = 100001
+ assert (
+ adapter.delete(filter={"op": "must", "field": "account_id", "conds": ["tenant"]}) == 100001
+ )
+ assert cursor.execute.call_args.args[1] == ["tenant", None]
+ adapter._conn.commit.assert_called_once_with()
diff --git a/uv.lock b/uv.lock
index 6a1de2b61..24539213f 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3554,6 +3554,9 @@ local-embed = [
ocr = [
{ name = "pytesseract" },
]
+opengauss = [
+ { name = "psycopg2-binary" },
+]
test = [
{ name = "boto3" },
{ name = "datasets" },
@@ -3639,6 +3642,7 @@ requires-dist = [
{ name = "pdfplumber", specifier = ">=0.10.0" },
{ name = "prompt-toolkit", marker = "extra == 'bot'", specifier = ">=3.0.0" },
{ name = "protobuf", specifier = ">=6.33.5" },
+ { name = "psycopg2-binary", marker = "extra == 'opengauss'", specifier = ">=2.9,<3" },
{ name = "py-machineid", marker = "extra == 'bot'", specifier = ">=1.0.0" },
{ name = "pydantic", specifier = ">=2.0.0" },
{ name = "pydantic-settings", marker = "extra == 'bot'", specifier = ">=2.0.0" },
@@ -3701,8 +3705,7 @@ requires-dist = [
{ name = "wheel", marker = "extra == 'build'" },
{ name = "xxhash", specifier = ">=3.0.0" },
]
-provides-extras = ["test", "auth", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "benchmark", "local-embed"]
-
+provides-extras = ["test", "auth", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "benchmark", "local-embed", "opengauss"]
[package.metadata.requires-dev]
dev = [{ name = "pytest", specifier = ">=9.0.2" }]
@@ -4349,6 +4352,69 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/57/bf/2086963c69bdac3d7cff1cc7ff79b8ce5ea0bec6797a017e1be338a46248/protobuf-6.33.5-py3-none-any.whl", hash = "sha256:69915a973dd0f60f31a08b8318b73eab2bd6a392c79184b3612226b0a3f8ec02", size = 170687, upload-time = "2026-01-29T21:51:32.557Z" },
]
+[[package]]
+name = "psycopg2-binary"
+version = "2.9.12"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2a/60/a3624f79acea344c16fbef3a94d28b89a8042ddfb8f3e4ca83f538671409/psycopg2_binary-2.9.12.tar.gz", hash = "sha256:5ac9444edc768c02a6b6a591f070b8aae28ff3a99be57560ac996001580f294c", size = 379686, upload-time = "2026-04-21T09:40:34.304Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/78/80/49bacf9e51617d8309f6f0123e29edc793f6f5f6700c7d1f1b20782fbb37/psycopg2_binary-2.9.12-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:9b818ceff717f98851a64bffd4c5eb5b3059ae280276dcecc52ac658dcf006a4", size = 3712314, upload-time = "2026-04-20T23:33:31.363Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/f2/98eeac7d60c43df9338287834edf9b3e69be68a2db78a57b1b81d705e735/psycopg2_binary-2.9.12-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d2fa0d7caca8635c56e373055094eeda3208d901d55dd0ff5abc1d4e47f82b56", size = 3822389, upload-time = "2026-04-20T23:33:34.178Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/7c/30575e75f14d5351a56a1971bb43fe7f8bf7edf1b654fb1bec65c42a8812/psycopg2_binary-2.9.12-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:864c261b3690e1207d14bbfe0a61e27567981b80c47a778561e49f676f7ce433", size = 4578448, upload-time = "2026-04-20T23:33:37.073Z" },
+ { url = "https://files.pythonhosted.org/packages/65/9b/4df366d89f28c527dc39d0b6c98a5ca74e30d37ac097b73f3352147568ae/psycopg2_binary-2.9.12-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c5ee5213445dd45312459029b8c4c0a695461eb517b753d2582315bd07995f5e", size = 4273705, upload-time = "2026-04-20T23:33:39.291Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/8a/c566803818eb03161ba869b6ba612bf7ad56816d98b9e5121e0a22ad6b0b/psycopg2_binary-2.9.12-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6f9cae1f848779b5b01f417e762c40d026ea93eb0648249a604728cda991dde3", size = 5893784, upload-time = "2026-04-20T23:33:41.658Z" },
+ { url = "https://files.pythonhosted.org/packages/63/fe/0dfa5797e0b229e0567bc378695224caf14d547f73b05be0c80549089772/psycopg2_binary-2.9.12-cp310-cp310-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:63a3ebbd543d3d1eda088ac99164e8c5bac15293ee91f20281fd17d050aee1c4", size = 4109306, upload-time = "2026-04-20T23:33:43.953Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/89/28063adf17a4ba501eedd9890feab0c649ee4d8bd0a97df0ff1e9584feab/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:d6fcbba8c9fed08a73b8ac61ea79e4821e45b1e92bb466230c5e746bbf3d5256", size = 3654400, upload-time = "2026-04-20T23:33:46.115Z" },
+ { url = "https://files.pythonhosted.org/packages/84/94/5a01de0aa4ead0b8d8d1aa4ec18cec0bd36d03fa714eaa5bb8a0b1b50020/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:36512911ebb2b60a0c3e44d0bb5048c1980aced91235d133b7874f3d1d93487c", size = 3299215, upload-time = "2026-04-20T23:33:48.202Z" },
+ { url = "https://files.pythonhosted.org/packages/7a/85/723bb085a61c6ac2dc0a0043f375f2fe7365363e27b073bad56ca5bda979/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:8ffdb59fe88f99589e34354a130217aa1fd2d615612402d6edc8b3dbc7a44463", size = 3047724, upload-time = "2026-04-20T23:33:50.74Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/67/4d8b1e0d2fc4166677380eac0edf9cdff91013aca2546e8ef7bc04b56158/psycopg2_binary-2.9.12-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:a46fe069b65255df410f856d842bc235f90e22ffdf532dda625fd4213d3fd9b1", size = 3349183, upload-time = "2026-04-20T23:33:59.635Z" },
+ { url = "https://files.pythonhosted.org/packages/73/99/21af7a5498637ea4dc91a17c281a53bc1d632fbafe00f6689fbfb32a9fed/psycopg2_binary-2.9.12-cp310-cp310-win_amd64.whl", hash = "sha256:ab29414b25dcb698bf26bf213e3348abdcd07bbd5de032a5bec15bd75b298b03", size = 2757036, upload-time = "2026-04-20T23:34:01.606Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/19/d4ce60954f3bb9d8e3bc5e5c4d1f2487de2d3851bf2391d54954c9df12a6/psycopg2_binary-2.9.12-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5c8ce6c61bd1b1f6b9c24ee32211599f6166af2c55abb19456090a21fd16554b", size = 3712338, upload-time = "2026-04-20T23:34:03.961Z" },
+ { url = "https://files.pythonhosted.org/packages/53/71/c85409ee0d78890f0660eff262e815e7dd2bb741a17611d82e9e8cd9dc5e/psycopg2_binary-2.9.12-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b4a9eaa6e7f4ff91bec10aa3fb296878e75187bced5cc4bafe17dc40915e1326", size = 3822407, upload-time = "2026-04-20T23:34:05.977Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/ed/60486c2c7f0d4d1ede2bfb1ed27e2498477ce646bc7f6b2759906303117e/psycopg2_binary-2.9.12-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:c6528cefc8e50fcc6f4a107e27a672058b36cc5736d665476aeb413ba88dbb06", size = 4578425, upload-time = "2026-04-20T23:34:08.246Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/b9/656cb03fad9f4f49f2145c334b1126ee75189929ca4e6187d485a2d59951/psycopg2_binary-2.9.12-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e4e184b1fb6072bf05388aa41c697e1b2d01b3473f107e7ec44f186a32cfd0b8", size = 4273709, upload-time = "2026-04-20T23:34:10.974Z" },
+ { url = "https://files.pythonhosted.org/packages/99/66/08cf0da0e25cc6fb142c89be45fc8418792858f0c4cbff5e24530ff02cd6/psycopg2_binary-2.9.12-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4766ab678563054d3f1d064a4db19cc4b5f9e3a8d9018592a8285cf200c248f3", size = 5893779, upload-time = "2026-04-20T23:34:13.905Z" },
+ { url = "https://files.pythonhosted.org/packages/17/d7/eecd9ce8e146d3721115d82d3836efdbb712187e4590325df549989d18f4/psycopg2_binary-2.9.12-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5a0253224780c978746cb9be55a946bcdaf40fe3519c0f622924cdabdafe2c39", size = 4109308, upload-time = "2026-04-20T23:34:16.761Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/2e/b1dc289b362cc8d45697b57eefbd673186f49a4ea0906928988e3affcc98/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0dc9228d47c46bda253d2ecd6bb93b56a9f2d7ad33b684a1fa3622bf74ffe30c", size = 3654405, upload-time = "2026-04-20T23:34:19.303Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/e4/4c4aea6473214dbdbd0fbba11aa4691e76dc01722c55724c5951719865ff/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f921f3cd87035ef7df233383011d7a53ea1d346224752c1385f1edfd790ceb6a", size = 3299187, upload-time = "2026-04-20T23:34:21.206Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/5d/b03b99986446a4f57b170ed9a2579fb7ff9783ca0fa5226b19db99737fee/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3d999bd982a723113c1a45b55a7a6a90d64d0ed2278020ed625c490ff7bef96c", size = 3047716, upload-time = "2026-04-20T23:34:23.077Z" },
+ { url = "https://files.pythonhosted.org/packages/14/86/382ee4afbd1d97500c9d2862b20c2fdeddf4b7335e984df3fb4309f64108/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:29d4d134bd0ab46ffb04e94aa3c5fa3ef582e9026609165e2f758ff76fc3a3be", size = 3349237, upload-time = "2026-04-20T23:34:25.211Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/16/9a57c75ba1eda7165c017342f526810d5f5a12647dde749c99ae9a7141d7/psycopg2_binary-2.9.12-cp311-cp311-win_amd64.whl", hash = "sha256:cb4a1dacdd48077150dc762a9e5ddbf32c256d66cb46f80839391aa458774936", size = 2757036, upload-time = "2026-04-20T23:34:27.77Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/9f/ef4ef3c8e15083df90ca35265cfd1a081a2f0cc07bb229c6314c6af817f4/psycopg2_binary-2.9.12-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5cdc05117180c5fa9c40eea8ea559ce64d73824c39d928b7da9fb5f6a9392433", size = 3712459, upload-time = "2026-04-20T23:34:30.549Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/01/3dd14e46ba48c1e1a6ec58ee599fa1b5efa00c246d5046cd903d0eeb1af1/psycopg2_binary-2.9.12-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d3227a3bc228c10d21011a99245edca923e4e8bf461857e869a507d9a41fe9f6", size = 3822936, upload-time = "2026-04-20T23:34:32.77Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/f7/0640e4901119d8a9f7a1784b927f494e2198e213ceb593753d1f2c8b1b30/psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:995ce929eede89db6254b50827e2b7fd61e50d11f0b116b29fffe4a2e53c4580", size = 4578676, upload-time = "2026-04-20T23:34:35.18Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/55/44df3965b5f297c50cc0b1b594a31c67d6127a9d133045b8a66611b14dfb/psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9fe06d93e72f1c048e731a2e3e7854a5bfaa58fc736068df90b352cefe66f03f", size = 4274917, upload-time = "2026-04-20T23:34:37.982Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/4b/74535248b1eac0c9336862e8617c765ac94dac76f9e25d7c4a79588c8907/psycopg2_binary-2.9.12-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40e7b28b63aaf737cb3a1edc3a9bbc9a9f4ad3dcb7152e8c1130e4050eddcb7d", size = 5894843, upload-time = "2026-04-20T23:34:40.856Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/ba/f1bf8d2ae71868ad800b661099086ee52bc0f8d9f05be1acd8ebb06757cc/psycopg2_binary-2.9.12-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:89d19a9f7899e8eb0656a2b3a08e0da04c720a06db6e0033eab5928aabe60fa9", size = 4110556, upload-time = "2026-04-20T23:34:44.016Z" },
+ { url = "https://files.pythonhosted.org/packages/45/46/c15706c338403b7c420bcc0c2905aad116cc064545686d8bf85f1999ea00/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:612b965daee295ae2da8f8218ce1d274645dc76ef3f1abf6a0a94fd57eff876d", size = 3655714, upload-time = "2026-04-20T23:34:46.233Z" },
+ { url = "https://files.pythonhosted.org/packages/b3/7c/a2d5dc09b64a4564db242a0fe418fde7d33f6f8259dd2c5b9d7def00fb5a/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b9a339b79d37c1b45f3235265f07cdeb0cb5ad7acd2ac7720a5920989c17c24e", size = 3301154, upload-time = "2026-04-20T23:34:49.528Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/e8/cc8c9a4ce71461f9ec548d38cadc41dc184b34c73e6455450775a9334ccd/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:3471336e1acfd9c7fe507b8bad5af9317b6a89294f9eb37bd9a030bb7bebcdc6", size = 3048882, upload-time = "2026-04-20T23:34:51.86Z" },
+ { url = "https://files.pythonhosted.org/packages/19/6a/31e2296bc0787c5ab75d3d118e40b239db8151b5192b90b77c72bc9256e9/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7af18183109e23502c8b2ae7f6926c0882766f35b5175a4cd737ad825e4d7a1b", size = 3351298, upload-time = "2026-04-20T23:34:54.124Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/a8/75f4e3e11203b590150abed2cf7794b9c9c9f7eceddae955191138b44dde/psycopg2_binary-2.9.12-cp312-cp312-win_amd64.whl", hash = "sha256:398fcd4db988c7d7d3713e2b8e18939776fd3fb447052daae4f24fa39daede4c", size = 2757230, upload-time = "2026-04-20T23:34:56.242Z" },
+ { url = "https://files.pythonhosted.org/packages/91/bb/4608c96f970f6e0c56572e87027ef4404f709382a3503e9934526d7ba051/psycopg2_binary-2.9.12-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7c729a73c7b1b84de3582f73cdd27d905121dc2c531f3d9a3c32a3011033b965", size = 3712419, upload-time = "2026-04-20T23:34:58.754Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/af/48f76af9d50d61cf390f8cd657b503168b089e2e9298e48465d029fcc713/psycopg2_binary-2.9.12-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4413d0caef93c5cf50b96863df4c2efe8c269bf2267df353225595e7e15e8df7", size = 3822990, upload-time = "2026-04-20T23:35:00.821Z" },
+ { url = "https://files.pythonhosted.org/packages/7a/df/aba0f99397cd811d32e06fc0cc781f1f3ce98bc0e729cb423925085d781a/psycopg2_binary-2.9.12-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4dfcf8e45ebb0c663be34a3442f65e17311f3367089cd4e5e3a3e8e62c978777", size = 4578696, upload-time = "2026-04-20T23:35:03.409Z" },
+ { url = "https://files.pythonhosted.org/packages/95/9c/eaa74021ac4e4d5c2f83d82fc6615a63f4fe6c94dc4e94c3990427053f67/psycopg2_binary-2.9.12-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c41321a14dd74aceb6a9a643b9253a334521babfa763fa873e33d89cfa122fb5", size = 4274982, upload-time = "2026-04-20T23:35:05.583Z" },
+ { url = "https://files.pythonhosted.org/packages/35/ed/c25deff98bd26187ba48b3b250a3ffc3037c46c5b89362534a15d200e0db/psycopg2_binary-2.9.12-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:83946ba43979ebfdc99a3cd0ee775c89f221df026984ba19d46133d8d75d3cd9", size = 5894867, upload-time = "2026-04-20T23:35:07.902Z" },
+ { url = "https://files.pythonhosted.org/packages/9a/81/8d0e21ca77373c6c9589e5c4528f6e8f0c08c62cafc76fb0bddb7a2cee22/psycopg2_binary-2.9.12-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:411e85815652d13560fbe731878daa5d92378c4995a22302071890ec3397d019", size = 4110578, upload-time = "2026-04-20T23:35:10.149Z" },
+ { url = "https://files.pythonhosted.org/packages/00/fc/f481e2435bd8f742d0123309174aae4165160ad3ef17c1b99c3622c241d2/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c8ad4c08e00f7679559eaed7aff1edfffc60c086b976f93972f686384a95e2c", size = 3655816, upload-time = "2026-04-20T23:35:12.56Z" },
+ { url = "https://files.pythonhosted.org/packages/53/79/b9f46466bdbe9f239c96cde8be33c1aace4842f06013b47b730dc9759187/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:00814e40fa23c2b37ef0a1e3c749d89982c73a9cb5046137f0752a22d432e82f", size = 3301307, upload-time = "2026-04-20T23:35:15.029Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/19/7dc003b32fe35024df89b658104f7c8538a8b2dcbde7a4e746ce929742e7/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:98062447aebc20ed20add1f547a364fd0ef8933640d5372ff1873f8deb9b61be", size = 3048968, upload-time = "2026-04-20T23:35:16.757Z" },
+ { url = "https://files.pythonhosted.org/packages/91/58/2dbd7db5c604d45f4950d988506aae672a14126ec22998ced5021cbb76bb/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:66a7685d7e548f10fb4ce32fb01a7b7f4aa702134de92a292c7bd9e0d3dbd290", size = 3351369, upload-time = "2026-04-20T23:35:18.933Z" },
+ { url = "https://files.pythonhosted.org/packages/42/ee/dee8dcaad07f735824de3d6563bc67119fa6c28257b17977a8d624f02fab/psycopg2_binary-2.9.12-cp313-cp313-win_amd64.whl", hash = "sha256:b6937f5fe4e180aeee87de907a2fa982ded6f7f15d7218f78a083e4e1d68f2a0", size = 2757347, upload-time = "2026-04-20T23:35:21.283Z" },
+ { url = "https://files.pythonhosted.org/packages/13/1b/708c0dca874acfad6d65314271859899a79007686f3a1f74e82a2ed4b645/psycopg2_binary-2.9.12-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6f3b3de8a74ef8db215f22edffb19e32dc6fa41340456de7ec99efdc8a7b3ec2", size = 3712428, upload-time = "2026-04-20T23:35:23.453Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/39/ddbea9d4b4de6aca9431b6ed253f530f8a02d3b8f9bcfd0dbfe2b3de6fe4/psycopg2_binary-2.9.12-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1006fb62f0f0bc5ce256a832356c6262e91be43f5e4eb15b5eaf38079464caf2", size = 3823184, upload-time = "2026-04-20T23:35:25.92Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/a0/bc2fef74b106fa345567122a0659e6d94512ed7dc0131ec44c9e5aba3725/psycopg2_binary-2.9.12-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:840066105706cd2eb29b9a1c2329620056582a4bf3e8169dec5c447042d0869f", size = 4579157, upload-time = "2026-04-20T23:35:28.542Z" },
+ { url = "https://files.pythonhosted.org/packages/57/d7/d4e3b2005d3de607ca4fbb0e8742e248056e52184a6b94ebda3c1c2c329b/psycopg2_binary-2.9.12-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:863f5d12241ebe1c76a72a04c2113b6dc905f90b9cef0e9be0efd994affd9354", size = 4274970, upload-time = "2026-04-20T23:35:30.418Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/42/c9853f8db3967fe08bcde11f53d53b85d351750cae726ce001cb68afa9c1/psycopg2_binary-2.9.12-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a99eaab34a9010f1a086b126de467466620a750634d114d20455f3a824aae033", size = 5895175, upload-time = "2026-04-20T23:35:33.584Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/fd/b82b5601a97630308bef079f545ffec481bbbc795c2ba5ec416a01d03f60/psycopg2_binary-2.9.12-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ffdd7dc5463ccd61845ac37b7012d0f35a1548df9febe14f8dd549be4a0bc81e", size = 4110658, upload-time = "2026-04-20T23:35:35.638Z" },
+ { url = "https://files.pythonhosted.org/packages/62/8c/32ca69b0389ef25dd22937bf9e8fbe2ce27aea20b05ded48c4ce4cb42475/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:54a0dfecab1b48731f934e06139dfe11e24219fb6d0ceb32177cf0375f14c7b5", size = 3656251, upload-time = "2026-04-20T23:35:37.854Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/29/96992a2b59e3b9d730fcf9612d0a387305025dc867a9fc490a9e496e074e/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:96937c9c5d891f772430f418a7a8b4691a90c3e6b93cf72b5bd7cad8cbca32a5", size = 3301810, upload-time = "2026-04-20T23:35:39.927Z" },
+ { url = "https://files.pythonhosted.org/packages/56/ad/44b06659949b243ae10112cd3b20a197f9bf3e81d5651379b9eb889bfaad/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:77b348775efd4cdab410ec6609d81ccecd1139c90265fa583a7255c8064bc03d", size = 3048977, upload-time = "2026-04-20T23:35:41.806Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/f2/10a1bcebadb6aa55e280e1f58975c36a7b560ea525184c7aa4064c466633/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:527e6342b3e44c2f0544f6b8e927d60de7f163f5723b8f1dfa7d2a84298738cd", size = 3351466, upload-time = "2026-04-20T23:35:43.993Z" },
+ { url = "https://files.pythonhosted.org/packages/20/be/b732c8418ffa5bcfda002890f5dc4c869fc17db66ff11f53b17cfe44afc0/psycopg2_binary-2.9.12-cp314-cp314-win_amd64.whl", hash = "sha256:f12ae41fcafadb39b2785e64a40f9db05d6de2ac114077457e0e7c597f3af980", size = 2848762, upload-time = "2026-04-20T23:35:46.421Z" },
+]
+
[[package]]
name = "py"
version = "1.11.0"