: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
feat(data-warehouse): add 23 tables to the Sentry source (#73850)
Tom Owers1a95e90cfb22
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/canonical_descriptions.pyindex 08a252d4b31e..9d73f65e1c4a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/canonical_descriptions.py@@ -192,4 +192,358 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"lastSeen": "Time at which this tag value was most recently observed.",},},+ "repos": {+ "description": "A version control repository linked to the Sentry organization.",+ "docs_url": "https://docs.sentry.io/api/integrations/list-an-organizations-repositories/",+ "columns": {+ "id": "Unique identifier for the repository.",+ "name": "Name of the repository.",+ "url": "URL of the repository.",+ "provider": "The source control provider backing the repository.",+ "status": "Status of the repository link (active or deleted).",+ "integrationId": "ID of the integration the repository was added through.",+ "externalId": "Identifier of the repository in the provider's own system.",+ "externalSlug": "Slug of the repository in the provider's own system.",+ "dateCreated": "Time at which the repository was linked to Sentry.",+ },+ },+ "repo_commits": {+ "description": "Commits Sentry has ingested for a linked repository.",+ "docs_url": "https://docs.sentry.io/api/integrations/list-a-repositorys-commits/",+ "columns": {+ "id": "The commit SHA.",+ "repo_id": "ID of the repository the commit belongs to (from the parent repository).",+ "message": "Commit message.",+ "dateCreated": "Time at which the commit was authored.",+ "author": "Author of the commit.",+ "pullRequest": "Pull request the commit was merged through, when known.",+ "suspectCommitType": "Why Sentry flagged this commit as a suspect for an issue.",+ },+ },+ "dashboards": {+ "description": "A custom dashboard defined in the organization.",+ "docs_url": "https://docs.sentry.io/api/dashboards/list-an-organizations-custom-dashboards/",+ "columns": {+ "id": "Unique identifier for the dashboard.",+ "title": "Title of the dashboard.",+ "dateCreated": "Time at which the dashboard was created.",+ "createdBy": "The user who created the dashboard.",+ "environment": "Environments the dashboard is filtered to.",+ "filters": "Saved release and global filters applied to the dashboard.",+ "lastVisited": "Time at which the dashboard was last opened.",+ "widgetDisplay": "Display types of the dashboard's widgets.",+ "widgetPreview": "Preview metadata for the dashboard's widgets.",+ "permissions": "Who is allowed to edit the dashboard.",+ "isFavorited": "Whether the requesting user has favorited the dashboard.",+ "projects": "IDs of the projects the dashboard covers.",+ },+ },+ "discover_saved_queries": {+ "description": "A saved Discover query in the organization.",+ "docs_url": "https://docs.sentry.io/api/discover/list-an-organizations-discover-saved-queries/",+ "columns": {+ "id": "Unique identifier for the saved query.",+ "name": "Name of the saved query.",+ "query": "The search query string.",+ "fields": "Columns the query selects.",+ "queryDataset": "Dataset the query runs against.",+ "datasetSource": "How the query's dataset was determined.",+ "projects": "IDs of the projects the query covers.",+ "environment": "Environments the query is filtered to.",+ "range": "Relative time range of the query.",+ "start": "Absolute start of the query's time range.",+ "end": "Absolute end of the query's time range.",+ "orderby": "Field the query results are ordered by.",+ "yAxis": "Aggregate functions charted for the query.",+ "display": "Chart display mode of the query.",+ "expired": "Whether the query's time range now falls outside retention.",+ "dateCreated": "Time at which the query was saved.",+ "dateUpdated": "Time at which the query was last edited.",+ "createdBy": "The user who saved the query.",+ },+ },+ "workflows": {+ "description": "An alert workflow that reacts to detector activity in the organization.",+ "docs_url": "https://docs.sentry.io/api/workflows/fetch-alerts/",+ "columns": {+ "id": "Unique identifier for the alert workflow.",+ "name": "Name of the alert workflow.",+ "organizationId": "ID of the organization the workflow belongs to.",+ "createdBy": "ID of the user who created the workflow.",+ "dateCreated": "Time at which the workflow was created.",+ "dateUpdated": "Time at which the workflow was last updated.",+ "triggers": "Condition group that starts the workflow.",+ "actionFilters": "Condition groups that gate the workflow's actions.",+ "environment": "Environment the workflow is scoped to.",+ "detectorIds": "IDs of the detectors connected to the workflow.",+ "enabled": "Whether the workflow is enabled.",+ "lastTriggered": "Time at which the workflow last fired.",+ "owner": "Team or user that owns the workflow.",+ },+ },+ "detectors": {+ "description": "A detector that watches a data source and opens issues when its conditions are met.",+ "docs_url": "https://docs.sentry.io/api/detectors/fetch-an-organizations-monitors/",+ "columns": {+ "id": "Unique identifier for the detector.",+ "name": "Name of the detector.",+ "type": "Type of the detector (e.g. error, metric_issue, issue_stream).",+ "description": "Description of the detector.",+ "projectId": "ID of the project the detector belongs to.",+ "owner": "Team or user that owns the detector.",+ "createdBy": "ID of the user who created the detector.",+ "dateCreated": "Time at which the detector was created.",+ "dateUpdated": "Time at which the detector was last updated.",+ "workflowIds": "IDs of the alert workflows connected to the detector.",+ "dataSources": "The queries or subscriptions the detector evaluates.",+ "conditionGroup": "Conditions that make the detector fire.",+ "latestGroup": "The most recent issue the detector opened.",+ "enabled": "Whether the detector is enabled.",+ },+ },+ "organization_tags": {+ "description": "A tag key seen across the organization's events, with value cardinality.",+ "docs_url": "https://docs.sentry.io/api/organizations/list-an-organizations-tags/",+ "columns": {+ "key": "The tag key.",+ "name": "Human-readable name of the tag key.",+ "uniqueValues": "Number of distinct values seen for this tag key.",+ "totalValues": "Total number of events carrying this tag key.",+ "topValues": "The most common values for this tag key.",+ },+ },+ "integrations": {+ "description": "A third-party integration installed on the organization.",+ "docs_url": "https://docs.sentry.io/api/integrations/list-an-organizations-available-integrations/",+ "columns": {+ "id": "Unique identifier for the organization's integration.",+ "name": "Name of the integration as it appears in Sentry.",+ "provider": "The integration provider (e.g. slack, github).",+ "status": "Status of the integration.",+ "domainName": "Domain of the connected third-party account.",+ "accountType": "Type of the connected third-party account.",+ "scopes": "Scopes granted to the integration.",+ "externalId": "Identifier of the account in the provider's own system.",+ "organizationId": "ID of the organization the integration is installed on.",+ "organizationIntegrationStatus": "Status of the link between the organization and the integration.",+ "gracePeriodEnd": "When a broken integration stops working entirely.",+ "outOfDate": "Whether the integration needs to be reinstalled to pick up new permissions.",+ },+ },+ "sentry_app_installations": {+ "description": "An integration platform app installed on the organization.",+ "docs_url": "https://docs.sentry.io/api/integration-platform/list-an-organizations-integration-platform-installations/",+ "columns": {+ "uuid": "Unique identifier for the installation.",+ "status": "Status of the installation (installed or pending).",+ "app": "The installed app's uuid, slug, and ID.",+ "organization": "The organization the app is installed on.",+ },+ },+ "replays": {+ "description": "Metadata for a session replay recorded in the organization.",+ "docs_url": "https://docs.sentry.io/api/replays/list-an-organizations-replays/",+ "columns": {+ "id": "Unique identifier for the replay.",+ "project_id": "ID of the project the replay belongs to.",+ "started_at": "Time at which the replay started.",+ "finished_at": "Time at which the replay ended.",+ "duration": "Length of the replay in seconds.",+ "environment": "Environment the replay was recorded in.",+ "replay_type": "How the replay was captured (session or buffer).",+ "platform": "Platform the replay was recorded on.",+ "user": "The user the replay is attributed to.",+ "sdk": "SDK name and version that recorded the replay.",+ "os": "Operating system the replay was recorded on.",+ "browser": "Browser the replay was recorded in.",+ "device": "Device the replay was recorded on.",+ "urls": "URLs visited during the replay.",+ "count_urls": "Number of URLs visited during the replay.",+ "count_errors": "Number of errors captured during the replay.",+ "count_warnings": "Number of warnings captured during the replay.",+ "count_infos": "Number of info-level logs captured during the replay.",+ "count_dead_clicks": "Number of dead clicks detected in the replay.",+ "count_rage_clicks": "Number of rage clicks detected in the replay.",+ "count_segments": "Number of recording segments making up the replay.",+ "activity": "Activity score Sentry assigns to the replay.",+ "error_ids": "IDs of the errors linked to the replay.",+ "trace_ids": "IDs of the traces linked to the replay.",+ "releases": "Releases seen during the replay.",+ "dist": "Distribution identifier of the build being replayed.",+ "tags": "Tags attached to the replay.",+ "is_archived": "Whether the replay has been archived.",+ "has_viewed": "Whether the requesting user has viewed the replay.",+ },+ },+ "organization_events": {+ "description": "Error events across the organization, queried through Discover.",+ "docs_url": "https://docs.sentry.io/api/discover/query-explore-events-in-table-format/",+ "columns": {+ "id": "The event ID.",+ "timestamp": "Time at which the event was recorded.",+ "transaction": "Transaction the event occurred in.",+ },+ },+ "sessions": {+ "description": "Release health session counts per day, grouped by project, release, environment, and session status.",+ "docs_url": "https://docs.sentry.io/api/releases/retrieve-release-health-session-statistics/",+ "columns": {+ "interval_start": "Start of the one-day bucket the counts cover.",+ "project": "Project the sessions belong to.",+ "release": "Release the sessions ran.",+ "environment": "Environment the sessions ran in.",+ "session_status": "Session status the counts are for (e.g. healthy, errored, crashed, abnormal).",+ "sum_session": "Number of sessions in the bucket.",+ "count_unique_user": "Number of distinct users in the bucket.",+ },+ },+ "organization_stats": {+ "description": "Daily event volume for the organization, grouped by outcome, data category, and drop reason.",+ "docs_url": "https://docs.sentry.io/api/organizations/retrieve-event-counts-for-an-organization-v2/",+ "columns": {+ "interval_start": "Start of the one-day bucket the counts cover.",+ "outcome": "What happened to the events (accepted, filtered, rate_limited, invalid, abuse, client_discard, cardinality_limited).",+ "category": "Data category of the events (e.g. error, transaction, attachment, replay, profile, monitor).",+ "reason": "Why the events were filtered or dropped.",+ "quantity": "Summed quantity for the bucket — event count for most categories, bytes for attachments.",+ },+ },+ "organization_stats_summary": {+ "description": "Event volume by project and data category over the retention window.",+ "docs_url": "https://docs.sentry.io/api/organizations/retrieve-an-organizations-events-count-by-project/",+ "columns": {+ "project_id": "ID of the project the counts are for.",+ "project_slug": "Slug of the project the counts are for.",+ "category": "Data category of the events (e.g. error, transaction, attachment).",+ "outcomes": "Event counts broken down by outcome.",+ "quantity": "Summed quantity for the project and category — event count for most categories, bytes for attachments.",+ "dropped": "Number of events dropped for the project and category.",+ "period_start": "Start of the period the counts cover.",+ "period_end": "End of the period the counts cover.",+ },+ },+ "trace_item_attributes": {+ "description": "The attribute keys available on each trace item dataset (spans, logs, trace metrics).",+ "docs_url": "https://docs.sentry.io/api/discover/list-trace-item-attributes/",+ "columns": {+ "dataset": "Trace item dataset the attribute belongs to (logs, preprod, processing_errors, spans, tracemetrics).",+ "key": "The attribute key.",+ "name": "Human-readable name of the attribute.",+ "attributeType": "Data type of the attribute.",+ "secondaryAliases": "Other names the attribute can be queried by.",+ "attributeSource": "Where the attribute comes from and whether it is a transformed alias.",+ "context": "Semantic convention details for the attribute, including deprecation and examples.",+ },+ },+ "trace_item_stats": {+ "description": "Attribute value distributions computed over recent trace items.",+ "docs_url": "https://docs.sentry.io/api/discover/retrieve-trace-item-statistics/",+ "columns": {+ "item_type": "Trace item dataset the distribution was computed over (spans or occurrences).",+ "attribute": "The attribute the distribution is for.",+ "label": "One observed value of the attribute.",+ "value": "How often the value was observed in the sampled trace items.",+ },+ },+ "release_deploys": {+ "description": "A deploy recorded against a release.",+ "docs_url": "https://docs.sentry.io/api/releases/list-a-releases-deploys/",+ "columns": {+ "id": "Unique identifier for the deploy.",+ "release_version": "Version of the release that was deployed (from the parent release).",+ "environment": "Environment the release was deployed to.",+ "name": "Optional name of the deploy.",+ "url": "Optional URL pointing at the deploy.",+ "dateStarted": "Time at which the deploy started.",+ "dateFinished": "Time at which the deploy finished.",+ },+ },+ "release_commits": {+ "description": "A commit associated with a release.",+ "docs_url": "https://docs.sentry.io/api/releases/list-an-organization-releases-commits/",+ "columns": {+ "id": "The commit SHA.",+ "release_version": "Version of the release the commit shipped in (from the parent release).",+ "message": "Commit message.",+ "dateCreated": "Time at which the commit was authored.",+ "author": "Author of the commit.",+ "repository": "Repository the commit belongs to.",+ "pullRequest": "Pull request the commit was merged through, when known.",+ "suspectCommitType": "Why Sentry flagged this commit as a suspect for an issue.",+ "releases": "Releases the commit appears in.",+ },+ },+ "monitor_checkins": {+ "description": "A check-in reported by a cron monitor.",+ "docs_url": "https://docs.sentry.io/api/crons/retrieve-check-ins-for-a-monitor/",+ "columns": {+ "id": "Unique identifier for the check-in.",+ "monitor_id": "ID of the monitor the check-in belongs to (from the parent monitor).",+ "status": "Outcome of the check-in (e.g. ok, error, in_progress, missed, timeout).",+ "environment": "Environment the check-in was reported for.",+ "duration": "How long the job ran, in milliseconds.",+ "dateCreated": "Time at which the check-in was created.",+ "dateAdded": "Time at which the check-in was recorded by Sentry.",+ "dateUpdated": "Time at which the check-in was last updated.",+ "dateInProgress": "Time at which the job reported it had started.",+ "dateClock": "Sentry's monitor clock time the check-in was evaluated against.",+ "expectedTime": "Time the check-in was expected by.",+ "monitorConfig": "Schedule configuration in force for this check-in.",+ "groups": "Issues opened from this check-in.",+ },+ },+ "project_user_feedback": {+ "description": "A user report submitted against an error in a project.",+ "docs_url": "https://docs.sentry.io/api/projects/list-a-projects-user-feedback/",+ "columns": {+ "id": "Unique identifier for the user report.",+ "project_id": "ID of the project the report belongs to (from the parent project).",+ "project_slug": "Slug of the project the report belongs to (from the parent project).",+ "name": "Name the reporter gave.",+ "email": "Email address the reporter gave.",+ "comments": "What the reporter said happened.",+ "eventID": "ID of the event the report is attached to.",+ "event": "The event the report is attached to.",+ "issue": "The issue the report's event belongs to.",+ "user": "The Sentry user record matched to the reporter.",+ "dateCreated": "Time at which the report was submitted.",+ },+ },+ "project_filters": {+ "description": "An inbound data filter configured on a project.",+ "docs_url": "https://docs.sentry.io/api/projects/list-a-projects-data-filters/",+ "columns": {+ "id": "Identifier of the filter (e.g. browser-extensions, legacy-browsers).",+ "project_id": "ID of the project the filter belongs to (from the parent project).",+ "project_slug": "Slug of the project the filter belongs to (from the parent project).",+ "active": "Whether the filter is on — a list of browser keys for the legacy browser filter.",+ },+ },+ "project_ownership": {+ "description": "The issue-owner rules configured on a project.",+ "docs_url": "https://docs.sentry.io/api/projects/retrieve-ownership-configuration-for-a-project/",+ "columns": {+ "project_id": "ID of the project the configuration belongs to.",+ "project_slug": "Slug of the project the configuration belongs to.",+ "raw": "The ownership rules as authored.",+ "schema": "The parsed ownership rules, as matchers and owners.",+ "fallthrough": "Whether everyone on the project is notified when no rule matches.",+ "autoAssignment": "How issues are auto-assigned from the ownership rules.",+ "codeownersAutoSync": "Whether the CODEOWNERS file is kept in sync automatically.",+ "isActive": "Whether the ownership configuration is active.",+ "dateCreated": "Time at which the configuration was created.",+ "lastUpdated": "Time at which the configuration was last updated.",+ },+ },+ "project_stats": {+ "description": "Daily event counts per project, one row per statistic per day.",+ "docs_url": "https://docs.sentry.io/api/projects/retrieve-event-counts-for-a-project/",+ "columns": {+ "project_id": "ID of the project the counts are for.",+ "project_slug": "Slug of the project the counts are for.",+ "stat": "Which count this row holds (received, rejected, blacklisted, generated).",+ "timestamp": "Start of the one-day bucket, as a UNIX timestamp in seconds.",+ "value": "Number of events in the bucket.",+ },+ },}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 b870ec5724f9..fdb2e42402f6 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@@ -1,7 +1,7 @@import reimport dataclassesfrom collections.abc import Callable, Iterable, Iterator-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, Optional, castfrom urllib.parse import quote, urljoin@@ -34,8 +34,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.sentry.settings import (ALLOWED_SENTRY_API_BASE_URLS,DEFAULT_SENTRY_API_BASE_URL,+ PROJECT_STAT_NAMES,REQUIRED_SENTRY_SCOPES,SENTRY_ENDPOINTS,+ SENTRY_RETENTION_DAYS,+ TRACE_ITEM_DATASETS,+ TRACE_ITEM_STATS_TYPES,SentryEndpointConfig,)@@ -123,6 +127,41 @@ def _sentry_incremental_window(cursor_path: str) -> IncrementalConfig:}+def _retention_floor(now: datetime) -> datetime:+ return now - timedelta(days=SENTRY_RETENTION_DAYS)+++def _retention_bounded_start_param(value: Any) -> str:+ """Format a datetime-like value clamped to Sentry's retention window.++ Sessions, stats, replays and Discover all reject a range that reaches further+ back than retention, so the 1970 sentinel used for issues would fail the first+ sync outright.+ """+ now = datetime.now(UTC)+ floor = _retention_floor(now)+ parsed = _parse_datetime_value(value)+ bounded = floor if parsed is None else min(max(parsed, floor), now)+ return bounded.strftime("%Y-%m-%dT%H:%M:%S")+++def _sentry_retention_incremental_window(cursor_path: str) -> IncrementalConfig:+ now = datetime.now(UTC)+ return {+ "cursor_path": cursor_path,+ "start_param": "start",+ "end_param": "end",+ "initial_value": _retention_bounded_start_param(_retention_floor(now)),+ "end_value": _start_param_for_sentry(now),+ "convert": _retention_bounded_start_param,+ }+++def _retention_window(incremental_value: Any = None) -> tuple[str, str]:+ now = datetime.now(UTC)+ return _retention_bounded_start_param(incremental_value), _start_param_for_sentry(now)++def _parse_next_link(link_header: str) -> str | None:if not link_header:return None@@ -488,6 +527,355 @@ def _iter_issue_tag_values_rows(resume_values_next_url = None+# ---------------------------------------------------------------------------+# Endpoints whose payload needs reshaping before it can be a table+# ---------------------------------------------------------------------------++# Sentry answers a request for a product surface the organization doesn't have with a+# 400, so an unavailable trace item dataset is indistinguishable from a rejected param.+_UNAVAILABLE_DATASET_STATUSES = (400, 403, 404)+# Per-project surfaces only ever go missing through permissions or an absent config.+_MISSING_PROJECT_RESOURCE_STATUSES = (403, 404)+++def _iter_rows_tolerating_unavailable(+ rows: Iterator[dict[str, Any]],+ endpoint: str,+ skippable_statuses: tuple[int, ...],+ **log_context: Any,+) -> Iterator[dict[str, Any]]:+ """Yield rows, treating the given statuses as "this slice isn't available here".++ Several of the newer product surfaces are gated per organization or per project, so+ one unavailable slice must not fail the whole table.+ """+ try:+ yield from rows+ except HTTPError as exc:+ response = exc.response+ if response is not None and response.status_code in skippable_statuses:+ logger.warning(+ "sentry_source.endpoint_slice_unavailable_skipped",+ endpoint=endpoint,+ status_code=response.status_code,+ **log_context,+ )+ return+ raise+++def _series_value(series: Any, index: int) -> Any:+ if not isinstance(series, list) or index >= len(series):+ return None+ return series[index]+++def _group_key(by: dict[str, Any], key: str) -> str:+ value = by.get(key)+ # Grouped dimensions land in the primary key, and Delta merges never match on a+ # null, so an absent dimension becomes an empty string rather than None.+ return "" if value is None else str(value)+++def _endpoint_path(endpoint: str, **values: str) -> str:+ """Resolve an endpoint's configured path so `settings.py` stays the only place paths live."""+ return SENTRY_ENDPOINTS[endpoint].path.format(**values)+++def _fetch_json(base_api_url: str, path: str, headers: dict[str, str], params: dict[str, Any]) -> Any:+ url = urljoin(f"{base_api_url}/", path.lstrip("/"))+ response = _request_with_retry(url=url, headers=headers, params=params)+ response.raise_for_status()+ return response.json()+++def _iter_sessions_rows(+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+ incremental_value: Any = None,+) -> Iterator[dict[str, Any]]:+ """Release health sessions, flattened to one row per interval per group."""+ start, end = _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": start,+ "end": end,+ },+ )++ intervals = payload.get("intervals") or []+ for group in payload.get("groups") or []:+ by = group.get("by") or {}+ series = group.get("series") or {}+ for index, interval_start in enumerate(intervals):+ yield {+ "interval_start": interval_start,+ "project": _group_key(by, "project"),+ "release": _group_key(by, "release"),+ "environment": _group_key(by, "environment"),+ "session_status": _group_key(by, "session.status"),+ "sum_session": _series_value(series.get("sum(session)"), index),+ "count_unique_user": _series_value(series.get("count_unique(user)"), index),+ }+++def _iter_organization_stats_rows(+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+ incremental_value: Any = None,+) -> Iterator[dict[str, Any]]:+ """Org-wide accepted/dropped event volume, flattened to one row per interval per group.++ ``project`` is deliberately not in ``groupBy``: Sentry collapses the series into a+ single period total when it is, which would make the interval column meaningless.+ Per-project volume lives in ``organization_stats_summary``.+ """+ start, end = _retention_window(incremental_value)+ payload = _fetch_json(+ base_api_url,+ _endpoint_path("organization_stats", organization_slug=organization_slug),+ headers,+ {+ "field": "sum(quantity)",+ "groupBy": ["outcome", "category", "reason"],+ "interval": "1d",+ "start": start,+ "end": end,+ },+ )++ intervals = payload.get("intervals") or []+ for group in payload.get("groups") or []:+ by = group.get("by") or {}+ series = group.get("series") or {}+ for index, interval_start in enumerate(intervals):+ yield {+ "interval_start": interval_start,+ "outcome": _group_key(by, "outcome"),+ "category": _group_key(by, "category"),+ "reason": _group_key(by, "reason"),+ "quantity": _series_value(series.get("sum(quantity)"), index),+ }+++def _iter_organization_stats_summary_rows(+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+) -> Iterator[dict[str, Any]]:+ """Per-project event volume for the retention window, one row per project per category."""+ payload = _fetch_json(+ base_api_url,+ _endpoint_path("organization_stats_summary", organization_slug=organization_slug),+ headers,+ {"field": "sum(quantity)", "statsPeriod": f"{SENTRY_RETENTION_DAYS}d"},+ )++ period_start = payload.get("start")+ period_end = payload.get("end")+ for project in payload.get("projects") or []:+ for stats in project.get("stats") or []:+ totals = stats.get("totals") or {}+ yield {+ "project_id": project.get("id"),+ "project_slug": project.get("slug"),+ "category": stats.get("category"),+ "outcomes": stats.get("outcomes"),+ # Lifted out of `totals` so the column names survive normalization —+ # `sum(quantity)` would otherwise land as an unreadable nested key.+ "quantity": totals.get("sum(quantity)"),+ "dropped": totals.get("dropped"),+ "period_start": period_start,+ "period_end": period_end,+ }+++def _iter_trace_item_attributes_rows(+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+) -> Iterator[dict[str, Any]]:+ """Attribute keys available on each trace item dataset (spans, logs, ...)."""+ for dataset in TRACE_ITEM_DATASETS:+ rows = _iter_endpoint_rows(+ base_api_url=base_api_url,+ path=_endpoint_path("trace_item_attributes", organization_slug=organization_slug),+ headers=headers,+ params={"dataset": dataset},+ max_pages=_MAX_PAGES_PER_PARENT,+ )+ for row in _iter_rows_tolerating_unavailable(+ rows, "trace_item_attributes", _UNAVAILABLE_DATASET_STATUSES, dataset=dataset+ ):+ row["dataset"] = dataset+ yield row+++def _iter_trace_item_stats_rows(+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+) -> Iterator[dict[str, Any]]:+ """Attribute value distributions over trace items, flattened to one row per label."""++ def _distributions(item_type: str) -> Iterator[dict[str, Any]]:+ payload = _fetch_json(+ base_api_url,+ _endpoint_path("trace_item_stats", organization_slug=organization_slug),+ headers,+ {"statsType": "attributeDistributions", "itemType": item_type},+ )+ for entry in payload.get("data") or []:+ distributions = (entry.get("attributeDistributions") or {}).get("data") or {}+ for attribute, buckets in distributions.items():+ for bucket in buckets or []:+ yield {+ "item_type": item_type,+ "attribute": attribute,+ "label": bucket.get("label"),+ "value": bucket.get("value"),+ }++ for item_type in TRACE_ITEM_STATS_TYPES:+ yield from _iter_rows_tolerating_unavailable(+ _distributions(item_type), "trace_item_stats", _UNAVAILABLE_DATASET_STATUSES, item_type=item_type+ )+++def _iter_projects(base_api_url: str, headers: dict[str, str], organization_slug: str) -> Iterator[dict[str, Any]]:+ return _iter_endpoint_rows(+ base_api_url=base_api_url,+ path=_endpoint_path("projects", organization_slug=organization_slug),+ headers=headers,+ params={"limit": 100},+ )+++def _iter_project_ownership_rows(+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+) -> Iterator[dict[str, Any]]:+ """Issue-owner rules, one row per project (the endpoint returns a single object)."""++ def _ownership(project_slug: str) -> Iterator[dict[str, Any]]:+ payload = _fetch_json(+ base_api_url,+ _endpoint_path(+ "project_ownership",+ organization_slug=organization_slug,+ project_slug=quote(project_slug, safe=""),+ ),+ headers,+ {},+ )+ if isinstance(payload, dict):+ yield payload++ for project in _iter_projects(base_api_url, headers, organization_slug):+ project_slug = project.get("slug")+ if not isinstance(project_slug, str) or not project_slug:+ continue+ for row in _iter_rows_tolerating_unavailable(+ _ownership(project_slug),+ "project_ownership",+ _MISSING_PROJECT_RESOURCE_STATUSES,+ project_slug=project_slug,+ ):+ row["project_id"] = project.get("id")+ row["project_slug"] = project_slug+ yield row+++def _epoch_seconds(value: Any) -> int | None:+ if isinstance(value, bool):+ return None+ if isinstance(value, int | float):+ return int(value)+ parsed = _parse_datetime_value(value)+ if parsed is not None:+ return int(parsed.timestamp())+ return None+++def _iter_project_stats_rows(+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+ incremental_value: Any = None,+) -> Iterator[dict[str, Any]]:+ """Per-project event counts, flattened from Sentry's [timestamp, value] point pairs."""+ now = datetime.now(UTC)+ floor = int(_retention_floor(now).timestamp())+ requested_since = _epoch_seconds(incremental_value)+ since = floor if requested_since is None else min(max(requested_since, floor), int(now.timestamp()))+ until = int(now.timestamp())++ def _points(project_slug: str, stat: str) -> Iterator[dict[str, Any]]:+ payload = _fetch_json(+ base_api_url,+ _endpoint_path(+ "project_stats",+ organization_slug=organization_slug,+ project_slug=quote(project_slug, safe=""),+ ),+ headers,+ {"stat": stat, "resolution": "1d", "since": since, "until": until},+ )+ for point in payload or []:+ if not isinstance(point, list) or len(point) < 2:+ continue+ yield {"stat": stat, "timestamp": point[0], "value": point[1]}++ for project in _iter_projects(base_api_url, headers, organization_slug):+ project_slug = project.get("slug")+ if not isinstance(project_slug, str) or not project_slug:+ continue+ for stat in PROJECT_STAT_NAMES:+ for row in _iter_rows_tolerating_unavailable(+ _points(project_slug, stat),+ "project_stats",+ _MISSING_PROJECT_RESOURCE_STATUSES,+ project_slug=project_slug,+ stat=stat,+ ):+ row["project_id"] = project.get("id")+ row["project_slug"] = project_slug+ yield row+++def _custom_endpoint_rows(+ endpoint: str,+ base_api_url: str,+ headers: dict[str, str],+ organization_slug: str,+ incremental_value: Any = None,+) -> Iterator[dict[str, Any]]:+ if endpoint == "sessions":+ return _iter_sessions_rows(base_api_url, headers, organization_slug, incremental_value)+ if endpoint == "organization_stats":+ return _iter_organization_stats_rows(base_api_url, headers, organization_slug, incremental_value)+ if endpoint == "organization_stats_summary":+ return _iter_organization_stats_summary_rows(base_api_url, headers, organization_slug)+ if endpoint == "trace_item_attributes":+ return _iter_trace_item_attributes_rows(base_api_url, headers, organization_slug)+ if endpoint == "trace_item_stats":+ return _iter_trace_item_stats_rows(base_api_url, headers, organization_slug)+ if endpoint == "project_ownership":+ return _iter_project_ownership_rows(base_api_url, headers, organization_slug)+ if endpoint == "project_stats":+ return _iter_project_stats_rows(base_api_url, headers, organization_slug, incremental_value)+ raise ValueError(f"No custom iterator registered for endpoint '{endpoint}'")++# ---------------------------------------------------------------------------# Credential validation# ---------------------------------------------------------------------------@@ -542,15 +930,20 @@ def get_resource(incremental_field: str | None = None,) -> EndpointResource:config = SENTRY_ENDPOINTS[endpoint]- if config.fanout or endpoint == "issue_tag_values":+ if config.fanout or config.custom_iterator:raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")- params: dict[str, Any] = {"limit": config.page_size}+ params: dict[str, Any] = {}+ if config.page_size_param:+ params[config.page_size_param] = config.page_size+ params.update(config.params)endpoint_config: Endpoint = {"path": config.path.format(organization_slug=organization_slug),"params": params,}+ if config.data_selector:+ endpoint_config["data_selector"] = config.data_selectorif endpoint == "issues":params["query"] = ""@@ -559,6 +952,13 @@ def get_resource(endpoint_config["incremental"] = _sentry_incremental_window(incremental_field or config.default_incremental_field or "lastSeen")+ elif should_use_incremental_field and config.incremental_fields:+ window_factory = (+ _sentry_retention_incremental_window if config.retention_bounded else _sentry_incremental_window+ )+ endpoint_config["incremental"] = window_factory(+ incremental_field or config.default_incremental_field or "dateCreated"+ )return {"name": config.name,@@ -658,6 +1058,21 @@ def sentry_source(),)+ # Endpoints whose payload isn't a paginated row list (time series, per-project+ # singletons) are reshaped by a bespoke iterator instead.+ if endpoint_config.custom_iterator:+ headers = _auth_headers(auth_token)+ return _make_source_response(+ endpoint_config,+ lambda: _custom_endpoint_rows(+ endpoint=endpoint,+ base_api_url=base_api_url,+ headers=headers,+ organization_slug=organization_slug,+ incremental_value=db_incremental_field_last_value if should_use_incremental_field else None,+ ),+ )+# --- Generic parent->child fan-out ---# Dependent resources don't currently support resume in the rest_source# framework; the manager is intentionally not threaded into this path.@@ -676,6 +1091,7 @@ def sentry_source(should_use_incremental_field=should_use_incremental_field,incremental_field=incremental_field,incremental_config_factory=_sentry_incremental_window,+ page_size_param=endpoint_config.page_size_param,),)# Sentry gates the service hooks API at the org level, so it 403s even@@ -692,7 +1108,9 @@ def sentry_source("client": _rest_api_client_config(base_api_url, auth_token),"resource_defaults": {"write_disposition": "replace",- "endpoint": {"params": {"limit": endpoint_config.page_size}},+ "endpoint": {"params": {endpoint_config.page_size_param: endpoint_config.page_size}}+ if endpoint_config.page_size_param+ else {},},"resources": [get_resource(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.pyindex 180ad7b1ddf5..1c0b2a54de63 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.py@@ -1,5 +1,5 @@-from dataclasses import dataclass-from typing import Literal+from dataclasses import dataclass, field+from typing import Any, Literalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (DependentEndpointConfig,@@ -20,11 +20,24 @@ REQUIRED_SENTRY_SCOPES = ("alerts:read","event:read","member:read",+ "org:integrations","org:read","project:read","team:read",)+# Sentry's time-series endpoints (sessions, stats, replays, Discover events) reject+# ranges older than the organization's event retention window, so every request has to+# carry a floor rather than the 1970 sentinel the issue endpoints tolerate.+SENTRY_RETENTION_DAYS = 90++# `dataset` values accepted by /trace-items/attributes/.+TRACE_ITEM_DATASETS = ("logs", "preprod", "processing_errors", "spans", "tracemetrics")+# `itemType` values accepted by /trace-items/stats/.+TRACE_ITEM_STATS_TYPES = ("spans", "occurrences")+# `stat` values accepted by the per-project stats endpoint.+PROJECT_STAT_NAMES = ("received", "rejected", "blacklisted", "generated")+LAST_SEEN_INCREMENTAL: IncrementalField = {"label": "lastSeen","type": IncrementalFieldType.DateTime,@@ -44,6 +57,31 @@ DATE_CREATED_INCREMENTAL: IncrementalField = {"field_type": IncrementalFieldType.DateTime,}+STARTED_AT_INCREMENTAL: IncrementalField = {+ "label": "started_at",+ "type": IncrementalFieldType.DateTime,+ "field": "started_at",+ "field_type": IncrementalFieldType.DateTime,+}+TIMESTAMP_INCREMENTAL: IncrementalField = {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+}+INTERVAL_START_INCREMENTAL: IncrementalField = {+ "label": "interval_start",+ "type": IncrementalFieldType.DateTime,+ "field": "interval_start",+ "field_type": IncrementalFieldType.DateTime,+}+EPOCH_TIMESTAMP_INCREMENTAL: IncrementalField = {+ "label": "timestamp",+ "type": IncrementalFieldType.Integer,+ "field": "timestamp",+ "field_type": IncrementalFieldType.Integer,+}+ISSUES_INCREMENTAL_FIELDS: list[IncrementalField] = [LAST_SEEN_INCREMENTAL, FIRST_SEEN_INCREMENTAL]DATE_CREATED_INCREMENTAL_FIELD: list[IncrementalField] = [DATE_CREATED_INCREMENTAL,@@ -51,6 +89,18 @@ DATE_CREATED_INCREMENTAL_FIELD: list[IncrementalField] = [LAST_SEEN_INCREMENTAL_FIELD: list[IncrementalField] = [LAST_SEEN_INCREMENTAL,]+STARTED_AT_INCREMENTAL_FIELD: list[IncrementalField] = [+ STARTED_AT_INCREMENTAL,+]+TIMESTAMP_INCREMENTAL_FIELD: list[IncrementalField] = [+ TIMESTAMP_INCREMENTAL,+]+INTERVAL_START_INCREMENTAL_FIELD: list[IncrementalField] = [+ INTERVAL_START_INCREMENTAL,+]+EPOCH_TIMESTAMP_INCREMENTAL_FIELD: list[IncrementalField] = [+ EPOCH_TIMESTAMP_INCREMENTAL,+]@dataclass@@ -64,6 +114,19 @@ class SentryEndpointConfig:sort_mode: Literal["asc", "desc"] = "asc"primary_key: str | list[str] = "id"fanout: DependentEndpointConfig | None = None+ # Static query params sent on every request for this endpoint.+ params: dict[str, Any] = field(default_factory=dict)+ # JSONPath to the row list when the payload wraps it (e.g. `{"data": [...]}`).+ data_selector: str | None = None+ # Query param carrying the page size. Endpoints whose spec documents no page-size+ # param set this to None so we don't send one.+ page_size_param: str | None = "limit"+ # Endpoints whose payload can't be paginated straight into rows and are handled by a+ # bespoke iterator in `sentry.py` instead of the shared REST resource path.+ custom_iterator: bool = False+ # Incremental windows on retention-bounded endpoints must be floored to+ # SENTRY_RETENTION_DAYS rather than starting from the 1970 sentinel.+ retention_bounded: bool = FalseSENTRY_ENDPOINTS: dict[str, SentryEndpointConfig] = {@@ -209,6 +272,237 @@ SENTRY_ENDPOINTS: dict[str, SentryEndpointConfig] = {partition_key="first_seen",sort_mode="desc",primary_key=["issue_id", "tag_key", "value"],+ custom_iterator=True,+ ),+ # --- Org-level flat endpoints ---+ "repos": SentryEndpointConfig(+ name="repos",+ path="/organizations/{organization_slug}/repos/",+ incremental_fields=[],+ partition_key="date_created",+ page_size_param=None,+ ),+ "dashboards": SentryEndpointConfig(+ name="dashboards",+ path="/organizations/{organization_slug}/dashboards/",+ incremental_fields=[],+ partition_key="date_created",+ page_size_param="per_page",+ ),+ "discover_saved_queries": SentryEndpointConfig(+ name="discover_saved_queries",+ path="/organizations/{organization_slug}/discover/saved/",+ incremental_fields=[],+ partition_key="date_created",+ page_size_param="per_page",+ ),+ "workflows": SentryEndpointConfig(+ name="workflows",+ path="/organizations/{organization_slug}/workflows/",+ incremental_fields=[],+ partition_key="date_created",+ page_size_param=None,+ ),+ "detectors": SentryEndpointConfig(+ name="detectors",+ path="/organizations/{organization_slug}/detectors/",+ incremental_fields=[],+ partition_key="date_created",+ page_size_param=None,+ ),+ "organization_tags": SentryEndpointConfig(+ name="organization_tags",+ path="/organizations/{organization_slug}/tags/",+ incremental_fields=[],+ primary_key="key",+ page_size_param=None,+ ),+ "integrations": SentryEndpointConfig(+ name="integrations",+ path="/organizations/{organization_slug}/integrations/",+ incremental_fields=[],+ page_size_param=None,+ ),+ "sentry_app_installations": SentryEndpointConfig(+ name="sentry_app_installations",+ path="/organizations/{organization_slug}/sentry-app-installations/",+ incremental_fields=[],+ primary_key="uuid",+ page_size_param=None,+ ),+ "replays": SentryEndpointConfig(+ name="replays",+ path="/organizations/{organization_slug}/replays/",+ incremental_fields=STARTED_AT_INCREMENTAL_FIELD,+ default_incremental_field="started_at",+ partition_key="started_at",+ params={"sort": "started_at"},+ data_selector="data",+ page_size_param="per_page",+ retention_bounded=True,+ ),+ "organization_events": SentryEndpointConfig(+ name="organization_events",+ path="/organizations/{organization_slug}/events/",+ incremental_fields=TIMESTAMP_INCREMENTAL_FIELD,+ default_incremental_field="timestamp",+ partition_key="timestamp",+ params={+ "dataset": "errors",+ "field": ["id", "timestamp", "transaction"],+ "sort": "timestamp",+ },+ data_selector="data",+ page_size_param="per_page",+ retention_bounded=True,+ ),+ # --- Org-level endpoints with bespoke payload reshaping ---+ "sessions": SentryEndpointConfig(+ name="sessions",+ path="/organizations/{organization_slug}/sessions/",+ incremental_fields=INTERVAL_START_INCREMENTAL_FIELD,+ default_incremental_field="interval_start",+ partition_key="interval_start",+ primary_key=["interval_start", "project", "release", "environment", "session_status"],+ custom_iterator=True,+ retention_bounded=True,+ ),+ "organization_stats": SentryEndpointConfig(+ name="organization_stats",+ path="/organizations/{organization_slug}/stats_v2/",+ incremental_fields=INTERVAL_START_INCREMENTAL_FIELD,+ default_incremental_field="interval_start",+ partition_key="interval_start",+ primary_key=["interval_start", "outcome", "category", "reason"],+ custom_iterator=True,+ retention_bounded=True,+ ),+ "organization_stats_summary": SentryEndpointConfig(+ name="organization_stats_summary",+ path="/organizations/{organization_slug}/stats-summary/",+ incremental_fields=[],+ primary_key=["project_id", "category"],+ custom_iterator=True,+ ),+ "trace_item_attributes": SentryEndpointConfig(+ name="trace_item_attributes",+ path="/organizations/{organization_slug}/trace-items/attributes/",+ incremental_fields=[],+ primary_key=["dataset", "key", "attribute_type"],+ custom_iterator=True,+ ),+ "trace_item_stats": SentryEndpointConfig(+ name="trace_item_stats",+ path="/organizations/{organization_slug}/trace-items/stats/",+ incremental_fields=[],+ primary_key=["item_type", "attribute", "label"],+ custom_iterator=True,+ ),+ "project_ownership": SentryEndpointConfig(+ name="project_ownership",+ path="/projects/{organization_slug}/{project_slug}/ownership/",+ incremental_fields=[],+ primary_key=["project_id"],+ custom_iterator=True,+ ),+ "project_stats": SentryEndpointConfig(+ name="project_stats",+ path="/projects/{organization_slug}/{project_slug}/stats/",+ incremental_fields=EPOCH_TIMESTAMP_INCREMENTAL_FIELD,+ default_incremental_field="timestamp",+ primary_key=["project_id", "stat", "timestamp"],+ custom_iterator=True,+ retention_bounded=True,+ ),+ # --- Parent/child fan-out endpoints ---+ "release_deploys": SentryEndpointConfig(+ name="release_deploys",+ path="/organizations/{organization_slug}/releases/{version}/deploys/",+ incremental_fields=[],+ partition_key="date_started",+ primary_key=["release_version", "id"],+ page_size_param=None,+ fanout=DependentEndpointConfig(+ parent_name="releases",+ resolve_param="version",+ resolve_field="version",+ include_from_parent=["version"],+ parent_field_renames={"version": "release_version"},+ ),+ ),+ "release_commits": SentryEndpointConfig(+ name="release_commits",+ path="/organizations/{organization_slug}/releases/{version}/commits/",+ incremental_fields=[],+ partition_key="date_created",+ primary_key=["release_version", "id"],+ page_size_param=None,+ fanout=DependentEndpointConfig(+ parent_name="releases",+ resolve_param="version",+ resolve_field="version",+ include_from_parent=["version"],+ parent_field_renames={"version": "release_version"},+ ),+ ),+ "repo_commits": SentryEndpointConfig(+ name="repo_commits",+ path="/organizations/{organization_slug}/repos/{repo_id}/commits/",+ incremental_fields=[],+ partition_key="date_created",+ primary_key=["repo_id", "id"],+ page_size_param=None,+ fanout=DependentEndpointConfig(+ parent_name="repos",+ resolve_param="repo_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "repo_id"},+ ),+ ),+ "monitor_checkins": SentryEndpointConfig(+ name="monitor_checkins",+ path="/organizations/{organization_slug}/monitors/{monitor_id_or_slug}/checkins/",+ incremental_fields=[],+ partition_key="date_created",+ primary_key=["monitor_id", "id"],+ page_size_param=None,+ fanout=DependentEndpointConfig(+ parent_name="monitors",+ resolve_param="monitor_id_or_slug",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "monitor_id"},+ ),+ ),+ "project_user_feedback": SentryEndpointConfig(+ name="project_user_feedback",+ path="/projects/{organization_slug}/{project_slug}/user-feedback/",+ incremental_fields=[],+ partition_key="date_created",+ primary_key=["project_id", "id"],+ page_size_param=None,+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="project_slug",+ resolve_field="slug",+ include_from_parent=["id", "slug"],+ parent_field_renames={"id": "project_id", "slug": "project_slug"},+ ),+ ),+ "project_filters": SentryEndpointConfig(+ name="project_filters",+ path="/projects/{organization_slug}/{project_slug}/filters/",+ incremental_fields=[],+ primary_key=["project_id", "id"],+ page_size_param=None,+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="project_slug",+ resolve_field="slug",+ include_from_parent=["id", "slug"],+ parent_field_renames={"id": "project_id", "slug": "project_slug"},+ ),),}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 8ac325378183..2fa71efce8b3 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@@ -1,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, castimport pytest@@ -12,17 +12,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry import (SentryPaginator,SentryResumeConfig,+ _custom_endpoint_rows,_normalize_api_base_url,_parse_next_link,+ _retention_bounded_start_param,_retry_wait_seconds,_start_param_for_sentry,get_resource,sentry_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.settings import REQUIRED_SENTRY_SCOPES+from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.settings import (+ REQUIRED_SENTRY_SCOPES,+ SENTRY_ENDPOINTS,+ SENTRY_RETENTION_DAYS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.source import SentrySource+CUSTOM_ITERATOR_ENDPOINTS = [+ name for name, config in SENTRY_ENDPOINTS.items() if config.custom_iterator and name != "issue_tag_values"+]+def _response(payload, status_code: int = 200, link_header: str = "") -> Mock:response = Mock()@@ -221,6 +231,19 @@ class TestSentryTransport:("issue_events",),("issue_hashes",),("issue_tag_values",),+ ("release_deploys",),+ ("release_commits",),+ ("repo_commits",),+ ("monitor_checkins",),+ ("project_user_feedback",),+ ("project_filters",),+ ("sessions",),+ ("organization_stats",),+ ("organization_stats_summary",),+ ("trace_item_attributes",),+ ("trace_item_stats",),+ ("project_ownership",),+ ("project_stats",),])def test_get_resource_rejects_fanout_endpoints(self, endpoint) -> None:@@ -975,3 +998,539 @@ class TestHelpers:)assert _retry_wait_seconds(state) == 9.0+++class TestSentryRetentionWindow:+ @parameterized.expand(+ [+ ("no_watermark", None),+ ("pre_retention_watermark", datetime(2001, 1, 1, tzinfo=UTC)),+ ("pre_retention_string", "2001-01-01T00:00:00Z"),+ ]+ )+ def test_start_param_floors_to_retention(self, _name, value) -> None:+ # Sentry rejects a range reaching further back than retention, so a missing or+ # stale watermark must not produce the 1970 sentinel the issues endpoints tolerate.+ floor = datetime.now(UTC) - timedelta(days=SENTRY_RETENTION_DAYS)++ parsed = datetime.strptime(_retention_bounded_start_param(value), "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC)++ assert abs((parsed - floor).total_seconds()) < 60++ def test_start_param_keeps_watermark_inside_retention(self) -> None:+ value = datetime.now(UTC) - timedelta(days=3)++ parsed = datetime.strptime(_retention_bounded_start_param(value), "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC)++ assert abs((parsed - value).total_seconds()) < 2++ def test_start_param_caps_future_watermark_at_now(self) -> None:+ now = datetime.now(UTC)++ parsed = datetime.strptime(+ _retention_bounded_start_param(datetime(2999, 1, 1, tzinfo=UTC)), "%Y-%m-%dT%H:%M:%S"+ ).replace(tzinfo=UTC)++ assert abs((parsed - now).total_seconds()) < 60+++class TestSentryNewFlatEndpoints:+ @parameterized.expand(+ [+ ("repos", "/organizations/acme/repos/", None, None),+ ("dashboards", "/organizations/acme/dashboards/", "per_page", None),+ ("discover_saved_queries", "/organizations/acme/discover/saved/", "per_page", None),+ ("workflows", "/organizations/acme/workflows/", None, None),+ ("detectors", "/organizations/acme/detectors/", None, None),+ ("organization_tags", "/organizations/acme/tags/", None, None),+ ("integrations", "/organizations/acme/integrations/", None, None),+ ("sentry_app_installations", "/organizations/acme/sentry-app-installations/", None, None),+ ("replays", "/organizations/acme/replays/", "per_page", "data"),+ ("organization_events", "/organizations/acme/events/", "per_page", "data"),+ ]+ )+ def test_resource_path_page_size_and_selector(self, endpoint, expected_path, page_size_param, selector) -> None:+ # Sending `limit` where Sentry documents `per_page` silently ignores the page size,+ # and dropping the selector on a `{"data": [...]}` payload yields zero rows.+ resource = cast(+ dict[str, Any],+ get_resource(endpoint=endpoint, organization_slug="acme", should_use_incremental_field=False),+ )++ params = resource["endpoint"]["params"]+ assert resource["endpoint"]["path"] == expected_path+ assert resource["table_format"] == "delta"+ assert resource["endpoint"].get("data_selector") == selector+ assert "limit" not in params or page_size_param == "limit"+ if page_size_param:+ assert params[page_size_param] == 100+ else:+ assert "per_page" not in params++ def test_replays_requests_ascending_sort(self) -> None:+ # sort_mode is "asc" for replays, so the request must ask for ascending+ # started_at or the incremental watermark advances to the newest row immediately.+ resource = cast(+ dict[str, Any],+ get_resource(endpoint="replays", organization_slug="acme", should_use_incremental_field=False),+ )++ assert resource["endpoint"]["params"]["sort"] == "started_at"+ assert SENTRY_ENDPOINTS["replays"].sort_mode == "asc"++ def test_organization_events_requests_discover_projection(self) -> None:+ resource = cast(+ dict[str, Any],+ get_resource(endpoint="organization_events", organization_slug="acme", should_use_incremental_field=False),+ )++ params = resource["endpoint"]["params"]+ assert params["dataset"] == "errors"+ assert params["field"] == ["id", "timestamp", "transaction"]+ assert params["sort"] == "timestamp"++ @parameterized.expand(+ [+ ("replays", "started_at"),+ ("organization_events", "timestamp"),+ ]+ )+ def test_incremental_window_is_retention_bounded(self, endpoint, cursor_path) -> None:+ # These endpoints 400 on a pre-retention `start`, so the first incremental sync+ # must not fall back to the 1970 sentinel used by the issues endpoints.+ resource = cast(+ dict[str, Any],+ get_resource(endpoint=endpoint, organization_slug="acme", should_use_incremental_field=True),+ )++ incremental = resource["endpoint"]["incremental"]+ assert incremental["cursor_path"] == cursor_path+ assert incremental["start_param"] == "start"+ assert incremental["end_param"] == "end"+ assert incremental["initial_value"] != "1970-01-01T00:00:00"+ floor = datetime.now(UTC) - timedelta(days=SENTRY_RETENTION_DAYS)+ parsed = datetime.strptime(incremental["initial_value"], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC)+ assert abs((parsed - floor).total_seconds()) < 60+ assert resource["write_disposition"]["disposition"] == "merge"+++class TestSentryNewFanoutEndpoints:+ @parameterized.expand(+ [+ (+ "release_deploys",+ "releases",+ {"version": "1.0.0"},+ {"id": "d1", "_releases_version": "1.0.0"},+ {"release_version": "1.0.0"},+ ),+ (+ "release_commits",+ "releases",+ {"version": "1.0.0"},+ {"id": "c1", "_releases_version": "1.0.0"},+ {"release_version": "1.0.0"},+ ),+ (+ "repo_commits",+ "repos",+ {"id": "77"},+ {"id": "c1", "_repos_id": "77"},+ {"repo_id": "77"},+ ),+ (+ "monitor_checkins",+ "monitors",+ {"id": "55"},+ {"id": "ci1", "_monitors_id": "55"},+ {"monitor_id": "55"},+ ),+ (+ "project_user_feedback",+ "projects",+ {"id": "1", "slug": "web"},+ {"id": "f1", "_projects_id": "1", "_projects_slug": "web"},+ {"project_id": "1", "project_slug": "web"},+ ),+ (+ "project_filters",+ "projects",+ {"id": "1", "slug": "web"},+ {"id": "browser-extensions", "_projects_id": "1", "_projects_slug": "web"},+ {"project_id": "1", "project_slug": "web"},+ ),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_parent_identifier_lands_in_the_row(+ self, endpoint, parent_name, parent_row, child_row, expected, mock_rest_api_resources+ ) -> None:+ # The parent identifier is part of each of these tables' composite primary key,+ # so losing the rename leaves a non-unique key and duplicate rows on every merge.+ mock_rest_api_resources.return_value = [+ _FakeDltResource(parent_name, [parent_row]),+ _FakeDltResource(endpoint, [child_row]),+ ]++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint=endpoint,+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert len(rows) == 1+ row = rows[0]+ for key, value in expected.items():+ assert row[key] == value+ assert not any(key.startswith("_") for key in row)+ assert set(resp.primary_keys or []) <= set(row)+++class TestSentryCustomIteratorEndpoints:+ @parameterized.expand([(endpoint,) for endpoint in CUSTOM_ITERATOR_ENDPOINTS])+ def test_every_custom_iterator_endpoint_is_routed(self, endpoint) -> None:+ # An endpoint marked custom_iterator with no matching branch would only blow up+ # mid-sync, once the pipeline pulls the first row.+ rows = _custom_endpoint_rows(+ endpoint=endpoint,+ base_api_url="https://sentry.io/api/0",+ headers={},+ organization_slug="acme",+ )++ assert iter(rows) is not None++ def test_unknown_custom_iterator_endpoint_raises(self) -> None:+ with pytest.raises(ValueError, match="No custom iterator registered"):+ _custom_endpoint_rows(+ endpoint="not_an_endpoint",+ base_api_url="https://sentry.io/api/0",+ headers={},+ organization_slug="acme",+ )++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_sessions_flattens_series_into_one_row_per_interval(self, mock_request) -> None:+ seen_params: list[dict | None] = []++ def side_effect(url, headers=None, params=None, timeout=None):+ seen_params.append(params)+ return _response(+ {+ "intervals": ["2026-03-01T00:00:00Z", "2026-03-02T00:00:00Z"],+ "groups": [+ {+ "by": {+ "project": 1,+ "release": "1.0.0",+ "environment": "prod",+ "session.status": "healthy",+ },+ "series": {"sum(session)": [5, 7], "count_unique(user)": [2, 3]},+ "totals": {"sum(session)": 12},+ },+ {+ "by": {"project": 1, "environment": "prod", "session.status": "crashed"},+ "series": {"sum(session)": [1, 0]},+ "totals": {"sum(session)": 1},+ },+ ],+ }+ )++ mock_request.side_effect = side_effect++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="sessions",+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [+ {+ "interval_start": "2026-03-01T00:00:00Z",+ "project": "1",+ "release": "1.0.0",+ "environment": "prod",+ "session_status": "healthy",+ "sum_session": 5,+ "count_unique_user": 2,+ },+ {+ "interval_start": "2026-03-02T00:00:00Z",+ "project": "1",+ "release": "1.0.0",+ "environment": "prod",+ "session_status": "healthy",+ "sum_session": 7,+ "count_unique_user": 3,+ },+ # An absent dimension becomes "" — a null would never match on merge.+ {+ "interval_start": "2026-03-01T00:00:00Z",+ "project": "1",+ "release": "",+ "environment": "prod",+ "session_status": "crashed",+ "sum_session": 1,+ "count_unique_user": None,+ },+ {+ "interval_start": "2026-03-02T00:00:00Z",+ "project": "1",+ "release": "",+ "environment": "prod",+ "session_status": "crashed",+ "sum_session": 0,+ "count_unique_user": None,+ },+ ]+ assert seen_params[0] is not None+ 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_organization_stats_flattens_series_and_excludes_project_grouping(self, mock_request) -> None:+ seen_params: list[dict | None] = []++ def side_effect(url, headers=None, params=None, timeout=None):+ seen_params.append(params)+ return _response(+ {+ "intervals": ["2026-03-01T00:00:00Z"],+ "groups": [+ {+ "by": {"outcome": "accepted", "category": "error", "reason": "none"},+ "series": {"sum(quantity)": [42]},+ "totals": {"sum(quantity)": 42},+ }+ ],+ }+ )++ mock_request.side_effect = side_effect++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="organization_stats",+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [+ {+ "interval_start": "2026-03-01T00:00:00Z",+ "outcome": "accepted",+ "category": "error",+ "reason": "none",+ "quantity": 42,+ }+ ]+ # Grouping by project collapses the series into a single period total, which+ # would make the interval column meaningless.+ assert seen_params[0] is not None+ assert "project" not in seen_params[0]["groupBy"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_stats_summary_yields_one_row_per_project_category(self, mock_request) -> None:+ mock_request.return_value = _response(+ {+ "start": "2026-01-01T00:00:00Z",+ "end": "2026-03-01T00:00:00Z",+ "projects": [+ {+ "id": "1",+ "slug": "web",+ "stats": [+ {"category": "error", "outcomes": {"accepted": 5}, "totals": {"sum(quantity)": 5}},+ {"category": "transaction", "outcomes": {"accepted": 2}, "totals": {"sum(quantity)": 2}},+ ],+ }+ ],+ }+ )++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="organization_stats_summary",+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert [(row["project_id"], row["category"]) for row in rows] == [("1", "error"), ("1", "transaction")]+ assert rows[0]["project_slug"] == "web"+ assert rows[0]["quantity"] == 5+ assert rows[0]["period_start"] == "2026-01-01T00:00:00Z"+ assert rows[0]["period_end"] == "2026-03-01T00:00:00Z"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_trace_item_attributes_stamps_dataset_and_skips_unavailable_ones(self, mock_request) -> None:+ def side_effect(url, headers=None, params=None, timeout=None):+ dataset = (params or {}).get("dataset")+ if dataset == "spans":+ return _response([{"key": "browser.name", "attributeType": "string"}])+ if dataset == "preprod":+ # Not every organization has every trace item dataset enabled.+ return _response(None, status_code=400)+ return _response([])++ mock_request.side_effect = side_effect++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="trace_item_attributes",+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [{"key": "browser.name", "attributeType": "string", "dataset": "spans"}]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_trace_item_stats_flattens_attribute_distributions(self, mock_request) -> None:+ def side_effect(url, headers=None, params=None, timeout=None):+ if (params or {}).get("itemType") == "spans":+ return _response(+ {+ "data": [+ {+ "attributeDistributions": {+ "data": {+ "sentry.device": [+ {"label": "mobile", "value": 3},+ {"label": "desktop", "value": 1},+ ]+ }+ }+ }+ ]+ }+ )+ return _response(None, status_code=403)++ mock_request.side_effect = side_effect++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="trace_item_stats",+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [+ {"item_type": "spans", "attribute": "sentry.device", "label": "mobile", "value": 3},+ {"item_type": "spans", "attribute": "sentry.device", "label": "desktop", "value": 1},+ ]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_project_ownership_yields_one_row_per_project_and_skips_missing_config(self, mock_request) -> None:+ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/projects/"):+ return _response([{"id": "1", "slug": "web"}, {"id": "2", "slug": "api"}])+ if url.endswith("/projects/acme/web/ownership/"):+ return _response({"raw": "*.py @backend", "fallthrough": True})+ return _response(None, status_code=404)++ mock_request.side_effect = side_effect++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="project_ownership",+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [{"raw": "*.py @backend", "fallthrough": True, "project_id": "1", "project_slug": "web"}]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_project_stats_flattens_point_pairs(self, mock_request) -> None:+ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/projects/"):+ return _response([{"id": "1", "slug": "web"}])+ if (params or {}).get("stat") == "received":+ return _response([[1772409600, 12], [1772496000, 8]])+ return _response([])++ mock_request.side_effect = side_effect++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="project_stats",+ team_id=123,+ job_id="job-id",+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [+ {"stat": "received", "timestamp": 1772409600, "value": 12, "project_id": "1", "project_slug": "web"},+ {"stat": "received", "timestamp": 1772496000, "value": 8, "project_id": "1", "project_slug": "web"},+ ]++ @parameterized.expand(+ [+ ("pre_retention_watermark", 946684800, True),+ ("no_watermark", None, True),+ ("recent_watermark", None, False),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ def test_project_stats_since_never_predates_retention(self, _name, watermark, expect_floor, mock_request) -> None:+ seen_params: list[dict | None] = []+ recent = int((datetime.now(UTC) - timedelta(days=2)).timestamp())++ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/projects/"):+ return _response([{"id": "1", "slug": "web"}])+ seen_params.append(params)+ return _response([])++ mock_request.side_effect = side_effect++ resp = sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="project_stats",+ team_id=123,+ job_id="job-id",+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark if expect_floor else recent,+ )++ list(cast(Any, resp.items()))++ floor = int((datetime.now(UTC) - timedelta(days=SENTRY_RETENTION_DAYS)).timestamp())+ assert seen_params+ since = seen_params[0]["since"] if seen_params[0] else None+ assert since is not None+ assert since >= floor - 60+ if expect_floor:+ assert abs(since - floor) < 60+ else:+ assert abs(since - recent) < 60