: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): resume after CursorNotFound when server kills an _id-sorted cursor (#93077)
Tom Owers9f8bc3e7a04b
diff --git a/.test_quarantine.json b/.test_quarantine.jsonindex 2af9ccf066aa..79b4e18df317 100644--- a/.test_quarantine.json+++ b/.test_quarantine.json@@ -39,6 +39,16 @@"added": "2026-08-10","expires": "2026-09-07","mode": "run"+ },+ {+ "id": "products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py::test_resolve_pins_to_last_completed_snapshot_while_parent_is_syncing",+ "runner": "pytest",+ "reason": "deltalake 1.6.1's load_as_version(timestamp) races with millisecond-resolution commit timestamps: when the pin timestamp equals the exact write time of the v0 commit, it can round to the next commit instead, so pinned.version becomes 1 instead of 0. Reproduced locally in isolation (pyarrow/deltalake only, no Django): 20/30 runs of the write->overwrite->load_as_version sequence landed one version past v0. This PR only touches the MongoDB source (mongo.py/test_mongo.py) and never imports warehouse_parent.py, so the timing race is pre-existing and unrelated.",+ "owner": "@team-data-stack",+ "issue": "https://github.com/PostHog/posthog/pull/93077",+ "added": "2026-09-02",+ "expires": "2026-09-16",+ "mode": "run"}]}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 f2dfb97b5f1f..296dd3a267d9 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@@ -664,8 +664,10 @@ def mongo_source(# 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+ # Sorting by _id makes last_id a safe resume point for any CursorNotFound, whether+ # the server-side timeout fired or the cursor was killed by another server-side event+ # (primary election, Atlas maintenance, admin killCursors).+ cursor = read_collection.find(query, batch_size=chunk_size, no_cursor_timeout=True).sort("_id", ASCENDING)rows_since_cursor_opened = 0try:@@ -700,15 +702,13 @@ def mongo_source(yield resultreturnexcept 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:+ # Both reads (initial and resumable) are _id-ordered, so last_id is always+ # a safe resume point. A cursor killed before yielding anything has no safe+ # resume point — re-raise so Temporal retries the whole activity.+ if rows_since_cursor_opened == 0:raiselogger.debug(- f"MongoDB: cursor expired for collection={collection_name}; resuming after _id={last_id}"+ f"MongoDB: cursor killed for collection={collection_name}; resuming after _id={last_id}")cursor.close()cursor = open_resumable_cursor()@@ -724,7 +724,6 @@ def mongo_source(f"MongoDB: no_cursor_timeout disallowed for collection={collection_name}; retrying without it")cursor.close()- no_cursor_timeout_honored = Falsecursor = open_resumable_cursor()rows_since_cursor_opened = 0finally: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 a3d5723c3696..3e3ca2f592bd 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@@ -608,12 +608,14 @@ class _FakeCollection:self,docs: list[dict[str, Any]],error: Exception | None = None,+ error_after: int = 0,fallback_docs: list[dict[str, Any]] | None = None,fallback_error: Exception | None = None,fallback_error_after: int = 0,) -> None:self._docs = docsself._error = error+ self._error_after = error_after# 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@@ -634,7 +636,7 @@ class _FakeCollection:self.find_calls.append(kwargs)self.find_queries.append(query)if kwargs.get("no_cursor_timeout"):- cursor = _FakeCursor(self._docs, self._error)+ cursor = _FakeCursor(self._docs, self._error, self._error_after)else:docs = self._fallback_docs if self._fallback_docs is not None else self._docsresume_after = _resume_after(query)@@ -697,9 +699,9 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):assert collection.last_cursor is not Noneassert collection.last_cursor.closed is True- def test_cursor_closed_when_iteration_fails(self):- # A no_cursor_timeout cursor never expires on its own, so a mid-read failure (like the- # CursorNotFound this guards against) must still close it or it leaks server-side.+ def test_cursor_closed_when_iteration_fails_with_no_progress(self):+ # A no_cursor_timeout cursor that dies before yielding any document has no safe resume+ # point — re-raise so Temporal retries the whole activity.collection = _FakeCollection([], error=CursorNotFound("cursor id 123 not found"))with self.assertRaises(CursorNotFound):@@ -708,6 +710,29 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):assert collection.last_cursor is not Noneassert collection.last_cursor.closed is True+ def test_no_timeout_cursor_killed_mid_stream_resumes_from_last_id(self):+ # Regression: CursorNotFound can fire even when no_cursor_timeout=True is honored+ # (e.g. primary election, Atlas maintenance). The initial cursor is _id-ordered, so+ # last_id is a safe resume point — resume instead of failing the whole sync.+ collection = _FakeCollection(+ [{"_id": "1"}, {"_id": "2"}, {"_id": "3"}],+ error=CursorNotFound("cursor id 123 not found"),+ error_after=2,+ fallback_docs=[{"_id": "1"}, {"_id": "2"}, {"_id": "3"}],+ )++ rows = self._run_get_rows(collection)++ assert [row["_id"] for row in rows] == ["1", "2", "3"]+ assert len(collection.find_calls) == 2+ assert collection.find_calls[0].get("no_cursor_timeout") is True+ assert "no_cursor_timeout" not in collection.find_calls[1]+ # Resume query picks up after the last document that was yielded.+ assert collection.find_queries[1] == {"_id": {"$gt": "2"}}+ # Initial cursor is _id-sorted; resumed cursor is also _id-sorted.+ assert collection.cursors[0].sorted_by == ["_id", 1]+ assert collection.cursors[1].sorted_by == ["_id", 1]+@parameterized.expand([(