: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
fix(warehouse-sources): tell a non-Enterprise Cursor team why analytics tables fail (#114051)
jake sciottob29bc95236d5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.pyindex f6552b4f56e5..d6f02a2fb48f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py@@ -34,6 +34,14 @@ class CursorRetryableError(Exception):pass+class CursorPlanError(requests.HTTPError):+ pass+++ENTERPRISE_PLAN_ERROR = "Cursor Enterprise plan required"+_ENTERPRISE_PLAN_MARKER = "member of an enterprise team"++@dataclasses.dataclassclass CursorResumeConfig:# Start (epoch ms) of the window being processed when the sync was interrupted.@@ -93,6 +101,17 @@ def _make_session(api_key: str) -> requests.Session:)+def _is_plan_rejection(response: requests.Response) -> bool:+ if response.status_code not in (401, 403):+ return False+ try:+ body = response.json()+ except ValueError:+ return False+ message = body.get("message") if isinstance(body, dict) else None+ return isinstance(message, str) and _ENTERPRISE_PLAN_MARKER in message.lower()++@retry(retry=retry_if_exception_type((@@ -129,6 +148,8 @@ def _fetch(if not response.ok:logger.error(f"Cursor API error: status={response.status_code}, body={response.text}, url={url}")+ if _is_plan_rejection(response):+ raise CursorPlanError(f"{ENTERPRISE_PLAN_ERROR} for url: {url}", response=response)response.raise_for_status()return response.json()@@ -144,6 +165,11 @@ KEY_FORBIDDEN_MESSAGE = ("Your Cursor Admin API key does not have access to this data. Admin API keys must be created ""by a team admin, and some endpoints require an Enterprise plan.")+ANALYTICS_PLAN_MESSAGE = (+ "This table reads Cursor's Analytics API, which needs a Cursor Enterprise plan. AI code tables also need "+ "AI code tracking turned on. Your Admin API key still syncs the other Cursor tables. Turn this table off, "+ "or turn it back on after your team moves to Enterprise."+)# `validate_via_probe` reports a transport failure as a `None` status, so anything Cursor did not# answer itself leaves the key unjudged. Calling it invalid sends someone off to mint a replacement# that fails the same way.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.pyindex 697860a1540a..92455f521480 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/source.py@@ -16,7 +16,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.cursor.cursor import (+ ANALYTICS_PLAN_MESSAGE,CURSOR_BASE_URL,+ ENTERPRISE_PLAN_ERROR,KEY_FORBIDDEN_MESSAGE,KEY_REJECTED_MESSAGE,CursorResumeConfig,@@ -79,6 +81,7 @@ You need a Cursor team plan (Business or Enterprise). A team admin can create andef get_non_retryable_errors(self) -> dict[str, str | None]:return {+ ENTERPRISE_PLAN_ERROR: ANALYTICS_PLAN_MESSAGE,# An invalid or revoked Admin API key surfaces as a requests HTTPError when `_fetch`# calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop# the sync. Match the stable status text and base host, not the per-request path.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.pyindex ea35507a315d..c90dfd3837f0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py@@ -6,9 +6,12 @@ import pytestfrom unittest import mockimport requests+import responsesfrom parameterized import parameterizedfrom tenacity import wait_none+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (ScriptedResponse,SourceDriver,@@ -69,6 +72,18 @@ def _batches(source: SourceResponse) -> Iterator[list[dict[str, Any]]]:return iter(cast(Iterable[list[dict[str, Any]]], source.items()))+CURSOR_PLAN_REJECTION = {+ "code": "error",+ "message": "You must be a member of an enterprise team to access this resource",+}+++def _resolve_friendly_error(error: Exception) -> str | None:+ errors = {**Any_Source_Errors, **CursorSource().get_non_retryable_errors()}+ message = f"{type(error).__name__}: {error}"+ return next((friendly for key, friendly in errors.items() if error_message_matches(message, [key])), None)++def _driver() -> SourceDriver:return SourceDriver(CursorSource(), CursorSourceConfig(api_key="key_test"))@@ -152,6 +167,71 @@ class TestCursorTransport:assert session.request.call_count == 1+ @parameterized.expand(+ [+ (+ "plan_rejection_on_analytics",+ "dau",+ 401,+ CURSOR_PLAN_REJECTION,+ cursor.CursorPlanError,+ cursor.ANALYTICS_PLAN_MESSAGE,+ ),+ (+ "plan_rejection_as_forbidden",+ "ai_code_commits",+ 403,+ CURSOR_PLAN_REJECTION,+ cursor.CursorPlanError,+ cursor.ANALYTICS_PLAN_MESSAGE,+ ),+ (+ "rejected_key_on_analytics",+ "dau",+ 401,+ {"code": "error", "message": "Invalid API key"},+ requests.HTTPError,+ cursor.KEY_REJECTED_MESSAGE,+ ),+ (+ "rejected_key_with_non_json_body",+ "members",+ 401,+ "Unauthorized",+ requests.HTTPError,+ cursor.KEY_REJECTED_MESSAGE,+ ),+ (+ "forbidden_key_on_admin_api",+ "members",+ 403,+ {"code": "error", "message": "Forbidden"},+ requests.HTTPError,+ cursor.KEY_FORBIDDEN_MESSAGE,+ ),+ ]+ )+ def test_rejected_request_resolves_to_the_message_for_its_cause(+ self,+ _name: str,+ endpoint: str,+ status: int,+ body: dict[str, str] | str,+ raised: type[requests.HTTPError],+ expected: str,+ ) -> None:+ config = CURSOR_ENDPOINTS[endpoint]+ with responses.RequestsMock() as mocked:+ if isinstance(body, dict):+ mocked.add(config.method, f"{cursor.CURSOR_BASE_URL}{config.path}", status=status, json=body)+ else:+ mocked.add(config.method, f"{cursor.CURSOR_BASE_URL}{config.path}", status=status, body=body)+ with pytest.raises(requests.HTTPError) as excinfo:+ list(_batches(cursor_source("key_test", endpoint, mock.Mock(), _manager())))++ assert type(excinfo.value) is raised+ assert _resolve_friendly_error(excinfo.value) == expected+def test_unknown_endpoint_raises(self):result = _driver().run("audit_logs", [])