Personal AI, On Personal Devices
Python
fix(connectors): recover Google timestamp and quota sync failures (#1100)
Huanyi Xie7a5f223d7a51
diff --git a/src/openjarvis/connectors/gmail.py b/src/openjarvis/connectors/gmail.pyindex 72c3315c..aa655c20 100644--- a/src/openjarvis/connectors/gmail.py+++ b/src/openjarvis/connectors/gmail.py@@ -10,7 +10,9 @@ from __future__ import annotationsimport base64import email.utilsimport logging+import randomimport re+import timefrom datetime import datetimefrom html.parser import HTMLParserfrom typing import Any, Dict, Iterator, List, Optional, Tuple@@ -54,6 +56,48 @@ _DEFAULT_CREDENTIALS_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "gmail.json"GmailAuthError = GoogleAuthError+def _is_rate_limited(response: httpx.Response) -> bool:+ """Distinguish Google's transient quotas from permission and daily limits."""+ if response.status_code == 429:+ return True+ if response.status_code != 403:+ return False+ try:+ payload = response.json()+ except ValueError:+ return False+ error = payload.get("error") if isinstance(payload, dict) else None+ details = error.get("errors", []) if isinstance(error, dict) else []+ return isinstance(details, list) and any(+ isinstance(item, dict)+ and item.get("reason") in {"rateLimitExceeded", "userRateLimitExceeded"}+ for item in details+ )+++def _gmail_get(url: str, token: str, params: Dict[str, str]) -> httpx.Response:+ """Retry idempotent Gmail reads with a bounded exponential quota backoff."""+ for attempt in range(6):+ response = httpx.get(+ url,+ headers={"Authorization": f"Bearer {token}"},+ params=params,+ timeout=30.0,+ )+ if not _is_rate_limited(response):+ return response+ if attempt == 5:+ raise httpx.HTTPStatusError(+ f"Gmail rate limited after 6 attempts (HTTP {response.status_code})",+ request=response.request,+ response=response,+ )+ delay = min(60.0, 2.0 ** (attempt + 1) + random.random())+ logger.info("Gmail rate limited; retrying in %.1fs", delay)+ time.sleep(delay)+ raise AssertionError("unreachable retry loop")++# ---------------------------------------------------------------------------# Module-level API functions (easy to patch in tests)# ---------------------------------------------------------------------------@@ -88,12 +132,7 @@ def _gmail_api_list_messages(if query:params["q"] = query- resp = httpx.get(- f"{_GMAIL_API_BASE}/messages",- headers={"Authorization": f"Bearer {token}"},- params=params,- timeout=30.0,- )+ resp = _gmail_get(f"{_GMAIL_API_BASE}/messages", token, params)resp.raise_for_status()return resp.json()@@ -145,12 +184,7 @@ def _gmail_api_get_message(token: str, msg_id: str) -> Dict[str, Any]:dictRaw API response for the message resource."""- resp = httpx.get(- f"{_GMAIL_API_BASE}/messages/{msg_id}",- headers={"Authorization": f"Bearer {token}"},- params={"format": "full"},- timeout=30.0,- )+ resp = _gmail_get(f"{_GMAIL_API_BASE}/messages/{msg_id}", token, {"format": "full"})resp.raise_for_status()return resp.json()diff --git a/src/openjarvis/connectors/google_tasks.py b/src/openjarvis/connectors/google_tasks.pyindex f4badb19..06b81019 100644--- a/src/openjarvis/connectors/google_tasks.py+++ b/src/openjarvis/connectors/google_tasks.py@@ -5,7 +5,7 @@ Uses OAuth2 tokens via the shared Google OAuth helper module.from __future__ import annotations-from datetime import datetime+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, Iterator, Optional@@ -86,7 +86,10 @@ class GoogleTasksConnector(BaseConnector):"showHidden": "false",}if since:- params["updatedMin"] = since.isoformat() + "Z"+ cutoff = since+ if cutoff.tzinfo is not None:+ cutoff = cutoff.astimezone(timezone.utc).replace(tzinfo=None)+ params["updatedMin"] = cutoff.isoformat() + "Z"tasks = call_with_refresh(_tasks_api_get,diff --git a/src/openjarvis/server/connectors_router.py b/src/openjarvis/server/connectors_router.pyindex 435d0a4e..ee841d73 100644--- a/src/openjarvis/server/connectors_router.py+++ b/src/openjarvis/server/connectors_router.py@@ -311,10 +311,10 @@ def create_connectors_router():"""Map common backend exceptions to a short user-facing message."""if "401" in raw or "Unauthorized" in raw:return "Authentication failed — credentials may have expired."+ if "429" in raw or "Too Many Requests" in raw or "rate limited" in raw.lower():+ return "Rate limited — wait a minute and try again."if "403" in raw or "Forbidden" in raw:return "Permission denied — check API scopes."- if "429" in raw or "Too Many Requests" in raw:- return "Rate limited — wait a minute and try again."if "timeout" in raw.lower():return "Connection timed out."return rawdiff --git a/tests/connectors/test_gmail_rate_limits.py b/tests/connectors/test_gmail_rate_limits.pynew file mode 100644index 00000000..fc8284a6--- /dev/null+++ b/tests/connectors/test_gmail_rate_limits.py@@ -0,0 +1,75 @@+"""Gmail uses HTTP 403 as well as 429 for transient quota limits."""++from unittest.mock import patch++import httpx+import pytest++from openjarvis.connectors import gmail+++def _response(status, reason=None):+ payload = (+ {"messages": []}+ if reason is None+ else {"error": {"errors": [{"reason": reason}]}}+ )+ return httpx.Response(+ status,+ json=payload,+ request=httpx.Request(+ "GET", "https://gmail.googleapis.com/gmail/v1/users/me/messages"+ ),+ )++[email protected]("operation", ["list", "get"])+ "status,reason",+ [(403, "rateLimitExceeded"), (403, "userRateLimitExceeded"), (429, None)],+)+def test_quota_failure_retries_read_request(operation, status, reason):+ with (+ patch.object(+ gmail.httpx, "get", side_effect=[_response(status, reason), _response(200)]+ ) as get,+ patch("time.sleep") as sleep,+ ):+ if operation == "list":+ gmail._gmail_api_list_messages("test-token")+ else:+ gmail._gmail_api_get_message("test-token", "message1")++ assert get.call_count == 2+ sleep.assert_called_once()+ assert 1 <= sleep.call_args.args[0] <= 60+++ "status,reason",+ [(401, "authError"), (403, "insufficientPermissions"), (403, "dailyLimitExceeded")],+)+def test_non_rate_failure_is_not_retried(status, reason):+ with (+ patch.object(gmail.httpx, "get", return_value=_response(status, reason)) as get,+ patch("time.sleep") as sleep,+ ):+ with pytest.raises(httpx.HTTPStatusError):+ gmail._gmail_api_list_messages("test-token")++ assert get.call_count == 1+ sleep.assert_not_called()+++def test_retry_budget_exhaustion_exposes_quota_cause():+ with (+ patch.object(+ gmail.httpx, "get", return_value=_response(403, "rateLimitExceeded")+ ) as get,+ patch("time.sleep") as sleep,+ ):+ with pytest.raises(httpx.HTTPStatusError, match="[Rr]ate limited"):+ gmail._gmail_api_list_messages("test-token")++ assert get.call_count == 6+ assert sleep.call_count == 5diff --git a/tests/connectors/test_google_tasks.py b/tests/connectors/test_google_tasks.pyindex 38e837f7..0ebfedf5 100644--- a/tests/connectors/test_google_tasks.py+++ b/tests/connectors/test_google_tasks.py@@ -2,7 +2,7 @@from __future__ import annotations-from datetime import datetime+from datetime import datetime, timedelta, timezonefrom unittest.mock import patchimport pytest@@ -70,3 +70,21 @@ def test_sync_yields_tasks(connector):assert docs[0].title == "Review PR #42"assert docs[0].metadata["status"] == "needsAction"assert docs[1].metadata["status"] == "completed"+++ "since",+ [+ datetime(2026, 10, 5, 1, 54, 24, 261272),+ datetime(2026, 10, 5, 1, 54, 24, 261272, tzinfo=timezone.utc),+ datetime(2026, 10, 5, 4, 54, 24, 261272, tzinfo=timezone(timedelta(hours=3))),+ ],+)+def test_sync_updated_min_is_valid_rfc3339_utc(connector, since):+ with patch(+ "openjarvis.connectors.google_tasks._tasks_api_get",+ side_effect=[_TASK_LISTS_RESPONSE, {"items": []}],+ ) as get:+ list(connector.sync(since=since))++ assert get.call_args.kwargs["params"]["updatedMin"] == "2026-10-05T01:54:24.261272Z"diff --git a/tests/server/test_connectors_router.py b/tests/server/test_connectors_router.pyindex 644c42ea..185e2743 100644--- a/tests/server/test_connectors_router.py+++ b/tests/server/test_connectors_router.py@@ -731,3 +731,49 @@ def test_connect_news_rss_requires_and_persists_feeds(app, tmp_path: Path) -> No]finally:_instances.pop("news_rss", None)+++def test_gmail_quota_exhaustion_is_reported_as_rate_limited(app, monkeypatch):+ import time++ import httpx++ from openjarvis.connectors._stubs import SyncStatus+ from openjarvis.connectors.sync_engine import SyncEngine+ from openjarvis.server.connectors_router import _instances++ class QuotaConnector:+ connector_id = "gmail"+ display_name = "Gmail"+ auth_type = "oauth"++ def is_connected(self):+ return True++ def sync_status(self):+ return SyncStatus()++ request = httpx.Request(+ "GET", "https://gmail.googleapis.com/gmail/v1/users/me/messages"+ )+ response = httpx.Response(403, request=request)++ def fail_sync(*args, **kwargs):+ raise httpx.HTTPStatusError(+ "Gmail rate limited after 6 attempts (HTTP 403)",+ request=request,+ response=response,+ )++ monkeypatch.setattr(SyncEngine, "sync", fail_sync)+ _instances["gmail"] = QuotaConnector()+ try:+ assert app.post("/v1/connectors/gmail/sync").status_code == 200+ for _ in range(100):+ state = app.get("/v1/connectors/gmail/sync").json()+ if state.get("state") == "error":+ break+ time.sleep(0.01)+ assert state["error"] == "Rate limited — wait a minute and try again."+ finally:+ _instances.pop("gmail", None)