Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(pgvector): address security, reliability, and test issues from review

Sameer630595322df8e033
diff --git a/pyproject.toml b/pyproject.toml
index 0fd96604..4491c28e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -128,7 +128,7 @@ vectorstore-qdrant = ["qdrant-client>=1.0.0"]
vectorstore-weaviate = ["weaviate-client>=4.0.0"]
vectorstore-pinecone = ["pinecone-client>=3.0.0"]
vectorstore-milvus = ["pymilvus>=2.0.0"]
-vectorstore-pgvector = ["psycopg[binary]>=3.0.0", "psycopg2-binary>=2.9.0", "pgvector>=0.2.0"]
+vectorstore-pgvector = ["psycopg[binary,pool]>=3.0.0", "psycopg2-binary>=2.9.0", "pgvector>=0.2.0"]
vectorstore-all = [
"semantica[vectorstore-qdrant,vectorstore-weaviate,vectorstore-pinecone,vectorstore-milvus,vectorstore-pgvector]"
diff --git a/semantica/vector_store/pgvector_store.py b/semantica/vector_store/pgvector_store.py
index 8f778b81..aea3642d 100644
--- a/semantica/vector_store/pgvector_store.py
+++ b/semantica/vector_store/pgvector_store.py
@@ -34,6 +34,8 @@ License: MIT
"""
import json
+import re
+import uuid
from contextlib import contextmanager
from typing import Any, Dict, List, Optional, Union
@@ -45,6 +47,7 @@ from ..utils.logging import get_logger
# Optional psycopg imports - prefer psycopg3, fallback to psycopg2
try:
import psycopg
+ from psycopg import sql as psycopg_sql
from psycopg_pool import ConnectionPool
PSYCOPG3_AVAILABLE = True
@@ -54,6 +57,7 @@ except (ImportError, OSError):
try:
import psycopg2
from psycopg2 import pool
+ from psycopg2 import sql as psycopg_sql
PSYCOPG2_AVAILABLE = True
except (ImportError, OSError):
@@ -63,11 +67,13 @@ except (ImportError, OSError):
# Optional pgvector import
try:
import pgvector
+ from pgvector.psycopg import register_vector
PGVECTOR_AVAILABLE = True
except (ImportError, OSError):
PGVECTOR_AVAILABLE = False
pgvector = None
+ register_vector = None
class PgVectorStore:
@@ -171,7 +177,7 @@ class PgVectorStore:
)
self.logger.debug("Connection pool initialized")
except Exception as e:
- raise ProcessingError(f"Failed to initialize connection pool: {str(e)}")
+ raise ProcessingError("Failed to initialize database connection pool") from e
@contextmanager
def _get_connection(self):
@@ -182,11 +188,17 @@ class PgVectorStore:
conn = self._pool.getconn()
else:
conn = self._pool.getconn()
+ # Register pgvector adapters for this connection
+ if register_vector:
+ register_vector(conn)
yield conn
+ except (ValidationError, ProcessingError):
+ # Re-raise framework exceptions without wrapping
+ raise
except Exception as e:
if conn:
conn.rollback()
- raise ProcessingError(f"Database connection error: {str(e)}")
+ raise ProcessingError("Database connection error") from e
finally:
if conn:
if PSYCOPG3_AVAILABLE:
@@ -212,29 +224,47 @@ class PgVectorStore:
except Exception as e:
if "pgvector extension is not installed" in str(e):
raise
- raise ProcessingError(f"Failed to verify pgvector extension: {str(e)}")
+ raise ProcessingError("Failed to verify pgvector extension") from e
def _ensure_table_exists(self):
"""Ensure the vector table exists."""
- create_table_sql = f"""
- CREATE TABLE IF NOT EXISTS {self.table_name} (
- id TEXT PRIMARY KEY,
- vector VECTOR({self.dimension}),
- metadata JSONB DEFAULT '{{}}',
- created_at TIMESTAMP DEFAULT NOW()
+ # Use safe SQL composition with identifiers
+ if PSYCOPG3_AVAILABLE:
+ create_table_sql = psycopg_sql.SQL("""
+ CREATE TABLE IF NOT EXISTS {} (
+ id TEXT PRIMARY KEY,
+ vector VECTOR({}),
+ metadata JSONB DEFAULT '{{}}',
+ created_at TIMESTAMP DEFAULT NOW()
+ )
+ """).format(
+ psycopg_sql.Identifier(self.table_name),
+ psycopg_sql.Literal(self.dimension)
)
- """
+ else:
+ # psycopg2 requires different approach - use %s for literals in composition
+ create_table_sql = psycopg_sql.SQL("""
+ CREATE TABLE IF NOT EXISTS {} (
+ id TEXT PRIMARY KEY,
+ vector VECTOR(%s),
+ metadata JSONB DEFAULT '{{}}',
+ created_at TIMESTAMP DEFAULT NOW()
+ )
+ """).format(psycopg_sql.Identifier(self.table_name))
with self._get_connection() as conn:
try:
cur = conn.cursor()
- cur.execute(create_table_sql)
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(create_table_sql)
+ else:
+ cur.execute(create_table_sql, (self.dimension,))
conn.commit()
cur.close()
self.logger.debug(f"Table {self.table_name} ensured")
except Exception as e:
conn.rollback()
- raise ProcessingError(f"Failed to create table: {str(e)}")
+ raise ProcessingError("Failed to create table") from e
def add(
self,
@@ -271,15 +301,9 @@ class PgVectorStore:
f"expected {self.dimension}"
)
- # Generate IDs if not provided
+ # Generate IDs if not provided - use UUID4 for collision safety
if ids is None:
- # Get current count for sequential IDs
- with self._get_connection() as conn:
- cur = conn.cursor()
- cur.execute(f"SELECT COUNT(*) FROM {self.table_name}")
- count = cur.fetchone()[0]
- cur.close()
- ids = [f"vec_{count + i}" for i in range(num_vectors)]
+ ids = [str(uuid.uuid4()) for _ in range(num_vectors)]
# Prepare metadata
if metadata is None:
@@ -289,28 +313,43 @@ class PgVectorStore:
f"Metadata length ({len(metadata)}) must match vectors length ({num_vectors})"
)
- # Batch insert
- insert_sql = f"""
- INSERT INTO {self.table_name} (id, vector, metadata)
- VALUES (%s, %s, %s)
- ON CONFLICT (id) DO UPDATE SET
- vector = EXCLUDED.vector,
- metadata = EXCLUDED.metadata
- """
+ # Batch insert using safe SQL composition
+ if PSYCOPG3_AVAILABLE:
+ insert_sql = psycopg_sql.SQL("""
+ INSERT INTO {} (id, vector, metadata)
+ VALUES (%s, %s, %s)
+ ON CONFLICT (id) DO UPDATE SET
+ vector = EXCLUDED.vector,
+ metadata = EXCLUDED.metadata
+ """).format(psycopg_sql.Identifier(self.table_name))
+ else:
+ insert_sql = """
+ INSERT INTO {} (id, vector, metadata)
+ VALUES (%s, %s, %s)
+ ON CONFLICT (id) DO UPDATE SET
+ vector = EXCLUDED.vector,
+ metadata = EXCLUDED.metadata
+ """.format(psycopg_sql.Identifier(self.table_name))
with self._get_connection() as conn:
try:
cur = conn.cursor()
for vec_id, vec, meta in zip(ids, vectors, metadata):
vec_list = vec.tolist() if isinstance(vec, np.ndarray) else list(vec)
- cur.execute(insert_sql, (vec_id, vec_list, json.dumps(meta)))
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(insert_sql, (vec_id, vec_list, json.dumps(meta)))
+ else:
+ cur.execute(insert_sql, (vec_id, vec_list, json.dumps(meta)))
conn.commit()
cur.close()
self.logger.info(f"Added {num_vectors} vectors")
return ids
+ except (ValidationError, ProcessingError):
+ conn.rollback()
+ raise
except Exception as e:
conn.rollback()
- raise ProcessingError(f"Failed to add vectors: {str(e)}")
+ raise ProcessingError("Failed to add vectors") from e
def search(
self,
@@ -350,35 +389,79 @@ class PgVectorStore:
query_list = query_vector.tolist() if isinstance(query_vector, np.ndarray) else list(query_vector)
if filter:
- # Build metadata filter condition
+ # Build metadata filter condition with safe key validation
filter_conditions = []
filter_values = []
for key, value in filter.items():
- filter_conditions.append(f"metadata->>{key} = %s")
+ # Validate key is safe to prevent SQL injection
+ if not self._is_safe_identifier(key):
+ raise ValidationError(
+ f"Invalid filter key: {key!r}. "
+ "Keys must be alphanumeric with underscores/hyphens only."
+ )
+ filter_conditions.append(psycopg_sql.SQL("metadata->>{} = %s").format(
+ psycopg_sql.Literal(key)
+ ))
filter_values.append(str(value))
- where_clause = " AND ".join(filter_conditions)
- search_sql = f"""
- SELECT id, vector {op} %s::vector AS score, metadata
- FROM {self.table_name}
- WHERE {where_clause}
- ORDER BY vector {op} %s::vector
- LIMIT %s
- """
+ where_clause = psycopg_sql.SQL(" AND ").join(filter_conditions)
+
+ if PSYCOPG3_AVAILABLE:
+ search_sql = psycopg_sql.SQL("""
+ SELECT id, vector {op} %s::vector AS score, metadata
+ FROM {table}
+ WHERE {where}
+ ORDER BY vector {op} %s::vector
+ LIMIT %s
+ """).format(
+ op=psycopg_sql.SQL(op),
+ table=psycopg_sql.Identifier(self.table_name),
+ where=where_clause
+ )
+ else:
+ # psycopg2: format table name, embed operator directly
+ search_sql = psycopg_sql.SQL("""
+ SELECT id, vector {op} %s::vector AS score, metadata
+ FROM {table}
+ WHERE {where}
+ ORDER BY vector {op} %s::vector
+ LIMIT %s
+ """).format(
+ op=psycopg_sql.SQL(op),
+ table=psycopg_sql.Identifier(self.table_name),
+ where=where_clause
+ )
params = [query_list] + filter_values + [query_list, top_k]
else:
- search_sql = f"""
- SELECT id, vector {op} %s::vector AS score, metadata
- FROM {self.table_name}
- ORDER BY vector {op} %s::vector
- LIMIT %s
- """
+ if PSYCOPG3_AVAILABLE:
+ search_sql = psycopg_sql.SQL("""
+ SELECT id, vector {op} %s::vector AS score, metadata
+ FROM {table}
+ ORDER BY vector {op} %s::vector
+ LIMIT %s
+ """).format(
+ op=psycopg_sql.SQL(op),
+ table=psycopg_sql.Identifier(self.table_name)
+ )
+ else:
+ search_sql = psycopg_sql.SQL("""
+ SELECT id, vector {op} %s::vector AS score, metadata
+ FROM {table}
+ ORDER BY vector {op} %s::vector
+ LIMIT %s
+ """).format(
+ op=psycopg_sql.SQL(op),
+ table=psycopg_sql.Identifier(self.table_name)
+ )
params = [query_list, query_list, top_k]
with self._get_connection() as conn:
try:
cur = conn.cursor()
- cur.execute(search_sql, params)
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(search_sql, params)
+ else:
+ cur.execute(search_sql, params)
rows = cur.fetchall()
cur.close()
@@ -400,8 +483,25 @@ class PgVectorStore:
})
return results
+ except (ValidationError, ProcessingError):
+ raise
except Exception as e:
- raise ProcessingError(f"Failed to search vectors: {str(e)}")
+ raise ProcessingError("Failed to search vectors") from e
+
+ def _is_safe_identifier(self, key: str) -> bool:
+ """
+ Validate that a string is safe to use as a SQL/jsonb identifier.
+
+ Only allows alphanumeric characters, underscores, and hyphens.
+ Rejects any string that could be used for SQL injection.
+ """
+ if not isinstance(key, str):
+ return False
+ if not key:
+ return False
+ # Only allow: alphanumeric, underscore, hyphen
+ # Must start with letter or underscore
+ return bool(re.match(r'^[a-zA-Z_][a-zA-Z0-9_-]*$', key))
def delete(self, ids: List[str]) -> bool:
"""
@@ -419,20 +519,34 @@ class PgVectorStore:
if not ids:
return True
- delete_sql = f"DELETE FROM {self.table_name} WHERE id = ANY(%s)"
+ # Use safe SQL composition for table name
+ if PSYCOPG3_AVAILABLE:
+ delete_sql = psycopg_sql.SQL("DELETE FROM {} WHERE id = ANY(%s)").format(
+ psycopg_sql.Identifier(self.table_name)
+ )
+ else:
+ delete_sql = psycopg_sql.SQL("DELETE FROM {} WHERE id = ANY(%s)").format(
+ psycopg_sql.Identifier(self.table_name)
+ )
with self._get_connection() as conn:
try:
cur = conn.cursor()
- cur.execute(delete_sql, (ids,))
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(delete_sql, (ids,))
+ else:
+ cur.execute(delete_sql, (ids,))
conn.commit()
deleted_count = cur.rowcount
cur.close()
self.logger.info(f"Deleted {deleted_count} vectors")
return True
+ except (ValidationError, ProcessingError):
+ conn.rollback()
+ raise
except Exception as e:
conn.rollback()
- raise ProcessingError(f"Failed to delete vectors: {str(e)}")
+ raise ProcessingError("Failed to delete vectors") from e
def update(
self,
@@ -485,28 +599,38 @@ class PgVectorStore:
f"Vector at index {i} has dimension {len(vec)}, expected {self.dimension}"
)
vec_list = vec.tolist() if isinstance(vec, np.ndarray) else list(vec)
- updates.append("vector = %s")
+ updates.append(psycopg_sql.SQL("vector = %s"))
params.append(vec_list)
if metadata is not None:
- updates.append("metadata = %s")
+ updates.append(psycopg_sql.SQL("metadata = %s"))
params.append(json.dumps(metadata[i]))
- update_sql = f"""
- UPDATE {self.table_name}
- SET {', '.join(updates)}
+ # Build safe UPDATE query
+ update_sql = psycopg_sql.SQL("""
+ UPDATE {}
+ SET {}
WHERE id = %s
- """
+ """).format(
+ psycopg_sql.Identifier(self.table_name),
+ psycopg_sql.SQL(", ").join(updates)
+ )
params.append(vec_id)
- cur.execute(update_sql, params)
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(update_sql, params)
+ else:
+ cur.execute(update_sql, params)
conn.commit()
cur.close()
self.logger.info(f"Updated {len(ids)} vectors")
return True
+ except (ValidationError, ProcessingError):
+ conn.rollback()
+ raise
except Exception as e:
conn.rollback()
- raise ProcessingError(f"Failed to update vectors: {str(e)}")
+ raise ProcessingError("Failed to update vectors") from e
def get(self, ids: List[str]) -> List[Dict[str, Any]]:
"""
@@ -524,16 +648,27 @@ class PgVectorStore:
if not ids:
return []
- get_sql = f"""
- SELECT id, vector, metadata
- FROM {self.table_name}
- WHERE id = ANY(%s)
- """
+ # Use safe SQL composition for table name
+ if PSYCOPG3_AVAILABLE:
+ get_sql = psycopg_sql.SQL("""
+ SELECT id, vector, metadata
+ FROM {}
+ WHERE id = ANY(%s)
+ """).format(psycopg_sql.Identifier(self.table_name))
+ else:
+ get_sql = psycopg_sql.SQL("""
+ SELECT id, vector, metadata
+ FROM {}
+ WHERE id = ANY(%s)
+ """).format(psycopg_sql.Identifier(self.table_name))
with self._get_connection() as conn:
try:
cur = conn.cursor()
- cur.execute(get_sql, (ids,))
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(get_sql, (ids,))
+ else:
+ cur.execute(get_sql, (ids,))
rows = cur.fetchall()
cur.close()
@@ -547,8 +682,10 @@ class PgVectorStore:
})
return results
+ except (ValidationError, ProcessingError):
+ raise
except Exception as e:
- raise ProcessingError(f"Failed to get vectors: {str(e)}")
+ raise ProcessingError("Failed to get vectors") from e
def create_index(
self,
@@ -579,6 +716,7 @@ class PgVectorStore:
)
params = params or {}
+ # Use safe identifier for index name
index_name = f"{self.table_name}_vector_{index_type}_idx"
# Determine distance function
@@ -604,37 +742,62 @@ class PgVectorStore:
cur.close()
return True
- # Build index creation SQL
+ # Build index creation SQL with safe composition
if index_type == "ivfflat":
lists = params.get("lists", 100)
- create_sql = f"""
- CREATE INDEX {index_name}
- ON {self.table_name}
- USING ivfflat (vector {ops})
- WITH (lists = {lists})
- """
+ # Validate lists is a positive integer
+ if not isinstance(lists, int) or lists <= 0:
+ raise ValidationError("lists must be a positive integer")
+ create_sql = psycopg_sql.SQL("""
+ CREATE INDEX {}
+ ON {}
+ USING ivfflat (vector {})
+ WITH (lists = {})
+ """).format(
+ psycopg_sql.Identifier(index_name),
+ psycopg_sql.Identifier(self.table_name),
+ psycopg_sql.SQL(ops),
+ psycopg_sql.Literal(lists)
+ )
elif index_type == "hnsw":
m = params.get("m", 16)
ef_construction = params.get("ef_construction", 64)
- create_sql = f"""
- CREATE INDEX {index_name}
- ON {self.table_name}
- USING hnsw (vector {ops})
- WITH (m = {m}, ef_construction = {ef_construction})
- """
-
- cur.execute(create_sql)
+ # Validate params are positive integers
+ if not isinstance(m, int) or m <= 0:
+ raise ValidationError("m must be a positive integer")
+ if not isinstance(ef_construction, int) or ef_construction <= 0:
+ raise ValidationError("ef_construction must be a positive integer")
+ create_sql = psycopg_sql.SQL("""
+ CREATE INDEX {}
+ ON {}
+ USING hnsw (vector {})
+ WITH (m = {}, ef_construction = {})
+ """).format(
+ psycopg_sql.Identifier(index_name),
+ psycopg_sql.Identifier(self.table_name),
+ psycopg_sql.SQL(ops),
+ psycopg_sql.Literal(m),
+ psycopg_sql.Literal(ef_construction)
+ )
+
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(create_sql)
+ else:
+ cur.execute(create_sql)
conn.commit()
cur.close()
self.logger.info(f"Created {index_type} index: {index_name}")
return True
+ except (ValidationError, ProcessingError):
+ conn.rollback()
+ raise
except Exception as e:
conn.rollback()
# If index already exists (race condition), consider it success
if "already exists" in str(e).lower():
self.logger.info(f"Index {index_name} already exists (race condition)")
return True
- raise ProcessingError(f"Failed to create index: {str(e)}")
+ raise ProcessingError("Failed to create index") from e
def drop_index(self, index_type: str = "hnsw") -> bool:
"""
@@ -646,19 +809,29 @@ class PgVectorStore:
Returns:
True if successful
"""
+ # Use safe identifier for index name
index_name = f"{self.table_name}_vector_{index_type}_idx"
with self._get_connection() as conn:
try:
cur = conn.cursor()
- cur.execute(f"DROP INDEX IF EXISTS {index_name}")
+ drop_sql = psycopg_sql.SQL("DROP INDEX IF EXISTS {}").format(
+ psycopg_sql.Identifier(index_name)
+ )
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(drop_sql)
+ else:
+ cur.execute(drop_sql)
conn.commit()
cur.close()
self.logger.info(f"Dropped index: {index_name}")
return True
+ except (ValidationError, ProcessingError):
+ conn.rollback()
+ raise
except Exception as e:
conn.rollback()
- raise ProcessingError(f"Failed to drop index: {str(e)}")
+ raise ProcessingError("Failed to drop index") from e
def get_stats(self) -> Dict[str, Any]:
"""
@@ -671,8 +844,14 @@ class PgVectorStore:
try:
cur = conn.cursor()
- # Get row count
- cur.execute(f"SELECT COUNT(*) FROM {self.table_name}")
+ # Get row count using safe SQL composition
+ count_sql = psycopg_sql.SQL("SELECT COUNT(*) FROM {}").format(
+ psycopg_sql.Identifier(self.table_name)
+ )
+ if PSYCOPG3_AVAILABLE:
+ cur.execute(count_sql)
+ else:
+ cur.execute(count_sql)
count = cur.fetchone()[0]
# Get index info
@@ -693,8 +872,10 @@ class PgVectorStore:
"indexes": indexes,
"psycopg_version": "3" if PSYCOPG3_AVAILABLE else "2",
}
+ except (ValidationError, ProcessingError):
+ raise
except Exception as e:
- raise ProcessingError(f"Failed to get stats: {str(e)}")
+ raise ProcessingError("Failed to get stats") from e
def close(self):
"""Close the connection pool."""
diff --git a/tests/vector_store/test_pgvector_store.py b/tests/vector_store/test_pgvector_store.py
index 68011553..3f134e43 100644
--- a/tests/vector_store/test_pgvector_store.py
+++ b/tests/vector_store/test_pgvector_store.py
@@ -321,9 +321,12 @@ class TestPgVectorStoreGet:
results = store.get(ids)
assert len(results) == 3
- assert all(r["id"] in ids for r in results)
+ result_ids = {r["id"] for r in results}
+ assert result_ids == set(ids)
assert all(r["vector"] is not None for r in results)
- assert all(r["metadata"]["index"] == i for i, r in enumerate(results))
+ # Don't assume ordering - check by id
+ for r in results:
+ assert r["metadata"]["index"] in [0, 1, 2]
def test_get_nonexistent_ids(self, store):
"""Test getting non-existent vector IDs."""
@@ -549,7 +552,7 @@ class TestPgVectorStoreDistanceMetrics:
"""Test different distance metrics."""
@pytest.fixture
-def l2_store(self, pg_available, unique_table_name):
+ def l2_store(self, pg_available, unique_table_name):
"""Create a store with L2 distance metric."""
if not pg_available:
pytest.skip("PostgreSQL not available")