From f7e8ee1dd066e7ed68ba92560440cf699fca30b3 Mon Sep 17 00:00:00 2001 From: KeyCOrigin Date: Wed, 4 Nov 2026 22:26:06 +0800 Subject: [PATCH 1/6] hybrid retriever: reuse query embedding across retries --- .../capabilities/kb/providers/hybrid_retriever.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/datamind/capabilities/kb/providers/hybrid_retriever.py b/datamind/capabilities/kb/providers/hybrid_retriever.py index 66a5f4a..bf05d86 100644 --- a/datamind/capabilities/kb/providers/hybrid_retriever.py +++ b/datamind/capabilities/kb/providers/hybrid_retriever.py @@ -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: From f48017f407c5f3ffdd85ed1770fd4b76da2f72c7 Mon Sep 17 00:00:00 2001 From: KeyCOrigin Date: Wed, 4 Nov 2026 22:43:32 +0800 Subject: [PATCH 2/6] test: expect single embedding call when vector read retries --- datamind/tests/test_read_recovery.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/datamind/tests/test_read_recovery.py b/datamind/tests/test_read_recovery.py index f52d6be..8893ea1 100644 --- a/datamind/tests/test_read_recovery.py +++ b/datamind/tests/test_read_recovery.py @@ -58,7 +58,7 @@ async def test_transient_failure_falls_back_after_bounded_retries(stage): hits = await retriever.aretrieve("needle", filters={"tenant": "a"}) assert [h.id for h in hits] == ["new"] assert hits[0].metadata["degraded"] is True - assert embed.calls == 2 + assert embed.calls == (2 if stage == "embedding" else 1) summary = recovery_summary(ctx.extra["recovery_events"]) assert summary["retries"] == 1 and summary["fallbacks"] == 1 assert summary["events"][0]["component"] == f"kb.{'embedding' if stage == 'embedding' else 'vector_query'}" From de981e7fa3351d5caf1379755780cbae73da76bf Mon Sep 17 00:00:00 2001 From: NankaiKey Date: Sun, 15 Nov 2026 16:30:02 +0000 Subject: [PATCH 3/6] fix: classify transient database errors for bounded read recovery --- datamind/core/db_errors.py | 57 +++++ datamind/core/recovery.py | 23 ++- datamind/tests/test_db_recovery.py | 321 +++++++++++++++++++++++++++++ 3 files changed, 396 insertions(+), 5 deletions(-) create mode 100644 datamind/core/db_errors.py create mode 100644 datamind/tests/test_db_recovery.py diff --git a/datamind/core/db_errors.py b/datamind/core/db_errors.py new file mode 100644 index 0000000..55b6ab1 --- /dev/null +++ b/datamind/core/db_errors.py @@ -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 diff --git a/datamind/core/recovery.py b/datamind/core/recovery.py index 58575a5..4a46ff9 100644 --- a/datamind/core/recovery.py +++ b/datamind/core/recovery.py @@ -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 @@ -19,7 +21,11 @@ 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 @@ -27,14 +33,21 @@ def is_transient(exc: Exception) -> bool: 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 diff --git a/datamind/tests/test_db_recovery.py b/datamind/tests/test_db_recovery.py new file mode 100644 index 0000000..f53da91 --- /dev/null +++ b/datamind/tests/test_db_recovery.py @@ -0,0 +1,321 @@ +"""Database code contracts plus recovery against real, independently locked SQLite. + +MySQL/PostgreSQL exceptions below model optional drivers' public attributes; +those tests do not claim to exercise live MySQL/PostgreSQL servers. +""" +from __future__ import annotations + +import sqlite3 + +import pytest +from sqlalchemy import event, text +from sqlalchemy.exc import OperationalError, TimeoutError as PoolTimeout +from sqlalchemy.pool import NullPool + +from datamind.capabilities.db.providers.sqlite import SQLiteDialect +from datamind.capabilities.db.service import DBService +from datamind.config import DBConfig, Settings +from datamind.core.context import RequestContext +from datamind.core.errors import CapabilityError, ConfigError +from datamind.core.logging import bind_context +from datamind.core.recovery import is_transient, recover_read +from datamind.workspace import Workspace + + +def driver_error(module, *args, **attrs): + error_type = type("DriverError", (Exception,), {"__module__": module}) + error = error_type(*args) + for name, value in attrs.items(): + setattr(error, name, value) + return error + + +def sqlite_error(code): + error = sqlite3.OperationalError("message is deliberately not classified") + if code is not None: + error.sqlite_errorcode = code + return error + + +def wrap(error): + return OperationalError("SELECT 42", {}, error) + + +@pytest.mark.parametrize("code,expected", [ + (5, True), (261, True), (517, True), (773, True), + (6, False), (262, False), (1, False), (8, False), (9, False), + (11, False), (14, False), (19, False), (999, False), (None, False), +]) +@pytest.mark.parametrize("wrapped", [False, True]) +def test_sqlite_codes(code, expected, wrapped): + error = sqlite_error(code) + assert is_transient(wrap(error) if wrapped else error) is expected + + +@pytest.mark.parametrize("module,field", [ + ("pymysql.err", "args"), ("MySQLdb", "args"), + ("mysql.connector.errors", "errno"), +]) +@pytest.mark.parametrize("code,expected", [ + (1205, True), (1213, True), (2006, True), (2013, True), + (1045, False), (1044, False), (1049, False), (1064, False), + (1146, False), (1054, False), (1062, False), (9999, False), (None, False), +]) +def test_mysql_driver_code_contracts(module, field, code, expected): + args = (code, "driver error") if field == "args" else ("driver error",) + error = driver_error(module, *args, **({"errno": code} if field == "errno" else {})) + assert is_transient(error) is expected + assert is_transient(wrap(error)) is expected + + +@pytest.mark.parametrize("module,field", [("psycopg.errors", "sqlstate"), ("psycopg2.errors", "pgcode")]) +@pytest.mark.parametrize("code,expected", [ + ("08000", True), ("08001", True), ("08003", True), ("08006", True), + ("40001", True), ("40P01", True), ("57P03", True), + ("08P01", False), ("57014", False), ("28P01", False), ("28000", False), + ("42501", False), ("42601", False), ("42P01", False), + ("23505", False), ("99999", False), (None, False), +]) +def test_postgres_driver_code_contracts(module, field, code, expected): + error = driver_error(module, "driver error", **{field: code}) + assert is_transient(error) is expected + assert is_transient(wrap(error)) is expected + + +def test_driver_subclasses_keep_code_rules_and_override_generic_oserror(): + base = type("DriverError", (OSError,), {"__module__": "pymysql.err"}) + + class ApplicationError(base): + pass + + assert is_transient(ApplicationError(1213, "deadlock")) + assert not is_transient(ApplicationError(1045, "authentication failed")) + + +@pytest.mark.parametrize("error", [ConnectionError(), TimeoutError(), PoolTimeout()]) +def test_sqlalchemy_orig_only_transient_error(error): + outer = wrap(error) + assert outer.__cause__ is None + assert is_transient(outer) + + +@pytest.mark.parametrize("error", [sqlite_error(1), driver_error("pymysql.err", 1045)]) +def test_explicit_database_rejection_precedes_incidental_network_cause(error): + error.__cause__ = ConnectionError() + outer = wrap(error) + outer.__cause__ = TimeoutError() + assert not is_transient(outer) + + +@pytest.mark.parametrize("outer_type", [RuntimeError, CapabilityError]) +def test_database_error_through_cause(outer_type): + outer = outer_type("db", "failed") if outer_type is CapabilityError else outer_type("failed") + outer.__cause__ = wrap(sqlite_error(5)) + assert is_transient(outer) + + +@pytest.mark.parametrize("outer_type", [ValueError, ConfigError, PermissionError, FileNotFoundError]) +def test_explicit_outer_rejection_still_wins(outer_type): + outer = outer_type("invalid operation") + outer.__cause__ = wrap(sqlite_error(5)) + assert not is_transient(outer) + + +def test_unknown_codes_messages_and_unrelated_attributes_are_not_retry_signals(): + assert not is_transient(sqlite3.OperationalError("database is locked")) + error = RuntimeError("database is locked, timeout, connection lost") + error.orig = ConnectionError() + error.errno = 1213 + error.sqlstate = "40001" + assert not is_transient(error) + assert not is_transient(wrap(RuntimeError("unknown driver error"))) + + +def test_exception_graph_cycles_terminate_and_do_not_hide_another_branch(): + outer = wrap(sqlite_error(5)) + outer.__cause__ = outer + assert is_transient(outer) + outer.orig = outer + assert not is_transient(outer) + outer.__cause__ = ConnectionError() + assert is_transient(outer) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error,expected_calls", [ + (driver_error("pymysql.err", 1213, "deadlock"), 2), + (driver_error("psycopg.errors", sqlstate="40001"), 2), + (driver_error("pymysql.err", 1045, "authentication failed"), 1), + (driver_error("psycopg2.errors", pgcode="57014"), 1), +]) +async def test_driver_codes_control_actual_recovery_loop(error, expected_calls): + calls = 0 + original = wrap(error) + + async def operation(): + nonlocal calls + calls += 1 + if calls == 1: + raise original + return 42 + + if expected_calls == 2: + assert await recover_read(operation, component="db_query_sql", retries=2) == 42 + else: + with pytest.raises(OperationalError) as caught: + await recover_read(operation, component="db_query_sql", retries=2) + assert caught.value is original + assert calls == expected_calls + + +@pytest.mark.asyncio +async def test_nested_database_retries_share_budget(): + calls = 0 + + async def operation(): + nonlocal calls + calls += 1 + raise wrap(driver_error("pymysql.err", 1213, "deadlock")) + + with pytest.raises(OperationalError): + await recover_read( + lambda: recover_read(operation, component="db.inner", retries=5), + component="db.outer", retries=1, + ) + assert calls == 2 + + +@pytest.fixture +def locked_database(tmp_path): + path = tmp_path / "locked.db" + dialect = SQLiteDialect() + engine = dialect.build_engine( + None, default_path=path, connect_args={"timeout": 0.005}, poolclass=NullPool, + ) + with engine.begin() as connection: + connection.execute(text("CREATE TABLE numbers (value INTEGER)")) + connection.execute(text("INSERT INTO numbers VALUES (42)")) + service = DBService(dialect=dialect, engine=engine, db_cfg=DBConfig()) + blocker = sqlite3.connect(path, isolation_level=None) + blocker.execute("BEGIN EXCLUSIVE") + try: + yield service, blocker + finally: + blocker.rollback() + blocker.close() + engine.dispose() + + +@pytest.mark.asyncio +async def test_real_sqlite_busy_recovers_after_other_connection_unlocks(locked_database): + service, blocker = locked_database + errors = [] + calls = 0 + + async def operation(): + nonlocal calls + calls += 1 + try: + return await service.query_sql("SELECT value FROM numbers") + except OperationalError as error: + errors.append(error) + # Release the actual exclusive lock only after the read has failed. + blocker.rollback() + raise + + ctx = RequestContext.new() + with bind_context(ctx): + result = await recover_read(operation, component="db_query_sql", retries=2) + assert result.rows == [[42]] + assert calls == 2 + assert len(errors) == 1 + assert errors[0].orig.sqlite_errorcode == sqlite3.SQLITE_BUSY + event, = ctx.extra["recovery_events"] + assert (event["attempts"], event["retries"], event["outcome"]) == (2, 1, "ok") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("retries", [0, 2]) +async def test_real_sqlite_busy_stops_at_retry_budget(locked_database, retries): + service, _ = locked_database + calls = 0 + + async def operation(): + nonlocal calls + calls += 1 + return await service.query_sql("SELECT value FROM numbers") + + with pytest.raises(OperationalError) as caught: + await recover_read(operation, component="db_query_sql", retries=retries) + assert caught.value.orig.sqlite_errorcode == sqlite3.SQLITE_BUSY + assert calls == retries + 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sql", ["SELECT value FROM absent_table", "SELECT * FRM numbers"]) +async def test_real_sqlite_sql_errors_are_not_retried(locked_database, sql): + service, blocker = locked_database + blocker.rollback() + calls = 0 + + async def operation(): + nonlocal calls + calls += 1 + return await service.query_sql(sql) + + with pytest.raises(OperationalError) as caught: + await recover_read(operation, component="db_query_sql", retries=2) + assert caught.value.orig.sqlite_errorcode == sqlite3.SQLITE_ERROR + assert calls == 1 + + +@pytest.mark.asyncio +async def test_workspace_db_tool_recovers_real_busy_on_pinned_revision(tmp_path, monkeypatch): + source = tmp_path / "source" + source.mkdir() + (source / "numbers.csv").write_text("value\n42\n") + settings = Settings( + llm={"api_key": "test", "model": "test"}, + data={"base_dir": tmp_path / "runtime"}, + workspace={"retention": "all"}, + ) + workspace = Workspace(settings) + manifest = await workspace.update(str(source), surfaces=("db",)) + async with workspace.reader(read_retries=1) as reader: + service = reader._system.services.db + table, = await service.list_tables() + service.engine.dispose() + + @event.listens_for(service.engine, "connect") + def set_busy_timeout(connection, _): + connection.execute("PRAGMA busy_timeout=5") + + original = service.query_sql + calls = 0 + blocker = sqlite3.connect(service.engine.url.database, isolation_level=None) + blocker.execute("BEGIN EXCLUSIVE") + + async def query(sql): + nonlocal calls + calls += 1 + try: + return await original(sql) + except OperationalError as error: + assert error.orig.sqlite_errorcode == sqlite3.SQLITE_BUSY + blocker.rollback() + raise + + monkeypatch.setattr(service, "query_sql", query) + ctx = RequestContext.new() + try: + with bind_context(ctx): + result = await reader.call("db_query_sql", sql=f'SELECT value FROM "{table}"') + finally: + blocker.rollback() + blocker.close() + assert str(result["rows"][0][0]) == "42" + assert calls == 2 + assert reader.revision == manifest["workspace_revision"] + record, = ctx.extra["recovery_events"] + assert record["retries"] == 1 + assert record["workspace_revision"] == reader.revision From c641cfd0d988d043bdd01f2b73440beac1001b6b Mon Sep 17 00:00:00 2001 From: NankaiKey Date: Sun, 15 Nov 2026 17:43:47 +0000 Subject: [PATCH 4/6] feat: add opt-in SQLite query fault injection experiments --- benchmark/robustness.py | 86 +++++-- datamind/capabilities/db/base.py | 10 +- datamind/experiment_faults.py | 164 ++++++++++++ datamind/tests/test_db_fault_injection.py | 295 ++++++++++++++++++++++ datamind/tests/test_robustness_runner.py | 62 +++++ docs/READ_RECOVERY.md | 77 ++++++ 6 files changed, 674 insertions(+), 20 deletions(-) create mode 100644 datamind/tests/test_db_fault_injection.py diff --git a/benchmark/robustness.py b/benchmark/robustness.py index 696a221..7bbc98b 100644 --- a/benchmark/robustness.py +++ b/benchmark/robustness.py @@ -21,9 +21,14 @@ import subprocess import sys import time +from contextlib import nullcontext from pathlib import Path from datamind.config import Settings +from datamind.core.context import RequestContext +from datamind.core.logging import bind_context +from datamind.core.recovery import recovery_summary +from datamind.experiment_faults import ExperimentFaultError, db_counts, db_faults from datamind.workspace import Workspace REPO = Path(__file__).resolve().parents[1] @@ -160,9 +165,16 @@ def source_and_tasks(args, output): if args.questions: tasks = [json.loads(line) for line in Path(args.questions).read_text().splitlines() if line.strip()] for i, task in enumerate(tasks): - if not isinstance(task.get("question"), str): - raise ValueError(f"task {i} needs a question") + field = "sql" if getattr(args, "execution", None) == "sql" else "question" + if not isinstance(task.get(field), str): + raise ValueError(f"task {i} needs {field}") task.setdefault("task_id", str(i)) + elif args.fixture and getattr(args, "execution", None) == "sql": + tasks = [ + {"task_id": "0", "sql": 'SELECT SUM(CAST(amount AS INTEGER)) FROM "{table}"', + "expected_rows": [[36]]}, + {"task_id": "1", "sql": 'SELECT COUNT(*) FROM "{table}"', "expected_rows": [[2]]}, + ] elif args.fixture: tasks = [{"task_id": "0", "question": "nebula", "expected_sources": ["doc0.md"]}, {"task_id": "1", "question": "orchid", "expected_sources": ["doc1.md"]}] @@ -173,6 +185,9 @@ def source_and_tasks(args, output): def score(task, result, execution): """No LLM judge or heuristic pretending to be official benchmark accuracy.""" + if execution == "sql": + return {"source_hit": None, "exact_answer_match": None, + "result_match": result.get("rows") == task["expected_rows"] if "expected_rows" in task else None} expected = task.get("expected_sources") observed = [r.get("source") for r in result.get("results", [])] if execution == "retrieval" else [ e.get("locator", {}).get("source") or e.get("source_id") for e in result.get("evidence", [])] @@ -221,9 +236,11 @@ async def failing(*a, **k): async def query_experiment(args, output, source, tasks): if not tasks: raise ValueError("Query experiments require --questions (or --fixture)") - if args.fixture and args.execution != "retrieval": - raise ValueError("Fixture mode cannot evaluate LLM answers; use --execution retrieval") + if args.fixture and args.execution == "agent": + raise ValueError("Fixture mode cannot evaluate LLM answers; use retrieval or sql") settings = settings_for(output / "runtime", args.fixture, args) + if args.component == "db" and settings.db.dialect != "sqlite": + raise ValueError("DB fault injection currently supports SQLite only") workspace = workspace_for(settings) built = await workspace.update(str(source), surfaces=args.surfaces.split(","), graph_sources=prepared_graph(args)) manifest = provenance(args, source) @@ -235,8 +252,9 @@ async def query_experiment(args, output, source, tasks): write_json(output / "build.json", built) rows = [] # Seeded task/policy ordering limits systematic cold/warm and order effects. + policies = ("none", "retry") if args.component == "db" else ("none", "retry", "fallback") jobs = [(repeat, task, policy, p) for repeat in range(args.repeats) for task in tasks - for policy in ("none", "retry", "fallback") for p in args.failure_probabilities] + for policy in policies for p in args.failure_probabilities] random.Random(args.seed).shuffle(jobs) for repeat, task, policy, probability in jobs: workspace.settings.retrieval.vector_failure_fallback = "bm25" if policy == "fallback" else "error" @@ -246,6 +264,9 @@ async def query_experiment(args, output, source, tasks): "workspace_revision": built["workspace_revision"], "fixture": args.fixture, "source_hit": False if task.get("expected_sources") else None, "exact_answer_match": False if task.get("reference_answer") is not None and args.execution == "agent" else None} + if args.component == "db": + row.update(fault_origin="simulated_exception", db_error=args.db_error, + result_match=False if "expected_rows" in task else None) try: async with workspace.reader(built["workspace_revision"], read_retries=0 if policy == "none" else args.retries) as reader: row["reader_setup_ms"] = (time.monotonic() - reader_started) * 1000 @@ -253,44 +274,66 @@ async def query_experiment(args, output, source, tasks): args.outage_ms, args.fault_delay_ms) runtime_env=None state=None - if args.execution=='retrieval': + if args.execution == 'retrieval': install_fault(reader, faults, args.component) else: state=output/'fault-states'/(digest([repeat,task['task_id'],policy,probability])+'.sqlite3') plan={'state':str(state),'seed':args.seed+repeat,'task':str(task['task_id']), 'component':args.component,'probability':probability, 'outage_ms':args.outage_ms,'delay_ms':args.fault_delay_ms} + if args.component == 'db': + plan['error'] = args.db_error runtime_env={'DATAMIND_TEST_READ_FAULT':json.dumps(plan), 'DATAMIND_WORKSPACE_READ_RETRIES':str(0 if policy=='none' else args.retries)} started = time.monotonic() + context = RequestContext.new() + context.extra['recovery_events'] = [] try: - async with asyncio.timeout(args.deadline_s): - result = await (reader.call("kb_search", query=task["question"], filters=task.get("filters")) - if args.execution == "retrieval" else reader.query(task["question"],runtime_env=runtime_env)) + with bind_context(context), db_faults(plan) if args.execution == 'sql' else nullcontext(): + async with asyncio.timeout(args.deadline_s): + if args.execution == "sql": + sql = task['sql'] + if '{table}' in sql: + tables = await reader._system.services.db.list_tables() + if len(tables) != 1: + raise ValueError("{table} requires exactly one published table") + sql = sql.replace('{table}', tables[0].replace('"', '""')) + result = await reader.call("db_query_sql", sql=sql) + elif args.execution == "retrieval": + result = await reader.call("kb_search", query=task["question"], filters=task.get("filters")) + else: + result = await reader.query(task["question"], runtime_env=runtime_env) row.update(outcome="ok", result=result, **score(task, result, args.execution)) except Exception as exc: row.update(outcome="error", error_type=type(exc).__name__, recovery=getattr(exc, "datamind_recovery", {}), source_hit=False if task.get("expected_sources") else None, exact_answer_match=False if task.get("reference_answer") is not None and args.execution == "agent" else None) + if isinstance(exc, ExperimentFaultError): + row['outcome'] = 'experiment_error' + if args.execution == 'sql': + row['recovery'] = recovery_summary(context.extra['recovery_events']) if state is not None: from datamind.experiment_faults import counts - actual=counts(state) + actual = db_counts(state) if args.component == 'db' else counts(state) faults.attempts,faults.injected=actual['attempts'],actual['injected'] + if args.component == 'db': + row['sql_executions'] = actual['executed'] row.update(latency_ms=(time.monotonic() - started) * 1000, injected_faults=faults.injected, component_attempts=faults.attempts) except Exception as exc: - row.update(outcome="reader_error", error_type=type(exc).__name__) + row.update(outcome="experiment_error" if isinstance(exc, ExperimentFaultError) else "reader_error", + error_type=type(exc).__name__) rows.append(row) append_row(output / "rows.jsonl", row) groups = [] for probability in args.failure_probabilities: - for policy in ("none", "retry", "fallback"): + for policy in policies: batch = [r for r in rows if r["policy"] == policy and r["failure_probability"] == probability] latencies = sorted(r["latency_ms"] for r in batch if "latency_ms" in r) groups.append({"policy": policy, "failure_probability": probability, "tasks": len(batch), "completion_rate": sum(r["outcome"] == "ok" for r in batch) / len(batch), "p95_latency_ms": latencies[math.ceil(.95 * len(latencies)) - 1] if latencies else None, **{key + "_rate": (sum(r.get(key) is True for r in batch) / sum(r.get(key) is not None for r in batch)) - if any(r.get(key) is not None for r in batch) else None for key in ("source_hit", "exact_answer_match")}}) + if any(r.get(key) is not None for r in batch) else None for key in ("source_hit", "exact_answer_match", "result_match")}}) write_json(output / "summary.json", {"fixture": args.fixture, "groups": groups}) @@ -422,8 +465,9 @@ def parser(): p.add_argument("--worker-timeout-s", type=float, default=300.) if command == "query": p.add_argument("--seed", type=int, default=0) - p.add_argument("--execution", choices=["retrieval", "agent"], default="retrieval") - p.add_argument("--component", choices=["embedding", "vector"], default="embedding") + p.add_argument("--execution", choices=["retrieval", "sql", "agent"], default="retrieval") + p.add_argument("--component", choices=["embedding", "vector", "db"], default="embedding") + p.add_argument("--db-error", choices=["sqlite_busy", "sqlite_locked", "sqlite_error"], default="sqlite_busy") p.add_argument("--failure-probabilities", type=float, nargs="+", default=[0., .1, .5, 1.]) p.add_argument("--outage-ms", type=float, default=0.) p.add_argument("--fault-delay-ms", type=float, default=0.) @@ -445,10 +489,16 @@ def main(): if args.command == "query": if any(not 0 <= p <= 1 for p in args.failure_probabilities) or not 0 <= args.retries <= 5: raise ValueError("probabilities must be in [0,1]; retries must be in [0,5]") - if args.repeats < 1 or args.deadline_s <= 0 or min(args.outage_ms, args.fault_delay_ms) < 0: + if (args.repeats < 1 or args.deadline_s <= 0 or min(args.outage_ms, args.fault_delay_ms) < 0 + or not all(math.isfinite(v) for v in (args.deadline_s, args.outage_ms, args.fault_delay_ms))): raise ValueError("invalid repeats/deadline/fault duration") - if "kb" not in args.surfaces.split(","): - raise ValueError("query fault experiments require the kb surface") + required_surface = "db" if args.component == "db" else "kb" + if required_surface not in args.surfaces.split(","): + raise ValueError(f"query fault experiments require the {required_surface} surface") + if args.execution == "sql" and args.component != "db": + raise ValueError("--execution sql requires --component db") + if args.component == "db" and args.execution == "retrieval": + raise ValueError("--component db requires --execution sql or agent") elif args.crash_stage == "none": raise ValueError("build experiment requires checkpoint or publication fault") output = Path(args.output).resolve() diff --git a/datamind/capabilities/db/base.py b/datamind/capabilities/db/base.py index a7f7bcb..ba22920 100644 --- a/datamind/capabilities/db/base.py +++ b/datamind/capabilities/db/base.py @@ -19,6 +19,7 @@ from datamind.core.errors import CapabilityError from datamind.core.protocols import ColumnSchema, QueryResult, TableSchema +from datamind.experiment_faults import before_db_read, record_db_execution from .safeguard import ( DestructiveSQLError, @@ -130,13 +131,14 @@ def _bound_query(self, sql: str, row_limit: int) -> str: async def _execute_bounded_readonly( self, engine: Engine, bounded: str, *, row_limit: int, timeout_s: float, ) -> QueryResult: - def _run() -> QueryResult: + def _run(fault_state) -> QueryResult: start = time.perf_counter() with engine.connect() as conn: # Per-connection read-only hint where supported. Base class # is conservative — dialects can strengthen (SET TRANSACTION # READ ONLY etc.). self._before_query(conn) + record_db_execution(fault_state) result = conn.execute(text(bounded)) columns = list(result.keys()) # Fetch one extra row so we can detect truncation. @@ -152,7 +154,11 @@ def _run() -> QueryResult: elapsed_ms=round(elapsed, 2), ) - return await asyncio.wait_for(asyncio.to_thread(_run), timeout=timeout_s) + async def _attempt(): + fault_state = await before_db_read(engine) + return await asyncio.to_thread(_run, fault_state) + + return await asyncio.wait_for(_attempt(), timeout=timeout_s) # ------------------------------------------------------------ safeguard diff --git a/datamind/experiment_faults.py b/datamind/experiment_faults.py index 86ffaaf..8063227 100644 --- a/datamind/experiment_faults.py +++ b/datamind/experiment_faults.py @@ -4,18 +4,29 @@ or document-facing tool for enabling faults. Normal execution does not create state. """ import asyncio +import contextvars import json +import math import os import random import sqlite3 import time +from contextlib import contextmanager +from dataclasses import dataclass from pathlib import Path +from sqlalchemy.exc import OperationalError + +from datamind.core.errors import ConfigError +from datamind.core.logging import current_context + def install(kb): raw=os.environ.get('DATAMIND_TEST_READ_FAULT') if not raw or kb is None:return plan=json.loads(raw) + # DB faults are installed at the shared read executor, not on KB providers. + if plan.get('component') == 'db':return if plan['component'] not in {'embedding','vector'}: raise ValueError('Unsupported experiment component') probability=float(plan['probability']) @@ -46,3 +57,156 @@ def counts(path): with sqlite3.connect(path) as db: attempts,injected=db.execute('SELECT attempts,injected FROM fault_state WHERE singleton=1').fetchone() return {'attempts':attempts,'injected':injected} + + +class ExperimentFaultError(ConfigError): + """Invalid experiment setup or state failure; never a retryable DB outage.""" + + +_SQLITE_ERRORS = { + "sqlite_busy": (sqlite3.SQLITE_BUSY, "SQLITE_BUSY"), + "sqlite_locked": (sqlite3.SQLITE_LOCKED, "SQLITE_LOCKED"), + "sqlite_error": (sqlite3.SQLITE_ERROR, "SQLITE_ERROR"), +} + + +@dataclass(frozen=True) +class _DBPlan: + state: Path + error: str + probability: float + outage_ms: float + delay_ms: float + seed: str + task: str + + +_DB_PLAN: contextvars.ContextVar[_DBPlan | None] = contextvars.ContextVar("db_fault_plan", default=None) + + +def _parse_db_plan(plan): + try: + if plan.get("component") != "db": + raise ValueError("component must be db") + error = plan.get("error", "sqlite_busy") + if error not in _SQLITE_ERRORS: + raise ValueError("unsupported DB fault; expected sqlite_busy, sqlite_locked or sqlite_error") + probability = float(plan["probability"]) + outage = float(plan.get("outage_ms", 0)) + delay = float(plan.get("delay_ms", 0)) + if not math.isfinite(probability) or not 0 <= probability <= 1: + raise ValueError("probability must be finite and between 0 and 1") + if not all(math.isfinite(v) and v >= 0 for v in (outage, delay)): + raise ValueError("outage_ms and delay_ms must be finite and nonnegative") + if not isinstance(plan["state"], str) or not plan["state"]: + raise ValueError("state must be a nonempty path") + return _DBPlan(Path(plan["state"]).expanduser().resolve(), error, probability, + outage, delay, str(plan["seed"]), str(plan["task"])) + except (KeyError, TypeError, ValueError, AttributeError, OSError) as exc: + raise ExperimentFaultError("Invalid DB fault plan: " + str(exc)) from exc + + +@contextmanager +def db_faults(plan): + """Enable a plan for this query/task only, including its retries and workers. + + No provider is monkey-patched, so recreating a service cannot double-install + the fault. The shared state file preserves the schedule across MCP processes. + """ + token = _DB_PLAN.set(_parse_db_plan(plan)) + try: + yield + finally: + _DB_PLAN.reset(token) + + +def _db_plan(): + plan = _DB_PLAN.get() + if plan is not None: + return plan + # Child MCP processes receive the trusted host's environment. Activate only + # inside a pinned workspace read, never while preparing/building a revision. + context = current_context() + raw = os.environ.get("DATAMIND_TEST_READ_FAULT") + if not raw or context is None or not context.extra.get("workspace_revision"): + return None + try: + value = json.loads(raw) + except (TypeError, ValueError) as exc: + raise ExperimentFaultError("Invalid read fault JSON") from exc + if not isinstance(value, dict): + raise ExperimentFaultError("Read fault plan must be an object") + return _parse_db_plan(value) if value.get("component") == "db" else None + + +@contextmanager +def _db_state(path): + try: + path.parent.mkdir(parents=True, exist_ok=True) + # Bound contention in the experiment store separately from the target DB. + connection = sqlite3.connect(path, timeout=0.1) + try: + with connection: + yield connection + finally: + connection.close() + except (sqlite3.Error, OSError) as exc: + raise ExperimentFaultError("DB fault state is unavailable") from exc + + +def _db_attempt(plan): + with _db_state(plan.state) as state: + state.execute("BEGIN IMMEDIATE") + state.execute("CREATE TABLE IF NOT EXISTS db_fault_state (" + "singleton INTEGER PRIMARY KEY, started REAL, attempts INTEGER, " + "injected INTEGER, executed INTEGER)") + state.execute("INSERT OR IGNORE INTO db_fault_state VALUES (1,?,0,0,0)", (time.monotonic(),)) + started, attempts = state.execute( + "SELECT started,attempts FROM db_fault_state WHERE singleton=1" + ).fetchone() + fail = (time.monotonic() - started < plan.outage_ms / 1000 or + random.Random(f"{plan.seed}:{plan.task}:{attempts}").random() < plan.probability) + state.execute("UPDATE db_fault_state SET attempts=attempts+1,injected=injected+? WHERE singleton=1", + (int(fail),)) + return fail + + +async def before_db_read(engine): + """Called after SQL validation and inside the query's timeout boundary.""" + plan = _db_plan() + if plan is None: + return None + if engine.dialect.name != "sqlite": + raise ExperimentFaultError("DB fault injection currently supports SQLite only") + database = engine.url.database + if database and database != ":memory:" and Path(database).resolve() == plan.state: + raise ExperimentFaultError("Fault state must be separate from the target database") + fail = await asyncio.to_thread(_db_attempt, plan) + if fail: + await asyncio.sleep(plan.delay_ms / 1000) + code, name = _SQLITE_ERRORS[plan.error] + original = sqlite3.OperationalError("injected experiment DB fault") + original.sqlite_errorcode = code + original.sqlite_errorname = name + error = OperationalError(None, None, original) + error.datamind_fault_injected = True + raise error + return plan.state + + +def record_db_execution(state_path): + """Count entries to conn.execute, not merely attempts or successful results.""" + if state_path is not None: + with _db_state(state_path) as state: + state.execute("UPDATE db_fault_state SET executed=executed+1 WHERE singleton=1") + + +def db_counts(path): + path = Path(path) + if not path.exists(): + return {"attempts": 0, "injected": 0, "executed": 0} + with _db_state(path) as state: + row = state.execute("SELECT attempts,injected,executed FROM db_fault_state WHERE singleton=1").fetchone() + if row is None: + raise ExperimentFaultError("DB fault state has no counter row") + return dict(zip(("attempts", "injected", "executed"), row)) diff --git a/datamind/tests/test_db_fault_injection.py b/datamind/tests/test_db_fault_injection.py new file mode 100644 index 0000000..251f5ac --- /dev/null +++ b/datamind/tests/test_db_fault_injection.py @@ -0,0 +1,295 @@ +"""Opt-in simulated DB faults use real SQLite reads and the existing recovery loop.""" +import asyncio +import json +import os +import sqlite3 +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace + +import pytest +from sqlalchemy.exc import OperationalError + +from datamind import experiment_faults as faults +from datamind.capabilities.db.providers.sqlite import SQLiteDialect +from datamind.capabilities.db.safeguard import DestructiveSQLError +from datamind.capabilities.db.service import DBService +from datamind.config import DBConfig, Settings +from datamind.core.context import RequestContext +from datamind.core.logging import bind_context +from datamind.core.recovery import is_transient, recover_read +from datamind.workspace import Workspace + + +@pytest.fixture +def service(tmp_path, monkeypatch): + monkeypatch.delenv("DATAMIND_TEST_READ_FAULT", raising=False) + dialect = SQLiteDialect() + engine = dialect.build_engine(None, default_path=tmp_path / "target.db") + try: + yield DBService(dialect=dialect, engine=engine, db_cfg=DBConfig()) + finally: + engine.dispose() + + +def plan(tmp_path, **kwargs): + return {"component": "db", "error": "sqlite_busy", "probability": 1, + "seed": 7, "task": "q", "state": str(tmp_path / "faults.db"), **kwargs} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error,code,retryable", [ + ("sqlite_busy", 5, True), ("sqlite_locked", 6, False), ("sqlite_error", 1, False), +]) +async def test_codes_are_sqlalchemy_wrapped_and_control_retries(service, tmp_path, error, code, retryable): + config = plan(tmp_path, error=error) + with faults.db_faults(config), pytest.raises(OperationalError) as caught: + await recover_read(lambda: service.query_sql("SELECT 42"), component="db_query_sql", retries=2) + assert caught.value.orig.sqlite_errorcode == code + assert caught.value.datamind_fault_injected is True + assert caught.value.__cause__ is None # exercises .orig, not just __cause__ + assert is_transient(caught.value) is retryable + assert faults.db_counts(config["state"]) == { + "attempts": 3 if retryable else 1, "injected": 3 if retryable else 1, "executed": 0, + } + + +@pytest.mark.asyncio +async def test_outage_recovers_after_window_and_state_survives_new_service(service, tmp_path, monkeypatch): + clock = [100.0] + monkeypatch.setattr(faults, "time", SimpleNamespace(monotonic=lambda: clock[0])) + config = plan(tmp_path, probability=0, outage_ms=100) + + async def operation(): + # A new service instance must consume the same persisted schedule. + recreated = DBService(dialect=SQLiteDialect(), engine=service.engine, db_cfg=DBConfig()) + try: + return await recreated.query_sql("SELECT 42") + except OperationalError: + clock[0] += 0.2 + raise + + with faults.db_faults(config): + result = await recover_read(operation, component="db_query_sql", retries=1) + assert result.rows == [[42]] + assert faults.db_counts(config["state"]) == {"attempts": 2, "injected": 1, "executed": 1} + # Leaving the scope restores normal execution even with a 100% fault plan. + assert (await service.query_sql("SELECT 42")).rows == [[42]] + assert faults.db_counts(config["state"])["attempts"] == 2 + + +@pytest.mark.asyncio +async def test_probability_schedule_is_paired_and_not_reset_on_reentry(service, tmp_path): + schedules = [] + for policy in ("none", "retry"): + config = plan(tmp_path, state=str(tmp_path / f"{policy}.db"), probability=0.4) + schedule = [] + for _ in range(12): + with faults.db_faults(config): + try: + await service.query_sql("SELECT 42") + except OperationalError: + schedule.append(True) + else: + schedule.append(False) + schedules.append(schedule) + assert faults.db_counts(config["state"]) == { + "attempts": 12, "injected": sum(schedule), "executed": 12 - sum(schedule), + } + assert schedules[0] == schedules[1] + assert any(schedules[0]) and not all(schedules[0]) + + +@pytest.mark.asyncio +async def test_delay_is_inside_query_timeout_and_never_executes_sql(service, tmp_path): + config = plan(tmp_path, delay_ms=1000) + service.db_cfg.query_timeout_s = 0.02 + with faults.db_faults(config), pytest.raises(TimeoutError): + await service.query_sql("SELECT 42") + assert faults.db_counts(config["state"]) == {"attempts": 1, "injected": 1, "executed": 0} + + +@pytest.mark.asyncio +async def test_overall_deadline_does_not_retry_delayed_injection(service, tmp_path): + config = plan(tmp_path, delay_ms=1000) + context = RequestContext.new() + context.extra["query_deadline"] = time.monotonic() + 0.05 + with bind_context(context), faults.db_faults(config), pytest.raises(TimeoutError): + await recover_read(lambda: service.query_sql("SELECT 42"), component="db_query_sql", retries=2) + record, = context.extra["recovery_events"] + assert record["attempts"] == 1 and record["retries"] == 0 + assert faults.db_counts(config["state"])["executed"] == 0 + + +@pytest.mark.asyncio +async def test_cancellation_during_injected_delay_never_executes_sql(service, tmp_path): + config = plan(tmp_path, delay_ms=10000) + with faults.db_faults(config): + task = asyncio.create_task(service.query_sql("SELECT 42")) + try: + async with asyncio.timeout(2): + while True: + try: + if faults.db_counts(config["state"])["injected"]: + break + except faults.ExperimentFaultError: + pass # the first state transaction may still be initializing + await asyncio.sleep(0.01) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert faults.db_counts(config["state"])["executed"] == 0 + + +@pytest.mark.asyncio +async def test_sql_validation_and_metadata_are_not_injected(service, tmp_path): + config = plan(tmp_path) + with faults.db_faults(config): + with pytest.raises(DestructiveSQLError): + await service.query_sql("DELETE FROM numbers") + assert await service.list_tables() == [] + assert not Path(config["state"]).exists() + + +@pytest.mark.asyncio +async def test_execution_counter_includes_real_sql_errors(service, tmp_path): + config = plan(tmp_path, probability=0) + with faults.db_faults(config), pytest.raises(OperationalError) as caught: + await service.query_sql("SELECT * FROM missing_table") + assert not getattr(caught.value, "datamind_fault_injected", False) + assert faults.db_counts(config["state"]) == {"attempts": 1, "injected": 0, "executed": 1} + + +@pytest.mark.asyncio +async def test_state_database_lock_is_not_a_target_db_fault_or_retried(service, tmp_path): + config = plan(tmp_path, probability=0) + with faults.db_faults(config): + await service.query_sql("SELECT 42") + blocker = sqlite3.connect(config["state"], isolation_level=None) + blocker.execute("BEGIN EXCLUSIVE") + calls = 0 + + async def operation(): + nonlocal calls + calls += 1 + return await service.query_sql("SELECT 42") + + try: + with pytest.raises(faults.ExperimentFaultError) as caught: + await recover_read(operation, component="db_query_sql", retries=2) + assert caught.value.__cause__.sqlite_errorcode == sqlite3.SQLITE_BUSY + assert not is_transient(caught.value) + assert calls == 1 + finally: + blocker.rollback() + blocker.close() + assert faults.db_counts(config["state"])["attempts"] == 1 + + +@pytest.mark.parametrize("kwargs", [ + {"probability": -1}, {"probability": float("nan")}, {"probability": float("inf")}, + {"delay_ms": -1}, {"outage_ms": float("nan")}, {"error": "unknown"}, {"state": ""}, +]) +def test_invalid_plan_fails_before_creating_state(tmp_path, kwargs): + with pytest.raises(faults.ExperimentFaultError): + with faults.db_faults(plan(tmp_path, **kwargs)): + pytest.fail("invalid plan was accepted") + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.asyncio +async def test_target_cannot_be_its_own_fault_state(service, tmp_path): + with faults.db_faults(plan(tmp_path, state=service.engine.url.database)): + with pytest.raises(faults.ExperimentFaultError): + await service.query_sql("SELECT 42") + + +@pytest.mark.asyncio +async def test_non_sqlite_backend_is_rejected_instead_of_spoofed(tmp_path): + with faults.db_faults(plan(tmp_path)): + with pytest.raises(faults.ExperimentFaultError, match="SQLite only"): + await faults.before_db_read(SimpleNamespace(dialect=SimpleNamespace(name="mysql"))) + assert not Path(plan(tmp_path)["state"]).exists() + + +def test_db_environment_plan_does_not_wrap_kb(tmp_path, monkeypatch): + config = plan(tmp_path) + monkeypatch.setenv("DATAMIND_TEST_READ_FAULT", json.dumps(config)) + faults.install(SimpleNamespace()) # no embedding or vector_store needed + assert not Path(config["state"]).exists() + + +@pytest.mark.asyncio +async def test_concurrent_query_plans_are_isolated(service, tmp_path): + async def query(name, probability): + config = plan(tmp_path, probability=probability, state=str(tmp_path / f"{name}.db")) + with faults.db_faults(config): + await asyncio.sleep(0) + return await service.query_sql("SELECT 42") + + failed, successful = await asyncio.gather(query("failed", 1), query("successful", 0), return_exceptions=True) + assert isinstance(failed, OperationalError) + assert successful.rows == [[42]] + assert faults.db_counts(tmp_path / "failed.db")["injected"] == 1 + assert faults.db_counts(tmp_path / "successful.db")["executed"] == 1 + + +@pytest.mark.asyncio +async def test_concurrent_attempts_are_counted_once(service, tmp_path): + config = plan(tmp_path) + with faults.db_faults(config): + results = await asyncio.gather(*(service.query_sql("SELECT 42") for _ in range(8)), return_exceptions=True) + assert all(isinstance(result, OperationalError) for result in results) + assert faults.db_counts(config["state"]) == {"attempts": 8, "injected": 8, "executed": 0} + + +@pytest.mark.asyncio +async def test_env_plan_skips_build_and_applies_to_workspace_read(tmp_path, monkeypatch): + config = plan(tmp_path) + monkeypatch.setenv("DATAMIND_TEST_READ_FAULT", json.dumps(config)) + source = tmp_path / "source" + source.mkdir() + (source / "numbers.csv").write_text("value\n42\n") + workspace = Workspace(Settings(llm={"api_key": "test", "model": "test"}, + data={"base_dir": tmp_path / "runtime"})) + manifest = await workspace.update(str(source), surfaces=("db",)) + assert not Path(config["state"]).exists() + async with workspace.reader(read_retries=1) as reader: + table, = await reader._system.services.db.list_tables() + with pytest.raises(OperationalError): + await reader.call("db_query_sql", sql=f'SELECT value FROM "{table}"') + assert reader.revision == manifest["workspace_revision"] + assert faults.db_counts(config["state"]) == {"attempts": 2, "injected": 2, "executed": 0} + + +def test_env_schedule_survives_child_process_recreation(tmp_path): + config = plan(tmp_path) + script = ''' +import asyncio, os +from datamind.capabilities.db.providers.sqlite import SQLiteDialect +from datamind.core.context import RequestContext +from datamind.core.logging import bind_context +from sqlalchemy.exc import OperationalError +async def main(): + dialect=SQLiteDialect() + engine=dialect.build_engine("sqlite:///:memory:") + context=RequestContext.new() + context.extra["workspace_revision"]="test-revision" + try: + with bind_context(context): + try: await dialect.execute_readonly(engine,"SELECT 42") + except OperationalError as error: assert error.orig.sqlite_errorcode == 5 + else: raise AssertionError("fault not injected") + finally: engine.dispose() +asyncio.run(main()) +''' + for _ in range(2): + subprocess.run([sys.executable, "-c", script], check=True, capture_output=True, + cwd=Path(__file__).resolve().parents[2], timeout=20, + env={**os.environ, "DATAMIND_TEST_READ_FAULT": json.dumps(config)}) + assert faults.db_counts(config["state"]) == {"attempts": 2, "injected": 2, "executed": 0} diff --git a/datamind/tests/test_robustness_runner.py b/datamind/tests/test_robustness_runner.py index de95e79..df4c486 100644 --- a/datamind/tests/test_robustness_runner.py +++ b/datamind/tests/test_robustness_runner.py @@ -5,6 +5,8 @@ import sys from pathlib import Path +import pytest + REPO = Path(__file__).resolve().parents[2] @@ -42,3 +44,63 @@ def test_process_exit_recovery_experiment_matches_cold_content(tmp_path): assert result["cold_metrics"]["sources_reused"] == 0 assert result["resume_metrics"]["graph_extraction_calls"] < result["cold_metrics"]["graph_extraction_calls"] assert result["resume_metrics"]["materialization_ms"] > 0 + + +@pytest.mark.parametrize("error,retry_attempts", [ + ("sqlite_busy", 2), ("sqlite_locked", 1), ("sqlite_error", 1), +]) +def test_db_experiment_executes_sql_and_distinguishes_attempts_from_execution(tmp_path, error, retry_attempts): + output = tmp_path / "db" + run_cli("query", "--fixture", "--surfaces", "db", "--execution", "sql", + "--component", "db", "--db-error", error, "--output", str(output), + "--failure-probabilities", "0", "1", "--repeats", "1") + manifest = json.loads((output / "manifest.json").read_text()) + assert manifest["result_kind"] == "fixture_smoke" + assert manifest["harness"]["db_error"] == error + rows = [json.loads(line) for line in (output / "rows.jsonl").read_text().splitlines()] + assert len(rows) == 8 + assert {row["policy"] for row in rows} == {"none", "retry"} + assert len({row["workspace_revision"] for row in rows}) == 1 + for row in rows: + assert row["fault_origin"] == "simulated_exception" + assert row["source_hit"] is None and row["exact_answer_match"] is None + if row["failure_probability"] == 0: + assert row["outcome"] == "ok" and row["result_match"] is True + assert row["component_attempts"] == row["sql_executions"] == 1 + assert row["injected_faults"] == row["recovery"]["retries"] == 0 + else: + attempts = retry_attempts if row["policy"] == "retry" else 1 + assert row["outcome"] == "error" and row["result_match"] is False + assert row["component_attempts"] == row["injected_faults"] == attempts + assert row["sql_executions"] == 0 + assert row["recovery"]["retries"] == attempts - 1 + summary = json.loads((output / "summary.json").read_text()) + for group in summary["groups"]: + expected = 1 if group["failure_probability"] == 0 else 0 + assert group["completion_rate"] == group["result_match_rate"] == expected + + +def test_db_experiment_scores_explicit_sql_tasks_without_labels(tmp_path): + tasks = tmp_path / "tasks.jsonl" + tasks.write_text('{"task_id":"q","sql":"SELECT 42"}\n') + output = tmp_path / "db" + run_cli("query", "--fixture", "--surfaces", "db", "--execution", "sql", + "--component", "db", "--questions", str(tasks), "--output", str(output), + "--failure-probabilities", "0", "--repeats", "1") + rows = [json.loads(line) for line in (output / "rows.jsonl").read_text().splitlines()] + assert len(rows) == 2 + assert all(row["result"]["rows"] == [[42]] and row["result_match"] is None for row in rows) + + +@pytest.mark.parametrize("extra", [ + ("--component", "db"), + ("--execution", "sql"), + ("--component", "db", "--execution", "sql", "--surfaces", "kb"), + ("--outage-ms", "nan"), +]) +def test_invalid_db_experiment_options_fail_before_build(tmp_path, extra): + output = tmp_path / "db" + result = subprocess.run([sys.executable, "-m", "benchmark.robustness", "query", "--fixture", + "--output", str(output), *extra], cwd=REPO, capture_output=True, timeout=20) + assert result.returncode != 0 + assert not output.exists() diff --git a/docs/READ_RECOVERY.md b/docs/READ_RECOVERY.md index 0f381cc..0f44647 100644 --- a/docs/READ_RECOVERY.md +++ b/docs/READ_RECOVERY.md @@ -128,6 +128,83 @@ credentials and endpoint configuration. Pin dependencies and retain the source checkout/environment for reproduction. This runner doesn't overwrite or append to a prior experiment and does not automatically make API-priced claims. +## Database query fault injection + +SQLite query faults use the same probability, initial outage window, and failed +attempt delay as KB faults. There is no fail-first-N mode. The condition is +`elapsed < outage_ms OR random < probability`: after the window ends, probabilistic +failures continue. A probability of 1 therefore never recovers on its own. + +```bash +python -m benchmark.robustness query --fixture \ + --surfaces db --execution sql --component db --db-error sqlite_busy \ + --failure-probabilities 0 0.3 1 --repeats 5 --seed 7 \ + --retries 1 --deadline-s 5 --output /absolute/new-db-experiment +``` + +This builds real local SQLite tables and compares `none` and `retry` against the +same published workspace revision. It uses no model or embedding API. Default +fixture SQL checks an aggregate and a row count; `result_match_rate` compares +returned rows to explicit labels, rather than treating execution as correctness. +DB experiments do not offer BM25 fallback because document retrieval is not a +general substitute for SQL results. + +For custom SQL tasks, pass `--questions` containing JSONL such as: + +```json +{"task_id":"q1","sql":"SELECT 42","expected_rows":[[42]]} +``` + +Use `--execution sql --component db --surfaces db` with either `--fixture` or +`--source`. Without `expected_rows`, result correctness is null. SQL may use +`"{table}"` as a placeholder only when the revision contains exactly one table; +otherwise supply explicit published table names. Agent mode accepts natural +language `question` tasks as before and passes the plan to child MCP processes. +It requires a configured Codex host; fixture mode cannot evaluate agent answers. + +Available errors are `sqlite_busy` (code 5, retryable), `sqlite_locked` (code 6, +conservatively non-retryable), and `sqlite_error` (code 1, non-retryable). Faults +are constructed `sqlite3.OperationalError` objects wrapped in SQLAlchemy +`OperationalError`, exercising `.orig` classification. They do not acquire real +database locks. Rows label this as `fault_origin: simulated_exception`; real lock +contention is covered separately by the SQLite recovery integration tests. +MySQL/PostgreSQL query injection is not implemented; non-SQLite targets are +rejected rather than assigned SQLite errors. + +Trusted experiment hosts can also supply `DATAMIND_TEST_READ_FAULT`: + +```json +{"component":"db","error":"sqlite_busy","probability":0.3,"outage_ms":0,"delay_ms":5,"seed":7,"task":"q1","state":"/tmp/db-faults/q1.retry.sqlite3"} +``` + +Environment plans activate only inside pinned workspace reads, not during +workspace builds. In-process harnesses can use +`with datamind.experiment_faults.db_faults(plan): ...` around a read/recovery +operation. No model-facing tool enables faults. With no plan, execution creates +no experiment state. Plans are task-local and do not wrap provider methods, so +recreated services cannot double-install the injection. + +The shared executor checks faults after read-only SQL validation and within its +query timeout. Each retry consumes another event. Delays respect cancellation +and deadlines. Metadata inspection and ingestion writes are excluded. This does +not add physical cancellation of SQL already running in a worker thread. + +Each policy/repeat/task/probability has a separate state file, while seed/task/ +attempt schedules are paired across policies. State survives service and MCP +process recreation on the same host; use fresh files for a new experiment. +The outage starts at the first eligible query attempt. Concurrent attempts are +assigned atomic sequence numbers, but their ordering depends on scheduling. + +`component_attempts` counts visits to the fault boundary; `injected_faults` +counts decisions to fail (including delays later cancelled); `sql_executions` +counts entries to the user-query `conn.execute`, including native SQL failures. +It excludes metadata/PRAGMA calls and attempts rejected before execution. +Recovery metadata reports retries separately. The state DB must differ from the +target DB; state-store failures raise non-retryable `ExperimentFaultError` and +are reported as `experiment_error`, not as a target database outage. State I/O +adds experiment overhead, including at probability zero, so compare with the +same instrumentation enabled. + ## Build interruption workload ```bash From 1df2420e833798c92d24e9d7643cf8698b20e37a Mon Sep 17 00:00:00 2001 From: NankaiKey Date: Sun, 15 Nov 2026 17:57:35 +0000 Subject: [PATCH 5/6] feat: complete SQL error matrix and batch recovery script --- benchmark/robustness.py | 10 +- benchmark/sql_errors.py | 306 ++++++++++++++++++++++ datamind/experiment_db_errors.py | 87 ++++++ datamind/experiment_faults.py | 31 +-- datamind/tests/test_db_fault_injection.py | 2 +- datamind/tests/test_sql_error_script.py | 139 ++++++++++ docs/READ_RECOVERY.md | 32 ++- docs/SQL_ERROR_EXPERIMENTS.md | 95 +++++++ 8 files changed, 669 insertions(+), 33 deletions(-) create mode 100644 benchmark/sql_errors.py create mode 100644 datamind/experiment_db_errors.py create mode 100644 datamind/tests/test_sql_error_script.py create mode 100644 docs/SQL_ERROR_EXPERIMENTS.md diff --git a/benchmark/robustness.py b/benchmark/robustness.py index 7bbc98b..4fb5d4d 100644 --- a/benchmark/robustness.py +++ b/benchmark/robustness.py @@ -29,6 +29,7 @@ from datamind.core.logging import bind_context from datamind.core.recovery import recovery_summary from datamind.experiment_faults import ExperimentFaultError, db_counts, db_faults +from datamind.experiment_db_errors import DB_FAULTS, build_db_fault from datamind.workspace import Workspace REPO = Path(__file__).resolve().parents[1] @@ -239,8 +240,11 @@ async def query_experiment(args, output, source, tasks): if args.fixture and args.execution == "agent": raise ValueError("Fixture mode cannot evaluate LLM answers; use retrieval or sql") settings = settings_for(output / "runtime", args.fixture, args) - if args.component == "db" and settings.db.dialect != "sqlite": - raise ValueError("DB fault injection currently supports SQLite only") + if args.component == "db": + backend = {"dolt": "mysql", "postgres": "postgresql"}.get(settings.db.dialect, settings.db.dialect) + if backend != DB_FAULTS[args.db_error].backend: + raise ValueError("--db-error must match the configured database backend") + build_db_fault(args.db_error) # fail before building if the optional driver is absent workspace = workspace_for(settings) built = await workspace.update(str(source), surfaces=args.surfaces.split(","), graph_sources=prepared_graph(args)) manifest = provenance(args, source) @@ -467,7 +471,7 @@ def parser(): p.add_argument("--seed", type=int, default=0) p.add_argument("--execution", choices=["retrieval", "sql", "agent"], default="retrieval") p.add_argument("--component", choices=["embedding", "vector", "db"], default="embedding") - p.add_argument("--db-error", choices=["sqlite_busy", "sqlite_locked", "sqlite_error"], default="sqlite_busy") + p.add_argument("--db-error", choices=sorted(DB_FAULTS), default="sqlite_busy") p.add_argument("--failure-probabilities", type=float, nargs="+", default=[0., .1, .5, 1.]) p.add_argument("--outage-ms", type=float, default=0.) p.add_argument("--fault-delay-ms", type=float, default=0.) diff --git a/benchmark/sql_errors.py b/benchmark/sql_errors.py new file mode 100644 index 0000000..77367ec --- /dev/null +++ b/benchmark/sql_errors.py @@ -0,0 +1,306 @@ +"""Batch SQL error/recovery checks; no external database or model is contacted. + + python -m benchmark.sql_errors --output /tmp/new-sql-errors + +SQLite scenarios execute real local SELECTs. MySQL/PostgreSQL scenarios use +actual optional driver exceptions and a synthetic successful return value; +their results are exception-contract checks, never server integration results. +""" +from __future__ import annotations + +import argparse +import asyncio +import csv +import hashlib +import importlib.metadata +import json +import math +import platform +import random +import sqlite3 +import subprocess +import time +from collections import defaultdict +from pathlib import Path + +from sqlalchemy import create_mock_engine, event, text +from sqlalchemy.exc import DBAPIError + +from datamind.capabilities.db.providers.sqlite import SQLiteDialect +from datamind.capabilities.db.service import DBService +from datamind.config import DBConfig +from datamind.core.context import RequestContext +from datamind.core.logging import bind_context +from datamind.core.recovery import is_transient, recover_read, recovery_summary +from datamind.experiment_db_errors import DB_FAULTS, FaultDriverUnavailable, build_db_fault +from datamind.experiment_faults import before_db_read, db_counts, db_faults + +REPO = Path(__file__).resolve().parents[1] + + +def error_code(error): + raw = error.orig if isinstance(error, DBAPIError) else error + return (getattr(raw, "sqlite_errorcode", None) or getattr(raw, "sqlstate", None) + or getattr(raw, "pgcode", None) or getattr(raw, "errno", None) + or (raw.args[0] if raw.args and isinstance(raw.args[0], int) else None)) + + +def expected_schedule(seed, task, probability, retries): + """Independent oracle for probability-only schedules (no timing assumptions).""" + for attempt in range(retries + 1): + if random.Random(f"{seed}:{task}:{attempt}").random() >= probability: + return attempt + 1, True + return retries + 1, False + + +async def run_simulated(args, output, service, name, wrapping, policy, probability, repeat): + spec = DB_FAULTS[name] + base = {"backend": spec.backend, "scenario": name, "wrapping": wrapping, + "policy": policy, "probability": probability, "repeat": repeat, + "fault_origin": "simulated_exception", "expected_code": spec.code, + "expected_retryable": spec.retryable, + "execution_kind": "sqlite_query" if spec.backend == "sqlite" else "driver_contract_simulation"} + try: + sample = build_db_fault(name, wrapped=wrapping == "sqlalchemy") + except FaultDriverUnavailable: + return {**base, "status": "skipped", "skip_reason": "optional_driver_missing", + "check_passed": None, "sql_executions": None} + classified = is_transient(sample) + budget = args.retries if policy == "retry" else 0 + task = f"{name}:{repeat}" + state = output / "fault-states" / f"{name}.{wrapping}.{policy}.{probability}.{repeat}.sqlite3" + plan = {"component": "db", "error": name, "probability": probability, + "seed": args.seed, "task": task, "state": str(state), + "outage_ms": args.outage_ms, "delay_ms": args.fault_delay_ms} + target = (service.engine if spec.backend == "sqlite" else + create_mock_engine(f"{spec.backend}://", lambda *a, **k: None)) + observed = [] + + async def operation(): + try: + if spec.backend == "sqlite": + return (await service.query_sql("SELECT value FROM numbers")).rows + await before_db_read(target) + return [[42]] # contract-only success; no SQL/server execution + except Exception as error: + if wrapping == "raw" and isinstance(error, DBAPIError): + error = error.orig + observed.append(error) + raise error from None + + context = RequestContext.new() + context.extra["query_deadline"] = time.monotonic() + args.deadline_s + started = time.monotonic() + result = None + failure = None + with bind_context(context), db_faults(plan): + try: + result = await recover_read(operation, component="db_query_sql", retries=budget) + except Exception as error: + failure = error + actual = db_counts(state) + passed = (classified == spec.retryable and error_code(sample) == spec.code + and actual["attempts"] <= budget + 1) + if args.outage_ms == 0 and args.fault_delay_ms == 0: + expected_attempts, expected_success = expected_schedule( + args.seed, task, probability, budget if spec.retryable else 0, + ) + passed &= actual["attempts"] == expected_attempts and (failure is None) == expected_success + if failure is None: + passed &= result == [[42]] + return {**base, "status": "completed", "check_passed": bool(passed), + "classified_retryable": classified, "observed_codes": [error_code(e) for e in observed], + "attempts": actual["attempts"], "injected": actual["injected"], + "sql_executions": actual["executed"] if spec.backend == "sqlite" else None, + "operation_succeeded": failure is None, + "result_match": result == [[42]] if spec.backend == "sqlite" else None, + "final_error_type": type(failure).__name__ if failure else None, + "recovery": recovery_summary(context.extra.get("recovery_events", [])), + "latency_ms": (time.monotonic() - started) * 1000} + + +async def run_native(args, service, name, wrapping, policy): + queries = { + "native_syntax": "SELECT FROM numbers", + "native_missing_table": "SELECT value FROM missing_table", + "native_missing_column": "SELECT absent FROM numbers", + } + locked = name.startswith("real_busy") + retryable = locked + budget = args.retries if policy == "retry" else 0 + blocker = None + calls = 0 + executions = 0 + errors = [] + + def count_execution(conn, cursor, statement, parameters, context, executemany): + nonlocal executions + if statement.startswith("SELECT * FROM ("): + executions += 1 + + event.listen(service.engine, "before_cursor_execute", count_execution) + if locked: + blocker = sqlite3.connect(service.engine.url.database, isolation_level=None) + blocker.execute("BEGIN EXCLUSIVE") + + async def operation(): + nonlocal calls + calls += 1 + try: + return (await service.query_sql(queries.get(name, "SELECT value FROM numbers"))).rows + except Exception as error: + if name == "real_busy_release" and error_code(error) == sqlite3.SQLITE_BUSY: + blocker.rollback() + if wrapping == "raw" and isinstance(error, DBAPIError): + error = error.orig + errors.append(error) + raise error from None + + context = RequestContext.new() + context.extra["query_deadline"] = time.monotonic() + args.deadline_s + failure = None + result = None + started = time.monotonic() + try: + with bind_context(context): + try: + result = await recover_read(operation, component="db_query_sql", retries=budget) + except Exception as error: + failure = error + finally: + if blocker is not None: + blocker.rollback() + blocker.close() + event.remove(service.engine, "before_cursor_execute", count_execution) + expected_success = name == "real_busy_release" and budget > 0 + expected_attempts = min(2, budget + 1) if name == "real_busy_release" else budget + 1 if locked else 1 + expected_code = sqlite3.SQLITE_BUSY if locked else sqlite3.SQLITE_ERROR + passed = (bool(errors) and all(error_code(error) == expected_code for error in errors) + and is_transient(errors[0]) == retryable + and calls == expected_attempts and (failure is None) == expected_success + and (not expected_success or result == [[42]])) + return {"backend": "sqlite", "scenario": name, "wrapping": wrapping, "policy": policy, + "probability": None, "repeat": 0, "fault_origin": "real_lock" if locked else "native_sql_error", + "execution_kind": "sqlite_query", "expected_code": 5 if locked else 1, + "expected_retryable": retryable, "classified_retryable": is_transient(errors[0]) if errors else None, + "observed_codes": [error_code(e) for e in errors], "status": "completed", + "check_passed": passed, "attempts": calls, "injected": 0, "sql_executions": executions, + "operation_succeeded": failure is None, "result_match": result == [[42]], + "final_error_type": type(failure).__name__ if failure else None, + "recovery": recovery_summary(context.extra.get("recovery_events", [])), + "latency_ms": (time.monotonic() - started) * 1000} + + +def write_reports(output, rows, args): + groups = defaultdict(list) + for row in rows: + groups[row["backend"], row["scenario"], row["wrapping"]].append(row) + lines = ["# SQL error and recovery checks", "", + "SQLite runs real local queries. MySQL/PostgreSQL use driver exceptions only; no server is contacted.", + "A passed check means behavior matched expectations, including expected query failures.", "", + "| Backend | Scenario | Wrapping | Passed | Failed | Skipped |", + "|---|---|---|---:|---:|---:|"] + for (backend, name, wrapping), batch in groups.items(): + lines.append(f"| {backend} | {name} | {wrapping} | " + f"{sum(r['check_passed'] is True for r in batch)} | " + f"{sum(r['check_passed'] is False for r in batch)} | " + f"{sum(r['status'] == 'skipped' for r in batch)} |") + (output / "REPORT.md").write_text("\n".join(lines) + "\n") + fields = list(dict.fromkeys(key for row in rows for key in row)) + with (output / "results.csv").open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + for row in rows: + writer.writerow({k: json.dumps(v) if isinstance(v, (dict, list)) else v for k, v in row.items()}) + summary = {"rows": len(rows), "passed": sum(r["check_passed"] is True for r in rows), + "failed": sum(r["check_passed"] is False for r in rows), + "skipped": sum(r["status"] == "skipped" for r in rows), + "live_mysql_postgres_servers": False} + (output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") + versions = {} + for package in ("sqlalchemy", "pymysql", "psycopg"): + try: + versions[package] = importlib.metadata.version(package) + except importlib.metadata.PackageNotFoundError: + versions[package] = None + commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=REPO, capture_output=True, text=True).stdout.strip() + manifest = {"result_kind": "sql_error_mechanism_checks", "arguments": vars(args), + "git_commit": commit, "versions": versions, "sqlite_version": sqlite3.sqlite_version, + "python": platform.python_version(), + "code_hash": hashlib.sha256(json.dumps([ + (str(path.relative_to(REPO)), hashlib.sha256(path.read_bytes()).hexdigest()) + for package in ("datamind", "benchmark") + for path in sorted((REPO / package).rglob("*.py")) + ]).encode()).hexdigest()} + (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + return summary + + +async def run(args): + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=False) + dialect = SQLiteDialect() + engine = dialect.build_engine(None, default_path=output / "target.sqlite3", connect_args={"timeout": 0.005}) + with engine.begin() as connection: + connection.execute(text("CREATE TABLE numbers (value INTEGER)")) + connection.execute(text("INSERT INTO numbers VALUES (42)")) + service = DBService(dialect=dialect, engine=engine, db_cfg=DBConfig(query_timeout_s=args.deadline_s)) + names = args.errors or [name for name, spec in DB_FAULTS.items() + if args.backend == "all" or spec.backend == args.backend] + forms = ("raw", "sqlalchemy") if args.wrapping == "both" else (args.wrapping,) + rows = [] + + def append(row): + rows.append(row) + with (output / "rows.jsonl").open("a") as handle: + handle.write(json.dumps(row) + "\n") + + try: + for name in names: + for wrapping in forms: + for policy in ("none", "retry"): + for probability in args.failure_probabilities: + for repeat in range(args.repeats): + append(await run_simulated(args, output, service, name, wrapping, policy, probability, repeat)) + if args.backend in {"sqlite", "all"} and not args.skip_native: + for name in ("native_syntax", "native_missing_table", "native_missing_column", "real_busy_release", "real_busy_persistent"): + for wrapping in forms: + for policy in ("none", "retry"): + append(await run_native(args, service, name, wrapping, policy)) + finally: + engine.dispose() + summary = write_reports(output, rows, args) + print(json.dumps({"output": str(output), **summary})) + return 1 if summary["failed"] or (args.require_drivers and summary["skipped"]) else 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, help="new experiment directory") + parser.add_argument("--backend", choices=["all", "sqlite", "mysql", "postgresql"], default="all") + parser.add_argument("--errors", nargs="+", choices=sorted(DB_FAULTS)) + parser.add_argument("--wrapping", choices=["both", "raw", "sqlalchemy"], default="both") + parser.add_argument("--failure-probabilities", nargs="+", type=float, default=[0, 0.3, 1]) + parser.add_argument("--repeats", type=int, default=1) + parser.add_argument("--retries", type=int, default=1) + parser.add_argument("--seed", type=int, default=7) + parser.add_argument("--outage-ms", type=float, default=0) + parser.add_argument("--fault-delay-ms", type=float, default=0) + parser.add_argument("--deadline-s", type=float, default=5) + parser.add_argument("--skip-native", action="store_true") + parser.add_argument("--require-drivers", action="store_true", help="fail if optional driver scenarios were skipped") + args = parser.parse_args(argv) + if (any(not math.isfinite(p) or not 0 <= p <= 1 for p in args.failure_probabilities) + or not 0 <= args.retries <= 5 or args.repeats < 1 + or not all(math.isfinite(v) and v >= 0 for v in (args.outage_ms, args.fault_delay_ms)) + or not math.isfinite(args.deadline_s) or args.deadline_s <= 0): + parser.error("invalid probability, retry budget, repeat count or duration") + if args.errors: + args.errors = list(dict.fromkeys(args.errors)) + if args.backend != "all" and any(DB_FAULTS[name].backend != args.backend for name in args.errors): + parser.error("--errors must match --backend") + return asyncio.run(run(args)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/datamind/experiment_db_errors.py b/datamind/experiment_db_errors.py new file mode 100644 index 0000000..f59c9eb --- /dev/null +++ b/datamind/experiment_db_errors.py @@ -0,0 +1,87 @@ +"""Construct opt-in DB experiment exceptions without contacting a server. + +Expected retry decisions are experiment labels, independent of recovery's rules. +Optional drivers are imported only when their fault is selected. +""" +from dataclasses import dataclass +import importlib +import sqlite3 + +from sqlalchemy.exc import DBAPIError + +from datamind.core.errors import ConfigError + + +class FaultDriverUnavailable(ConfigError): + """An optional driver required by the selected experiment is absent.""" + + +@dataclass(frozen=True) +class DBFault: + backend: str + code: int | str + retryable: bool + kind: str = "OperationalError" + native_name: str = "" + + +DB_FAULTS = { + "sqlite_busy": DBFault("sqlite", 5, True, native_name="SQLITE_BUSY"), + "sqlite_busy_snapshot": DBFault("sqlite", 517, True, native_name="SQLITE_BUSY_SNAPSHOT"), + "sqlite_locked": DBFault("sqlite", 6, False, native_name="SQLITE_LOCKED"), + "sqlite_error": DBFault("sqlite", 1, False, native_name="SQLITE_ERROR"), + "sqlite_readonly": DBFault("sqlite", 8, False, native_name="SQLITE_READONLY"), + "sqlite_interrupt": DBFault("sqlite", 9, False, native_name="SQLITE_INTERRUPT"), + "sqlite_corrupt": DBFault("sqlite", 11, False, "DatabaseError", "SQLITE_CORRUPT"), + "sqlite_cantopen": DBFault("sqlite", 14, False, native_name="SQLITE_CANTOPEN"), + "sqlite_constraint": DBFault("sqlite", 19, False, "IntegrityError", "SQLITE_CONSTRAINT"), + "sqlite_auth": DBFault("sqlite", 23, False, "DatabaseError", "SQLITE_AUTH"), + "mysql_lock_timeout": DBFault("mysql", 1205, True), + "mysql_deadlock": DBFault("mysql", 1213, True), + "mysql_server_gone": DBFault("mysql", 2006, True), + "mysql_connection_lost": DBFault("mysql", 2013, True), + "mysql_auth": DBFault("mysql", 1045, False), + "mysql_unknown_database": DBFault("mysql", 1049, False), + "mysql_permission": DBFault("mysql", 1142, False), + "mysql_syntax": DBFault("mysql", 1064, False, "ProgrammingError"), + "mysql_missing_table": DBFault("mysql", 1146, False, "ProgrammingError"), + "mysql_missing_column": DBFault("mysql", 1054, False, "ProgrammingError"), + "mysql_duplicate": DBFault("mysql", 1062, False, "IntegrityError"), + "postgres_connection_failure": DBFault("postgresql", "08006", True), + "postgres_serialization": DBFault("postgresql", "40001", True), + "postgres_deadlock": DBFault("postgresql", "40P01", True), + "postgres_startup": DBFault("postgresql", "57P03", True), + "postgres_auth": DBFault("postgresql", "28P01", False), + "postgres_permission": DBFault("postgresql", "42501", False), + "postgres_syntax": DBFault("postgresql", "42601", False), + "postgres_missing_table": DBFault("postgresql", "42P01", False), + "postgres_missing_column": DBFault("postgresql", "42703", False), + "postgres_duplicate": DBFault("postgresql", "23505", False), + "postgres_cancelled": DBFault("postgresql", "57014", False), + "postgres_protocol": DBFault("postgresql", "08P01", False), +} + + +def build_db_fault(name, *, wrapped=True): + """Return an actual driver exception, optionally mapped by SQLAlchemy.""" + if name not in DB_FAULTS: + raise ConfigError("Unknown database experiment error") + spec = DB_FAULTS[name] + try: + if spec.backend == "sqlite": + driver = sqlite3 + original = getattr(driver, spec.kind)("injected experiment DB fault") + original.sqlite_errorcode = spec.code + original.sqlite_errorname = spec.native_name + elif spec.backend == "mysql": + driver = importlib.import_module("pymysql") + original = getattr(driver.err, spec.kind)(spec.code, "injected experiment DB fault") + else: + driver = importlib.import_module("psycopg") + original = driver.errors.lookup(spec.code)("injected experiment DB fault") + except ImportError as exc: + extra = "mysql" if spec.backend == "mysql" else "postgres" + raise FaultDriverUnavailable(f"Install datamind[{extra}] for {spec.backend} fault simulation") from exc + error = DBAPIError.instance(None, None, original, driver.Error) if wrapped else original + error.datamind_fault_injected = True + return error diff --git a/datamind/experiment_faults.py b/datamind/experiment_faults.py index 8063227..1def121 100644 --- a/datamind/experiment_faults.py +++ b/datamind/experiment_faults.py @@ -15,10 +15,9 @@ from dataclasses import dataclass from pathlib import Path -from sqlalchemy.exc import OperationalError - from datamind.core.errors import ConfigError from datamind.core.logging import current_context +from datamind.experiment_db_errors import DB_FAULTS, FaultDriverUnavailable, build_db_fault def install(kb): @@ -63,13 +62,6 @@ class ExperimentFaultError(ConfigError): """Invalid experiment setup or state failure; never a retryable DB outage.""" -_SQLITE_ERRORS = { - "sqlite_busy": (sqlite3.SQLITE_BUSY, "SQLITE_BUSY"), - "sqlite_locked": (sqlite3.SQLITE_LOCKED, "SQLITE_LOCKED"), - "sqlite_error": (sqlite3.SQLITE_ERROR, "SQLITE_ERROR"), -} - - @dataclass(frozen=True) class _DBPlan: state: Path @@ -89,8 +81,8 @@ def _parse_db_plan(plan): if plan.get("component") != "db": raise ValueError("component must be db") error = plan.get("error", "sqlite_busy") - if error not in _SQLITE_ERRORS: - raise ValueError("unsupported DB fault; expected sqlite_busy, sqlite_locked or sqlite_error") + if error not in DB_FAULTS: + raise ValueError("unsupported DB fault") probability = float(plan["probability"]) outage = float(plan.get("outage_ms", 0)) delay = float(plan.get("delay_ms", 0)) @@ -176,20 +168,19 @@ async def before_db_read(engine): plan = _db_plan() if plan is None: return None - if engine.dialect.name != "sqlite": - raise ExperimentFaultError("DB fault injection currently supports SQLite only") - database = engine.url.database + backend = DB_FAULTS[plan.error].backend + if engine.dialect.name != backend: + raise ExperimentFaultError(f"{plan.error} requires {backend} target") + database = engine.url.database if backend == "sqlite" else None if database and database != ":memory:" and Path(database).resolve() == plan.state: raise ExperimentFaultError("Fault state must be separate from the target database") fail = await asyncio.to_thread(_db_attempt, plan) if fail: await asyncio.sleep(plan.delay_ms / 1000) - code, name = _SQLITE_ERRORS[plan.error] - original = sqlite3.OperationalError("injected experiment DB fault") - original.sqlite_errorcode = code - original.sqlite_errorname = name - error = OperationalError(None, None, original) - error.datamind_fault_injected = True + try: + error = build_db_fault(plan.error) + except FaultDriverUnavailable as exc: + raise ExperimentFaultError("Selected DB fault driver is unavailable") from exc raise error return plan.state diff --git a/datamind/tests/test_db_fault_injection.py b/datamind/tests/test_db_fault_injection.py index 251f5ac..e790058 100644 --- a/datamind/tests/test_db_fault_injection.py +++ b/datamind/tests/test_db_fault_injection.py @@ -212,7 +212,7 @@ async def test_target_cannot_be_its_own_fault_state(service, tmp_path): @pytest.mark.asyncio async def test_non_sqlite_backend_is_rejected_instead_of_spoofed(tmp_path): with faults.db_faults(plan(tmp_path)): - with pytest.raises(faults.ExperimentFaultError, match="SQLite only"): + with pytest.raises(faults.ExperimentFaultError, match="requires sqlite"): await faults.before_db_read(SimpleNamespace(dialect=SimpleNamespace(name="mysql"))) assert not Path(plan(tmp_path)["state"]).exists() diff --git a/datamind/tests/test_sql_error_script.py b/datamind/tests/test_sql_error_script.py new file mode 100644 index 0000000..f71762d --- /dev/null +++ b/datamind/tests/test_sql_error_script.py @@ -0,0 +1,139 @@ +"""Public SQL error script reports actual behavior and explicit driver skips.""" +import csv +import importlib +import json +import subprocess +import sys +from pathlib import Path + +import pytest +from sqlalchemy import create_mock_engine +from sqlalchemy.exc import DBAPIError + +from benchmark import sql_errors +from datamind.core.recovery import is_transient +from datamind.experiment_db_errors import DB_FAULTS, FaultDriverUnavailable, build_db_fault +from datamind.experiment_faults import ExperimentFaultError, before_db_read, db_faults + +REPO = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize("name", list(DB_FAULTS)) +@pytest.mark.parametrize("wrapped", [False, True]) +def test_real_driver_classes_match_catalog_labels(name, wrapped): + spec = DB_FAULTS[name] + if spec.backend != "sqlite": + pytest.importorskip("pymysql" if spec.backend == "mysql" else "psycopg") + error = build_db_fault(name, wrapped=wrapped) + assert isinstance(error, DBAPIError) is wrapped + assert sql_errors.error_code(error) == spec.code + assert is_transient(error) is spec.retryable + assert error.datamind_fault_injected is True + raw = error.orig if wrapped else error + module = type(raw).__module__ + assert module.startswith({"sqlite": "sqlite3", "mysql": "pymysql", "postgresql": "psycopg"}[spec.backend]) + + +def test_sqlite_script_writes_all_reports_and_runs_real_errors(tmp_path): + output = tmp_path / "sql-errors" + result = subprocess.run([ + sys.executable, "-m", "benchmark.sql_errors", "--backend", "sqlite", + "--failure-probabilities", "0", "1", "--output", str(output), + ], cwd=REPO, capture_output=True, text=True, timeout=30) + assert result.returncode == 0, result.stderr + summary = json.loads((output / "summary.json").read_text()) + assert summary == {"rows": 100, "passed": 100, "failed": 0, "skipped": 0, + "live_mysql_postgres_servers": False} + rows = [json.loads(line) for line in (output / "rows.jsonl").read_text().splitlines()] + with (output / "results.csv").open() as handle: + assert len(list(csv.DictReader(handle))) == len(rows) + assert "native_missing_column" in (output / "REPORT.md").read_text() + manifest = json.loads((output / "manifest.json").read_text()) + assert manifest["code_hash"] and manifest["result_kind"] == "sql_error_mechanism_checks" + for row in rows: + if row["scenario"] == "real_busy_release" and row["policy"] == "retry": + assert row["operation_succeeded"] and row["attempts"] == 2 + assert row["sql_executions"] == 2 and row["injected"] == 0 + if row["scenario"] == "native_syntax": + assert not row["operation_succeeded"] and row["check_passed"] + assert row["observed_codes"] == [1] + # Existing reports and inputs are never overwritten. + again = subprocess.run([sys.executable, "-m", "benchmark.sql_errors", "--output", str(output)], + cwd=REPO, capture_output=True, timeout=20) + assert again.returncode != 0 + assert json.loads((output / "summary.json").read_text()) == summary + + +@pytest.mark.parametrize("backend,name,driver", [ + ("mysql", "mysql_deadlock", "pymysql"), + ("postgresql", "postgres_serialization", "psycopg"), +]) +def test_serverless_driver_checks_do_not_claim_sql_execution(tmp_path, backend, name, driver): + pytest.importorskip(driver) + output = tmp_path / backend + assert sql_errors.main(["--backend", backend, "--errors", name, "--require-drivers", + "--failure-probabilities", "0", "1", "--output", str(output)]) == 0 + rows = [json.loads(line) for line in (output / "rows.jsonl").read_text().splitlines()] + assert len(rows) == 8 and all(row["check_passed"] for row in rows) + assert all(row["execution_kind"] == "driver_contract_simulation" + and row["sql_executions"] is None and row["result_match"] is None for row in rows) + + +@pytest.mark.parametrize("required,exit_code", [(False, 0), (True, 1)]) +def test_missing_optional_driver_is_an_explicit_skip(tmp_path, monkeypatch, required, exit_code): + original = importlib.import_module + + def missing_driver(name, *args, **kwargs): + if name == "pymysql": + raise ModuleNotFoundError("driver unavailable") + return original(name, *args, **kwargs) + + monkeypatch.setattr(importlib, "import_module", missing_driver) + with pytest.raises(FaultDriverUnavailable): + build_db_fault("mysql_deadlock") + output = tmp_path / "missing" + args = ["--backend", "mysql", "--errors", "mysql_deadlock", "--wrapping", "raw", + "--failure-probabilities", "1", "--output", str(output)] + assert sql_errors.main(args + (["--require-drivers"] if required else [])) == exit_code + summary = json.loads((output / "summary.json").read_text()) + assert summary["passed"] == summary["failed"] == 0 and summary["skipped"] == 2 + + +def test_bad_classification_fails_the_script_instead_of_passing_expected_sql_failures(tmp_path, monkeypatch): + monkeypatch.setattr(sql_errors, "is_transient", lambda error: True) + output = tmp_path / "bad-classifier" + assert sql_errors.main(["--backend", "sqlite", "--errors", "sqlite_locked", "--wrapping", "raw", + "--failure-probabilities", "1", "--skip-native", "--output", str(output)]) == 1 + summary = json.loads((output / "summary.json").read_text()) + assert summary["failed"] == 2 + + +@pytest.mark.asyncio +async def test_provider_driver_setup_failure_is_not_a_target_database_outage(tmp_path, monkeypatch): + original = importlib.import_module + + def missing_driver(name, *args, **kwargs): + if name == "pymysql": + raise ModuleNotFoundError("driver unavailable") + return original(name, *args, **kwargs) + + engine = create_mock_engine("mysql://", lambda *a, **k: None) + monkeypatch.setattr(importlib, "import_module", missing_driver) + plan = {"component": "db", "error": "mysql_deadlock", "probability": 1, + "seed": 7, "task": "q", "state": str(tmp_path / "state.db")} + with db_faults(plan), pytest.raises(ExperimentFaultError) as caught: + await before_db_read(engine) + assert isinstance(caught.value.__cause__, FaultDriverUnavailable) + assert not is_transient(caught.value) + + +@pytest.mark.parametrize("extra", [ + ["--failure-probabilities", "nan"], ["--retries", "6"], ["--fault-delay-ms", "-1"], + ["--backend", "sqlite", "--errors", "mysql_deadlock"], +]) +def test_invalid_cli_does_not_create_output(tmp_path, extra): + output = tmp_path / "invalid" + with pytest.raises(SystemExit) as caught: + sql_errors.main(["--output", str(output), *extra]) + assert caught.value.code == 2 + assert not output.exists() diff --git a/docs/READ_RECOVERY.md b/docs/READ_RECOVERY.md index 0f44647..ddfc4c0 100644 --- a/docs/READ_RECOVERY.md +++ b/docs/READ_RECOVERY.md @@ -130,7 +130,7 @@ to a prior experiment and does not automatically make API-priced claims. ## Database query fault injection -SQLite query faults use the same probability, initial outage window, and failed +Database query faults use the same probability, initial outage window, and failed attempt delay as KB faults. There is no fail-first-N mode. The condition is `elapsed < outage_ms OR random < probability`: after the window ends, probabilistic failures continue. A probability of 1 therefore never recovers on its own. @@ -162,14 +162,28 @@ otherwise supply explicit published table names. Agent mode accepts natural language `question` tasks as before and passes the plan to child MCP processes. It requires a configured Codex host; fixture mode cannot evaluate agent answers. -Available errors are `sqlite_busy` (code 5, retryable), `sqlite_locked` (code 6, -conservatively non-retryable), and `sqlite_error` (code 1, non-retryable). Faults -are constructed `sqlite3.OperationalError` objects wrapped in SQLAlchemy -`OperationalError`, exercising `.orig` classification. They do not acquire real -database locks. Rows label this as `fault_origin: simulated_exception`; real lock -contention is covered separately by the SQLite recovery integration tests. -MySQL/PostgreSQL query injection is not implemented; non-SQLite targets are -rejected rather than assigned SQLite errors. +Faults include `sqlite_busy` (code 5, retryable), `sqlite_locked` (code 6, +conservatively non-retryable), and `sqlite_error` (code 1, non-retryable), plus +extended SQLite BUSY, permission, corruption and constraint cases. MySQL faults +include `mysql_deadlock`, `mysql_lock_timeout`, disconnections, authentication, +syntax and schema errors. See `--help` or `datamind.experiment_db_errors.DB_FAULTS` +for all 33 named errors and their expected decisions. + +Faults use actual driver exception classes mapped by SQLAlchemy, exercising +`.orig` classification. These constructed errors do not acquire real database +locks. Rows label them `fault_origin: simulated_exception`; real lock contention +is checked separately by the batch script and integration tests. Errors must +match the target engine's backend: SQLite faults cannot be injected into MySQL. +MySQL/Dolt injection requires the mysql extra. PostgreSQL exception construction +and the common executor support PostgreSQL dialects with the postgres extra, +but this change does not add a registered PostgreSQL service adapter. + +For a serverless batch of all error types, raw/wrapped exceptions and native +SQLite errors, see [SQL error experiments](SQL_ERROR_EXPERIMENTS.md): + +```bash +python -m benchmark.sql_errors --output /absolute/new-sql-error-report +``` Trusted experiment hosts can also supply `DATAMIND_TEST_READ_FAULT`: diff --git a/docs/SQL_ERROR_EXPERIMENTS.md b/docs/SQL_ERROR_EXPERIMENTS.md new file mode 100644 index 0000000..290ea5e --- /dev/null +++ b/docs/SQL_ERROR_EXPERIMENTS.md @@ -0,0 +1,95 @@ +# SQL error and recovery experiments + +Run the complete script from the repository root: + +```bash +python -m benchmark.sql_errors --output /tmp/new-sql-errors +``` + +The output directory must not already exist. The script only creates and queries +experiment-owned local files. It never connects to MySQL/PostgreSQL, calls a +model, or edits an existing workspace. + +SQLite needs no optional driver. To include actual MySQL/PostgreSQL exception +classes, install the existing optional extras in your development environment: + +```bash +python -m pip install -e '.[mysql,postgres]' +python -m benchmark.sql_errors --require-drivers --output /tmp/new-all-sql-errors +``` + +Without these extras, corresponding rows are explicitly `skipped`, never passed. +`--require-drivers` returns a nonzero exit status if any case was skipped. + +## Coverage + +The default matrix has 416 checks when both optional drivers are installed: + +- 33 error types, raw and SQLAlchemy-wrapped exceptions, no-retry and retry + policies, and probabilities 0, 0.3 and 1: 396 simulated-error checks. +- Five native SQLite scenarios, raw/wrapped errors and both policies: 20 checks. + +| Backend | Error types | +|---|---| +| SQLite | BUSY, BUSY_SNAPSHOT, LOCKED, SQL error, read-only, interrupt, corruption, cannot-open, constraint, authorization | +| MySQL | Lock timeout, deadlock, server gone, connection lost, authentication, unknown database, permission, syntax, missing table, missing column, duplicate key | +| PostgreSQL | Connection failure, serialization failure, deadlock, startup, authentication, permission, syntax, missing table, missing column, duplicate key, cancellation, protocol violation | + +SQLite simulated cases inject errors at DataMind's common read executor, then +execute real local SELECTs when the attempt is allowed through. MySQL/PostgreSQL +rows are `execution_kind: driver_contract_simulation`: they use real PyMySQL or +Psycopg exception objects and a synthetic successful return value. Their +`sql_executions` and `result_match` are null. These checks validate exception +classification and recovery control flow, not server behavior or adapter support. + +Native SQLite scenarios execute invalid SQL for syntax, missing-table and +missing-column errors. Two more scenarios hold an actual `BEGIN EXCLUSIVE` +lock from another connection: one releases the lock after a failed read, allowing +retry to recover; the other holds it until the retry budget is exhausted. +These rows are labeled `native_sql_error` or `real_lock`; no probability-based +exception is injected into them. + +## Options + +```bash +# SQLite only, with two retries and more samples +python -m benchmark.sql_errors --backend sqlite --retries 2 --repeats 5 \ + --failure-probabilities 0 0.1 0.3 0.5 1 --output /tmp/new-sqlite-sweep + +# Selected cases; no native SQLite scenarios +python -m benchmark.sql_errors --errors sqlite_busy mysql_deadlock postgres_deadlock \ + --wrapping sqlalchemy --skip-native --output /tmp/new-selected-errors + +# A temporary outage followed by normal operation +python -m benchmark.sql_errors --backend sqlite --errors sqlite_busy --skip-native \ + --failure-probabilities 0 --outage-ms 80 --retries 3 --output /tmp/new-outage-check +``` + +`--fault-delay-ms` delays injected failures inside the read timeout/deadline. +`--deadline-s` bounds each recovery operation. Outage and probability conditions +are combined with OR, matching KB behavior. There is no fail-first-N mode. +State files and task-local contexts preserve the probability sequence; policies +start from the same seeded sequence but retries consume subsequent events. +The native lock-release scenario is an actual unlock operation, not an additional +fault-scheduling mode. + +## Reports and interpretation + +- `rows.jsonl`: individual checks, observed codes, classification, attempt and + retry counts, operation success, execution kind, and timing. +- `results.csv`: the same rows for spreadsheet analysis. +- `REPORT.md`: checks passed, failed and skipped by backend/error/wrapping. +- `summary.json`: aggregate check counts and explicit server-integration status. +- `manifest.json`: arguments, commit, source-code hash and runtime versions. + +A check **passes** when behavior matches expectations. For example, a syntax +error should fail the query without retrying; that is a passed check with +`operation_succeeded: false`. It is not a recovered query. Classification labels +and the probability-only schedule oracle are independent of the recovery +implementation. Timing-window scenarios check classification, bounded attempts +and successful-result content without assuming a particular elapsed-time order. + +Exit status is nonzero for a failed check, invalid arguments, unavailable required +drivers, or infrastructure failure. Rows are written incrementally. Reports +distinguish simulated errors from native errors and real locks; do not treat +this script's check-pass rate as benchmark task accuracy or recovery success rate. From 594c4083339426816bcdc1f0f9718e7f66259fc4 Mon Sep 17 00:00:00 2001 From: NankaiKey Date: Mon, 16 Nov 2026 04:56:10 +0000 Subject: [PATCH 6/6] test: cover PostgreSQL admin shutdown and lock unavailable faults --- datamind/experiment_db_errors.py | 4 ++++ datamind/tests/test_sql_error_script.py | 10 ++++++++++ docs/READ_RECOVERY.md | 5 ++++- docs/SQL_ERROR_EXPERIMENTS.md | 20 ++++++++++++++++---- 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/datamind/experiment_db_errors.py b/datamind/experiment_db_errors.py index f59c9eb..7559828 100644 --- a/datamind/experiment_db_errors.py +++ b/datamind/experiment_db_errors.py @@ -51,6 +51,10 @@ class DBFault: "postgres_serialization": DBFault("postgresql", "40001", True), "postgres_deadlock": DBFault("postgresql", "40P01", True), "postgres_startup": DBFault("postgresql", "57P03", True), + # Known gaps found against real servers: record current classification until + # a separate recovery-policy change permits these independent-read retries. + "postgres_admin_shutdown": DBFault("postgresql", "57P01", False), + "postgres_lock_not_available": DBFault("postgresql", "55P03", False), "postgres_auth": DBFault("postgresql", "28P01", False), "postgres_permission": DBFault("postgresql", "42501", False), "postgres_syntax": DBFault("postgresql", "42601", False), diff --git a/datamind/tests/test_sql_error_script.py b/datamind/tests/test_sql_error_script.py index f71762d..4b3c773 100644 --- a/datamind/tests/test_sql_error_script.py +++ b/datamind/tests/test_sql_error_script.py @@ -67,6 +67,8 @@ def test_sqlite_script_writes_all_reports_and_runs_real_errors(tmp_path): @pytest.mark.parametrize("backend,name,driver", [ ("mysql", "mysql_deadlock", "pymysql"), ("postgresql", "postgres_serialization", "psycopg"), + ("postgresql", "postgres_admin_shutdown", "psycopg"), + ("postgresql", "postgres_lock_not_available", "psycopg"), ]) def test_serverless_driver_checks_do_not_claim_sql_execution(tmp_path, backend, name, driver): pytest.importorskip(driver) @@ -77,6 +79,14 @@ def test_serverless_driver_checks_do_not_claim_sql_execution(tmp_path, backend, assert len(rows) == 8 and all(row["check_passed"] for row in rows) assert all(row["execution_kind"] == "driver_contract_simulation" and row["sql_executions"] is None and row["result_match"] is None for row in rows) + if name in {"postgres_admin_shutdown", "postgres_lock_not_available"}: + for row in rows: + assert row["classified_retryable"] is False + if row["probability"] == 1: + assert row["observed_codes"] == [DB_FAULTS[name].code] + assert row["attempts"] == 1 + assert row["recovery"]["retries"] == 0 + assert not row["operation_succeeded"] @pytest.mark.parametrize("required,exit_code", [(False, 0), (True, 1)]) diff --git a/docs/READ_RECOVERY.md b/docs/READ_RECOVERY.md index ddfc4c0..c762489 100644 --- a/docs/READ_RECOVERY.md +++ b/docs/READ_RECOVERY.md @@ -167,7 +167,10 @@ conservatively non-retryable), and `sqlite_error` (code 1, non-retryable), plus extended SQLite BUSY, permission, corruption and constraint cases. MySQL faults include `mysql_deadlock`, `mysql_lock_timeout`, disconnections, authentication, syntax and schema errors. See `--help` or `datamind.experiment_db_errors.DB_FAULTS` -for all 33 named errors and their expected decisions. +for all 35 named errors and their expected decisions. The real-server omissions +`postgres_admin_shutdown` (57P01) and `postgres_lock_not_available` (55P03) are +included as currently non-retryable cases; adding injection coverage does not +change the recovery allowlist. Faults use actual driver exception classes mapped by SQLAlchemy, exercising `.orig` classification. These constructed errors do not acquire real database diff --git a/docs/SQL_ERROR_EXPERIMENTS.md b/docs/SQL_ERROR_EXPERIMENTS.md index 290ea5e..25aae9b 100644 --- a/docs/SQL_ERROR_EXPERIMENTS.md +++ b/docs/SQL_ERROR_EXPERIMENTS.md @@ -23,17 +23,29 @@ Without these extras, corresponding rows are explicitly `skipped`, never passed. ## Coverage -The default matrix has 416 checks when both optional drivers are installed: +The default matrix has 440 checks when both optional drivers are installed: -- 33 error types, raw and SQLAlchemy-wrapped exceptions, no-retry and retry - policies, and probabilities 0, 0.3 and 1: 396 simulated-error checks. +- 35 error types, raw and SQLAlchemy-wrapped exceptions, no-retry and retry + policies, and probabilities 0, 0.3 and 1: 420 simulated-error checks. - Five native SQLite scenarios, raw/wrapped errors and both policies: 20 checks. | Backend | Error types | |---|---| | SQLite | BUSY, BUSY_SNAPSHOT, LOCKED, SQL error, read-only, interrupt, corruption, cannot-open, constraint, authorization | | MySQL | Lock timeout, deadlock, server gone, connection lost, authentication, unknown database, permission, syntax, missing table, missing column, duplicate key | -| PostgreSQL | Connection failure, serialization failure, deadlock, startup, authentication, permission, syntax, missing table, missing column, duplicate key, cancellation, protocol violation | +| PostgreSQL | Connection failure, serialization failure, deadlock, startup, administrator termination, lock not available, authentication, permission, syntax, missing table, missing column, duplicate key, cancellation, protocol violation | + +`postgres_admin_shutdown` (57P01) and `postgres_lock_not_available` (55P03) +cover omissions discovered against real PostgreSQL. Their labels currently +expect no retry, matching the existing recovery allowlist. A passed check for +these cases documents current behavior, not successful recovery or resolution of +the policy gap. This coverage change does not modify that allowlist. + +```bash +python -m benchmark.sql_errors --backend postgresql \ + --errors postgres_admin_shutdown postgres_lock_not_available \ + --require-drivers --output /tmp/new-postgres-gap-checks +``` SQLite simulated cases inject errors at DataMind's common read executor, then execute real local SELECTs when the attempt is allowed through. MySQL/PostgreSQL