Skip to content

Commit b8b4a2c

Browse files
committed
fix: prevent race condition in vectordb tables creation
Signed-off-by: kyteinsky <kyteinsky@gmail.com>
1 parent c8b3b56 commit b8b4a2c

2 files changed

Lines changed: 12 additions & 0 deletions

File tree

context_chat_backend/vectordb/pgvector.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,13 @@ def __init__(self, embedding: Embeddings | None = None, **kwargs):
134134
# tried to create the tables but it was already created in another process
135135
# init the client again to detect it already exists, and continue from there
136136
self.client = PGVector(embedding, collection_name=COLLECTION_NAME, **kwargs)
137+
except sa.exc.ProgrammingError as pe: # pyright: ignore[reportAttributeAccessIssue]
138+
if not isinstance(pe.orig, psycopg.errors.DuplicateTable):
139+
raise
140+
141+
# multiple processes raced to CREATE TABLE, all but one lost so tables now exist, retry
142+
# may not be necessary now since initial tables creation happens in main.py now
143+
self.client = PGVector(embedding, collection_name=COLLECTION_NAME, **kwargs)
137144

138145
def get_instance(self) -> VectorStore:
139146
return self.client

main.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from context_chat_backend.controller import app # isort: skip
1717
from context_chat_backend.logger import get_logging_config, setup_logging # isort: skip
1818
from context_chat_backend.utils import is_k8s_env, redact_config # isort: skip
19+
from context_chat_backend.dyn_loader import VectorDBLoader # isort: skip
1920

2021
LOGGER_CONFIG_NAME = 'logger_config.yaml'
2122
LOGGER_K8S_CONFIG_NAME = 'logger_config.k8s.yaml'
@@ -64,6 +65,10 @@ def _setup_log_levels(debug: bool):
6465
'sqlalchemy',
6566
])
6667

68+
# init the vectordb in the main process before workers are forked so that
69+
# no two worker processes race to CREATE TABLE at the same time
70+
VectorDBLoader(app_config).load()
71+
6772
print(f'CPU count: {cpu_count()}, Memory: {psutil.virtual_memory()}')
6873
print('App config:\n' + redact_config(app_config).model_dump_json(indent=2), flush=True)
6974

0 commit comments

Comments
 (0)