: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(warehouse-sources): treat mongodb key rotation as retryable (#93078)
posthog[bot]cb4272b68acd
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 296dd3a267d9..0ba80ff788f6 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@@ -589,6 +589,19 @@ MONGO_DOCUMENT_MISSING_ID_ERROR = ("view whose pipeline removes _id. Sync the underlying collection instead, or add _id to the view.")+# A cluster signs every command reply with a cluster-time HMAC, keyed off a key document the config+# servers rotate. While a rotation is in flight, a command fails with OperationFailure code 211+# (KeyNotFound), and the cluster clears that on its own. Match the code rather than the message,+# whose key id and cluster time vary per occurrence, and raise our own text instead: pymongo's+# str() appends the whole server response. The source's get_retryable_errors matches this phrase to+# keep the occurrence out of error tracking.+_KEY_NOT_FOUND_ERROR_CODE = 211++MONGO_KEYS_UNAVAILABLE_ERROR = (+ "PostHog couldn't read this MongoDB collection because the cluster's signing keys were briefly "+ "unavailable. This clears by itself, and the sync will run again automatically."+)+def mongo_source(connection_string: str,@@ -714,6 +727,8 @@ def mongo_source(cursor = open_resumable_cursor()rows_since_cursor_opened = 0except OperationFailure as e:+ if e.code == _KEY_NOT_FOUND_ERROR_CODE:+ raise OperationFailure(MONGO_KEYS_UNAVAILABLE_ERROR, e.code) from 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 CursorNotFounddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/source.pyindex c9499a8cc1ac..8dfb926bdcb0 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@@ -202,13 +202,23 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin# fixed "connection pool paused" phrase pymongo always uses for this state, not the# surrounding host/timeout values.#+ # 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.+ # mongo.py rewrites that failure to MONGO_KEYS_UNAVAILABLE_ERROR, so match our own stable+ # phrase — pymongo's text appends the whole server response instead.+ ## pymongo raises NotPrimaryError when an in-flight read is killed because the server node# is shutting down or stepping down (OperationFailure codeName 'InterruptedAtShutdown',# code 11600) — a routine replica-set failover such as a rolling restart or managed-cluster# maintenance. The driver reconnects to the newly-elected primary, so Temporal retrying the# whole activity is self-recovering. Match the stable errmsg phrase, not the volatile# topologyVersion/clusterTime blob pymongo appends.- return {"The resolution lifetime expired", "connection pool paused", "interrupted at shutdown"}+ return {+ "The resolution lifetime expired",+ "connection pool paused",+ "the cluster's signing keys were briefly unavailable",+ "interrupted at shutdown",+ }def get_schemas(self,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 c0d82035975b..820dca1f391d 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@@ -18,6 +18,7 @@ from pymongo.server_description import ServerDescriptionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZEfrom products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (MONGO_DOCUMENT_MISSING_ID_ERROR,+ MONGO_KEYS_UNAVAILABLE_ERROR,MONGO_MAX_CHUNK_ROWS,MONGO_MIN_CHUNK_ROWS,_adaptive_chunk_size,@@ -515,6 +516,14 @@ class TestGetRetryableErrors(SimpleTestCase):f"MongoDB connection pool paused should be classified retryable: {error_msg}")+ def test_signing_keys_unavailable_is_classified_retryable(self):+ # mongo.py rewrites OperationFailure code 211 (KeyNotFound) to this message, so it is the+ # text that reaches classification. Without a match the run reports as a bug nobody can act+ # on, because the cluster clears a key rotation on its own.+ assert any(pattern in MONGO_KEYS_UNAVAILABLE_ERROR for pattern in self.retryable), (+ f"MongoDB signing keys unavailable should be classified retryable: {MONGO_KEYS_UNAVAILABLE_ERROR}"+ )+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.@@ -792,6 +801,25 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):assert collection.cursors[0].closed is Trueassert collection.cursors[1].closed is True+ def test_key_rotation_failure_reports_a_message_without_the_server_response(self):+ # A cluster mid key rotation fails a getMore with code 211 part way through the read, and+ # pymongo's str() appends the whole server response, which must not reach the customer's+ # sync error. The rewrite must also come before the no_cursor_timeout fallback check, which+ # re-raises everything once a document was read.+ raw_error = OperationFailure(+ "No keys found for HMAC that is valid for time: { ts: Timestamp(1756713600, 4) } with id: "+ "7300000000000000001, full error: {'ok': 0.0, 'errmsg': 'No keys found for HMAC', 'code': 211, "+ "'codeName': 'KeyNotFound'}",+ 211,+ )+ collection = _FakeCollection([{"_id": "1"}, {"_id": "2"}], error=raw_error, error_after=1)++ with self.assertRaises(OperationFailure) as ctx:+ self._run_get_rows(collection)++ assert str(ctx.exception) == MONGO_KEYS_UNAVAILABLE_ERROR+ assert ctx.exception.__cause__ is raw_error+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.