: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(sentry): stop crashing sessions sync on a plan-retention 400 (#104761)
Tom Owersf27a7d7cb095
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.pyindex b1757932922a..a2e4f74a66b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py@@ -818,6 +818,21 @@ class SentryStatsSummaryRejectedError(Exception):"""The stats-summary endpoint rejected our request with a non-recoverable 400."""+# Sessions (release health) shares the same failure mode as organization_stats_summary: a plan's+# release-health data retention can be shorter than SENTRY_RETENTION_DAYS, so the clamped window+# still lands outside it and Sentry 400s. The wording never interpolates the org, URL, or response+# body.+SESSIONS_REJECTED_MESSAGE = (+ "Sentry rejected PostHog's request for your release health data (the sessions table) with an "+ "HTTP 400. This usually means the requested date range is outside your Sentry plan's session "+ "data retention. Remove that table from this source's selected tables, then re-enable the sync."+)+++class SentrySessionsRejectedError(Exception):+ """The sessions endpoint rejected our request with a non-recoverable 400."""++def _iter_rows_tolerating_unavailable(rows: Iterator[dict[str, Any]],endpoint: str,@@ -877,18 +892,35 @@ def _iter_sessions_rows() -> Iterator[dict[str, Any]]:"""Release health sessions, flattened to one row per interval per group."""window = _retention_window(incremental_value)- payload = _fetch_json(- base_api_url,- _endpoint_path("sessions", organization_slug=organization_slug),- headers,- {- "field": ["sum(session)", "count_unique(user)"],- "groupBy": ["project", "release", "environment", "session.status"],- "interval": "1d",- "start": window.start,- "end": window.end,- },- )+ try:+ payload = _fetch_json(+ base_api_url,+ _endpoint_path("sessions", organization_slug=organization_slug),+ headers,+ {+ "field": ["sum(session)", "count_unique(user)"],+ "groupBy": ["project", "release", "environment", "session.status"],+ "interval": "1d",+ "start": window.start,+ "end": window.end,+ },+ )+ except HTTPError as exc:+ response = exc.response+ if response is not None and response.status_code == 400:+ try:+ body = response.json()+ except JSONDecodeError:+ body = None+ detail = body.get("detail") if isinstance(body, dict) else None+ if detail == _NO_PROJECTS_AVAILABLE_DETAIL:+ logger.warning(+ "sentry_source.sessions_no_projects_skipped",+ organization_slug=organization_slug,+ )+ return+ raise SentrySessionsRejectedError(SESSIONS_REJECTED_MESSAGE) from exc+ raiseintervals = payload.get("intervals") or []for group in payload.get("groups") or []:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.pyindex 3c15d30f8707..92606b50b8c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sentry import SentrySourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry import (SENTRY_RATE_LIMITED_MESSAGE,+ SESSIONS_REJECTED_MESSAGE,STATS_SUMMARY_REJECTED_MESSAGE,SentryResumeConfig,_normalize_organization_slug,@@ -130,6 +131,8 @@ class SentrySource(ResumableSource[SentrySourceConfig, SentryResumeConfig]):# skipped no-projects case (see sentry.py). Deterministic for the request we build, so# stop retrying; the message is defined at the raise site so it stays credential-safe.STATS_SUMMARY_REJECTED_MESSAGE: None,+ # Raised as `SentrySessionsRejectedError` for the same reason — see sentry.py.+ SESSIONS_REJECTED_MESSAGE: None,}def get_retryable_errors(self) -> set[str]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.pyindex 35ecc2b96274..2cabd7f073c4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.senSentryPaginator,SentryRateLimitedError,SentryResumeConfig,+ SentrySessionsRejectedError,SentryStatsSummaryRejectedError,_custom_endpoint_rows,_issues_parent_row_filter,@@ -1729,6 +1730,47 @@ class TestSentryCustomIteratorEndpoints:assert seen_params[0]["groupBy"] == ["project", "release", "environment", "session.status"]assert seen_params[0]["interval"] == "1d"+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_sessions_skips_when_token_has_no_project_access(self, mock_request) -> None:+ # Same failure mode as organization_stats_summary: the token's user isn't a member of any+ # project in the org, and Sentry 400s this endpoint rather than returning an empty result.+ mock_request.return_value = _response({"detail": "No projects available"}, status_code=400)++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="sessions",+ team_id=123,+ job_id="job-id",+ )++ assert list(cast(Any, resp.items())) == []++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_sessions_other_400_is_classified_non_retryable(self, mock_request) -> None:+ # A clamped window can still fall outside the org's actual release-health retention, which+ # Sentry rejects with a 400. That's deterministic for the request we build, so it must fail+ # fast with a credential-safe message instead of retrying the raw HTTPError (whose URL+ # embeds the org slug).+ mock_request.return_value = _response({"detail": 'Invalid field: "bogus"'}, status_code=400)++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="sessions",+ team_id=123,+ job_id="job-id",+ )++ with pytest.raises(SentrySessionsRejectedError) as exc_info:+ list(cast(Any, resp.items()))++ message = str(exc_info.value)+ assert "acme" not in message and "sentry.io" not in message+ assert error_message_matches(message, SentrySource().get_non_retryable_errors())+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")def test_organization_stats_flattens_series_and_excludes_project_grouping(self, mock_request) -> None:seen_params: list[dict | None] = []