Skip to content

: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.

feat(data-warehouse): add monte carlo events and domains tables (#115407)

Tom Owers6c7d9e2e4038
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.md
index 8c3a068aee66..b86a6a6a2cd9 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
@@ -5711,14 +5711,14 @@ Note: GraphQL API pinned to version 2024-10 in monday.py. The boards query selec
## MonteCarlo — **thin**
-Today (5): `alerts`, `monitors`, `tables`, `users`, `warehouses`
+Today (7): `alerts`, `domains`, `events`, `monitors`, `tables`, `users`, `warehouses`
Diffed against: <https://apidocs.getmontecarlo.com/>
-- [ ] `getIncidents` — incidents group related alerts and are the unit teams triage — the headline object above alerts (high)
-- [ ] `getEvents / getEventGroups` — raw detector events (freshness, volume, schema change) underlying alerts (high)
-- [ ] `getEventsForIncidents` — incident timeline / state-transition history (high)
-- [ ] `getDomainsV2 + getDomainsForMcons` — domain lookup and the domain-to-asset membership join for the mcons already synced (high)
+- ~~`getIncidents`~~ — deprecated in the GraphQL schema; `getAlerts` replaced it and is already synced as `alerts`
+- [x] `getEvents / getEventGroups` — raw detector events (freshness, volume, schema change) underlying alerts (high). Added as `events` (incremental on `createdTime`). `getEventGroups` skipped: it takes one required `alertId` and regroups the same events, which carry their alert id.
+- ~~`getEventsForIncidents`~~ — deprecated in the GraphQL schema; the timeline events it returned are in `events` (`INCIDENT_*` event types)
+- [x] `getDomainsV2 + getDomainsForMcons` — domain lookup and the domain-to-asset membership join for the mcons already synced (high). Added as `domains`; its `assignments` column holds the member MCONs. `getDomainsForMcons` skipped: it returns per-warehouse domain counts for a batch of at most 250 MCONs, not a per-asset membership row.
- [ ] `getFhEvents / getFhEventsByMonitor` — field-health event series per monitor — the per-field metric history behind monitor results (medium)
- [ ] `getDbtRuns / getDbtJobExecutions / getDbtTestResults` — dbt run and test outcomes tied to the same tables already synced (medium)
- [ ] `getQueryLogs / getAggregatedQueries` — warehouse query logs attributed to tables — usage and cost analysis (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/canonical_descriptions.py
index c815adc08c69..c0d8964c5b1c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/canonical_descriptions.py
@@ -34,6 +34,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"monitorTags": "Tags on the monitors that produced this alert.",
},
},
+ "domains": {
+ "description": "Domains in Monte Carlo — named groups of data assets, used to scope monitors, alerts, and ownership.",
+ "docs_url": "https://apidocs.getmontecarlo.com/",
+ "columns": {
+ "id": "Unique identifier for the domain.",
+ "uuid": "Domain UUID.",
+ "name": "Domain name.",
+ "description": "Domain description.",
+ "domainTag": "The domain's tag representation.",
+ "createdBy": "Full name of the user who created the domain.",
+ "createdByEmail": "Email of the user who created the domain.",
+ "objAssignmentUpdateTime": "When the domain's object assignments were last updated.",
+ "assignments": "MCONs of the objects explicitly assigned to the domain.",
+ "excludedAssignments": "MCONs of the objects explicitly excluded from the domain.",
+ "tags": "Table tag key/value pairs that add tables to the domain.",
+ "excludedTags": "Table tag key/value pairs that exclude tables from the domain.",
+ },
+ },
+ "events": {
+ "description": "Events raised by Monte Carlo detectors (freshness, volume, schema change, rule breaches) and alert timeline updates. Alerts group related events.",
+ "docs_url": "https://apidocs.getmontecarlo.com/",
+ "columns": {
+ "uuid": "Unique identifier for the event.",
+ "eventType": "Type of event (e.g. FRESH_ANOM, SIZE_ANOM, SCHEMA_CHANGE, INCIDENT_STATUS_UPDATE).",
+ "eventState": "Current state of the event (e.g. OPEN, RESOLVED, MUTED, TIMELINE).",
+ "createdTime": "When the event was created.",
+ "eventGeneratedTime": "When the detector generated the event.",
+ "description": "Human-readable description of the event.",
+ "data": "Event-type-specific payload, as a JSON string.",
+ "importanceScore": "Importance score of the affected table.",
+ "isImportant": "Whether the affected table is considered important.",
+ "isChild": "Whether the event is a child of another event.",
+ "isMerged": "Whether the event originally belonged to another alert that was merged into its current alert.",
+ "monitorId": "UUID of the monitor or rule that generated the event.",
+ "parentMonitorId": "UUID of the parent monitor, where applicable.",
+ "totalComments": "Number of comments on the event.",
+ "notifiedUsers": "Users notified about the event.",
+ "customRuleEntities": "Tables referenced by the custom rule, if the event comes from one.",
+ "customRuleProjects": "Projects referenced by the custom rule, if the event comes from one.",
+ "customRuleDatasets": "Datasets referenced by the custom rule, if the event comes from one.",
+ "ackTimestamp": "When the event was acknowledged.",
+ "ackBy": "User who acknowledged the event.",
+ "alert": "Alert the event belongs to. Joins to the alerts table on uuid.",
+ "warehouse": "Warehouse connection the event belongs to (uuid and name).",
+ "table": "Table the event is about (MCON and full table id).",
+ },
+ },
"monitors": {
"description": "Monitors configured in Monte Carlo — the table, metric, validation, and custom rule checks that watch data assets and raise alerts.",
"docs_url": "https://docs.getmontecarlo.com/docs/monitors-overview",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/monte_carlo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/monte_carlo.py
index af554bbd480a..75a7f1bced68 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/monte_carlo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/monte_carlo.py
@@ -205,6 +205,33 @@ def _get_offset_rows(
resumable_source_manager.save_state(MonteCarloResumeConfig(offset=offset))
+def _get_event_rows(
+ session: requests.Session,
+ config: MonteCarloEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MonteCarloResumeConfig],
+ resume: MonteCarloResumeConfig | None,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ start = _parse_incremental_value(db_incremental_field_last_value)
+ start_time = _format_datetime(start) if start is not None else None
+ cursor: str | None = None
+ if resume is not None and resume.cursor:
+ # Replay the cursor against the filter it was issued for.
+ cursor = resume.cursor
+ start_time = resume.window_after
+ logger.debug(f"Monte Carlo: resuming {config.name} from cursor {cursor}")
+
+ variables: dict[str, Any] = {"descOrder": False}
+ if start_time is not None:
+ variables["startTime"] = start_time
+
+ for rows, next_cursor in _relay_pages(session, config, logger, variables, cursor):
+ if next_cursor:
+ resumable_source_manager.save_state(MonteCarloResumeConfig(cursor=next_cursor, window_after=start_time))
+ yield rows
+
+
def _alert_windows(start: datetime, end: datetime) -> Iterator[tuple[datetime, datetime]]:
window_start = start
while window_start < end:
@@ -305,6 +332,15 @@ def get_rows(
incremental_field if should_use_incremental_field else None,
db_incremental_field_last_value if should_use_incremental_field else None,
)
+ elif endpoint == "events":
+ yield from _get_event_rows(
+ session,
+ config,
+ logger,
+ resumable_source_manager,
+ resume,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ )
elif config.pagination == "relay":
yield from _get_relay_rows(session, config, logger, resumable_source_manager, resume)
elif config.pagination == "offset":
@@ -341,10 +377,10 @@ def monte_carlo_source(
incremental_field=incremental_field,
),
primary_keys=endpoint_config.primary_keys,
- # getAlerts documents no within-page ordering guarantee we could verify, so the
- # incremental watermark is only persisted at successful job end (desc mode) rather
+ # getAlerts and getEvents document no within-page ordering guarantee we could verify, so
+ # the incremental watermark is only persisted at successful job end (desc mode) rather
# than checkpointed per batch against an assumed ascending order.
- sort_mode="desc" if endpoint == "alerts" else "asc",
+ sort_mode="desc" if endpoint in ("alerts", "events") else "asc",
partition_count=1 if endpoint_config.partition_key else None,
partition_size=1 if endpoint_config.partition_key else None,
partition_mode="datetime" if endpoint_config.partition_key else None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/settings.py
index 7525dbd239ce..950863a349e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/settings.py
@@ -166,6 +166,65 @@ query PostHogGetWarehouses {
}
"""
+EVENTS_QUERY = """
+query PostHogGetEvents($first: Int!, $after: String, $startTime: DateTime, $descOrder: Boolean) {
+ getEvents(first: $first, after: $after, startTime: $startTime, descOrder: $descOrder) {
+ edges {
+ node {
+ uuid
+ eventType
+ eventState
+ createdTime
+ eventGeneratedTime
+ description
+ data
+ importanceScore
+ isImportant
+ isChild
+ isMerged
+ monitorId
+ parentMonitorId
+ totalComments
+ notifiedUsers
+ customRuleEntities
+ customRuleProjects
+ customRuleDatasets
+ ackTimestamp
+ ackBy { email }
+ alert { id }
+ warehouse { uuid name }
+ table { mcon fullTableId }
+ }
+ }
+ pageInfo { endCursor hasNextPage }
+ }
+}
+"""
+
+DOMAINS_QUERY = """
+query PostHogGetDomains($first: Int!, $after: String) {
+ getDomainsV2(first: $first, after: $after) {
+ edges {
+ node {
+ id
+ uuid
+ name
+ description
+ domainTag
+ createdBy
+ createdByEmail
+ objAssignmentUpdateTime
+ assignments
+ excludedAssignments
+ tags { name value }
+ excludedTags { name value }
+ }
+ }
+ pageInfo { endCursor hasNextPage }
+ }
+}
+"""
+
VALIDATE_CREDENTIALS_QUERY = """
query PostHogValidateCredentials {
getUser { email }
@@ -212,6 +271,29 @@ MONTE_CARLO_ENDPOINTS: dict[str, MonteCarloEndpointConfig] = {
},
],
),
+ "domains": MonteCarloEndpointConfig(
+ name="domains",
+ query=DOMAINS_QUERY,
+ data_path="getDomainsV2",
+ pagination="relay",
+ primary_keys=["id"],
+ ),
+ "events": MonteCarloEndpointConfig(
+ name="events",
+ query=EVENTS_QUERY,
+ data_path="getEvents",
+ pagination="relay",
+ primary_keys=["uuid"],
+ partition_key="createdTime",
+ incremental_fields=[
+ {
+ "label": "createdTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdTime",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
"monitors": MonteCarloEndpointConfig(
name="monitors",
query=MONITORS_QUERY,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py
index 4575daa76bcf..48987619b35a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py
@@ -146,7 +146,7 @@ class TestValidateCredentials:
class TestRelayEndpoints:
- @parameterized.expand([("tables", "getTables"), ("users", "getUsersInAccount")])
+ @parameterized.expand([("domains", "getDomainsV2"), ("tables", "getTables"), ("users", "getUsersInAccount")])
def test_paginates_until_has_next_page_false(self, endpoint: str, data_path: str) -> None:
responses = [
_relay_page(data_path, [{"id": "1"}, {"id": "2"}], "cursor-1"),
@@ -169,6 +169,50 @@ class TestRelayEndpoints:
assert executor.calls[0]["after"] == "cursor-42"
+class TestEventsEndpoint:
+ @parameterized.expand(
+ [
+ ("incremental", True, datetime(2026, 6, 1, tzinfo=UTC), "2026-06-01T00:00:00Z"),
+ ("incremental_first_sync", True, None, None),
+ ("full_refresh_ignores_watermark", False, datetime(2026, 6, 1, tzinfo=UTC), None),
+ ]
+ )
+ def test_start_time_filter(
+ self, _label: str, use_incremental: bool, watermark: datetime | None, expected_start: str | None
+ ) -> None:
+ responses = [
+ _relay_page("getEvents", [{"uuid": "e-1"}], "cursor-1"),
+ _relay_page("getEvents", [{"uuid": "e-2"}], None),
+ ]
+ rows, executor, manager = _collect(
+ "events",
+ responses,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert [row["uuid"] for row in rows] == ["e-1", "e-2"]
+ for call in executor.calls:
+ assert call.get("startTime") == expected_start
+ assert call["descOrder"] is False
+ assert executor.calls[1]["after"] == "cursor-1"
+ assert [(state.cursor, state.window_after) for state in manager.saved] == [("cursor-1", expected_start)]
+
+ def test_resume_replays_cursor_against_saved_start_time(self) -> None:
+ manager = _FakeResumableManager(MonteCarloResumeConfig(cursor="cursor-3", window_after="2026-05-01T00:00:00Z"))
+ responses = [_relay_page("getEvents", [{"uuid": "e-9"}], None)]
+ _, executor, _ = _collect(
+ "events",
+ responses,
+ manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+
+ assert executor.calls[0]["after"] == "cursor-3"
+ assert executor.calls[0]["startTime"] == "2026-05-01T00:00:00Z"
+
+
class TestOffsetEndpoint:
def test_paginates_until_short_page(self) -> None:
page_size = MONTE_CARLO_ENDPOINTS["monitors"].page_size
@@ -281,6 +325,8 @@ class TestSourceResponse:
@parameterized.expand(
[
("alerts", ["uuid"], "desc"),
+ ("domains", ["id"], "asc"),
+ ("events", ["uuid"], "desc"),
("monitors", ["uuid"], "asc"),
("tables", ["id"], "asc"),
("users", ["id"], "asc"),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo_source.py
index 73c1f1c6546f..002974cb5d80 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo_source.py
@@ -20,6 +20,8 @@ class TestMonteCarloSource:
@parameterized.expand(
[
("alerts", True),
+ ("domains", False),
+ ("events", True),
("monitors", False),
("tables", False),
("users", False),