Skip to content

: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.

fix(mongodb): fail clearly when a document has no _id field (#89701)

Tom Owers6aa40a8a20fe
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.py
index f3b6758b2b23..f2dfb97b5f1f 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
@@ -578,6 +578,18 @@ def _is_no_cursor_timeout_unsupported(error: OperationFailure) -> bool:
return any(marker in message for marker in _NO_CURSOR_TIMEOUT_UNSUPPORTED_MARKERS)
+# A find() against a MongoDB view returns the view pipeline's output, which has no `_id` when the
+# pipeline drops it (a $group on another key, a $project that excludes `_id`). The importer keys
+# every collection on `_id`: primary key, incremental cursor, and Delta merge dedup all read it, so
+# an `_id`-less document can't be synced and retrying never recovers. Raise this instead of the bare
+# `doc["_id"]` KeyError, and match it in the source's get_non_retryable_errors.
+MONGO_DOCUMENT_MISSING_ID_ERROR = (
+ "PostHog couldn't import this MongoDB collection because one of its documents has no _id field. "
+ "PostHog uses _id as the primary key for every collection. This usually means the collection is a "
+ "view whose pipeline removes _id. Sync the underlying collection instead, or add _id to the view."
+)
+
+
def mongo_source(
connection_string: str,
collection_name: str,
@@ -660,6 +672,8 @@ def mongo_source(
while True:
try:
for doc in cursor:
+ if "_id" not in doc:
+ raise ValueError(MONGO_DOCUMENT_MISSING_ID_ERROR)
last_id = doc["_id"]
rows_since_cursor_opened += 1
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.py
index c784f36b9500..0170288f0561 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
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (
DATABASE_NAME_REQUIRED_ERROR,
+ MONGO_DOCUMENT_MISSING_ID_ERROR,
_parse_connection_string,
filter_mongo_incremental_fields,
get_collection_names,
@@ -140,6 +141,10 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin
# reach the user — match the stable 'not authorized' fragment. Granting permission is a
# config change the user must make, so this never recovers on retry.
"not authorized": _MONGO_NOT_AUTHORIZED_MESSAGE,
+ # A view whose pipeline drops `_id` yields documents the importer can't key on. mongo.py
+ # raises MONGO_DOCUMENT_MISSING_ID_ERROR for this instead of a bare KeyError. Every retry
+ # reads the same `_id`-less documents, so it never recovers. Match our own stable phrase.
+ "one of its documents has no _id field": MONGO_DOCUMENT_MISSING_ID_ERROR,
"SSL handshake failed": None,
# Atlas SQL / Data Federation endpoints live under *.query.mongodb.net and are served by
# a query proxy the standard MongoDB driver can't drive: the handshake is closed, the
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.py
index 471abed1c153..a3d5723c3696 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
@@ -17,6 +17,7 @@ from pymongo.server_description import ServerDescription
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZE
from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (
+ MONGO_DOCUMENT_MISSING_ID_ERROR,
MONGO_MAX_CHUNK_ROWS,
MONGO_MIN_CHUNK_ROWS,
_adaptive_chunk_size,
@@ -377,6 +378,9 @@ class TestMongoDBNonRetryableErrors(SimpleTestCase):
"bad auth : authentication failed, full error: {'ok': 0, 'errmsg': 'bad auth : "
"authentication failed', 'code': 8000, 'codeName': 'AtlasError'}",
),
+ # Our own error for a view whose pipeline drops _id. Retrying reads the same _id-less
+ # documents forever, so it must be classified non-retryable.
+ ("document_missing_id", MONGO_DOCUMENT_MISSING_ID_ERROR),
("dns_failure", "The DNS query name does not exist: example.mongodb.net."),
("ssl_failure", "SSL handshake failed: certificate verify failed"),
# pymongo InvalidURI raised before any network call when credentials in the connection
@@ -459,6 +463,7 @@ class TestMongoDBNonRetryableErrors(SimpleTestCase):
("unreachable_topology", "Topology Description:", "allowlist"),
("atlas_sql_endpoint", "query.mongodb.net", "connection string"),
("unescaped_credentials", "must be escaped according to RFC 3986", "connection string"),
+ ("document_missing_id", "one of its documents has no _id field", "view"),
]
)
def test_pattern_has_friendly_message(self, _name, pattern, expected_substring):
@@ -771,6 +776,17 @@ class TestMongoSourceCursorLifecycle(SimpleTestCase):
# cursors[2] is the read reopened after CursorNotFound; assert it resumes _id-ordered.
assert collection.cursors[2].sorted_by == ["_id", 1]
+ def test_document_without_id_raises_actionable_error(self):
+ # A view whose pipeline drops _id yields documents with no _id, which the importer can't key
+ # on. Regression: get_rows used to crash on doc["_id"] with a bare KeyError('_id'). It must
+ # raise the actionable, non-retryable message instead.
+ collection = _FakeCollection([{"name": "no id here"}])
+
+ with self.assertRaises(ValueError) as ctx:
+ self._run_get_rows(collection)
+
+ assert str(ctx.exception) == MONGO_DOCUMENT_MISSING_ID_ERROR
+
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.