: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(data-warehouse): fall back when MongoDB rejects noCursorTimeout (#78186)
Tom Owers84c70d474f47
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 e796f0423edd..6fa585ec6be9 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,7 +3,6 @@ from __future__ import annotationsimport mathimport uuidimport base64-import itertoolsimport contextlibimport collectionsfrom collections.abc import Callable, Iterator@@ -15,10 +14,11 @@ import certifiimport structlogfrom bson import Binary, DatetimeMS, ObjectIdfrom bson.codec_options import DatetimeConversion-from pymongo import MongoClient+from pymongo import ASCENDING, MongoClientfrom pymongo.collection import Collection+from pymongo.cursor import Cursorfrom pymongo.database import Database-from pymongo.errors import OperationFailure, PyMongoError+from pymongo.errors import CursorNotFound, OperationFailure, PyMongoErrorfrom pymongo.server_description import ServerDescriptionfrom structlog.types import FilteringBoundLogger@@ -561,14 +561,20 @@ 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"). A collection that's actually-# a view hits the same limitation from a different angle: MongoDB rewrites a find() against a-# view into an aggregate(), and noCursorTimeout isn't a valid aggregation option, so the read-# fails immediately with "Option noCursorTimeout not supported in aggregation" instead. Both are-# matched as substrings since the full errors also carry volatile clusterTime/signature payloads.-_NO_TIMEOUT_CURSORS_DISALLOWED = "noTimeout cursors are disallowed"-_NO_TIMEOUT_NOT_SUPPORTED_IN_AGGREGATION = "noCursorTimeout not supported in aggregation"+# Several MongoDB-compatible backends reject no_cursor_timeout instead of honoring it: Atlas+# free/shared/flex tiers ("noTimeout cursors are disallowed in this atlas tier", code 8000), a+# collection that is really a view (MongoDB rewrites the find() into an aggregate(), where the+# option isn't valid, code 9), and AWS DocumentDB / Azure Cosmos DB's Mongo API ("Field+# 'noCursorTimeout' is currently not supported", code 303). Matching the option name rather than+# each backend's phrasing covers backends we haven't seen yet while keeping the fallback narrow —+# only an error about the option we passed can trigger it. Substrings, because the full errors also+# carry volatile clusterTime/signature payloads.+_NO_CURSOR_TIMEOUT_UNSUPPORTED_MARKERS = ("notimeout cursors are disallowed", "nocursortimeout")+++def _is_no_cursor_timeout_unsupported(error: OperationFailure) -> bool:+ message = str(error).lower()+ return any(marker in message for marker in _NO_CURSOR_TIMEOUT_UNSUPPORTED_MARKERS)def mongo_source(@@ -625,59 +631,87 @@ def mongo_source(db_incremental_field_last_value,)+ last_id: Any = None++ def open_resumable_cursor() -> Cursor[Any]:+ # Sorting by _id makes the read order deterministic, which is what lets an expired+ # cursor be reopened after the last document we saw. _id is always uniquely indexed,+ # so this is an index scan rather than a blocking sort.+ clauses = [clause for clause in (query, {} if last_id is None else {"_id": {"$gt": last_id}}) if clause]+ if not clauses:+ resume_query: dict[str, Any] = {}+ elif len(clauses) == 1:+ resume_query = clauses[0]+ else:+ resume_query = {"$and": clauses}+ return read_collection.find(resume_query, batch_size=chunk_size).sort("_id", ASCENDING)+# Between chunks, the pipeline writes/merges the accumulated Arrow table before pulling# more rows, which can pause consumption of this cursor well past MongoDB's default# 10-minute idle-cursor timeout — the server then kills it, and the next getMore raises# CursorNotFound. no_cursor_timeout disables that server-side expiry; we close the cursor# explicitly in the finally block below so it doesn't linger on the server instead.cursor = read_collection.find(query, batch_size=chunk_size, no_cursor_timeout=True)+ no_cursor_timeout_honored = True+ rows_since_cursor_opened = 0try:- 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:- error_message = str(e)- if (- _NO_TIMEOUT_CURSORS_DISALLOWED not in error_message- and _NO_TIMEOUT_NOT_SUPPORTED_IN_AGGREGATION not in error_message- ):- 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 precise- # diagnostic context rather than silently dropping rows.- processed_doc = _process_doc_with_field_logging(doc, collection_name, logger)-- # Stringify _id so it's always a scalar string downstream,- # regardless of BSON type (ObjectId, UUID Binary, numeric, etc.).- result: dict[str, Any] = {- "_id": str(processed_doc["_id"]),- }- # extract incremental field from the document if it exists- if incremental_field:- incremental_value = processed_doc.get(incremental_field, None)- if incremental_value is None:- continue- result[incremental_field] = incremental_value-- result["data"] = processed_doc-- yield result+ while True:+ try:+ for doc in cursor:+ last_id = doc["_id"]+ rows_since_cursor_opened += 1++ # 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 precise+ # diagnostic context rather than silently dropping rows.+ processed_doc = _process_doc_with_field_logging(doc, collection_name, logger)++ # Stringify _id so it's always a scalar string downstream,+ # regardless of BSON type (ObjectId, UUID Binary, numeric, etc.).+ result: dict[str, Any] = {+ "_id": str(processed_doc["_id"]),+ }+ # extract incremental field from the document if it exists+ if incremental_field:+ incremental_value = processed_doc.get(incremental_field, None)+ if incremental_value is None:+ continue+ result[incremental_field] = incremental_value++ result["data"] = processed_doc++ yield result+ return+ except CursorNotFound:+ # Only reachable once the server-side timeout is back in play, i.e. after the+ # fallback below dropped no_cursor_timeout. That read is _id-ordered, so pick+ # up after the last document instead of failing the whole sync. Requiring+ # progress since the cursor opened stops a cursor that dies immediately from+ # looping forever on the same query.+ if no_cursor_timeout_honored or rows_since_cursor_opened == 0:+ raise+ logger.debug(+ f"MongoDB: cursor expired for collection={collection_name}; resuming after _id={last_id}"+ )+ cursor.close()+ cursor = open_resumable_cursor()+ rows_since_cursor_opened = 0+ except OperationFailure as e:+ # The option is rejected when the cursor is opened, before any document is+ # yielded, so retrying without it can't duplicate rows. The tradeoff is that+ # the server-side idle timeout applies again — hence the CursorNotFound+ # resume above.+ if last_id is not None or not _is_no_cursor_timeout_unsupported(e):+ raise+ logger.debug(+ f"MongoDB: no_cursor_timeout disallowed for collection={collection_name}; retrying without it"+ )+ cursor.close()+ no_cursor_timeout_honored = False+ cursor = open_resumable_cursor()+ rows_since_cursor_opened = 0finally:cursor.close()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.pyindex 18ccfed514b9..471abed1c153 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@@ -564,37 +564,61 @@ class TestAdaptiveChunkSize(SimpleTestCase):class _FakeCursor:- 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, error_after: int = 0) -> None:self._iter = iter(docs)self._error = error+ self._error_after = error_after+ self._yielded = 0self.closed = False+ self.sorted_by: list[Any] | None = Nonedef __iter__(self) -> "_FakeCursor":return selfdef __next__(self) -> dict[str, Any]:- if self._error is not None:+ if self._error is not None and self._yielded >= self._error_after:raise self._error- return next(self._iter)+ doc = next(self._iter)+ self._yielded += 1+ return doc++ def sort(self, key: str, direction: int) -> "_FakeCursor":+ self.sorted_by = [key, direction]+ return selfdef close(self) -> None:self.closed = True+def _resume_after(query: dict[str, Any]) -> Any:+ for clause in query.get("$and", [query]):+ predicate = clause.get("_id")+ if isinstance(predicate, dict) and "$gt" in predicate:+ return predicate["$gt"]+ return None++class _FakeCollection:def __init__(self,docs: list[dict[str, Any]],error: Exception | None = None,fallback_docs: list[dict[str, Any]] | None = None,+ fallback_error: Exception | None = None,+ fallback_error_after: int = 0,) -> 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_docs+ # Raised by the first fallback cursor only, so a resumed read can be asserted on.+ self._fallback_error = fallback_error+ self._fallback_error_after = fallback_error_after+ self._fallback_error_raised = Falseself.find_kwargs: dict[str, Any] | None = Noneself.find_calls: list[dict[str, Any]] = []+ self.find_queries: list[dict[str, Any]] = []self.cursors: list[_FakeCursor] = []self.last_cursor: _FakeCursor | None = Noneself.database = MagicMock()@@ -603,10 +627,19 @@ class _FakeCollection:def find(self, query: dict[str, Any], **kwargs: Any) -> _FakeCursor:self.find_kwargs = kwargsself.find_calls.append(kwargs)+ self.find_queries.append(query)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)+ docs = self._fallback_docs if self._fallback_docs is not None else self._docs+ resume_after = _resume_after(query)+ if resume_after is not None:+ docs = [doc for doc in docs if doc["_id"] > resume_after]+ if self._fallback_error is not None and not self._fallback_error_raised:+ self._fallback_error_raised = True+ cursor = _FakeCursor(docs, self._fallback_error, self._fallback_error_after)+ else:+ cursor = _FakeCursor(docs)self.cursors.append(cursor)self.last_cursor = cursorreturn cursor@@ -682,14 +715,19 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):"Option noCursorTimeout not supported in aggregation, full error: {'ok': 0, 'errmsg': ""'Option noCursorTimeout not supported in aggregation', 'code': 9, 'codeName': 'FailedToParse'}",),+ (+ "backend_does_not_support_the_field",+ "Field 'noCursorTimeout' is currently not supported, full error: {'ok': 0.0, 'code': 303, "+ "'errmsg': \"Field 'noCursorTimeout' is currently not supported\", 'codeName': 'CommandNotSupported'}",+ ),])def test_falls_back_to_normal_cursor_when_no_timeout_is_rejected(self, _name: str, error_message: str):- # Regression: some Atlas tiers (free/shared) reject no_cursor_timeout=True outright with- # OperationFailure code 8000, and MongoDB rewrites find() against a view into an- # aggregate() where noCursorTimeout isn't a valid option — both fail permanently without- # this fallback. Both fire on the very first read, so the fallback cursor must run instead- # and yield the real rows.+ # Regression: some Atlas tiers (free/shared/flex) reject no_cursor_timeout=True outright+ # with OperationFailure code 8000, MongoDB rewrites find() against a view into an+ # aggregate() where noCursorTimeout isn't a valid option, and DocumentDB / Cosmos DB reject+ # the field itself with code 303 — all fail permanently without this fallback. All fire on+ # the very first read, so the fallback cursor must run instead and yield the real rows.notimeout_error = OperationFailure(error_message)collection = _FakeCollection([], error=notimeout_error, fallback_docs=[{"_id": "1"}, {"_id": "2"}])@@ -712,3 +750,38 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):self._run_get_rows(collection)assert len(collection.find_calls) == 1++ def test_expired_fallback_cursor_resumes_after_the_last_document(self):+ # Dropping no_cursor_timeout puts the server's 10-minute idle timeout back in play, so a+ # long sync on these backends dies mid-read with CursorNotFound. The fallback read is+ # _id-ordered, so it must resume after the last document rather than lose the whole sync+ # (or restart and emit duplicates).+ collection = _FakeCollection(+ [],+ error=OperationFailure("Field 'noCursorTimeout' is currently not supported"),+ fallback_docs=[{"_id": "1"}, {"_id": "2"}, {"_id": "3"}],+ fallback_error=CursorNotFound("cursor id 123 not found"),+ fallback_error_after=2,+ )++ rows = self._run_get_rows(collection)++ assert [row["_id"] for row in rows] == ["1", "2", "3"]+ assert collection.find_queries[-1] == {"_id": {"$gt": "2"}}+ # cursors[2] is the read reopened after CursorNotFound; assert it resumes _id-ordered.+ assert collection.cursors[2].sorted_by == ["_id", 1]++ def test_fallback_cursor_that_expires_without_progress_is_not_retried_forever(self):+ # Resuming re-runs the same query, so a cursor that dies before yielding anything would+ # loop forever without this guard.+ collection = _FakeCollection(+ [],+ error=OperationFailure("Field 'noCursorTimeout' is currently not supported"),+ fallback_docs=[{"_id": "1"}],+ fallback_error=CursorNotFound("cursor id 123 not found"),+ )++ with self.assertRaises(CursorNotFound):+ self._run_get_rows(collection)++ assert len(collection.find_calls) == 2