: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mongodb): fall back when Atlas tier disallows no_cursor_timeout cursors (#74986)
Tom Owers4018fc7c6231
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.pyindex f6bd5e03db48..866500b6b13a 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@@ -3,6 +3,7 @@ from __future__ import annotationsimport mathimport uuidimport base64+import itertoolsimport contextlibimport collectionsfrom collections.abc import Callable, Iterator@@ -17,7 +18,7 @@ from bson.codec_options import DatetimeConversionfrom pymongo import MongoClientfrom pymongo.collection import Collectionfrom pymongo.database import Database-from pymongo.errors import PyMongoError+from pymongo.errors import OperationFailure, PyMongoErrorfrom pymongo.server_description import ServerDescriptionfrom structlog.types import FilteringBoundLogger@@ -560,6 +561,12 @@ def _get_rows_to_sync(collection: Collection, query: dict[str, Any], logger: Filreturn 0+# Some Atlas tiers (e.g. free/shared) reject no_cursor_timeout outright with OperationFailure+# code 8000 ("noTimeout cursors are disallowed in this atlas tier"). Matched as a substring since+# the full error also carries the volatile clusterTime/signature payload.+_NO_TIMEOUT_CURSORS_DISALLOWED = "noTimeout cursors are disallowed"++def mongo_source(connection_string: str,collection_name: str,@@ -622,7 +629,26 @@ def mongo_source(cursor = read_collection.find(query, batch_size=chunk_size, no_cursor_timeout=True)try:- for doc in cursor:+ doc_iter: Iterator[dict[str, Any]] = iter(cursor)+ try:+ first_doc = next(doc_iter)+ doc_iter = itertools.chain([first_doc], doc_iter)+ except StopIteration:+ pass+ except OperationFailure as e:+ if _NO_TIMEOUT_CURSORS_DISALLOWED not in str(e):+ raise+ # Fails on the very first read before any document is yielded, so it's safe to+ # retry without no_cursor_timeout — the tradeoff is the CursorNotFound risk that+ # option guards against (see the comment above cursor creation).+ logger.debug(+ f"MongoDB: no_cursor_timeout disallowed for collection={collection_name}; retrying without it"+ )+ cursor.close()+ cursor = read_collection.find(query, batch_size=chunk_size)+ doc_iter = iter(cursor)++ for doc in doc_iter:# Convert BSON types (ObjectId, Binary, UUID, DatetimeMS) to SQL-safe# values. _process_doc_with_field_logging logs the offending field name# before re-raising, so any exception here fails the sync with precisediff --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.pyindex 729d04837dd6..988ca68cb3df 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@@ -12,7 +12,7 @@ from django.test import SimpleTestCase, override_settingsfrom bson import Binary, DatetimeMS, ObjectIdfrom bson.binary import UUID_SUBTYPEfrom parameterized import parameterized-from pymongo.errors import CursorNotFound, ServerSelectionTimeoutError+from pymongo.errors import CursorNotFound, OperationFailure, ServerSelectionTimeoutErrorfrom pymongo.server_description import ServerDescriptionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZE@@ -570,18 +570,34 @@ class _FakeCursor:class _FakeCollection:- def __init__(self, docs: list[dict[str, Any]], error: Exception | None = None) -> None:+ def __init__(+ self,+ docs: list[dict[str, Any]],+ error: Exception | None = None,+ fallback_docs: list[dict[str, Any]] | None = None,+ ) -> None:self._docs = docsself._error = error+ # Docs returned by a second find() call made without no_cursor_timeout, simulating the+ # fallback path taken when the tier rejects that option.+ self._fallback_docs = fallback_docsself.find_kwargs: dict[str, Any] | None = None+ self.find_calls: list[dict[str, Any]] = []+ self.cursors: list[_FakeCursor] = []self.last_cursor: _FakeCursor | None = Noneself.database = MagicMock()self.database.command.return_value = {"avgObjSize": None}def find(self, query: dict[str, Any], **kwargs: Any) -> _FakeCursor:self.find_kwargs = kwargs- self.last_cursor = _FakeCursor(self._docs, self._error)- return self.last_cursor+ self.find_calls.append(kwargs)+ if kwargs.get("no_cursor_timeout"):+ cursor = _FakeCursor(self._docs, self._error)+ else:+ cursor = _FakeCursor(self._fallback_docs if self._fallback_docs is not None else self._docs, None)+ self.cursors.append(cursor)+ self.last_cursor = cursor+ return cursordef count_documents(self, query: dict[str, Any]) -> int:return len(self._docs)@@ -641,3 +657,33 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):assert collection.last_cursor is not Noneassert collection.last_cursor.closed is True++ def test_falls_back_to_normal_cursor_when_tier_disallows_no_timeout(self):+ # Regression: some Atlas tiers (free/shared) reject no_cursor_timeout=True outright with+ # OperationFailure code 8000, which previously failed the sync permanently. This fires on+ # the very first read, so the fallback cursor must run instead and yield the real rows.+ notimeout_error = OperationFailure(+ "noTimeout cursors are disallowed in this atlas tier, full error: {'ok': 0, 'errmsg': "+ "'noTimeout cursors are disallowed in this atlas tier', 'code': 8000, 'codeName': 'AtlasError'}"+ )+ collection = _FakeCollection([], error=notimeout_error, fallback_docs=[{"_id": "1"}, {"_id": "2"}])++ rows = self._run_get_rows(collection)++ assert len(rows) == 2+ assert len(collection.find_calls) == 2+ assert collection.find_calls[0]["no_cursor_timeout"] is True+ assert "no_cursor_timeout" not in collection.find_calls[1]+ assert collection.cursors[0].closed is True+ assert collection.cursors[1].closed is True++ def test_other_operation_failures_are_not_retried(self):+ # The fallback must be scoped to the specific tier-limitation error, not OperationFailure+ # in general, or it would silently mask unrelated server errors.+ other_error = OperationFailure("not authorized on db to execute command find")+ collection = _FakeCollection([], error=other_error)++ with self.assertRaises(OperationFailure):+ self._run_get_rows(collection)++ assert len(collection.find_calls) == 1