: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): read each collection's indexes once during schema discovery (#108970)
Tom Owers179853d75280
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 22d95f856e72..960ac869d530 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@@ -22,6 +22,7 @@ from pymongo.errors import CursorNotFound, OperationFailure, PyMongoError, Servefrom pymongo.server_description import ServerDescriptionfrom structlog.types import FilteringBoundLogger+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention@@ -158,44 +159,60 @@ def _process_nested_value(value: Any) -> Any:return value-def get_indexes(collection: Collection) -> list[str]:- """Get all indexes for a MongoDB collection."""- try:- index_cursor = collection.list_indexes()- return [field for index in index_cursor for field in index["key"].keys()]- except Exception:- return []+@frozen+class CollectionIndexKeys:+ """A collection's index keys, split by whether the key leads its index.++ `WHERE field >= last_max` queries are only accelerated by an index whose leading key is+ `field`; a non-leading position in a compound index doesn't support that access pattern.+ """++ covered: frozenset[str]+ leading: frozenset[str]-def get_leading_index_keys(collection: Collection) -> set[str] | None:- """Return the set of fields that are the first key of any index.+def get_index_keys(collection: Collection) -> CollectionIndexKeys | None:+ """Read a collection's index keys in one round trip.- `WHERE field >= last_max` queries are only accelerated by indexes whose- leading key is `field`; non-leading positions in compound indexes don't- support this access pattern. Returns None when index discovery fails so- the caller can default to no warning.+ Returns None when index discovery fails, so the caller can tell "this collection has no+ matching index" apart from "we don't know what this collection is indexed on"."""try:- index_cursor = collection.list_indexes()- result: set[str] = set()- for index in index_cursor:+ covered: set[str] = set()+ leading: set[str] = set()+ for index in collection.list_indexes():keys = index.get("key")if not keys:continue- leading = next(iter(keys.keys()), None)- if leading is not None:- result.add(leading)- return result+ covered.update(keys.keys())+ first_key = next(iter(keys.keys()), None)+ if first_key is not None:+ leading.add(first_key)+ return CollectionIndexKeys(covered=frozenset(covered), leading=frozenset(leading))except Exception as e:- structlog.get_logger().warning("Failed to detect leading index keys for MongoDB collection", exc_info=e)+ structlog.get_logger().warning("Failed to read index keys for MongoDB collection", exc_info=e)return None+def get_index_keys_by_collection(db: Database, collection_names: list[str]) -> dict[str, CollectionIndexKeys | None]:+ """Read index keys for several collections at once.++ Schema discovery answers a blocking HTTP request, so one round trip per collection in series+ runs a database with many collections past that request's gateway deadline. Bounded the same+ way as the schema-inference pool above.+ """+ if not collection_names:+ return {}++ with ThreadPoolExecutor(max_workers=min(len(collection_names), 4)) as executor:+ results = executor.map(get_index_keys, [db[name] for name in collection_names])+ return dict(zip(collection_names, results))++def filter_mongo_incremental_fields(- columns: list[tuple[str, str]], collection: Collection+ columns: list[tuple[str, str]], indexed_fields: frozenset[str]) -> list[tuple[str, IncrementalFieldType]]:results: list[tuple[str, IncrementalFieldType]] = []- indexed_fields = get_indexes(collection)for column_name, type in columns:# Only include fields that have indexesdiff --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 1e7badd16ac4..8a3e6e90248f 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@@ -28,7 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mo_parse_connection_string,filter_mongo_incremental_fields,get_collection_names,- get_leading_index_keys,+ get_index_keys_by_collection,get_schemas as get_mongo_schemas,get_server_metadata as get_mongo_server_metadata,mongo_client,@@ -316,38 +316,37 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixinmongo_schemas = get_mongo_schemas(config, team_id=team_id, names=names)connection_params = _parse_connection_string(config.connection_string, config.database_name)- leading_keys_by_collection: dict[str, set[str] | None] = {}with mongo_client(config.connection_string, team_id=team_id) as client:db = client[connection_params["database"]]- filtered_results = [- (collection_name, filter_mongo_incremental_fields(columns, db[collection_name]))- for collection_name, columns in mongo_schemas.items()- ]- for collection_name in mongo_schemas:- leading_keys_by_collection[collection_name] = get_leading_index_keys(db[collection_name])-- return [- SourceSchema(- name=name,- supports_incremental=len(incremental_fields) > 0,- supports_append=len(incremental_fields) > 0,- incremental_fields=[- {- "label": field_name,- "type": field_type,- "field": field_name,- "field_type": field_type,- "is_indexed": (- True- if leading_keys_by_collection.get(name) is None- else field_name in (leading_keys_by_collection.get(name) or set())- ),- }- for field_name, field_type in incremental_fields- ],+ index_keys_by_collection = get_index_keys_by_collection(db, list(mongo_schemas))++ schemas: list[SourceSchema] = []+ for collection_name, columns in mongo_schemas.items():+ index_keys = index_keys_by_collection.get(collection_name)+ incremental_fields = filter_mongo_incremental_fields(+ columns, index_keys.covered if index_keys else frozenset())- for name, incremental_fields in filtered_results- ]+ schemas.append(+ SourceSchema(+ name=collection_name,+ supports_incremental=len(incremental_fields) > 0,+ supports_append=len(incremental_fields) > 0,+ incremental_fields=[+ {+ "label": field_name,+ "type": field_type,+ "field": field_name,+ "field_type": field_type,+ # Index discovery failed, so we can't tell an unindexed field from an+ # indexed one. Don't warn on a guess.+ "is_indexed": True if index_keys is None else field_name in index_keys.leading,+ }+ for field_name, field_type in incremental_fields+ ],+ )+ )++ return schemasdef validate_credentials(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 909bbc4038db..b41dfed2957d 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@@ -37,7 +37,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mo_make_safe_server_selector,_process_doc_with_field_logging,_process_nested_value,- get_leading_index_keys,+ get_index_keys,+ get_index_keys_by_collection,get_server_metadata,mongo_source,)@@ -315,9 +316,9 @@ class TestProcessDocWithFieldLogging(SimpleTestCase):assert "_id=<unavailable>" in log_msg-class TestGetLeadingIndexKeys(SimpleTestCase):- """The MongoDB warning hinges on whether the user's chosen incremental- field is the *leading* key of any index — non-leading positions in compound+class TestGetIndexKeys(SimpleTestCase):+ """A field is offered as an incremental cursor when any index covers it, and the MongoDB+ warning hinges on whether it is the *leading* key of one — non-leading positions in compoundindexes don't speed up `WHERE field >= last_max` queries."""@@ -327,25 +328,51 @@ class TestGetLeadingIndexKeys(SimpleTestCase):coll.list_indexes.return_value = iter(indexes)return coll- def test_collects_leading_keys_only(self):+ def test_separates_covered_keys_from_leading_keys(self):coll = self._collection_with_indexes([{"key": {"_id": 1}},{"key": {"updated_at": -1}},- # `user_id` is the leading key here; `created_at` is not+ # `user_id` is the leading key here; `created_at` is covered but not leading{"key": {"user_id": 1, "created_at": 1}},])- assert get_leading_index_keys(coll) == {"_id", "updated_at", "user_id"}+ index_keys = get_index_keys(coll)++ assert index_keys is not None+ assert index_keys.covered == frozenset({"_id", "updated_at", "user_id", "created_at"})+ assert index_keys.leading == frozenset({"_id", "updated_at", "user_id"})def test_returns_none_on_failure(self):coll = MagicMock()coll.list_indexes.side_effect = RuntimeError("network down")- assert get_leading_index_keys(coll) is None+ assert get_index_keys(coll) is None++ def test_returns_empty_keys_for_collection_with_no_indexes(self):+ index_keys = get_index_keys(self._collection_with_indexes([]))++ assert index_keys is not None+ assert index_keys.covered == frozenset()+ assert index_keys.leading == frozenset()++ def test_reads_each_collection_indexes_once(self):+ # Schema discovery answers a blocking HTTP request, so a second round trip per collection+ # is what runs a database with many collections past that request's deadline.+ collections = {name: self._collection_with_indexes([{"key": {"_id": 1}}]) for name in ("a", "b", "c")}+ db = MagicMock()+ db.__getitem__.side_effect = lambda name: collections[name]++ result = get_index_keys_by_collection(db, list(collections))++ assert set(result) == set(collections)+ for name, coll in collections.items():+ assert coll.list_indexes.call_count == 1, f"{name} was read more than once"++ def test_reads_nothing_when_no_collections(self):+ db = MagicMock()- def test_returns_empty_set_for_collection_with_no_indexes(self):- coll = self._collection_with_indexes([])- assert get_leading_index_keys(coll) == set()+ assert get_index_keys_by_collection(db, []) == {}+ db.__getitem__.assert_not_called()class TestBuildQuery(SimpleTestCase):