: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 4 missing tables to the Grafana IRM source (#118223)
Tom Owers9494a00b97f5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 89df95f3514b..d2c1513b3c0f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -5505,10 +5505,10 @@ Today (14): `alert_groups`, `escalation_chains`, `escalation_policies`, `incidenDiffed against: <https://grafana.com/docs/grafana-cloud/observe-and-act/respond-to-incidents/reference/incident-api/reference/>-- [ ] `Custom fields (POST /api/plugins/grafana-irm-app/resources/api/v1/FieldsService.GetFields)` — resolve fieldUUID values already included in incidents and activity into named analytical dimensions (high)-- [ ] `Roles (POST /api/plugins/grafana-irm-app/resources/api/v1/RolesService.GetRoles)` — resolve roleID values in synced incident membership previews to named response responsibilities (high)-- [ ] `Alerts (GET /api/v1/alerts/)` — measure individual alert volume and inspect payloads hidden by alert group aggregation (high)-- [ ] `Incident membership (POST /api/plugins/grafana-irm-app/resources/api/v1/IncidentsService.GetIncidentMembership)` — include all responders and observers when comparing incident participation and response workload (medium)+- [x] `Custom fields (POST /api/plugins/grafana-irm-app/resources/api/v1/FieldsService.GetFields)` — resolve fieldUUID values already included in incidents and activity into named analytical dimensions (high)+- [x] `Roles (POST /api/plugins/grafana-irm-app/resources/api/v1/RolesService.GetRoles)` — resolve roleID values in synced incident membership previews to named response responsibilities (high)+- [x] `Alerts (GET /api/v1/alerts/)` — measure individual alert volume and inspect payloads hidden by alert group aggregation (high)+- [x] `Incident membership (POST /api/plugins/grafana-irm-app/resources/api/v1/IncidentsService.GetIncidentMembership)` — include all responders and observers when comparing incident participation and response workload (medium)- [ ] `Final schedule shifts (GET /api/v1/schedules/{schedule_id}/final_shifts)` — measure actual scheduled hours per responder after rotations and overrides are applied (medium)- [ ] `Key updates (POST /api/plugins/grafana-irm-app/resources/api/v1/KeyUpdatesService.QueryKeyUpdates)` — analyze incident communications, update frequency, and status changes across incident timelines (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/canonical_descriptions.pyindex 52a03e7e326f..fd1430940c97 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/canonical_descriptions.py@@ -33,6 +33,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"last_alert": "The most recent alert in the group, including its raw payload.",},},+ "alerts": {+ "description": "A single alert received by an OnCall integration, with its raw payload. Alerts are grouped into alert groups.",+ "docs_url": f"{_ONCALL_DOCS}alerts/",+ "columns": {+ "id": "Unique identifier for the alert.",+ "alert_group_id": "ID of the alert group the alert belongs to.",+ "created_at": "When the alert was received.",+ "payload": "Raw payload the monitoring system sent with the alert.",+ },+ },"resolution_notes": {"description": "A note attached to an alert group that explains how it was resolved.","docs_url": f"{_ONCALL_DOCS}resolution_notes/",@@ -191,4 +201,49 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"url": "Link attached to the item.",},},+ "incident_membership": {+ "description": "A person involved in an incident and the role they hold in it. Covers every participant, not only the important roles in the incident membership preview.",+ "docs_url": _INCIDENT_DOCS,+ "columns": {+ "incidentID": "ID of the incident.",+ "roleID": "ID of the role the user holds in the incident.",+ "userID": "ID of the user, copied from the nested user object.",+ "role": "The role the user holds in the incident.",+ "user": "The user involved in the incident.",+ },+ },+ "incident_roles": {+ "description": "A role that people can hold in an incident, such as commander or investigator.",+ "docs_url": _INCIDENT_DOCS,+ "columns": {+ "roleID": "Unique identifier for the role.",+ "orgID": "ID of the organization that owns the role.",+ "name": "Name of the role.",+ "description": "Description of the role.",+ "important": "Whether the role is important.",+ "mandatory": "Whether the role is mandatory.",+ "archived": "Whether the role is archived.",+ "createdAt": "When the role was created.",+ "updatedAt": "When the role was last updated.",+ },+ },+ "incident_custom_fields": {+ "description": "A custom field that can be set on incidents. Resolves the field UUIDs in incident field values.",+ "docs_url": _INCIDENT_DOCS,+ "columns": {+ "uuid": "Unique identifier for the field.",+ "name": "Name of the field.",+ "slug": "URL-friendly identifier for the field.",+ "description": "Description of the field.",+ "type": "Data type of the field.",+ "domainName": "Domain the field belongs to.",+ "selectoptions": "Options a user can pick from, for select-type fields.",+ "required": "Whether the field is required.",+ "archived": "Whether the field is archived.",+ "immutable": "Whether the field can be changed.",+ "source": "Where the field comes from.",+ "externalID": "ID of the field in an external system.",+ "version": "Version of the field definition.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/grafana_irm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/grafana_irm.pyindex 8711ff8abf14..d5763e04f50c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/grafana_irm.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/grafana_irm.py@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,PageNumberPaginator,+ SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (@@ -24,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resEndpointResource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import reach_safe_pointfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.grafana_irm.settings import (GRAFANA_IRM_ENDPOINTS,@@ -200,6 +202,95 @@ def _incident_client(token: str, stack_url: str) -> RESTClient:)+def _oncall_client(token: str, stack_url: str, oncall_api_url: str) -> RESTClient:+ return RESTClient(+ base_url=oncall_api_url,+ headers={"Accept": "application/json", "X-Grafana-URL": stack_url},+ auth=BearerTokenAuth(token),+ allowed_hosts=[],+ allow_redirects=False,+ request_timeout=REQUEST_TIMEOUT_SECONDS,+ )+++def _alert_pages(client: RESTClient) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every alert group and yield its alerts page by page.++ The alerts list rejects requests without an ``alert_group_id`` filter, which the declarative+ fan-out can only bind into the URL path.+ """+ alert_groups = GRAFANA_IRM_ENDPOINTS["alert_groups"]+ alerts = GRAFANA_IRM_ENDPOINTS["alerts"]++ for alert_group_page in client.paginate(+ alert_groups.path,+ params={"perpage": ONCALL_PAGE_SIZE},+ paginator=_oncall_paginator(),+ data_selector=alert_groups.data_selector,+ data_selector_required=True,+ ):+ for alert_group in alert_group_page:+ alert_group_id = alert_group.get("id")+ if not alert_group_id:+ continue+ found = False+ for alert_page in client.paginate(+ alerts.path,+ params={"perpage": ONCALL_PAGE_SIZE, "alert_group_id": alert_group_id},+ paginator=_oncall_paginator(),+ data_selector=alerts.data_selector,+ data_selector_required=True,+ ):+ if alert_page:+ found = True+ yield alert_page+ if not found:+ reach_safe_point()+++def _incident_membership_pages(client: RESTClient) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every incident and yield the full list of people involved in it.++ Assignments carry no incident ID and nest the user, so both IDs are lifted onto each row to+ form the primary key.+ """+ incidents = GRAFANA_IRM_ENDPOINTS["incidents"]+ membership = GRAFANA_IRM_ENDPOINTS["incident_membership"]+ incident_query = {"query": {"limit": INCIDENT_PAGE_SIZE, "orderField": "createdTime", "orderDirection": "ASC"}}++ for incident_page in client.paginate(+ incidents.path,+ method="post",+ json=incident_query,+ paginator=IncidentCursorPaginator(),+ data_selector=incidents.data_selector,+ data_selector_required=True,+ ):+ for incident in incident_page:+ incident_id = incident.get("incidentID")+ if not incident_id:+ continue+ rows: list[dict[str, Any]] = []+ for assignment_page in client.paginate(+ membership.path,+ method="post",+ json={"incidentID": incident_id},+ paginator=SinglePagePaginator(),+ data_selector=membership.data_selector,+ data_selector_required=True,+ data_selector_empty_ok=True,+ ):+ for assignment in assignment_page:+ user_id = (assignment.get("user") or {}).get("userID")+ # An assignment without a user would have a null primary key.+ if user_id:+ rows.append({**assignment, "incidentID": incident_id, "userID": user_id})+ if rows:+ yield rows+ else:+ reach_safe_point()++def _incident_activity_pages(client: RESTClient) -> Iterator[list[dict[str, Any]]]:"""Fan out over every incident and yield its activity timeline page by page.@@ -260,11 +351,15 @@ def grafana_irm_source("partition_keys": [config.partition_key],}- if endpoint == "incident_activity":- client = _incident_client(token, stack_url)+ fan_out_pages: dict[str, Callable[[], Iterator[list[dict[str, Any]]]]] = {+ "incident_activity": lambda: _incident_activity_pages(_incident_client(token, stack_url)),+ "incident_membership": lambda: _incident_membership_pages(_incident_client(token, stack_url)),+ "alerts": lambda: _alert_pages(_oncall_client(token, stack_url, oncall_api_url)),+ }+ if endpoint in fan_out_pages:return SourceResponse(name=endpoint,- items=lambda: _incident_activity_pages(client),+ items=fan_out_pages[endpoint],primary_keys=list(config.primary_keys),**partition_kwargs,)@@ -331,7 +426,9 @@ def validate_credentials(auth_header = {"Authorization": f"Bearer {token}", "Accept": "application/json"}if probe_oncall:- oncall_path = config.path if config is not None else GRAFANA_IRM_ENDPOINTS["alert_groups"].path+ # A fan-out child needs a parent ID, so probe its parent, which takes the same permission.+ probe_name = (config.parent or config.name) if config is not None else "alert_groups"+ oncall_path = GRAFANA_IRM_ENDPOINTS[probe_name].pathstatus = _probe(session,"GET",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/settings.pyindex 46a95da5c4c3..e904c6ca4204 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/settings.py@@ -25,6 +25,8 @@ class GrafanaIRMEndpointConfig:data_selector: str = "results"# Credential-like fields dropped from every row before it reaches the warehouse.dropped_fields: tuple[str, ...] = ()+ # Fan-out child: one request per row of this parent endpoint, so credential checks probe the parent.+ parent: str | None = Nonedescription: str | None = None@@ -36,6 +38,14 @@ GRAFANA_IRM_ENDPOINTS: dict[str, GrafanaIRMEndpointConfig] = {partition_key="created_at",description="OnCall alert groups. Full refresh only: the API lists newest first and states change after creation",),+ "alerts": GrafanaIRMEndpointConfig(+ name="alerts",+ api="oncall",+ path="/api/v1/alerts/",+ partition_key="created_at",+ parent="alert_groups",+ description="Individual OnCall alerts with their raw payloads. Fetched per alert group, so large alert histories take longer",+ ),"resolution_notes": GrafanaIRMEndpointConfig(name="resolution_notes",api="oncall",@@ -123,6 +133,30 @@ GRAFANA_IRM_ENDPOINTS: dict[str, GrafanaIRMEndpointConfig] = {data_selector="activityItems",description="Timeline entries of every incident. Fetched per incident, so large incident histories take longer",),+ "incident_membership": GrafanaIRMEndpointConfig(+ name="incident_membership",+ api="incident",+ path="/IncidentsService.GetIncidentMembership",+ # One row per role a user holds in an incident; `userID` is lifted out of the nested user.+ primary_keys=("incidentID", "roleID", "userID"),+ data_selector="assignments",+ parent="incidents",+ description="Every person involved in every incident, with their role. Fetched per incident",+ ),+ "incident_roles": GrafanaIRMEndpointConfig(+ name="incident_roles",+ api="incident",+ path="/RolesService.GetRoles",+ primary_keys=("roleID",),+ data_selector="roles",+ ),+ "incident_custom_fields": GrafanaIRMEndpointConfig(+ name="incident_custom_fields",+ api="incident",+ path="/FieldsService.GetFields",+ primary_keys=("uuid",),+ data_selector="fields",+ ),}ENDPOINTS = tuple(GRAFANA_IRM_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/tests/test_grafana_irm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/tests/test_grafana_irm.pyindex 2a4fd3fe51a6..b8743089b04a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/tests/test_grafana_irm.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana_irm/tests/test_grafana_irm.py@@ -25,6 +25,7 @@ STACK_URL = "https://acme.grafana.net"ONCALL_URL = "https://oncall-prod-us-central-0.grafana.net/oncall"INCIDENT_PATH = "/api/plugins/grafana-irm-app/resources/api/v1/IncidentsService.QueryIncidentPreviews"ACTIVITY_PATH = "/api/plugins/grafana-irm-app/resources/api/v1/ActivityService.QueryActivity"+MEMBERSHIP_PATH = "/api/plugins/grafana-irm-app/resources/api/v1/IncidentsService.GetIncidentMembership"def _driver() -> SourceDriver:@@ -198,6 +199,95 @@ def test_incident_activity_fans_out_over_every_incident() -> None:assert result.response.primary_keys == ["incidentID", "activityItemID"]+def test_alerts_fan_out_over_every_alert_group() -> None:+ result = _driver().run(+ "alerts",+ [+ ScriptedResponse(json=_oncall_page([{"id": "IG1"}], 1, total_pages=2)),+ ScriptedResponse(json=_oncall_page([{"id": "AL1", "alert_group_id": "IG1"}], 1, total_pages=2)),+ ScriptedResponse(json=_oncall_page([{"id": "AL2", "alert_group_id": "IG1"}], 2, total_pages=2)),+ ScriptedResponse(json=_oncall_page([{"id": "IG2"}, {"title": "no id"}], 2, total_pages=2)),+ ScriptedResponse(json=_oncall_page([], 1, total_pages=1)),+ ],+ )++ assert result.raised is None+ assert result.rows == [{"id": "AL1", "alert_group_id": "IG1"}, {"id": "AL2", "alert_group_id": "IG1"}]+ assert [(request.path, request.param("alert_group_id"), request.param("page")) for request in result.requests] == [+ ("/oncall/api/v1/alert_groups/", None, "1"),+ ("/oncall/api/v1/alerts/", "IG1", "1"),+ ("/oncall/api/v1/alerts/", "IG1", "2"),+ ("/oncall/api/v1/alert_groups/", None, "2"),+ ("/oncall/api/v1/alerts/", "IG2", "1"),+ ]+ for request in result.requests:+ assert request.param("perpage") == "100"+ assert request.headers["x-grafana-url"] == STACK_URL+ assert result.response is not None+ assert result.response.primary_keys == ["id"]+ assert result.response.partition_keys == ["created_at"]+++def test_incident_membership_lifts_ids_onto_each_assignment() -> None:+ commander = {"roleID": 1, "name": "commander"}+ result = _driver().run(+ "incident_membership",+ [+ ScriptedResponse(+ json={"incidentPreviews": [{"incidentID": "1"}, {"incidentID": "2"}], "cursor": {"hasMore": False}}+ ),+ ScriptedResponse(+ json={+ "assignments": [+ {"role": commander, "roleID": 1, "user": {"userID": "user-a", "name": "Ada"}},+ {"role": commander, "roleID": 1, "user": None},+ {"roleID": 2, "user": {"userID": "user-b"}},+ ],+ "error": "",+ }+ ),+ ScriptedResponse(json={"assignments": None, "error": ""}),+ ],+ )++ assert result.raised is None+ assert result.rows == [+ {+ "role": commander,+ "roleID": 1,+ "user": {"userID": "user-a", "name": "Ada"},+ "incidentID": "1",+ "userID": "user-a",+ },+ {"roleID": 2, "user": {"userID": "user-b"}, "incidentID": "1", "userID": "user-b"},+ ]+ assert result.paths == [INCIDENT_PATH, MEMBERSHIP_PATH, MEMBERSHIP_PATH]+ assert [request.json() for request in result.requests[1:]] == [{"incidentID": "1"}, {"incidentID": "2"}]+ assert result.response is not None+ assert result.response.primary_keys == ["incidentID", "roleID", "userID"]+++ ("endpoint", "path", "body", "primary_key"),+ [+ ("incident_roles", "RolesService.GetRoles", {"roles": [{"roleID": 1}, {"roleID": 2}]}, "roleID"),+ ("incident_custom_fields", "FieldsService.GetFields", {"fields": [{"uuid": "f-1"}, {"uuid": "f-2"}]}, "uuid"),+ ],+)+def test_incident_lookup_tables_are_one_unfiltered_request(+ endpoint: str, path: str, body: dict[str, Any], primary_key: str+) -> None:+ result = _driver().run(endpoint, [ScriptedResponse(json={**body, "error": ""})])++ assert result.raised is None+ assert result.rows == next(iter(body.values()))+ assert result.paths == [f"/api/plugins/grafana-irm-app/resources/api/v1/{path}"]+ assert result.requests[0].method == "POST"+ assert result.requests[0].json() == {}+ assert result.response is not None+ assert result.response.primary_keys == [primary_key]++@pytest.mark.parametrize(("oncall_status", "incident_status", "schema_name", "expected_ok", "message_part"),[@@ -208,6 +298,8 @@ def test_incident_activity_fans_out_over_every_incident() -> None:(404, 200, None, False, "Admin & API"),(200, 404, None, False, "isn't enabled"),(403, None, "alert_groups", False, "permission"),+ (200, None, "alerts", True, None),+ (403, None, "alerts", False, "permission"),(None, 403, "incidents", False, "permission"),(500, 200, None, False, "HTTP 500"),],