: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
feat(warehouse-sources): record the MongoDB version a source reports (#100594)
Daniel RCc590b281392f
diff --git a/products/warehouse_sources/backend/management/commands/backfill_mongodb_server_versions.py b/products/warehouse_sources/backend/management/commands/backfill_mongodb_server_versions.pynew file mode 100644index 000000000000..95f7d45226ef--- /dev/null+++ b/products/warehouse_sources/backend/management/commands/backfill_mongodb_server_versions.py@@ -0,0 +1,138 @@+"""Record the MongoDB version and wire version each MongoDB source's cluster reports.++The schema-discovery pass records this for every source on its own schedule, so this command is+for answering the question now instead of waiting for that pass to come round. The wire version+decides whether a source survives a pymongo wire-version floor change, and no other column holds+it, so an upgrade that raises the floor is otherwise unmeasurable until customer syncs start+failing.+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandParser++import structlog++from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.types import ExternalDataSourceType++logger = structlog.get_logger(__name__)++# pymongo 4.14 raises its floor from wire version 7 (MongoDB 4.0) to 8 (MongoDB 4.2). The pinned+# driver is 4.13, which still accepts 7, so this is the floor a cluster has to clear after that+# upgrade and not one it fails today.+TARGET_MIN_WIRE_VERSION = 8+++class Command(BaseCommand):+ help = (+ "Probe every MongoDB source for the server version its cluster reports and store it on the "+ "source's connection_metadata. Reports a version breakdown and how many clusters sit below "+ "the floor pymongo 4.14 introduces. Previews by default; pass --live-run to persist."+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument(+ "--team-id",+ type=int,+ default=None,+ help="Only probe sources belonging to this team.",+ )+ parser.add_argument(+ "--limit",+ type=int,+ default=None,+ help="Only probe the first N sources, for a cautious first batch.",+ )+ parser.add_argument(+ "--refresh",+ action="store_true",+ help="Re-probe sources that already have a recorded server version.",+ )+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Persist the probed versions. Without this the command only reports what it found.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ sources = self._sources(team_id=options["team_id"], limit=options["limit"], refresh=options["refresh"])+ live_run = options["live_run"]+ source_impl = SourceRegistry.get_source(ExternalDataSourceType.MONGODB)++ versions: dict[str, int] = {}+ below_floor = 0+ probed = 0+ failed = 0+ partial = 0++ for source in sources:+ metadata = self._probe(source_impl, source)+ if metadata is None:+ failed += 1+ continue++ probed += 1+ version = str(metadata.get("server_version") or "unknown")+ versions[version] = versions.get(version, 0) + 1+ wire_version = metadata.get("wire_version")+ if isinstance(wire_version, int) and wire_version < TARGET_MIN_WIRE_VERSION:+ below_floor += 1+ self.stdout.write(+ f"source {source.id} (team {source.team_id}): MongoDB {version}, "+ f"wire version {wire_version} is below the pymongo 4.14 floor of {TARGET_MIN_WIRE_VERSION}"+ )+ if metadata.get("handshaked_nodes") != metadata.get("topology_nodes"):+ partial += 1++ if live_run:+ # Probing costs a network round trip per source, so the merge re-reads the row+ # under a lock rather than trusting the snapshot this run opened with.+ source.merge_connection_metadata(metadata)++ self.stdout.write(f"probed {probed}, failed {failed}, below the pymongo 4.14 floor {below_floor}")+ if partial:+ # A source whose nodes were not all handshaked may hide an older member, so its wire+ # version is a ceiling rather than a reading.+ self.stdout.write(f" {partial} source(s) reported only part of their topology")+ for version, count in sorted(versions.items()):+ self.stdout.write(f" MongoDB {version}: {count}")+ if not live_run:+ self.stdout.write("preview only, nothing written. Re-run with --live-run to persist.")++ def _sources(self, *, team_id: int | None, limit: int | None, refresh: bool) -> list[ExternalDataSource]:+ sources = ExternalDataSource.objects.filter(+ source_type=ExternalDataSourceType.MONGODB,+ deleted=False,+ ).order_by("created_at")++ if team_id is not None:+ sources = sources.filter(team_id=team_id)+ if not refresh:+ sources = sources.exclude(connection_metadata__server_version__isnull=False)+ if limit is not None:+ sources = sources[:limit]++ # A source with no stored credentials has nothing to connect with, and reaching one costs a+ # full server-selection timeout, so drop those before probing rather than counting them as+ # failures.+ return [source for source in sources if source.job_inputs]++ def _probe(self, source_impl: Any, source: ExternalDataSource) -> dict[str, Any] | None:+ # An unreachable or misconfigured cluster is the common case here, not an exception worth+ # stopping for: this command's whole purpose is to survey a population that includes broken+ # sources, so a failure is logged and the survey continues.+ try:+ config = source_impl.parse_config(source.job_inputs)+ metadata = source_impl.get_server_metadata(config, source.team_id)+ except Exception as error:+ logger.warning(+ "Could not probe MongoDB source",+ source_id=str(source.id),+ team_id=source.team_id,+ error=str(error),+ )+ return None++ return metadata if isinstance(metadata, dict) else Nonediff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex 487cc03e70d9..692eba28f020 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -1,6 +1,7 @@+from typing import Anyfrom uuid import UUID-from django.db import models+from django.db import models, transactionfrom django.utils import timezoneimport structlog@@ -90,6 +91,31 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldclass Meta:db_table = "posthog_externaldatasource"+ def merge_connection_metadata(self, metadata: dict[str, Any]) -> None:+ """Merge ``metadata`` into ``connection_metadata`` under a lock on this row.++ Several writers share the field: the API stores direct-query connection config, and the+ schema-discovery pass and the backfill command store probed server versions. Each one holds+ a row it read before a network round trip, so a plain read-modify-write drops whichever+ write landed in between. Re-reading under the lock is what makes the merge safe, and the+ lock covers only that re-read and the write, with no network call inside it.++ ``of=("self",)`` keeps the lock on this row. The default manager joins+ ``revenue_analytics_config``, and an unqualified ``FOR UPDATE`` would lock the joined rows+ as well.++ ``updated_at`` stays out of the write so a probe does not read as a customer edit.+ """+ with transaction.atomic():+ locked = type(self).objects.select_for_update(of=("self",)).get(pk=self.pk)+ # The field is an unconstrained JSONField, so a non-mapping value is replaced rather+ # than unpacked, which would raise.+ existing = locked.connection_metadata if isinstance(locked.connection_metadata, dict) else {}+ merged = {**existing, **metadata}+ locked.connection_metadata = merged+ locked.save(update_fields=["connection_metadata"])+ self.connection_metadata = merged+@propertydef is_direct_query(self) -> bool:return self.access_method == self.AccessMethod.DIRECTdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.pyindex 1afed73fcb5d..dce580c08aef 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py@@ -452,6 +452,14 @@ class _BaseSource(ABC, Generic[ConfigType]):redirect the row's injected token. Default: no row-backed credentials."""return False+ def get_server_metadata(self, config: ConfigType, team_id: int) -> dict[str, Any]:+ """Version facts probed from the upstream server, which the schema-discovery pass merges+ onto the source's ``connection_metadata``. Distinct from ``get_connection_metadata``, which+ the API calls for direct-query sources only and which returns that mode's connection+ config, so a source that implements one does not implement the other by accident. The keys+ vary per source, so the shape is a dict and not a fixed contract. No-op by default."""+ return {}+def on_source_created(self, source_model: "ExternalDataSource", team_id: int) -> None:"""Post-create hook. Custom claims its OAuth2 integration row here. No-op by default."""return Nonediff --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 0ba80ff788f6..22fdf7c11e99 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@@ -293,6 +293,43 @@ def mongo_client(connection_string: str, team_id: int) -> Iterator[MongoClient]:client.close()+def get_server_metadata(connection_string: str, team_id: int) -> dict[str, Any]:+ """Probe the cluster for the MongoDB version it reports, and for its wire version.++ The driver refuses any server below its own wire-version floor, and that floor rises across+ pymongo releases, so whether a source survives a driver upgrade is a property of the source+ and not of our code. Nothing else records it, which makes the question unanswerable before an+ upgrade ships. AWS DocumentDB and Azure Cosmos DB's Mongo API report the MongoDB version they+ emulate, and that emulated version is what the driver gates on.+ """+ with mongo_client(connection_string, team_id) as client:+ # buildInfo is answered by every server version we accept and by the DocumentDB and Cosmos+ # DB Mongo APIs, whereas `hello` was added in MongoDB 5.0 and is missing from the older+ # emulation levels this probe most needs to identify. Asking for it also completes the+ # handshake that fills in the wire versions read below, so they cost no extra round trip.+ server_version = str(client.server_info().get("version") or "")+ # A node pymongo has not handshaked with reports wire version 0, which would read as older+ # than any real server and hide the true floor.+ descriptions = list(client.topology_description.server_descriptions().values())+ handshaked = [description for description in descriptions if description.is_server_type_known]++ metadata: dict[str, Any] = {+ "engine": "mongodb",+ "server_version": server_version,+ # Server selection returns as soon as one node is usable, so a replica set can still hold+ # members this probe never handshaked with. Both counts are recorded because a reading that+ # skipped an older secondary would otherwise pass as an all-clear: it is complete only+ # where the two agree.+ "handshaked_nodes": len(handshaked),+ "topology_nodes": len(descriptions),+ }+ # pymongo rejects a whole topology when any single node sits below its floor, so the weakest+ # node is what decides whether an upgrade cuts this source off.+ if handshaked:+ metadata["wire_version"] = min(description.max_wire_version for description in handshaked)+ return metadata++def _get_partition_settings(collection: Collection, collection_name: str, partition_size_bytes: int = DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES) -> PartitionSettings | None:diff --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 8dfb926bdcb0..9b8db0771f6a 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@@ -1,4 +1,4 @@-from typing import Optional, cast+from typing import Any, Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.moget_collection_names,get_leading_index_keys,get_schemas as get_mongo_schemas,+ get_server_metadata as get_mongo_server_metadata,mongo_client,mongo_source,)@@ -348,6 +349,9 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixinreturn True, None+ def get_server_metadata(self, config: MongoDBSourceConfig, team_id: int) -> dict[str, Any]:+ return get_mongo_server_metadata(config.connection_string, team_id)+def source_for_pipeline(self, config: MongoDBSourceConfig, inputs: SourceInputs) -> SourceResponse:return mongo_source(connection_string=config.connection_string,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 820dca1f391d..362e2d1354dd 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@@ -2,7 +2,7 @@ import uuidimport base64import datetimeimport contextlib-from collections.abc import Iterable+from collections.abc import Iterable, Iteratorfrom typing import Any, castfrom unittest.mock import MagicMock, patch@@ -13,6 +13,7 @@ from bson import Binary, DatetimeMS, ObjectIdfrom bson.binary import UUID_SUBTYPEfrom parameterized import parameterizedfrom pymongo.errors import CursorNotFound, OperationFailure, ServerSelectionTimeoutError+from pymongo.hello import Hellofrom pymongo.server_description import ServerDescriptionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZE@@ -29,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mo_process_doc_with_field_logging,_process_nested_value,get_leading_index_keys,+ get_server_metadata,mongo_source,)from products.warehouse_sources.backend.types import IncrementalFieldType@@ -876,3 +878,63 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):self._run_get_rows(collection)assert len(collection.find_calls) == 2+++class TestGetServerMetadata(SimpleTestCase):+ @staticmethod+ def _server(host: str, max_wire_version: int | None) -> ServerDescription:+ # A ServerDescription built without a hello response is the state pymongo holds for a node+ # it has not handshaked with, which is what the probe has to leave out.+ if max_wire_version is None:+ return ServerDescription((host, 27017))+ return ServerDescription(+ (host, 27017),+ Hello({"ok": 1, "isWritablePrimary": True, "minWireVersion": 0, "maxWireVersion": max_wire_version}),+ )++ @contextlib.contextmanager+ def _patched_client(self, server_version: str, servers: list[ServerDescription]) -> Iterator[None]:+ client = MagicMock()+ client.server_info.return_value = {"version": server_version}+ client.topology_description.server_descriptions.return_value = {server.address: server for server in servers}+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo.mongo_client"+ ) as client_factory:+ client_factory.return_value.__enter__.return_value = client+ yield++ @parameterized.expand(+ [+ ("single_node", "7.0.14", [("a.example.com", 21)], 21, 1, 1),+ # The driver refuses the whole topology over one node below its floor, so reporting+ # anything but the weakest node would mark this source safe to upgrade when it is not.+ ("replica_set_reports_weakest_node", "4.0.28", [("a.example.com", 21), ("b.example.com", 7)], 7, 2, 2),+ # Server selection returns on the first usable node, so the wire version here comes+ # from a partial view. The counts have to disagree, or the reading passes as complete+ # and an older secondary the probe never saw goes uncounted.+ ("unhandshaked_node_is_ignored", "6.0.1", [("a.example.com", 13), ("b.example.com", None)], 13, 1, 2),+ ("no_handshaked_node_reports_no_wire_version", "", [("a.example.com", None)], None, 0, 1),+ ]+ )+ def test_wire_version_comes_from_the_weakest_handshaked_node(+ self,+ _name: str,+ server_version: str,+ nodes: list[tuple[str, int | None]],+ expected_wire_version: int | None,+ expected_handshaked_nodes: int,+ expected_topology_nodes: int,+ ) -> None:+ servers = [self._server(host, max_wire_version) for host, max_wire_version in nodes]++ with self._patched_client(server_version, servers):+ metadata = get_server_metadata("mongodb://user:[email protected]/db?tls=true", team_id=1)++ assert metadata["engine"] == "mongodb"+ assert metadata["server_version"] == server_version+ assert metadata["handshaked_nodes"] == expected_handshaked_nodes+ assert metadata["topology_nodes"] == expected_topology_nodes+ if expected_wire_version is None:+ assert "wire_version" not in metadata+ else:+ assert metadata["wire_version"] == expected_wire_versiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.pyindex bf14f55d406f..de7055a6edb5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py@@ -120,6 +120,21 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:raiseschemas_to_sync = {s.name: s.label for s in schemas}++ try:+ server_metadata = new_source.get_server_metadata(config, inputs.team_id)+ if isinstance(server_metadata, dict) and server_metadata:+ # `source` was read before schema discovery, which is a network call of its own, so+ # the merge re-reads the row under a lock rather than trusting that snapshot.+ source.merge_connection_metadata(server_metadata)+ except Exception:+ # Recording the version is incidental to schema discovery, and both steps here can fail+ # on their own: the probe opens a connection to the customer's server, and the merge+ # waits on a row lock that the backfill command can hold. Neither says anything about+ # the schemas already discovered above, so a pass that otherwise succeeded stays+ # successful. A real connection fault still reaches the user through the per-schema sync+ # path, which has its own reporting.+ logger.warning("Could not record source server metadata", exc_info=True)else:raise ValueError(f"Source type missing from SourceRegistry: {source.source_type}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.pyindex 7854ccb2bd3c..1c3e137d0750 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py@@ -3,6 +3,8 @@ import contextlibimport pytestfrom unittest import mock+from django.db import OperationalError+from posthog.models.integration import UndecryptedIntegrationSecretErrorfrom posthog.temporal.common.errors import NonReportableError@@ -14,11 +16,12 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie)-def _patch_common(source_mock, schemas_created=None, source_api_version=None):+def _patch_common(source_mock, schemas_created=None, source_api_version=None, merge_error=None):"""Patch DB + registry so the activity runs without a database or real source."""existing_source = mock.MagicMock(source_type="GoogleAds", job_inputs={"k": "v"}, deleted=False, api_version=source_api_version)+ existing_source.merge_connection_metadata.side_effect = merge_errorobjects = mock.MagicMock()objects.filter.return_value.exclude.return_value.exists.return_value = Trueobjects.get.return_value = existing_source@@ -38,8 +41,10 @@ def _patch_common(source_mock, schemas_created=None, source_api_version=None):}-def _run_activity(source_mock, schemas_created=None, source_api_version=None):- patches = _patch_common(source_mock, schemas_created, source_api_version=source_api_version)+def _run_activity(source_mock, schemas_created=None, source_api_version=None, merge_error=None):+ patches = _patch_common(+ source_mock, schemas_created, source_api_version=source_api_version, merge_error=merge_error+ )with contextlib.ExitStack() as stack:entered = {name: stack.enter_context(patcher) for name, patcher in patches.items()}sync_new_schemas_activity(SyncNewSchemasActivityInputs(source_id="src", team_id=1))@@ -191,3 +196,43 @@ def test_auto_enable_not_called_when_nothing_created():mocks = _run_activity(source_mock)mocks["auto_enable_new_schemas"].assert_not_called()+++def test_probed_metadata_goes_through_the_locked_merge():+ # `source` is read before schema discovery, which is itself a network call, so the write has to+ # re-read the row. Assigning the field here would drop a write that landed in between.+ source_mock = mock.MagicMock()+ source_mock.parse_config.return_value = {}+ source_mock.get_schemas.return_value = []+ source_mock.get_server_metadata.return_value = {"engine": "mongodb", "wire_version": 7}++ mocks = _run_activity(source_mock)++ source = mocks["objects"].get.return_value+ source.merge_connection_metadata.assert_called_once_with({"engine": "mongodb", "wire_version": 7})+ source.save.assert_not_called()+++ "probe_error,merge_error,expected_merge_calls",+ [+ (Exception("connection refused"), None, 0),+ (None, OperationalError("canceling statement due to lock timeout"), 1),+ ],+ ids=["the_probe_fails", "the_locked_merge_fails"],+)+def test_a_failed_metadata_write_leaves_discovery_successful(probe_error, merge_error, expected_merge_calls):+ # Recording the version is incidental to discovery, and each step fails on its own terms: the+ # probe reaches an unreachable server, and the merge waits on a row lock the backfill command can+ # hold. Either one escaping would fail every discovery pass for that source, and the schemas+ # found just above would never reconcile.+ source_mock = mock.MagicMock()+ source_mock.parse_config.return_value = {}+ source_mock.get_schemas.return_value = []+ source_mock.get_server_metadata.return_value = {"engine": "mongodb", "wire_version": 7}+ source_mock.get_server_metadata.side_effect = probe_error++ mocks = _run_activity(source_mock, merge_error=merge_error)++ mocks["sync_old_schemas_with_new_schemas"].assert_called_once()+ assert mocks["objects"].get.return_value.merge_connection_metadata.call_count == expected_merge_callsdiff --git a/products/warehouse_sources/backend/tests/management/test_backfill_mongodb_server_versions.py b/products/warehouse_sources/backend/tests/management/test_backfill_mongodb_server_versions.pynew file mode 100644index 000000000000..0359cc50b590--- /dev/null+++ b/products/warehouse_sources/backend/tests/management/test_backfill_mongodb_server_versions.py@@ -0,0 +1,84 @@+import uuid+from typing import Any++import pytest+from unittest.mock import patch++from django.core.management import call_command++from posthog.api.test.test_organization import create_organization+from posthog.api.test.test_team import create_team++from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++pytestmark = [pytest.mark.django_db]++COMMAND = "backfill_mongodb_server_versions"+PROBE = "products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source.get_mongo_server_metadata"+++def team():+ return create_team(organization=create_organization("test org"))+++def _create_source(team, host: str) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ source_type="MongoDB",+ job_inputs={"connection_string": f"mongodb://user:pass@{host}/db?tls=true", "database_name": "db"},+ )+++def test_preview_run_probes_but_writes_nothing(team) -> None:+ source = _create_source(team, "reachable.example.com")++ with patch(PROBE, return_value={"engine": "mongodb", "server_version": "4.0.28", "wire_version": 7}) as probe:+ call_command(COMMAND)++ # Asserting the probe ran is what separates "the command declined to write" from "the command+ # never selected the source", which would make the assertion below pass for the wrong reason.+ assert probe.call_count == 1+ source.refresh_from_db()+ assert source.connection_metadata == {}+++def test_unreachable_source_does_not_stop_the_survey(team) -> None:+ unreachable = _create_source(team, "unreachable.example.com")+ reachable = _create_source(team, "reachable.example.com")++ def probe(connection_string: str, team_id: int) -> dict[str, Any]:+ if "unreachable" in connection_string:+ raise TimeoutError("server selection timed out")+ return {"engine": "mongodb", "server_version": "7.0.14", "wire_version": 21}++ with patch(PROBE, side_effect=probe):+ call_command(COMMAND, "--live-run")++ unreachable.refresh_from_db()+ reachable.refresh_from_db()+ assert unreachable.connection_metadata == {}+ assert reachable.connection_metadata == {"engine": "mongodb", "server_version": "7.0.14", "wire_version": 21}+++def test_live_run_keeps_a_write_that_landed_during_the_probe(team) -> None:+ # Probing costs a round trip per source and the discovery pass writes the same field, so a+ # merge into this run's opening snapshot would drop whatever landed while the probe ran.+ source = _create_source(team, "reachable.example.com")++ def probe(connection_string: str, team_id: int) -> dict[str, Any]:+ ExternalDataSource.objects.filter(pk=source.pk).update(connection_metadata={"database": "analytics"})+ return {"engine": "mongodb", "server_version": "7.0.14", "wire_version": 21}++ with patch(PROBE, side_effect=probe):+ call_command(COMMAND, "--live-run")++ source.refresh_from_db()+ assert source.connection_metadata == {+ "database": "analytics",+ "engine": "mongodb",+ "server_version": "7.0.14",+ "wire_version": 21,+ }diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 66f0ed418121..8507d730330a 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -1281,3 +1281,62 @@ class TestRepartitionHoldsImport:naive = (datetime.now(UTC) - timedelta(minutes=5)).replace(tzinfo=None).isoformat()schema = self._schema_with({"temp_uri": "s3://t", "held_at": naive})assert schema.repartition_holds_import is True+++class TestMergeConnectionMetadata(BaseTest):+ def _source(self, connection_metadata: Any) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ source_type="MongoDB",+ connection_metadata=connection_metadata,+ )++ def test_a_write_that_lands_before_the_merge_survives(self) -> None:+ source = self._source({})+ ExternalDataSource.objects.filter(pk=source.pk).update(connection_metadata={"database": "analytics"})++ source.merge_connection_metadata({"engine": "mongodb", "wire_version": 7})++ source.refresh_from_db()+ assert source.connection_metadata == {"database": "analytics", "engine": "mongodb", "wire_version": 7}++ def test_the_merged_value_wins_on_overlap(self) -> None:+ source = self._source({"wire_version": 21})++ source.merge_connection_metadata({"wire_version": 7})++ source.refresh_from_db()+ assert source.connection_metadata == {"wire_version": 7}++ @parameterized.expand([("a_list", ["unexpected"]), ("null", None)])+ def test_a_value_that_is_not_a_mapping_is_replaced(self, _name: str, stored: Any) -> None:+ source = self._source(stored)++ source.merge_connection_metadata({"engine": "mongodb"})++ source.refresh_from_db()+ assert source.connection_metadata == {"engine": "mongodb"}++ def test_the_lock_stays_off_the_joined_config_row(self) -> None:+ # The default manager joins revenue_analytics_config, so an unqualified FOR UPDATE would+ # lock that table's rows as well as this one.+ source = self._source({})++ with CaptureQueriesContext(connection) as queries:+ source.merge_connection_metadata({"engine": "mongodb"})++ locking = [query["sql"] for query in queries.captured_queries if "FOR UPDATE" in query["sql"]]+ assert len(locking) == 1+ assert 'FOR UPDATE OF "posthog_externaldatasource"' in locking[0]++ def test_updated_at_is_left_where_it_was(self) -> None:+ # A probe is not a customer edit, so it must not move the source's updated_at.+ source = self._source({})+ before = source.updated_at++ source.merge_connection_metadata({"engine": "mongodb"})++ source.refresh_from_db()+ assert source.updated_at == before