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(conversations): skip deleted Gmail messages instead of stalling sync (#87280)

posthog[bot]66b838bb7a1d
diff --git a/products/conversations/backend/services/gmail_sync.py b/products/conversations/backend/services/gmail_sync.py
index 501b88764383..edb8c9848250 100644
--- a/products/conversations/backend/services/gmail_sync.py
+++ b/products/conversations/backend/services/gmail_sync.py
@@ -316,22 +316,25 @@ def _ingest_message_id(
gmail_message_id: str,
internal_emails: set[str],
) -> None:
- payload = _get_json(
+ payload = _get_json_allowing_missing(
integration=integration,
access_token=access_token,
url=f"{GMAIL_API_BASE_URL}/messages/{gmail_message_id}",
endpoint="/gmail/v1/users/me/messages/{message_id}",
params={"format": "full"},
)
+ # The user deleted the message between the history page and this fetch. Skip it.
+ if payload is None:
+ return
def load_attachment_data(attachment_id: str) -> str:
- attachment = _get_json(
+ attachment = _get_json_allowing_missing(
integration=integration,
access_token=access_token,
url=f"{GMAIL_API_BASE_URL}/messages/{gmail_message_id}/attachments/{attachment_id}",
endpoint="/gmail/v1/users/me/messages/{message_id}/attachments/{attachment_id}",
)
- return str(attachment.get("data") or "")
+ return str(attachment.get("data") or "") if attachment else ""
try:
parsed = _parse_gmail_message(
@@ -535,6 +538,26 @@ def _get_json(
return _response_json(response, "Gmail API")
+def _get_json_allowing_missing(
+ *,
+ integration: Integration,
+ access_token: str,
+ url: str,
+ endpoint: str,
+ params: dict[str, Any] | None = None,
+) -> dict[str, Any] | None:
+ response = _request(
+ integration=integration,
+ access_token=access_token,
+ url=url,
+ endpoint=endpoint,
+ params=params,
+ )
+ if response.status_code == 404:
+ return None
+ return _response_json(response, "Gmail API")
+
+
def _response_json(response: requests.Response, operation: str) -> dict[str, Any]:
if response.status_code != 200:
raise GmailSyncError(f"{operation} returned {response.status_code}: {response.text[:200]}")
diff --git a/products/conversations/backend/tests/test_gmail_sync.py b/products/conversations/backend/tests/test_gmail_sync.py
index ee0a77aab66d..1ef0b2b8be52 100644
--- a/products/conversations/backend/tests/test_gmail_sync.py
+++ b/products/conversations/backend/tests/test_gmail_sync.py
@@ -207,6 +207,63 @@ class TestGmailSync(BaseTest):
assert gmail_sync.GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY not in self.integration.config
assert EmailThreadMessage.objects.for_team(self.team.id).count() == 2
+ def test_deleted_message_is_skipped_and_cursor_advances(self) -> None:
+ self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] = "100"
+ self.integration.save(update_fields=["config"])
+ history = {
+ "history": [
+ {
+ "id": "101",
+ "messagesAdded": [
+ {"message": {"id": "deleted-1"}},
+ {"message": {"id": "gmail-2"}},
+ ],
+ }
+ ],
+ "historyId": "101",
+ }
+ second_message = _gmail_message(
+ label="INBOX", sender="[email protected]", recipient=self.user.email, message_id="gmail-2"
+ )
+
+ with patch.object(
+ gmail_sync,
+ "google_workspace_request",
+ side_effect=[
+ _response(history),
+ _response({"error": {"message": "Requested entity was not found."}}, status_code=404),
+ _response(second_message),
+ ],
+ ):
+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)
+
+ self.integration.refresh_from_db()
+ assert self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] == "101"
+ assert gmail_sync.GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY not in self.integration.config
+ message = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get()
+ assert message.comment.content == "Customer message body"
+
+ def test_deleted_attachment_is_skipped(self) -> None:
+ message = _gmail_message(label="INBOX", sender="[email protected]", recipient=self.user.email)
+ message["payload"]["body"] = {"attachmentId": "body-attachment"}
+
+ with patch.object(
+ gmail_sync,
+ "google_workspace_request",
+ side_effect=[
+ _response({"emailAddress": self.user.email, "historyId": "100"}),
+ _response({"messages": [{"id": "gmail-1"}]}),
+ _response(message),
+ _response({"error": {"message": "Requested entity was not found."}}, status_code=404),
+ ],
+ ):
+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)
+
+ imported = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get()
+ assert imported.comment.content == ""
+ self.integration.refresh_from_db()
+ assert self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] == "100"
+
def test_incremental_sync_is_idempotent(self) -> None:
self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] = "100"
self.integration.save(update_fields=["config"])