Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse-sources): retry a MotherDuck outage instead of blaming the token (#101832)

posthog[bot]fab142369feb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
index 4a7b51107c08..f7c2d4bff5ad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py
@@ -35,6 +35,7 @@ import duckdb
import pyarrow as pa
import structlog
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import AnsiIdentifierQuoter
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (
@@ -60,6 +61,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.types import IncrementalFieldType
__all__ = [
+ "MOTHERDUCK_TRANSIENT_ERRORS",
+ "MOTHERDUCK_UNAVAILABLE_MESSAGE",
"MotherDuckConnectionError",
"MotherDuckImplementation",
"build_motherduck_connection_string",
@@ -83,6 +86,17 @@ MOTHERDUCK_SYSTEM_SCHEMAS = ("information_schema", "pg_catalog")
# consulted for an account-wide connection; pinning a database scopes discovery on its own.
MOTHERDUCK_SYSTEM_DATABASES = ("md_information_schema", "system", "temp", "memory", "_duckdb_ui")
+# DuckDB reports MotherDuck being unreachable as an `Invalid Input Error` from the client
+# extension's init, the same class a wrong database name or access token produces, so the class
+# below cannot tell an outage from a config problem. These are MotherDuck's own wordings for one.
+# Matched as one phrase: "please try again later" alone also ends other driver errors.
+MOTHERDUCK_TRANSIENT_ERRORS = ("could not connect to motherduck. please try again later",)
+
+MOTHERDUCK_UNAVAILABLE_MESSAGE = (
+ "MotherDuck is temporarily unavailable, so PostHog couldn't connect. This isn't a problem with "
+ "your database name or access token. Try again in a few minutes."
+)
+
# DuckDB prefixes every error message with its stable error class ("Catalog Error:", "Binder
# Error:", …). The text after the prefix carries volatile object names, so we match the class.
MOTHERDUCK_ERROR_CLASSES = {
@@ -164,6 +178,8 @@ def translate_motherduck_error(error: Exception) -> str:
"Your MotherDuck plan has reached its compute limit. Queries may be slow or fail until the "
"limit resets. Upgrade your MotherDuck plan for more capacity."
)
+ if error_message_matches(message, MOTHERDUCK_TRANSIENT_ERRORS):
+ return MOTHERDUCK_UNAVAILABLE_MESSAGE
for key, value in MOTHERDUCK_ERROR_CLASSES.items():
if key in message:
return value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py
index feb21757694f..c87a50e7acc4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/source.py
@@ -11,7 +11,10 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldInputConfig,
SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ FieldType,
+ error_message_matches,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.motherduck import (
@@ -19,6 +22,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck import (
MOTHERDUCK_ERROR_CLASSES,
+ MOTHERDUCK_TRANSIENT_ERRORS,
+ MOTHERDUCK_UNAVAILABLE_MESSAGE,
MotherDuckConnectionError,
MotherDuckImplementation,
connect,
@@ -30,6 +35,10 @@ if TYPE_CHECKING:
_MOTHERDUCK_IMPLEMENTATION = MotherDuckImplementation()
+_CONNECTION_DETAILS_MESSAGE = (
+ "MotherDuck rejected the connection details. Check the database name and access token, then resync."
+)
+
@SourceRegistry.register
class MotherduckSource(SQLSource[MotherduckSourceConfig]):
@@ -97,16 +106,26 @@ class MotherduckSource(SQLSource[MotherduckSourceConfig]):
**self.default_non_retryable_errors(),
"Catalog Error": "A database, schema, or table this source syncs no longer exists in MotherDuck, or your access token lost access to it. Check that it still exists, then resync.",
"Binder Error": "A column this source syncs no longer exists in MotherDuck. Reset the table so we pick up its new shape, then resync.",
- # `connect()` (motherduck.py) already translates a raw "Invalid Input Error" into this
- # user-facing text before raising `MotherDuckConnectionError`, so a connection failure's
- # message never contains the DuckDB class name to match on — only the translated text does.
- MOTHERDUCK_ERROR_CLASSES[
- "Invalid Input Error"
- ]: "MotherDuck rejected the connection details. Check the database name and access token, then resync.",
+ # `connect()` translates before it raises, so the message carries this text rather than
+ # DuckDB's class name. Keying on the class would also catch an outage, which stays retryable.
+ MOTHERDUCK_ERROR_CLASSES["Invalid Input Error"]: _CONNECTION_DETAILS_MESSAGE,
"Invalid MotherDuck token": None,
"UNAUTHENTICATED": "Your MotherDuck token is invalid or expired. Generate a new access token and reconnect.",
}
+ def get_retryable_errors(self) -> set[str]:
+ # A MotherDuck outage clears on its own, so the next attempt recovers. Both the driver's
+ # own wording and the translation of it are matched: which one reaches classification
+ # depends on where in the sync the failure was raised.
+ return {*MOTHERDUCK_TRANSIENT_ERRORS, MOTHERDUCK_UNAVAILABLE_MESSAGE}
+
+ def get_retry_exhausted_errors(self) -> dict[str, str]:
+ return dict.fromkeys(
+ self.get_retryable_errors(),
+ "MotherDuck was unavailable for this whole sync, so it couldn't finish. This isn't a "
+ "problem with your connection details. The next sync runs on schedule.",
+ )
+
@staticmethod
def normalized_database(config: MotherduckSourceConfig) -> str | None:
"""The configured database, or None when the source spans the whole account."""
@@ -150,6 +169,8 @@ class MotherduckSource(SQLSource[MotherduckSourceConfig]):
False,
"MotherDuck rejected the access token. Check that the token is correct and has not expired.",
)
+ if error_message_matches(error_msg, MOTHERDUCK_TRANSIENT_ERRORS):
+ return False, MOTHERDUCK_UNAVAILABLE_MESSAGE
for key, value in MOTHERDUCK_ERROR_CLASSES.items():
if key in error_msg:
return False, value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py
index f3df897559fc..184631dbe20b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py
@@ -27,6 +27,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck
from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.source import MotherduckSource
from products.warehouse_sources.backend.types import IncrementalFieldType
+_SERVICE_UNAVAILABLE_ERROR = (
+ 'Invalid Input Error: Initialization function "motherduck_duckdb_cpp_init" failed: '
+ "Request failed: Could not connect to MotherDuck. Please try again later"
+)
+
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck"
_CONNECT_PATH = f"{_MODULE}.duckdb.connect"
@@ -120,6 +125,7 @@ class TestMotherDuck:
"reached its compute limit",
),
("Catalog Error: Table with name nope does not exist", "Can't find that database or schema"),
+ (_SERVICE_UNAVAILABLE_ERROR, "MotherDuck is temporarily unavailable"),
# Unmapped errors surface their first line only (DuckDB appends candidate/hint blocks).
("Parser Error: syntax error at or near\nCandidate bindings: ...", "Parser Error: syntax error at or near"),
],
@@ -543,17 +549,42 @@ class TestMotherDuck:
non_retryable = source.get_non_retryable_errors()
assert any(pattern in error_msg for pattern in non_retryable), f"Error should be non-retryable: {error_msg}"
- def test_connection_failure_is_non_retryable_end_to_end(self, source):
+ @pytest.mark.parametrize(
+ "driver_error",
+ [
+ "Invalid Input Error: bad connection option",
+ "Invalid Input Error: bad connection option, please try again later",
+ ],
+ ids=["bad_option", "generic_try_again_phrase"],
+ )
+ def test_connection_failure_is_non_retryable_end_to_end(self, source, driver_error):
# Reproduces the real path: `connect()` wraps and translates the driver error before
# raising, so the non-retryable match has to run against that translated text, not the
# raw DuckDB error class. A key that only matches the raw class (as this dict used to)
# would let a bad database name or malformed token retry indefinitely.
- with patch(_CONNECT_PATH, side_effect=duckdb.Error("Invalid Input Error: bad connection option")):
+ with patch(_CONNECT_PATH, side_effect=duckdb.Error(driver_error)):
with pytest.raises(MotherDuckConnectionError) as exc_info:
connect("md-token", "my_db")
assert error_message_matches(str(exc_info.value), source.get_non_retryable_errors())
+ def test_service_outages_keep_retrying(self, source):
+ # The import activity consults the non-retryable set first, so an outage has to miss that
+ # set entirely or it stops the sync and asks the owner to check credentials they can't fix.
+ assert not error_message_matches(_SERVICE_UNAVAILABLE_ERROR, source.get_non_retryable_errors())
+ assert error_message_matches(_SERVICE_UNAVAILABLE_ERROR, source.get_retryable_errors())
+ assert error_message_matches(_SERVICE_UNAVAILABLE_ERROR, source.get_retry_exhausted_errors())
+
+ def test_an_outage_stays_retryable_once_connect_has_translated_it(self, source):
+ # `connect()` replaces the driver text with our own copy, so classification runs against
+ # that copy for any failure raised while opening a connection.
+ with patch(_CONNECT_PATH, side_effect=duckdb.Error(_SERVICE_UNAVAILABLE_ERROR)):
+ with pytest.raises(MotherDuckConnectionError) as exc_info:
+ connect("md-token", "my_db")
+
+ assert not error_message_matches(str(exc_info.value), source.get_non_retryable_errors())
+ assert error_message_matches(str(exc_info.value), source.get_retryable_errors())
+
def test_validate_credentials_requires_an_access_token(self, source):
ok, message = source.validate_credentials(_make_config(access_token=""), team_id=1)
assert ok is False
@@ -574,6 +605,7 @@ class TestMotherDuck:
(Exception("Catalog Error: Database with name nope does not exist!"), "database and schema names"),
(Exception("Binder Error: Referenced column not found"), "rejected the query"),
(Exception("Invalid Input Error: bad option"), "connection details"),
+ (Exception(_SERVICE_UNAVAILABLE_ERROR), "MotherDuck is temporarily unavailable"),
(ValueError("Invalid MotherDuck database name: 'my db'"), "Invalid MotherDuck database name"),
(Exception("something totally unexpected"), "Could not connect to MotherDuck"),
],