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): handle non-ObjectId _id incremental cursor (#66436)

Tom Owersdafd515caf15
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 b3647494b916..115d2a79837c 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
@@ -197,13 +197,23 @@ def _build_query(
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
if incremental_field_type == IncrementalFieldType.ObjectID:
- query = {incremental_field: {"$gt": ObjectId(str(db_incremental_field_last_value)), "$exists": True}}
+ query = {incremental_field: {"$gt": _coerce_object_id_cursor(db_incremental_field_last_value), "$exists": True}}
else:
query = {incremental_field: {"$gt": db_incremental_field_last_value, "$exists": True}}
return query
+def _coerce_object_id_cursor(last_value: Any) -> Any:
+ """`_id` is offered as an ObjectID incremental cursor, but MongoDB `_id` values aren't
+ always ObjectIds — collections frequently key on UUIDs or other strings. Only wrap the
+ cursor in ObjectId when it's a valid 24-char hex id; otherwise compare the raw string so
+ a non-ObjectId `_id` doesn't raise InvalidId and permanently break every incremental sync.
+ """
+ value = str(last_value)
+ return ObjectId(value) if ObjectId.is_valid(value) else value
+
+
def _make_safe_server_selector(team_id: int) -> Callable[[list[ServerDescription]], list[ServerDescription]]:
"""Create a PyMongo server_selector that rejects servers resolving to internal IPs.
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 73fb57901332..b07e3210e8a8 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
@@ -13,12 +13,14 @@ from pymongo.errors import ServerSelectionTimeoutError
from pymongo.server_description import ServerDescription
from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (
+ _build_query,
_get_rows_to_sync,
_make_safe_server_selector,
_process_doc_with_field_logging,
_process_nested_value,
get_leading_index_keys,
)
+from products.warehouse_sources.backend.types import IncrementalFieldType
class TestSafeServerSelector(SimpleTestCase):
@@ -322,6 +324,27 @@ class TestGetLeadingIndexKeys(SimpleTestCase):
assert get_leading_index_keys(coll) == set()
+class TestBuildQuery(SimpleTestCase):
+ """`_id` is offered as an ObjectID incremental cursor, but MongoDB `_id` values aren't
+ always ObjectIds — a non-ObjectId cursor must not crash query construction."""
+
+ _OID_HEX = "507f1f77bcf86cd799439011"
+ _UUID = "fffdb62e-4704-4671-984c-ffcff3a8dd52"
+
+ @parameterized.expand(
+ [
+ # A valid 24-char hex cursor stays an ObjectId so native ordered comparison is preserved.
+ ("objectid_cursor_is_wrapped", _OID_HEX, ObjectId(_OID_HEX)),
+ # Regression: a UUID-string `_id` previously raised bson.errors.InvalidId here,
+ # permanently breaking every incremental sync for collections that key on UUIDs.
+ ("uuid_cursor_compares_as_string", _UUID, _UUID),
+ ]
+ )
+ def test_cursor_coercion(self, _name: str, cursor: str, expected_gt):
+ query = _build_query(True, "_id", IncrementalFieldType.ObjectID, cursor)
+ assert query == {"_id": {"$gt": expected_gt, "$exists": True}}
+
+
class TestMongoDBNonRetryableErrors(SimpleTestCase):
"""The non-retryable match is case-sensitive substring matching, so the patterns
must match the exact casing pymongo produces."""