Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions datamind/capabilities/kb/providers/hybrid_retriever.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,16 +145,20 @@ async def _retrieve(self, query, *, top_k, filters, version):
bm25, ids, texts, metas = await self._ensure_lexical_at_version(version)
k_inner = top_k * self._cm
stage = "kb.embedding"
# Reuse a completed embedding across vector-search retries within this
# retrieval only. Failed embedding attempts leave the cache empty.
query_vector: list[float] | None = None

async def vector_search():
nonlocal stage
stage = "kb.embedding"
vec = await self._embed.embed_query(query)
nonlocal stage, query_vector
if query_vector is None:
stage = "kb.embedding"
query_vector = await self._embed.embed_query(query)
stage = "kb.vector_query"
kwargs = {"top_k": k_inner, "where": filters}
if version is not None:
kwargs["version"] = version
return await self._store.query(vec, **kwargs)
return await self._store.query(query_vector, **kwargs)

def rank_lexical():
if bm25 is not None and ids:
Expand Down
57 changes: 57 additions & 0 deletions datamind/core/db_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Conservative error-code classification for replayable database reads.

True means the caller may retry an independent read in a fresh transaction;
it does not authorize replaying writes or statements inside a failed transaction.
False means a recognized driver error is not on the retry allowlist. None means
this is not a recognized driver error, so generic recovery rules may apply.
Optional database drivers are deliberately not imported here.
"""
from __future__ import annotations

import sqlite3


_MYSQL_TRANSIENT = frozenset({1205, 1213, 2006, 2013})
_POSTGRES_TRANSIENT = frozenset({
"08000", # connection_exception
"08001", # sqlclient_unable_to_establish_sqlconnection
"08003", # connection_does_not_exist
"08006", # connection_failure
"40001", # serialization_failure
"40P01", # deadlock_detected
"57P03", # cannot_connect_now (e.g. server startup)
})


def _from_driver(exc: Exception, *modules: str) -> bool:
# Include driver bases so application-defined subclasses retain their rules.
return any(
cls.__module__ == module or cls.__module__.startswith(module + ".")
for cls in type(exc).__mro__
for module in modules
)


def classify_db_error(exc: Exception) -> bool | None:
"""Classify a raw driver exception using codes, never message substrings."""
if isinstance(exc, sqlite3.Error):
code = getattr(exc, "sqlite_errorcode", None)
# Extended codes retain the primary code in the low eight bits.
# BUSY_SNAPSHOT requires a new transaction, not a statement-level retry.
# LOCKED can indicate a local cursor/schema conflict: do not retry it
# indiscriminately, nor INTERRUPT, corruption, SQL or permission errors.
return type(code) is int and (code & 0xFF) == sqlite3.SQLITE_BUSY

if _from_driver(exc, "pymysql", "MySQLdb", "mysql.connector"):
code = getattr(exc, "errno", None)
if code is None and exc.args:
code = exc.args[0]
return type(code) is int and code in _MYSQL_TRANSIENT

if _from_driver(exc, "psycopg", "psycopg2"):
code = getattr(exc, "sqlstate", None) or getattr(exc, "pgcode", None)
# Do not allow every 08xxx error: 08P01 is a protocol violation.
# In particular, 57014 (query cancellation) must not restart the query.
return isinstance(code, str) and code in _POSTGRES_TRANSIENT

return None
23 changes: 18 additions & 5 deletions datamind/core/recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
from typing import Any, Awaitable, Callable, TypeVar

import httpx
from sqlalchemy.exc import DBAPIError, TimeoutError as SQLAlchemyTimeoutError

from .db_errors import classify_db_error
from .errors import CapabilityError, ConfigError, ExternalServiceError
from .logging import current_context, get_logger

Expand All @@ -19,22 +21,33 @@
def is_transient(exc: Exception) -> bool:
"""Do not mask auth, invalid responses, bad filters, or local path errors."""
seen: set[int] = set()
while id(exc) not in seen:
pending = [exc]
while pending:
exc = pending.pop()
if id(exc) in seen:
continue
seen.add(id(exc))
if isinstance(exc, (ConfigError, ValueError, PermissionError, FileNotFoundError)):
return False
if isinstance(exc, httpx.HTTPStatusError):
return exc.response.status_code in {408, 429} or exc.response.status_code >= 500
if isinstance(exc, ExternalServiceError) and exc.status_code is not None:
return exc.status_code in {408, 429} or exc.status_code >= 500
if isinstance(exc, (TimeoutError, ConnectionError, httpx.TransportError)):
db_decision = classify_db_error(exc)
if db_decision is not None:
return db_decision
if isinstance(exc, (TimeoutError, ConnectionError, httpx.TransportError, SQLAlchemyTimeoutError)):
return True
if isinstance(exc, OSError) and not isinstance(exc, (CapabilityError, ExternalServiceError)):
return True
cause = exc.__cause__
if not isinstance(cause, Exception):
return False
exc = cause
if isinstance(cause, Exception):
pending.append(cause)
# SQLAlchemy's original driver error may exist only in .orig. Inspect
# it before the generic cause: explicit database codes take precedence
# over incidental network/OS exceptions deeper in the chain.
if isinstance(exc, DBAPIError) and isinstance(exc.orig, Exception):
pending.append(exc.orig)
return False


Expand Down
Loading
Loading