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(mongodb): keep syncs enabled after a short cluster outage (#101378)

posthog[bot]65cac196f9aa
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index a2555582d6fb..4e5ccd4eb208 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -1966,12 +1966,15 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
except Exception as e:
# `validate_credentials` above just probed the same connection successfully, so a
- # failure here that the source itself classifies as non-retryable (e.g. a connect-time
- # timeout, which usually means an unreachable host or unconfigured firewall) is an
- # expected customer/upstream condition, not a bug — don't flood error tracking with it.
+ # failure here that the source itself classifies is an expected customer or upstream
+ # condition rather than a bug, and must not flood error tracking. Both maps count: a
+ # non-retryable match names something only the customer can fix, such as bad
+ # credentials, and a retryable match names a transient failure `get_retryable_errors`
+ # already exists to keep out of error tracking.
# Mirrors `refresh_schemas`'s `_classify_refresh_schemas_error`.
error_text = str(e)
- if not any(pattern and pattern in error_text for pattern in new_source.get_non_retryable_errors()):
+ expected_patterns = (*new_source.get_non_retryable_errors(), *new_source.get_retryable_errors())
+ if not any(pattern and pattern in error_text for pattern in expected_patterns):
capture_exception(e)
return Response(
status=status.HTTP_400_BAD_REQUEST,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
index 017e93ae2a20..22d95f856e72 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
@@ -18,7 +18,7 @@ from pymongo import ASCENDING, MongoClient
from pymongo.collection import Collection
from pymongo.cursor import Cursor
from pymongo.database import Database
-from pymongo.errors import CursorNotFound, OperationFailure, PyMongoError
+from pymongo.errors import CursorNotFound, OperationFailure, PyMongoError, ServerSelectionTimeoutError
from pymongo.server_description import ServerDescription
from structlog.types import FilteringBoundLogger
@@ -31,6 +31,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.par
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ DATABASE_HOST_NOT_ALLOWED_ERROR,
+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,
+ TEMPORARY_HOST_RESOLUTION_PREFIX,
+ HostNotAllowedError,
_is_host_safe,
log_connection_open,
)
@@ -246,6 +250,12 @@ def _coerce_object_id_cursor(last_value: Any) -> Any:
return ObjectId(value) if ObjectId.is_valid(value) else value
+# No node was selectable, or the outbound host policy refused every one. The extraction read
+# that follows cannot succeed either, so a best-effort probe that swallows one of these spends a
+# whole server-selection window of worker time before the attempt fails anyway. Re-raise instead.
+_UNREACHABLE_CLUSTER_ERRORS = (ServerSelectionTimeoutError, HostNotAllowedError)
+
+
def _make_safe_server_selector(team_id: int) -> Callable[[list[ServerDescription]], list[ServerDescription]]:
"""Create a PyMongo server_selector that rejects servers resolving to internal IPs.
@@ -255,11 +265,23 @@ def _make_safe_server_selector(team_id: int) -> Callable[[list[ServerDescription
def selector(server_descriptions: list[ServerDescription]) -> list[ServerDescription]:
safe = []
+ rejection: str | None = None
for server in server_descriptions:
host = server.address[0]
- is_safe, _ = _is_host_safe(host, team_id)
+ is_safe, error = _is_host_safe(host, team_id)
if is_safe:
safe.append(server)
+ elif rejection is None and not (error or "").startswith(TEMPORARY_HOST_RESOLUTION_PREFIX):
+ rejection = error or DATABASE_HOST_NOT_ALLOWED_GUIDANCE
+ # pymongo only calls a custom selector with at least one candidate, so an empty result
+ # after a policy rejection means every member was refused. Returning [] instead would let
+ # server selection time out as an ordinary unreachable-cluster error, which retries on
+ # every schedule and keeps the monitors handshaking with a host the policy already refused.
+ # Raising the shared host error stops the schedule and gives the user the fix. A resolver
+ # that never answered is not a policy decision, so it leaves `rejection` unset and the
+ # empty selection retries as before.
+ if not safe and rejection is not None:
+ raise HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: {rejection}")
return safe
return selector
@@ -356,6 +378,8 @@ def _get_partition_settings(
partition_count=partition_count,
partition_size=partition_size,
)
+ except _UNREACHABLE_CLUSTER_ERRORS:
+ raise
except Exception:
return None
@@ -574,6 +598,8 @@ def _get_avg_document_size(collection: Collection, logger: FilteringBoundLogger)
stats = collection.database.command("collStats", collection.name)
avg_obj_size = stats.get("avgObjSize")
return int(avg_obj_size) if avg_obj_size else None
+ except _UNREACHABLE_CLUSTER_ERRORS:
+ raise
except Exception as e:
logger.debug(f"MongoDB: could not read collStats avgObjSize ({e}); using default chunk size")
return None
@@ -584,6 +610,8 @@ def _get_rows_to_sync(collection: Collection, query: dict[str, Any], logger: Fil
rows_to_sync = collection.count_documents(query)
logger.debug(f"_get_rows_to_sync: rows_to_sync={rows_to_sync}")
return rows_to_sync
+ except _UNREACHABLE_CLUSTER_ERRORS:
+ raise
except PyMongoError as e:
# rows_to_sync is only a progress estimate, so a failed count degrades to 0
# rather than failing the sync. Connectivity/auth failures here are expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py
index 731eb561475d..e8ad01c88be0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py
@@ -10,7 +10,12 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldInputConfigType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixin
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,
+ HOST_RESOLUTION_EXHAUSTED_MESSAGE,
+ HostNotAllowedError,
+ ValidateDatabaseHostMixin,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
@@ -36,6 +41,10 @@ _MONGO_UNREACHABLE_MESSAGE = (
"IP addresses are allowlisted in your database's network access settings."
)
+# The same condition reached through a sync rather than the connect form. The schema keeps retrying
+# instead of being disabled, so nothing needs re-enabling and the copy has to say so.
+_MONGO_UNREACHABLE_RETRY_MESSAGE = f"{_MONGO_UNREACHABLE_MESSAGE} The next sync runs on schedule."
+
# `_parse_connection_string` raises a ValueError when the string isn't a usable MongoDB URI: a
# wrong or missing scheme, or a host/port that urlparse rejects. The raw reason gives the user
# little to act on, so point at the expected scheme and format instead.
@@ -64,6 +73,15 @@ _MONGO_HOST_UNRESOLVED_MESSAGE = (
"string is spelled correctly."
)
+# pymongo drops a server from the topology when its replica set name differs from the one the
+# connection string asks for, so the cluster the user named is never selectable. The name has to be
+# corrected before any sync can run.
+_MONGO_REPLICA_SET_MISMATCH_MESSAGE = (
+ "The replica set name in your connection string doesn't match the one your cluster reports. "
+ "Check the replicaSet option in the connection string, or copy the current connection string "
+ "from your database provider, then re-enable this sync."
+)
+
_MONGO_AUTHENTICATION_FAILED_MESSAGE = (
"MongoDB authentication failed. Please check the username and password for this source."
)
@@ -98,14 +116,21 @@ _MONGO_NO_COLLECTIONS_MESSAGE = (
"your user has read access to that database's collections."
)
-# Substrings pymongo embeds in ServerSelectionTimeoutError when the OS can't resolve the host.
-_DNS_RESOLUTION_FAILURE_MARKERS = (
+# Substrings pymongo embeds in ServerSelectionTimeoutError when the resolver says the host name
+# does not exist (EAI_NONAME). The name never resolves until the user corrects it, so a sync that
+# fails this way is a connection-string mistake rather than an outage.
+_DNS_NAME_NOT_FOUND_MARKERS = (
"No address associated with hostname",
"nodename nor servname provided",
"Name or service not known",
- "Temporary failure in name resolution",
)
+_DNS_TEMPORARY_FAILURE_MARKER = "Temporary failure in name resolution"
+
+# The markers above plus EAI_AGAIN, where the resolver itself did not answer. Validation reports
+# both the same way; only the permanent ones classify a sync failure as non-retryable.
+_DNS_RESOLUTION_FAILURE_MARKERS = (*_DNS_NAME_NOT_FOUND_MARKERS, _DNS_TEMPORARY_FAILURE_MARKER)
+
# For a `mongodb+srv://` URI, pymongo resolves the SRV record via dnspython inside the
# MongoClient constructor and wraps any dnspython exception as ConfigurationError. dnspython's
# NXDOMAIN carries this fixed prefix when the SRV record's DNS name doesn't exist at all —
@@ -161,22 +186,25 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin
# topology never leaves Unknown, and server selection times out (ServerSelectionTimeoutError,
# frequently "connection closed"). This is a wrong-endpoint misconfiguration — the importer
# needs a regular cluster connection string — so retrying never recovers. The host suffix
- # is the stable signal here, and it must be matched before the generic "Topology Description:"
- # entry below so Atlas SQL users get the wrong-endpoint message rather than the allowlist one.
+ # is the stable signal here. Non-retryable patterns are matched before retryable ones,
+ # so this still wins over the "Topology Description:" entry in `get_retryable_errors`
+ # and Atlas SQL users get the wrong-endpoint message.
"query.mongodb.net": _MONGO_ATLAS_SQL_MESSAGE,
- # pymongo raises ServerSelectionTimeoutError when it can't select a usable cluster node
- # for the whole selection timeout. The reason varies — "No servers found yet" / "No
- # replica set members found yet" when nothing was ever discovered, or a per-server
- # "<host>: connection closed ... error=AutoReconnect(...)" when a host resolves but every
- # connection attempt is dropped for the entire window. All of these carry the
- # "Topology Description:" suffix that only ServerSelectionTimeoutError emits, so we key
- # off that single marker. On a managed cluster this is a persistent connectivity problem
- # — the worker IP isn't allowlisted, the cluster is paused/decommissioned, or the
- # connection string points at an endpoint the driver can't speak to — not a momentary
- # blip, so retrying the job won't recover it. A transient mid-sync drop surfaces
- # differently (a bare AutoReconnect / NetworkTimeout with no topology description) and
- # stays retryable.
- "Topology Description:": _MONGO_UNREACHABLE_MESSAGE,
+ # The resolver answered that the cluster host name does not exist. pymongo surfaces it
+ # as a ServerSelectionTimeoutError whose topology description carries the OS marker, so
+ # match the marker rather than the topology suffix, which a reachable-but-down cluster
+ # emits too. A name that does not resolve stays unresolved until the user fixes it.
+ **dict.fromkeys(_DNS_NAME_NOT_FOUND_MARKERS, _MONGO_HOST_UNRESOLVED_MESSAGE),
+ # pymongo removes every server whose replica set name differs from the `replicaSet` the
+ # connection string asks for, which empties the topology and names the set rather than a
+ # host in the selection error. A cluster that is merely down keeps its servers as Unknown
+ # and reports "No replica set members found yet" instead, so this wording only appears on
+ # a name mismatch. Both shapes are fixed literals in pymongo, so match them directly and
+ # let them beat the "Topology Description:" entry in `get_retryable_errors`.
+ "No replica set members available for replica set name": _MONGO_REPLICA_SET_MISMATCH_MESSAGE,
+ # The same mismatch on a direct connection: pymongo marks the node Unknown with a
+ # ConfigurationError naming both sets, and that text is what the selection timeout carries.
+ "client is configured to connect to a replica set named": _MONGO_REPLICA_SET_MISMATCH_MESSAGE,
# MongoDB OperationFailure code 211 (KeyNotFound): the cluster's HMAC keystore has no
# valid key for the cursor's timestamp. pymongo formats the full server error response
# as part of the exception message; the leading phrase before the variable parts
@@ -196,10 +224,18 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin
#
# pymongo also raises a bare AutoReconnect("<address>: connection pool paused ...") when a
# connection checkout finds the pool not yet READY after an earlier network blip — the
- # pool's background monitor clears this on its own once it reconnects, so it's distinct
- # from the persistent "Topology Description:" server-selection failures above. Match the
- # fixed "connection pool paused" phrase pymongo always uses for this state, not the
- # surrounding host/timeout values.
+ # pool's background monitor clears this on its own once it reconnects. Match the fixed
+ # "connection pool paused" phrase pymongo always uses for this state, not the surrounding
+ # host/timeout values.
+ #
+ # pymongo raises ServerSelectionTimeoutError when it can't select a usable cluster node for
+ # the whole selection timeout, and only that error carries the "Topology Description:"
+ # suffix. The suffix alone cannot tell a persistent problem (the worker IP isn't allowlisted,
+ # the cluster is decommissioned) from a cluster that is merely down for one selection window
+ # — a restart, a failover, a short provider outage — because both emit identical text. Treat
+ # the class as retryable so a blip does not disable the schema; the persistent shapes that
+ # can be named are matched above and still do. `get_retry_exhausted_errors` supplies the
+ # message once the retries run out.
#
# A cluster that is rotating its signing keys fails a command with OperationFailure code 211
# (KeyNotFound), which it clears on its own, so Temporal retrying the activity recovers.
@@ -217,6 +253,22 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin
"connection pool paused",
"the cluster's signing keys were briefly unavailable",
"interrupted at shutdown",
+ "Topology Description:",
+ }
+
+ def get_retry_exhausted_errors(self) -> dict[str, str]:
+ # A server-selection timeout that outlived the retry budget leaves `latest_error` holding
+ # the raw topology dump: every seed host, port, and per-server driver exception. Replace it
+ # with the two things the user can act on, and say the schema is still enabled.
+ #
+ # A resolver that keeps answering EAI_AGAIN fails the same server selection, so its error
+ # carries the topology marker as well. The finalizer stores the first pattern that matches,
+ # so the resolver marker is listed first: without it the user reads the allowlist guidance
+ # and checks network access rules that are already correct. The shared resolver message
+ # names the lookup instead, and says the sync stays enabled.
+ return {
+ _DNS_TEMPORARY_FAILURE_MARKER: HOST_RESOLUTION_EXHAUSTED_MESSAGE,
+ "Topology Description:": _MONGO_UNREACHABLE_RETRY_MESSAGE,
}
def get_schemas(
@@ -313,6 +365,12 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin
# rather than mislabelling it as an authentication problem.
capture_exception(e)
return False, _MONGO_CONNECT_FAILED_MESSAGE
+ except HostNotAllowedError:
+ # An SRV URI skips the host check above, so a cluster whose members resolve to private
+ # addresses is only refused once `_make_safe_server_selector` sees them. Report the same
+ # guidance the sync path stores for this condition, and don't capture it: the host is
+ # the user's to fix, never our bug.
+ return False, DATABASE_HOST_NOT_ALLOWED_GUIDANCE
except ServerSelectionTimeoutError as e:
# pymongo dumps a verbose topology description into str(e); surface a concise,
# actionable message instead. A DNS failure means the host doesn't resolve at all,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.py
index 580b02c40408..fe65b9a13955 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_database_name.py
@@ -3,6 +3,11 @@ from unittest.mock import patch
from pymongo.errors import ConfigurationError, InvalidURI, OperationFailure, ServerSelectionTimeoutError
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (
+ DATABASE_HOST_NOT_ALLOWED_ERROR,
+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,
+ HostNotAllowedError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mongodb import (
MongoDBSourceConfig,
)
@@ -109,6 +114,19 @@ class TestMongoValidateCredentialsServerSelection:
assert err == _MONGO_HOST_UNRESOLVED_MESSAGE
assert "Topology Description" not in (err or "")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source.get_collection_names")
+ def test_private_srv_members_return_host_guidance(self, mock_get_collections):
+ # An SRV URI skips the up-front host check, so the connect form only learns the members are
+ # private when the server selector refuses them. That must read as a host problem rather
+ # than the generic connect failure, which also reports to error tracking.
+ mock_get_collections.side_effect = HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: internal IP")
+ config = MongoDBSourceConfig.from_dict({"connection_string": _SRV_WITH_DB})
+
+ ok, err = MongoDBSource().validate_credentials(config, team_id=1)
+
+ assert ok is False
+ assert err == DATABASE_HOST_NOT_ALLOWED_GUIDANCE
+
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source.get_collection_names")
def test_unreachable_cluster_returns_allowlist_message(self, mock_get_collections):
mock_get_collections.side_effect = ServerSelectionTimeoutError(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py
index dda8c7e0e815..1dc5a0a23230 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py
@@ -5,6 +5,7 @@ import contextlib
from collections.abc import Iterable, Iterator
from typing import Any, cast
+import pytest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
@@ -17,6 +18,11 @@ from pymongo.hello import Hello
from pymongo.server_description import ServerDescription
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZE
+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 (
+ DATABASE_HOST_NOT_ALLOWED_ERROR,
+ HostNotAllowedError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (
MONGO_DOCUMENT_MISSING_ID_ERROR,
MONGO_KEYS_UNAVAILABLE_ERROR,
@@ -24,6 +30,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mo
MONGO_MIN_CHUNK_ROWS,
_adaptive_chunk_size,
_build_query,
+ _get_avg_document_size,
+ _get_partition_settings,
_get_rows_to_sync,
_list_importable_collection_names,
_make_safe_server_selector,
@@ -51,16 +59,20 @@ class TestSafeServerSelector(SimpleTestCase):
assert result[0].address == ("8.8.8.8", 27017)
@override_settings(CLOUD_DEPLOYMENT="US")
- def test_returns_empty_when_all_servers_internal(self):
+ def test_raises_when_all_servers_internal(self):
+ # Returning an empty selection would let pymongo time out with the same text a cluster
+ # outage produces, which is classified retryable — so the schedule would keep probing a
+ # host the policy already refused. The raised error disables the sync instead.
selector = _make_safe_server_selector(team_id=999)
servers = [
ServerDescription(("10.0.0.1", 27017)),
ServerDescription(("192.168.1.1", 27017)),
]
- result = selector(servers)
+ with pytest.raises(HostNotAllowedError) as excinfo:
+ selector(servers)
- assert result == []
+ assert DATABASE_HOST_NOT_ALLOWED_ERROR in str(excinfo.value)
@override_settings(CLOUD_DEPLOYMENT="US")
def test_allows_all_public_servers(self):
@@ -86,9 +98,8 @@ class TestSafeServerSelector(SimpleTestCase):
selector = _make_safe_server_selector(team_id=999)
servers = [ServerDescription((host, 27017))]
- result = selector(servers)
-
- assert result == []
+ with pytest.raises(HostNotAllowedError):
+ selector(servers)
@override_settings(CLOUD_DEPLOYMENT="US")
def test_whitelisted_team_allows_internal_ips(self):
@@ -399,26 +410,13 @@ class TestMongoDBNonRetryableErrors(SimpleTestCase):
"Port contains non-digit characters. Hint: username and password must be escaped "
"according to RFC 3986, use urllib.parse.quote_plus",
),
- # ServerSelectionTimeoutError variants — cluster unreachable for the whole selection
- # timeout. All carry the "Topology Description:" suffix regardless of the per-reason text.
- ("no_servers", "No servers found yet, Timeout: 5.0s, Topology Description: ..."),
- (
- "no_replica_set_members",
- "No replica set members found yet, Timeout: 10.0s, Topology Description: "
- "<TopologyDescription topology_type: ReplicaSetNoPrimary>",
- ),
- # Host resolves but every connection attempt is closed for the whole window — the driver
- # never identifies the server (topology_type: Unknown) and wraps the per-server
- # AutoReconnect. Persistent connectivity/config problem, not a momentary blip.
+ # The resolver says the cluster host name does not exist. pymongo reports it as a
+ # server-selection timeout, but the OS marker makes it a connection-string mistake that
+ # no retry recovers, unlike the bare topology timeout below.
(
- "connection_closed_selection_timeout",
- "cluster0.example.mongodb.net:27017: connection closed (configured timeouts: "
- "socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 10.0s, "
- "Topology Description: <TopologyDescription id: abc, topology_type: Unknown, "
- "servers: [<ServerDescription ('cluster0.example.mongodb.net', 27017) "
- "server_type: Unknown, rtt: None, error=AutoReconnect('cluster0.example.mongodb.net:"
- "27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, "
- "connectTimeoutMS: 20000.0ms)')>]>",
+ "dns_name_not_found",
+ "cluster0.example.mongodb.net:27017: [Errno -2] Name or service not known, Timeout: "
+ "10.0s, Topology Description: <TopologyDescription topology_type: Unknown>",
),
# Atlas SQL / Data Federation endpoint (*.query.mongodb.net) — unusable by the standard
# driver, so the topology stays Unknown and selection times out. Despite the "connection
@@ -432,6 +430,26 @@ class TestMongoDBNonRetryableErrors(SimpleTestCase):
"('atlas-sql-681905984ce3f87167df11fa-wf3cgp.a.query.mongodb.net', 27017) "
"server_type: Unknown, rtt: None, error=AutoReconnect('...connection closed...')>]>",
),
+ # The connection string names a replica set the cluster doesn't answer to, so pymongo
+ # drops every server and the selection error names the set instead of a host. Only a
+ # corrected name recovers this, unlike the "found yet" wording a down cluster emits.
+ (
+ "replica_set_name_no_members",
+ 'No replica set members available for replica set name "rs0", Timeout: 10.0s, '
+ "Topology Description: <TopologyDescription id: 6a304febea674ebc4c8c051e, "
+ "topology_type: ReplicaSetNoPrimary, servers: []>",
+ ),
+ # The same mismatch on a direct connection: the node stays Unknown carrying pymongo's
+ # ConfigurationError, which names both set names.
+ (
+ "replica_set_name_mismatch",
+ "client is configured to connect to a replica set named 'rs0' but this node belongs "
+ "to a set named 'rs1', Timeout: 10.0s, Topology Description: <TopologyDescription "
+ "id: 6a304febea674ebc4c8c051e, topology_type: Single, servers: [<ServerDescription "
+ "('cluster0.example.mongodb.net', 27017) server_type: Unknown, rtt: None, "
+ 'error=ConfigurationError("client is configured to connect to a replica set named '
+ "'rs0' but this node belongs to a set named 'rs1'\")>]>",
+ ),
# MongoDB OperationFailure code 211 (KeyNotFound): the cluster's HMAC keystore has no
# valid key for the cursor's timestamp. Retrying the same cursor always fails the same
# way, so it must be classified non-retryable.
@@ -461,6 +479,24 @@ class TestMongoDBNonRetryableErrors(SimpleTestCase):
"cluster0.example.mongodb.net:27017: connection closed (configured timeouts: "
"socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)",
),
+ # A cluster that is down for one selection window emits the same server-selection
+ # timeout a permanently blocked one does, so none of these may disable the schema.
+ ("no_servers", "No servers found yet, Timeout: 5.0s, Topology Description: ..."),
+ (
+ "no_replica_set_members",
+ "No replica set members found yet, Timeout: 10.0s, Topology Description: "
+ "<TopologyDescription topology_type: ReplicaSetNoPrimary>",
+ ),
+ (
+ "connection_closed_selection_timeout",
+ "cluster0.example.mongodb.net:27017: connection closed (configured timeouts: "
+ "socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 10.0s, "
+ "Topology Description: <TopologyDescription id: abc, topology_type: Unknown, "
+ "servers: [<ServerDescription ('cluster0.example.mongodb.net', 27017) "
+ "server_type: Unknown, rtt: None, error=AutoReconnect('cluster0.example.mongodb.net:"
+ "27017: connection closed (configured timeouts: socketTimeoutMS: 20000.0ms, "
+ "connectTimeoutMS: 20000.0ms)')>]>",
+ ),
]
)
def test_transient_errors_are_retryable(self, _name, error_msg):
@@ -473,11 +509,13 @@ class TestMongoDBNonRetryableErrors(SimpleTestCase):
("code_name", "AuthenticationFailed", "password"),
("message", "Authentication failed", "password"),
("atlas_bad_auth", "bad auth", "password"),
- ("unreachable_topology", "Topology Description:", "allowlist"),
+ ("dns_name_not_found", "Name or service not known", "resolved"),
("atlas_sql_endpoint", "query.mongodb.net", "connection string"),
("unescaped_credentials", "must be escaped according to RFC 3986", "connection string"),
("document_missing_id", "one of its documents has no _id field", "view"),
("key_not_found", "No keys found for HMAC", "key management"),
+ ("replica_set_no_members", "No replica set members available for replica set name", "replica set"),
+ ("replica_set_mismatch", "client is configured to connect to a replica set named", "replica set"),
]
)
def test_pattern_has_friendly_message(self, _name, pattern, expected_substring):
@@ -526,6 +564,49 @@ class TestGetRetryableErrors(SimpleTestCase):
f"MongoDB signing keys unavailable should be classified retryable: {MONGO_KEYS_UNAVAILABLE_ERROR}"
)
+ def test_server_selection_timeout_is_classified_retryable(self):
+ # Regression: a cluster down for one selection window used to disable the schema, leaving
+ # the table stale until someone re-enabled the sync by hand.
+ error_msg = (
+ "No replica set members found yet, Timeout: 10.0s, Topology Description: "
+ "<TopologyDescription topology_type: ReplicaSetNoPrimary>"
+ )
+ assert any(pattern in error_msg for pattern in self.retryable), (
+ f"MongoDB server selection timeout should be classified retryable: {error_msg}"
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "unreachable_cluster",
+ "No servers found yet, Timeout: 5.0s, Topology Description: <TopologyDescription ...>",
+ "allowlisted",
+ ),
+ # A resolver answering EAI_AGAIN fails server selection too, so this error carries the
+ # topology marker as well and would otherwise be told to check a correct allowlist.
+ (
+ "temporary_resolution_failure",
+ "cluster0.example.mongodb.net:27017: [Errno -3] Temporary failure in name resolution, "
+ "Timeout: 10.0s, Topology Description: <TopologyDescription ...>",
+ "dns records",
+ ),
+ ]
+ )
+ def test_exhausted_retries_replace_the_topology_dump(self, _name, error_msg, expected_phrase):
+ # The schema stays enabled, so the stored error is what the user reads. Left alone it would
+ # be the raw dump of every seed host, port, and per-server driver exception. Mirror the
+ # finalizer's first-match selection over get_retry_exhausted_errors.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source import MongoDBSource
+
+ exhausted = MongoDBSource().get_retry_exhausted_errors()
+ message = next(
+ (m for pattern, m in exhausted.items() if error_message_matches(error_msg, [pattern])),
+ None,
+ )
+ assert message is not None, f"Exhausted retryable error must surface a message: {error_msg}"
+ assert "Topology Description" not in message
+ assert expected_phrase in message.lower()
+
def test_interrupted_at_shutdown_is_classified_retryable(self):
# NotPrimaryError raised when a read is killed by a routine replica-set failover (the
# primary shutting down or stepping down); the next retry hits the new primary.
@@ -550,9 +631,7 @@ class TestGetRowsToSync(SimpleTestCase):
def test_pymongo_error_returns_zero_without_capture(self):
coll = MagicMock()
- coll.count_documents.side_effect = ServerSelectionTimeoutError(
- "atlas-sql.query.mongodb.net:27017: connection closed, Timeout: 10.0s"
- )
+ coll.count_documents.side_effect = OperationFailure("count command not supported on this view")
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo.capture_exception"
) as capture:
@@ -569,6 +648,40 @@ class TestGetRowsToSync(SimpleTestCase):
capture.assert_called_once()
+class TestProbesFailFastOnUnreachableCluster(SimpleTestCase):
+ """The metadata probes are best-effort and swallow their errors. Each one runs its own server
+ selection, so swallowing an unreachable cluster spends another full selection window before
+ the extraction read fails the attempt anyway."""
+
+ @parameterized.expand(
+ [
+ ("server_selection_timeout", ServerSelectionTimeoutError("No servers found yet, Topology Description: .")),
+ ("host_not_allowed", HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: internal IP")),
+ ]
+ )
+ def test_rows_to_sync_propagates(self, _name, error):
+ coll = MagicMock()
+ coll.count_documents.side_effect = error
+
+ with pytest.raises(type(error)):
+ _get_rows_to_sync(coll, {}, MagicMock())
+
+ @parameterized.expand(
+ [
+ ("server_selection_timeout", ServerSelectionTimeoutError("No servers found yet, Topology Description: .")),
+ ("host_not_allowed", HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: internal IP")),
+ ]
+ )
+ def test_collstats_probes_propagate(self, _name, error):
+ coll = MagicMock()
+ coll.database.command.side_effect = error
+
+ with pytest.raises(type(error)):
+ _get_partition_settings(coll, "orders")
+ with pytest.raises(type(error)):
+ _get_avg_document_size(coll, MagicMock())
+
+
class TestListImportableCollectionNames(SimpleTestCase):
def test_excludes_reserved_system_collections(self):
db = MagicMock()
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
index 7a69ab9233fa..07d2d01e2c33 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
@@ -127,18 +127,21 @@ class TestExternalDataSchema(APIBaseTest):
@parameterized.expand(
[
- ("expected_source_error", Exception("Invalid API Key provided"), False),
+ ("non_retryable_source_error", Exception("Invalid API Key provided"), False),
+ ("retryable_source_error", Exception("Request rate limit exceeded"), False),
("unclassified_error", RuntimeError("schema parser exploded"), True),
]
)
@mock.patch("products.warehouse_sources.backend.presentation.views.external_data_schema.capture_exception")
- def test_incremental_fields_capture_depends_on_non_retryable_classification(
+ def test_incremental_fields_capture_depends_on_source_error_classification(
self, _name, raised_exception, should_capture, mock_capture_exception
):
# `validate_credentials` above this call already probed the same connection successfully, so
- # a failure the source itself classifies as non-retryable (e.g. bad credentials, an
- # unreachable host) is an expected customer/upstream condition and must not flood error
- # tracking - mirrors `refresh_schemas`'s equivalent classification.
+ # a failure the source itself classifies is an expected customer/upstream condition and must
+ # not flood error tracking - mirrors `refresh_schemas`'s equivalent classification. A
+ # retryable classification counts too: a source that moves a condition from the
+ # non-retryable map to the retryable one still declares it self-recovering, so the guard
+ # must read both or that move starts minting error-tracking issues.
source = ExternalDataSource.objects.create(
team=self.team,
source_type=ExternalDataSourceType.STRIPE,