You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/08/03 19:09:06 UTC

(superset) branch master updated: fix(versioning): stop filing every operational failure under the migration race (#42709)

This is an automated email from the ASF dual-hosted git repository.

rusackas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/master by this push:
     new bf34c7f2b47 fix(versioning): stop filing every operational failure under the migration race (#42709)
bf34c7f2b47 is described below

commit bf34c7f2b479b8aadc5294d941fc58e725f39e26
Author: Mike Bridge <mi...@bridgecanada.com>
AuthorDate: Mon Aug 3 20:08:59 2026 +0100

    fix(versioning): stop filing every operational failure under the migration race (#42709)
    
    Co-authored-by: Claude Opus 5 (1M context) <no...@anthropic.com>
---
 superset/versioning/baseline/collection.py         |  20 +++-
 superset/versioning/changes/listener.py            |  56 ++++-------
 superset/versioning/db_errors.py                   |  69 +++++++++++++
 superset/versioning/metrics.py                     |  54 ++++++++++
 superset/versioning/queries.py                     |  28 ++++--
 tests/unit_tests/versioning/test_collection.py     |  73 ++++++++++++++
 tests/unit_tests/versioning/test_db_errors.py      | 109 +++++++++++++++++++++
 tests/unit_tests/versioning/test_listener.py       |  47 +++++++++
 .../versioning/test_queries_change_records.py      |  61 ++++++++++++
 9 files changed, 471 insertions(+), 46 deletions(-)

diff --git a/superset/versioning/baseline/collection.py b/superset/versioning/baseline/collection.py
index 7ab78a9d608..cfe39df82c7 100644
--- a/superset/versioning/baseline/collection.py
+++ b/superset/versioning/baseline/collection.py
@@ -45,6 +45,9 @@ import sqlalchemy as sa
 from sqlalchemy.exc import OperationalError, ProgrammingError
 from sqlalchemy.orm import Session
 
+from superset.versioning.db_errors import is_missing_table_error
+from superset.versioning.metrics import incr_capture_error
+
 # Populated at app startup (superset/initialization/__init__.py) before
 # register_baseline_listener() is called.
 VERSIONED_MODELS: list[type] = []
@@ -140,14 +143,21 @@ def shadow_row_count(session: Session, obj: Any, version_table: Any) -> int | No
                 )
                 .scalar()
             )
-    except (OperationalError, ProgrammingError):
-        # Missing table: OperationalError on SQLite/MySQL,
-        # ProgrammingError (UndefinedTable) on PostgreSQL.
-        return None
-    except Exception:  # pylint: disable=broad-except
+    except Exception as ex:  # pylint: disable=broad-except
+        if isinstance(
+            ex, (OperationalError, ProgrammingError)
+        ) and is_missing_table_error(ex):
+            # Missing version table (migration not yet applied) — the one
+            # benign case; stay quiet.
+            return None
+        # Any other failure also returns None, and the caller then skips
+        # baseline capture for this flush — that loss must be visible on
+        # the same alerting surface as the change-record path, not filed
+        # under the migration race.
         logger.exception(
             "baseline_listener: count query failed for %s id=%s",
             type(obj).__name__,
             getattr(obj, "id", None),
         )
+        incr_capture_error("shadow_count")
         return None
diff --git a/superset/versioning/changes/listener.py b/superset/versioning/changes/listener.py
index e02f662dcbf..813db920f88 100644
--- a/superset/versioning/changes/listener.py
+++ b/superset/versioning/changes/listener.py
@@ -60,10 +60,12 @@ from superset.versioning.changes.state import (
     compute_records_from_state,
 )
 from superset.versioning.changes.table import ENTITY_KIND_BY_CLASS_NAME
+from superset.versioning.db_errors import is_missing_table_error
 from superset.versioning.diff import (
     ChangeRecord,
     fold_dashboard_layout_with_chart_changes,
 )
+from superset.versioning.metrics import incr_capture_error
 
 logger = logging.getLogger(__name__)
 
@@ -169,29 +171,6 @@ def build_action_headline(
 # is correctly deduped.
 _REGISTERED_SENTINEL = "_versioning_change_listener_registered"
 
-#: Metric namespace for swallowed capture-path failures. The capture
-#: listeners fail open (a versioning bug must never break a user's save),
-#: so the read path (``activity/orchestrator``) is richly instrumented but
-#: the write path historically logged-and-swallowed with no counter. Each
-#: ``_incr_capture_error(stage)`` emits ``<prefix>.<stage>.error`` so a
-#: systematic capture regression is alertable rather than log-grep-only.
-_CAPTURE_METRIC_PREFIX: str = "superset.versioning.capture"
-
-
-def _incr_capture_error(stage: str) -> None:
-    """Emit a counter for a swallowed capture-path failure at *stage*.
-
-    Best-effort: metrics emission must never itself break a user's save,
-    so it is wrapped in the same fail-open posture as the call site.
-    """
-    # pylint: disable=import-outside-toplevel
-    try:
-        from superset.extensions import stats_logger_manager
-
-        stats_logger_manager.instance.incr(f"{_CAPTURE_METRIC_PREFIX}.{stage}.error")
-    except Exception:  # pylint: disable=broad-except
-        logger.exception("version_changes: failed to emit capture-error metric")
-
 
 def _capture_dirty_entity_initial_state(
     session: Session,
@@ -281,7 +260,7 @@ def _append_child_records_to_buffer(
                     del buffer[key]
     except Exception:  # pylint: disable=broad-except
         logger.exception("version_changes: child-diff failed for tx %s", tx_id)
-        _incr_capture_error("child_diff")
+        incr_capture_error("child_diff")
 
 
 def _current_transaction_id(session: Session) -> int | None:
@@ -369,7 +348,7 @@ def _stamp_action_kind_on_transaction(session: Session, tx_id: int) -> None:
             action_kind,
             tx_id,
         )
-        _incr_capture_error("action_kind_stamp")
+        incr_capture_error("action_kind_stamp")
 
 
 def _persist_buffered_records(
@@ -379,11 +358,12 @@ def _persist_buffered_records(
 ) -> None:
     """Bulk-insert *buffer*'s records under *tx_id* and reset the buffer.
 
-    Catches ``OperationalError`` / ``ProgrammingError`` to handle the
-    pre-migration startup race (version_changes table missing — the
-    former on SQLite/MySQL, the latter on PostgreSQL), and ``Exception``
-    as the listener-boundary safety net so a malformed record can't
-    crash the user's save.
+    Swallows the pre-migration startup race silently (version_changes
+    table missing — verified via :func:`is_missing_table_error`, not
+    inferred from the exception class, because ``OperationalError`` also
+    covers deadlocks and dropped connections that must be logged and
+    counted). ``Exception`` is the listener-boundary safety net so a
+    malformed record can't crash the user's save.
 
     The insert runs under a SAVEPOINT (``begin_nested`` on the
     connection): on PostgreSQL a failed statement aborts the enclosing
@@ -395,16 +375,22 @@ def _persist_buffered_records(
     try:
         with session.connection().begin_nested():
             bulk_insert_records(session, tx_id, buffer)
-    except (OperationalError, ProgrammingError):
-        # version_changes table missing (migration not yet applied).
-        pass
-    except Exception:  # pylint: disable=broad-except
+    except Exception as ex:  # pylint: disable=broad-except
+        if isinstance(
+            ex, (OperationalError, ProgrammingError)
+        ) and is_missing_table_error(ex):
+            # version_changes table missing (migration not yet applied) —
+            # the one genuinely benign case; stay quiet.
+            return
+        # Everything else — a deadlock or dropped connection as much as a
+        # malformed record — is a real capture loss. Swallowing it silently
+        # made "the save succeeded but its history doesn't exist" invisible.
         logger.exception(
             "version_changes: bulk insert failed for tx %s (%d entities)",
             tx_id,
             len(buffer),
         )
-        _incr_capture_error("bulk_insert")
+        incr_capture_error("bulk_insert")
 
 
 def register_change_record_listener() -> None:  # noqa: C901
diff --git a/superset/versioning/db_errors.py b/superset/versioning/db_errors.py
new file mode 100644
index 00000000000..4b840edb81a
--- /dev/null
+++ b/superset/versioning/db_errors.py
@@ -0,0 +1,69 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Classify database errors the versioning capture path swallows.
+
+The capture listeners fail open — a versioning bug must never break a
+user's save — and one failure is genuinely benign: the versioning tables
+not existing yet, during the window between deploying the code and
+running its migration. The listeners swallow that case silently.
+
+But the exception classes that case raises (``OperationalError`` on
+SQLite/MySQL, ``ProgrammingError`` on PostgreSQL) also cover deadlocks,
+lock timeouts, and dropped connections. Swallowing the whole class turns
+any of those into a silent capture drop: the user's save succeeds and its
+version history quietly doesn't exist. :func:`is_missing_table_error`
+separates the benign case from everything else, so the listeners can stay
+quiet for the migration race and log-plus-count the rest.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy.exc import DBAPIError
+
+#: PostgreSQL SQLSTATE for "relation does not exist" (undefined_table).
+_PG_UNDEFINED_TABLE = "42P01"
+
+#: MySQL/MariaDB error code for "Table ... doesn't exist".
+_MYSQL_NO_SUCH_TABLE = 1146
+
+
+def is_missing_table_error(exc: DBAPIError) -> bool:
+    """Whether *exc* is a "table does not exist" error on any supported
+    metadata database, as raised during the pre-migration startup race.
+
+    Checks driver error codes first (psycopg2's ``pgcode``, MySQL's
+    numeric errno) and falls back to SQLite's message, which is the only
+    signal that driver provides. Deliberately narrow: an ambiguous error
+    should be logged by the caller, not swallowed — over-reporting is
+    recoverable, a silent capture drop is not.
+    """
+    orig = getattr(exc, "orig", None)
+
+    # PostgreSQL via psycopg2. (psycopg 3 spells it ``sqlstate``; checked
+    # too so a driver swap doesn't silently widen the swallow.)
+    pgcode = getattr(orig, "pgcode", None) or getattr(orig, "sqlstate", None)
+    if pgcode is not None:
+        return pgcode == _PG_UNDEFINED_TABLE
+
+    # MySQL/MariaDB drivers put the numeric errno first in args.
+    args = getattr(orig, "args", ())
+    if args and isinstance(args[0], int):
+        return args[0] == _MYSQL_NO_SUCH_TABLE
+
+    # SQLite has no error codes on OperationalError; the message is the
+    # documented, stable signal.
+    return "no such table" in str(orig if orig is not None else exc).lower()
diff --git a/superset/versioning/metrics.py b/superset/versioning/metrics.py
new file mode 100644
index 00000000000..9357852ed54
--- /dev/null
+++ b/superset/versioning/metrics.py
@@ -0,0 +1,54 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Metrics for swallowed capture-path failures.
+
+The capture listeners fail open (a versioning bug must never break a
+user's save), so the read path (``activity/orchestrator``) is richly
+instrumented but the write path historically logged-and-swallowed with no
+counter. Each :func:`incr_capture_error` call emits
+``superset.versioning.capture.<stage>.error`` so a systematic capture
+regression is alertable rather than log-grep-only.
+
+Shared across the capture subpackages — the change-record listener
+(``changes/listener.py``) and the baseline probe
+(``baseline/collection.py``) both swallow failures under the same
+fail-open posture, and an alerting surface with a blind quadrant defeats
+its purpose.
+"""
+
+from __future__ import annotations
+
+import logging
+
+logger = logging.getLogger(__name__)
+
+_CAPTURE_METRIC_PREFIX: str = "superset.versioning.capture"
+
+
+def incr_capture_error(stage: str) -> None:
+    """Emit a counter for a swallowed capture-path failure at *stage*.
+
+    Best-effort: metrics emission must never itself break a user's save,
+    so it is wrapped in the same fail-open posture as the call sites.
+    """
+    # pylint: disable=import-outside-toplevel
+    try:
+        from superset.extensions import stats_logger_manager
+
+        stats_logger_manager.instance.incr(f"{_CAPTURE_METRIC_PREFIX}.{stage}.error")
+    except Exception:  # pylint: disable=broad-except
+        logger.exception("versioning: failed to emit capture-error metric")
diff --git a/superset/versioning/queries.py b/superset/versioning/queries.py
index fa4f1939e76..b7a6b898dff 100644
--- a/superset/versioning/queries.py
+++ b/superset/versioning/queries.py
@@ -30,6 +30,7 @@ both the read endpoints and the ETag emission path in
 
 from __future__ import annotations
 
+import logging
 import uuid
 from typing import Any
 from uuid import UUID
@@ -40,6 +41,9 @@ from sqlalchemy_continuum import version_class
 
 from superset.extensions import db
 from superset.versioning.baseline import CONTINUUM_BOOKKEEPING_COLUMNS
+from superset.versioning.db_errors import is_missing_table_error
+
+logger = logging.getLogger(__name__)
 
 # Fixed UUIDv5 namespace under which per-(entity, transaction) version UUIDs
 # are derived. Never change this constant — changing it invalidates every
@@ -236,10 +240,12 @@ def list_change_records_batch(
     transactions are represented by an empty list in the result so
     callers can use ``result.get(tx_id, [])`` without guarding.
 
-    If the ``version_changes`` table is missing (pre-migration or
-    freshly downgraded), returns an empty dict rather than propagating
+    Any operational failure returns an empty dict rather than propagating
     the error — consistent with this being a descriptive layer that
-    should not break the list endpoint.
+    should not break the list endpoint. The missing-table case
+    (pre-migration or freshly downgraded) stays silent; every other
+    failure (deadlock, dropped connection) is logged, since it renders
+    the affected saves as empty change lists.
     """
     # pylint: disable=import-outside-toplevel
     from superset.versioning.changes import version_changes_table
@@ -278,9 +284,19 @@ def list_change_records_batch(
                 .mappings()
                 .all()
             )
-    except (sa.exc.OperationalError, sa.exc.ProgrammingError):
-        # Missing version_changes table: OperationalError on SQLite/MySQL,
-        # ProgrammingError (UndefinedTable) on PostgreSQL.
+    except (sa.exc.OperationalError, sa.exc.ProgrammingError) as ex:
+        if is_missing_table_error(ex):
+            # Missing version_changes table (migration not yet applied) —
+            # the one benign case; stay quiet.
+            return {}
+        # A transient failure (deadlock, dropped connection) renders
+        # every affected save as an empty change list — recoverable on
+        # refresh, but it must not masquerade as the migration race.
+        logger.exception(
+            "version_changes: change-record query failed for %s id=%s",
+            entity_kind,
+            entity_id,
+        )
         return {}
 
     grouped: dict[int, list[dict[str, Any]]] = {tx: [] for tx in transaction_ids}
diff --git a/tests/unit_tests/versioning/test_collection.py b/tests/unit_tests/versioning/test_collection.py
new file mode 100644
index 00000000000..6ba0b913583
--- /dev/null
+++ b/tests/unit_tests/versioning/test_collection.py
@@ -0,0 +1,73 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""The baseline shadow-row probe classifies its failures the same way the
+change-record listener does: the missing-table migration race stays
+silent, everything else is logged and counted. These tests make the
+classify-then-log branch deletion-proof — without them, removing the log
+or the metric fails nothing."""
+
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+from sqlalchemy.exc import OperationalError
+
+from superset.versioning.baseline import collection
+
+
+def _session_raising(error: Exception) -> MagicMock:
+    session = MagicMock()
+    session.connection.side_effect = error
+    return session
+
+
+def _probe(session: MagicMock) -> Any:
+    return collection.shadow_row_count(
+        session, SimpleNamespace(id=7), version_table=MagicMock()
+    )
+
+
+def test_missing_table_probe_stays_silent(mocker: Any) -> None:
+    log_spy = mocker.patch.object(collection.logger, "exception")
+    metric_spy = mocker.patch.object(collection, "incr_capture_error")
+    error = OperationalError("SELECT", {}, Exception("no such table: slices_version"))
+
+    assert _probe(_session_raising(error)) is None
+    log_spy.assert_not_called()
+    metric_spy.assert_not_called()
+
+
+def test_transient_probe_failure_is_logged_and_counted(mocker: Any) -> None:
+    # A deadlock here returns None and the caller skips baseline capture
+    # for the flush — that loss must be visible, not filed under the
+    # migration race.
+    log_spy = mocker.patch.object(collection.logger, "exception")
+    metric_spy = mocker.patch.object(collection, "incr_capture_error")
+    error = OperationalError("SELECT", {}, Exception("database is locked"))
+
+    assert _probe(_session_raising(error)) is None
+    log_spy.assert_called_once()
+    metric_spy.assert_called_once_with("shadow_count")
+
+
+def test_unexpected_probe_failure_is_logged_and_counted(mocker: Any) -> None:
+    log_spy = mocker.patch.object(collection.logger, "exception")
+    metric_spy = mocker.patch.object(collection, "incr_capture_error")
+
+    assert _probe(_session_raising(RuntimeError("boom"))) is None
+    log_spy.assert_called_once()
+    metric_spy.assert_called_once_with("shadow_count")
diff --git a/tests/unit_tests/versioning/test_db_errors.py b/tests/unit_tests/versioning/test_db_errors.py
new file mode 100644
index 00000000000..a4940848968
--- /dev/null
+++ b/tests/unit_tests/versioning/test_db_errors.py
@@ -0,0 +1,109 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""The capture path stays quiet only for the pre-migration missing-table
+race; every other operational failure must classify as loggable. These
+tests pin the driver-specific shapes the predicate reads, per supported
+metadata database."""
+
+from typing import Any
+
+from sqlalchemy.exc import OperationalError, ProgrammingError
+
+from superset.versioning.db_errors import is_missing_table_error
+
+
+class _FakeDriverError(Exception):
+    """Stands in for a DBAPI driver exception, carrying whichever
+    attributes the real driver would set."""
+
+    def __init__(self, *args: Any, **attrs: Any) -> None:
+        super().__init__(*args)
+        for name, value in attrs.items():
+            setattr(self, name, value)
+
+
+def _wrap(
+    exc_cls: type, driver_error: Exception
+) -> OperationalError | ProgrammingError:
+    return exc_cls("SELECT 1", {}, driver_error)
+
+
+def test_postgres_undefined_table_is_missing_table() -> None:
+    # psycopg2 stamps pgcode; UndefinedTable is SQLSTATE 42P01.
+    error = _wrap(
+        ProgrammingError,
+        _FakeDriverError('relation "version_changes" does not exist', pgcode="42P01"),
+    )
+    assert is_missing_table_error(error) is True
+
+
+def test_postgres_deadlock_is_not_missing_table() -> None:
+    # Deadlock is SQLSTATE 40P01 — same OperationalError class on the
+    # SQLAlchemy side, and the case the old class-based swallow lost.
+    error = _wrap(
+        OperationalError,
+        _FakeDriverError("deadlock detected", pgcode="40P01"),
+    )
+    assert is_missing_table_error(error) is False
+
+
+def test_psycopg3_sqlstate_spelling_is_recognized() -> None:
+    # psycopg 3 exposes the code as `sqlstate`, not `pgcode`; a driver
+    # swap must not silently widen the swallow back to the whole class.
+    error = _wrap(
+        ProgrammingError,
+        _FakeDriverError('relation "version_changes" does not exist', sqlstate="42P01"),
+    )
+    assert is_missing_table_error(error) is True
+
+
+def test_mysql_no_such_table_is_missing_table() -> None:
+    # mysqlclient raises with (errno, message) args; 1146 is
+    # "Table ... doesn't exist".
+    error = _wrap(
+        ProgrammingError,
+        _FakeDriverError(1146, "Table 'superset.version_changes' doesn't exist"),
+    )
+    assert is_missing_table_error(error) is True
+
+
+def test_mysql_lock_wait_timeout_is_not_missing_table() -> None:
+    error = _wrap(
+        OperationalError,
+        _FakeDriverError(1205, "Lock wait timeout exceeded"),
+    )
+    assert is_missing_table_error(error) is False
+
+
+def test_sqlite_no_such_table_is_missing_table() -> None:
+    # SQLite's OperationalError carries no code; the message is the signal.
+    error = _wrap(OperationalError, _FakeDriverError("no such table: version_changes"))
+    assert is_missing_table_error(error) is True
+
+
+def test_sqlite_locked_database_is_not_missing_table() -> None:
+    error = _wrap(OperationalError, _FakeDriverError("database is locked"))
+    assert is_missing_table_error(error) is False
+
+
+def test_connection_drop_with_no_code_is_not_missing_table() -> None:
+    # A dropped connection often surfaces with no driver code at all.
+    error = _wrap(
+        OperationalError,
+        _FakeDriverError("server closed the connection unexpectedly"),
+    )
+    assert is_missing_table_error(error) is False
diff --git a/tests/unit_tests/versioning/test_listener.py b/tests/unit_tests/versioning/test_listener.py
index 922a4011be1..2eeca0d3678 100644
--- a/tests/unit_tests/versioning/test_listener.py
+++ b/tests/unit_tests/versioning/test_listener.py
@@ -202,3 +202,50 @@ def test_terminal_event_clears_transaction_state(
     getattr(lifecycle_session, terminal_event)()
 
     assert lifecycle_session.info == {"unrelated": "preserved"}
+
+
+def test_missing_table_stays_silent_during_persist(
+    lifecycle_session: Session,
+    mocker: Any,
+) -> None:
+    """The pre-migration race (version_changes not yet created) is the one
+    benign persist failure; it must produce neither a log line nor a
+    capture-error metric."""
+    mocker.patch.object(
+        listener,
+        "bulk_insert_records",
+        side_effect=sa.exc.OperationalError(
+            "INSERT", {}, Exception("no such table: version_changes")
+        ),
+    )
+    log_spy = mocker.patch.object(listener.logger, "exception")
+    metric_spy = mocker.patch.object(listener, "incr_capture_error")
+
+    listener._persist_buffered_records(lifecycle_session, tx_id=1, buffer={})
+
+    log_spy.assert_not_called()
+    metric_spy.assert_not_called()
+
+
+def test_transient_persist_failure_is_logged_and_counted(
+    lifecycle_session: Session,
+    mocker: Any,
+) -> None:
+    """A deadlock (or any operational failure that is not the missing-table
+    race) drops the save's change records; swallowing it under the
+    missing-table branch made that loss invisible — no log, no metric,
+    while the user's save reported success."""
+    mocker.patch.object(
+        listener,
+        "bulk_insert_records",
+        side_effect=sa.exc.OperationalError(
+            "INSERT", {}, Exception("database is locked")
+        ),
+    )
+    log_spy = mocker.patch.object(listener.logger, "exception")
+    metric_spy = mocker.patch.object(listener, "incr_capture_error")
+
+    listener._persist_buffered_records(lifecycle_session, tx_id=1, buffer={})
+
+    log_spy.assert_called_once()
+    metric_spy.assert_called_once_with("bulk_insert")
diff --git a/tests/unit_tests/versioning/test_queries_change_records.py b/tests/unit_tests/versioning/test_queries_change_records.py
new file mode 100644
index 00000000000..411f4f44011
--- /dev/null
+++ b/tests/unit_tests/versioning/test_queries_change_records.py
@@ -0,0 +1,61 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""The change-record read path fails open to an empty dict, but only the
+missing-table migration race may do so silently — a transient failure
+renders every affected save as an empty change list and must leave a log
+line. These tests make that branch deletion-proof."""
+
+from typing import Any
+from unittest.mock import MagicMock
+
+import sqlalchemy as sa
+
+from superset.versioning import queries
+
+
+def _db_raising(mocker: Any, error: Exception) -> None:
+    db_mock = MagicMock()
+    db_mock.session.connection.side_effect = error
+    mocker.patch.object(queries, "db", db_mock)
+
+
+def test_missing_table_read_stays_silent(mocker: Any) -> None:
+    log_spy = mocker.patch.object(queries.logger, "exception")
+    _db_raising(
+        mocker,
+        sa.exc.OperationalError(
+            "SELECT", {}, Exception("no such table: version_changes")
+        ),
+    )
+
+    result = queries.list_change_records_batch("chart", 1, [10, 11])
+    assert result == {}
+    log_spy.assert_not_called()
+
+
+def test_transient_read_failure_is_logged(mocker: Any) -> None:
+    # Recoverable on refresh, but it must not masquerade as the
+    # migration race.
+    log_spy = mocker.patch.object(queries.logger, "exception")
+    _db_raising(
+        mocker,
+        sa.exc.OperationalError("SELECT", {}, Exception("database is locked")),
+    )
+
+    result = queries.list_change_records_batch("chart", 1, [10, 11])
+    assert result == {}
+    log_spy.assert_called_once()