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 5 missing tables to the MonteCarlo source (#118098)

Tom Owers40f7db88eb0d
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 74a7c984930d..01d072d1be8d 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
@@ -8148,7 +8148,7 @@ Note: Compared all GET operations in the official llms.txt, including nested acc
## MonteCarlo — **thin**
-Today (7): `alerts`, `domains`, `events`, `monitors`, `tables`, `users`, `warehouses`
+Today (12): `alerts`, `dbt_runs`, `dbt_test_results`, `domains`, `events`, `fh_events`, `job_executions`, `job_schedules`, `monitors`, `tables`, `users`, `warehouses`
Diffed against: <https://apidocs.getmontecarlo.com/>
@@ -8156,10 +8156,10 @@ Diffed against: <https://apidocs.getmontecarlo.com/>
- [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)
-- [ ] `getJobExecutions / getJobSchedules` — pipeline job execution history for freshness root-causing (medium)
+- [x] `getFhEvents / getFhEventsByMonitor` — field-health event series per monitor — the per-field metric history behind monitor results (medium). Added as `fh_events` (`getFhEventsByMonitor` fanned out over metric monitors, incremental on `date`). `getFhEvents` skipped: it takes one alert id and returns a subset of the same events, which carry their `alertUuid`.
+- [x] `getDbtRuns / getDbtJobExecutions / getDbtTestResults` — dbt run and test outcomes tied to the same tables already synced (medium). Added as `dbt_runs` (full refresh) and `dbt_test_results` (incremental on `runStartedAt`). `getDbtJobExecutions` skipped: it needs one required `jobUuid` per call, and each `dbt_runs` row already carries its job execution.
+- [ ] `getQueryLogs / getAggregatedQueries` — warehouse query logs attributed to tables — usage and cost analysis (medium). Not added: `getAggregatedQueries` is deprecated and takes one table MCON per call; `getQueryLogs` is a search API with offset paging, no documented sort field or depth limit, and the full SQL text of each query.
+- [x] `getJobExecutions / getJobSchedules` — pipeline job execution history for freshness root-causing (medium). Added as `job_executions` (monitor run history, fanned out over monitors, incremental on `startTime` through `historyDays`) and `job_schedules` (data collector schedules, fanned out over warehouses, full refresh).
- [ ] `getDataProductsV2` — data product definitions that group assets for SLA reporting (medium)
- [ ] `getAccountUsage / getAssetsUsage / getBillingMonitorUsage` — monitored-asset and monitor usage counts — how consumption is tracked (medium)
- [ ] `getAuthorizationGroups + getAccountRoles` — user group/role membership lookup for the users table already synced (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 c0d8964c5b1c..debfb13e6a17 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,44 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"monitorTags": "Tags on the monitors that produced this alert.",
},
},
+ "dbt_runs": {
+ "description": "dbt runs (one per dbt command invocation) that Monte Carlo imported from dbt Cloud or dbt Core.",
+ "docs_url": "https://apidocs.getmontecarlo.com/#query-getDbtRuns",
+ "columns": {
+ "id": "Relay node ID of the dbt run.",
+ "uuid": "Unique identifier for the dbt run.",
+ "dbtRunId": "dbt run ID.",
+ "createdTime": "When Monte Carlo recorded the run.",
+ "updatedTime": "When Monte Carlo last updated the run.",
+ "generatedAt": "When dbt generated the run_results.json file.",
+ "startedAt": "When the run started.",
+ "command": "dbt command that was executed.",
+ "branch": "Code branch the dbt command ran against.",
+ "hasLogs": "Whether the run has logs.",
+ "dbtProject": "dbt project the run belongs to (uuid and project name).",
+ "job": "dbt job the run belongs to (uuid, job id, job name and MCON).",
+ "jobExecution": "dbt job execution the run is part of (uuid, status, start and finish times, display name).",
+ },
+ },
+ "dbt_test_results": {
+ "description": "Results of dbt tests, one row per test node per dbt run, linked to the tables they test.",
+ "docs_url": "https://apidocs.getmontecarlo.com/#query-getDbtTestResults",
+ "columns": {
+ "runUuid": "UUID of the dbt run. Joins to the dbt_runs table on uuid.",
+ "nodeId": "dbt node ID of the test.",
+ "nodeName": "dbt node name of the test.",
+ "runStartedAt": "When the dbt run started.",
+ "startedAt": "When the test node started to execute.",
+ "executionTime": "Total execution time of the test node, in seconds.",
+ "status": "Execution status of the test.",
+ "mcon": "MCON of the table the test is associated with.",
+ "jobName": "dbt job name.",
+ "jobMcon": "MCON of the dbt job.",
+ "command": "dbt command that was executed.",
+ "modelId": "ID of the dbt model the test is associated with.",
+ "modelName": "Name of the dbt model the test is associated with.",
+ },
+ },
"domains": {
"description": "Domains in Monte Carlo — named groups of data assets, used to scope monitors, alerts, and ownership.",
"docs_url": "https://apidocs.getmontecarlo.com/",
@@ -81,6 +119,64 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"table": "Table the event is about (MCON and full table id).",
},
},
+ "fh_events": {
+ "description": "Metric monitor (field health) events: the metric value series that each metric monitor records per field, with its thresholds.",
+ "docs_url": "https://apidocs.getmontecarlo.com/#query-getFhEventsByMonitor",
+ "columns": {
+ "monitorUuid": "UUID of the metric monitor that recorded the event. Joins to the monitors table on uuid.",
+ "eventUuid": "Unique identifier for the event.",
+ "alertUuid": "UUID of the alert associated with the event, if any. Joins to the alerts table on uuid.",
+ "eventType": "Type of the event.",
+ "date": "Timestamp of the metric point.",
+ "metric": "Metric name.",
+ "field": "Field (column) name the metric is computed on.",
+ "whereCondition": "Segmented where condition, for segmented monitors.",
+ "value": "Metric value.",
+ "lowerThreshold": "Lower threshold.",
+ "upperThreshold": "Upper threshold.",
+ "thresholdType": "Threshold type (explicit or auto).",
+ "comparisonOperator": "Threshold comparison operator.",
+ "autoOperator": "Operator used when thresholds are automatic.",
+ "historicalMean": "Historical mean value.",
+ "aggTimeInterval": "Aggregation time interval of the metric (for example hour or day).",
+ "customMetricDisplayName": "Display name of the custom metric.",
+ "customMetricSqlExpression": "SQL expression evaluated for the custom metric.",
+ "timeSeriesUuid": "UUID of the time series.",
+ "parentTimeSeriesUuid": "UUID of the parent time series.",
+ "detectorFeedback": "Feedback recorded for the detector about this event (id and reason).",
+ },
+ },
+ "job_executions": {
+ "description": "Run history of Monte Carlo monitors: one row per monitor job execution with its status, timing and errors.",
+ "docs_url": "https://apidocs.getmontecarlo.com/#query-getJobExecutions",
+ "columns": {
+ "monitorUuid": "UUID of the monitor that ran. Joins to the monitors table on uuid.",
+ "jobExecutionUuid": "Unique identifier for the job execution.",
+ "startTime": "When the job was scheduled.",
+ "endTime": "When the job completed.",
+ "status": "Status of the job execution (e.g. SUCCESS, FAILED, TIMEOUT).",
+ "exceptions": "Exceptions captured during the job execution.",
+ "tableMonitorWarning": "Whether a table monitor failure was treated as a warning without a failure notification.",
+ "sizeCollectionTableMcon": "MCON of the table for size collection executions in table monitors.",
+ "sizeCollectionEnabled": "Whether size collection is enabled for the asset.",
+ "totalInvocationsCount": "Total number of invocations for the job execution.",
+ "totalResultCount": "Total number of objects the job execution returned.",
+ "totalExecutionDuration": "Total execution duration, in seconds.",
+ "consolidatingJobUuid": "UUID of the consolidating job execution.",
+ },
+ },
+ "job_schedules": {
+ "description": "Data collector job schedules for each warehouse connection, such as metadata and query log collection.",
+ "docs_url": "https://apidocs.getmontecarlo.com/#query-getJobSchedules",
+ "columns": {
+ "uuid": "Unique identifier for the schedule.",
+ "resourceId": "UUID of the warehouse the schedule belongs to. Joins to the warehouses table on uuid.",
+ "connectionId": "ID of the connection the schedule belongs to.",
+ "internalJobType": "Type of job (e.g. METADATA, QUERY_LOGS).",
+ "limits": "Limits configuration for the job, as a JSON string.",
+ "intervalInSeconds": "Interval between job runs, in seconds.",
+ },
+ },
"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 75a7f1bced68..4a2ecc0edd53 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
@@ -1,3 +1,4 @@
+import math
import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
@@ -11,8 +12,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.settings import (
+ MONITOR_UUIDS_QUERY,
MONTE_CARLO_ENDPOINTS,
VALIDATE_CREDENTIALS_QUERY,
+ WAREHOUSES_QUERY,
MonteCarloEndpointConfig,
)
@@ -24,6 +27,22 @@ ALERT_WINDOW = timedelta(days=30)
# Alerts history is unbounded and the API requires a time range, so the first sync is
# capped to the trailing year instead of guessing at account age.
DEFAULT_LOOKBACK_DAYS = 365
+MONITOR_PAGE_SIZE = 100
+# Metric monitors (STATS) are the monitors that produce a field-health event series.
+FH_EVENT_MONITOR_TYPES = ["STATS"]
+# A monitor can write a metric point dated before the newest point of another monitor (daily
+# buckets land after hourly ones), so incremental syncs re-read a trailing overlap; merge dedupes it.
+FH_EVENTS_OVERLAP = timedelta(days=2)
+# A dbt run that started before the watermark can upload its test results after a newer run has
+# synced, so incremental syncs re-read a trailing overlap of run start times; merge dedupes it.
+DBT_TEST_RESULTS_OVERLAP = timedelta(days=2)
+# getJobExecutions only filters by whole days back and a job's startTime stays fixed while it
+# runs, so one extra day catches status updates on jobs that finished after the last sync.
+JOB_EXECUTIONS_OVERLAP = timedelta(days=1)
+
+
+# (after, before) bounds of one time-range query.
+Window = tuple[datetime, datetime]
class MonteCarloRetryableError(Exception):
@@ -240,6 +259,40 @@ def _alert_windows(start: datetime, end: datetime) -> Iterator[tuple[datetime, d
window_start = window_end
+def _window_start(value: Any, now: datetime, overlap: timedelta = timedelta(0)) -> datetime:
+ start = _parse_incremental_value(value)
+ if start is None or start > now:
+ return now - timedelta(days=DEFAULT_LOOKBACK_DAYS)
+ return start - overlap
+
+
+def _resumed_windows(
+ start: datetime,
+ now: datetime,
+ resume: MonteCarloResumeConfig | None,
+ logger: FilteringBoundLogger,
+ name: str,
+) -> tuple[list[Window], str | None]:
+ """Windows to walk from `start` (or the resumed window) to now, plus the cursor to resume the first one from."""
+ resume_cursor: str | None = None
+ pinned_before: datetime | None = None
+ if resume is not None and resume.window_after is not None:
+ resumed_after = _parse_incremental_value(resume.window_after)
+ if resumed_after is not None:
+ start = resumed_after
+ resume_cursor = resume.cursor
+ if resume.cursor and resume.window_before is not None:
+ pinned_before = _parse_incremental_value(resume.window_before)
+ logger.debug(f"Monte Carlo: resuming {name} from window_after={resume.window_after}")
+
+ windows = list(_alert_windows(start, now))
+ if pinned_before is not None and windows:
+ # Replay the interrupted window with its original upper bound so the saved cursor
+ # stays valid, then continue from that bound.
+ windows = [(windows[0][0], pinned_before), *list(_alert_windows(pinned_before, now))]
+ return windows, resume_cursor
+
+
def _get_alert_rows(
session: requests.Session,
config: MonteCarloEndpointConfig,
@@ -258,26 +311,8 @@ def _get_alert_rows(
filter_arg = "updatedTime" if filter_field == "updatedTime" else "createdTime"
now = datetime.now(UTC)
- start = _parse_incremental_value(db_incremental_field_last_value)
- if start is None or start > now:
- start = now - timedelta(days=DEFAULT_LOOKBACK_DAYS)
-
- resume_cursor: str | None = None
- pinned_before: datetime | None = None
- if resume is not None and resume.window_after is not None:
- resumed_after = _parse_incremental_value(resume.window_after)
- if resumed_after is not None:
- start = resumed_after
- resume_cursor = resume.cursor
- if resume.cursor and resume.window_before is not None:
- pinned_before = _parse_incremental_value(resume.window_before)
- logger.debug(f"Monte Carlo: resuming alerts from window_after={resume.window_after}")
-
- windows = list(_alert_windows(start, now))
- if pinned_before is not None and windows:
- # Replay the interrupted window with its original upper bound so the saved cursor
- # stays valid, then continue from that bound.
- windows = [(windows[0][0], pinned_before), *list(_alert_windows(pinned_before, now))]
+ start = _window_start(db_incremental_field_last_value, now)
+ windows, resume_cursor = _resumed_windows(start, now, resume, logger, config.name)
for index, (window_after, window_before) in enumerate(windows):
time_range = {"after": _format_datetime(window_after), "before": _format_datetime(window_before)}
@@ -300,6 +335,151 @@ def _get_alert_rows(
resumable_source_manager.save_state(MonteCarloResumeConfig(window_after=time_range["before"]))
+def _get_dbt_test_result_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]]]:
+ """getDbtTestResults requires a run start time range, so walk windows oldest-first like alerts."""
+ now = datetime.now(UTC)
+ start = _window_start(db_incremental_field_last_value, now, overlap=DBT_TEST_RESULTS_OVERLAP)
+ windows, resume_cursor = _resumed_windows(start, now, resume, logger, config.name)
+
+ for window_after, window_before in windows:
+ run_start_time = _format_datetime(window_after)
+ run_end_time = _format_datetime(window_before)
+ cursor = resume_cursor
+ resume_cursor = None
+
+ # Every earlier window is fully yielded, so this window is where a resume starts.
+ resumable_source_manager.save_state(
+ MonteCarloResumeConfig(cursor=cursor, window_after=run_start_time, window_before=run_end_time)
+ )
+ resumable_source_manager.safe_point()
+
+ variables = {"runStartTime": run_start_time, "runEndTime": run_end_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=run_start_time, window_before=run_end_time)
+ )
+ yield rows
+
+
+def _iter_monitor_uuids(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ monitor_types: list[str] | None,
+ start_offset: int,
+) -> Iterator[tuple[int, str]]:
+ """Yield (position, uuid) for each monitor, starting at `start_offset` in the monitor list."""
+ offset = start_offset
+ while True:
+ variables: dict[str, Any] = {"limit": MONITOR_PAGE_SIZE, "offset": offset}
+ if monitor_types is not None:
+ variables["monitorTypes"] = monitor_types
+ monitors = _execute_query(session, MONITOR_UUIDS_QUERY, variables, logger).get("getMonitors") or []
+ for index, monitor in enumerate(monitors):
+ if monitor and monitor.get("uuid"):
+ yield offset + index, monitor["uuid"]
+ if len(monitors) < MONITOR_PAGE_SIZE:
+ break
+ offset += len(monitors)
+
+
+def _get_fh_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]]]:
+ """Fan out over metric monitors. getFhEventsByMonitor requires a time range, so each monitor
+ walks the same windows as alerts."""
+ now = datetime.now(UTC)
+ start = _window_start(db_incremental_field_last_value, now, overlap=FH_EVENTS_OVERLAP)
+ start_offset = 0
+ if resume is not None and resume.window_after is not None:
+ resumed_after = _parse_incremental_value(resume.window_after)
+ if resumed_after is not None:
+ # Keep the original lower bound so monitors read before the resume and after it agree.
+ start = resumed_after
+ start_offset = resume.offset or 0
+ logger.debug(f"Monte Carlo: resuming {config.name} from monitor offset {start_offset}")
+
+ start_time = _format_datetime(start)
+ windows = [(_format_datetime(after), _format_datetime(before)) for after, before in _alert_windows(start, now)]
+
+ for monitor_index, monitor_uuid in _iter_monitor_uuids(session, logger, FH_EVENT_MONITOR_TYPES, start_offset):
+ # Earlier monitors are fully yielded. A resume re-reads this monitor, and merge dedupes it.
+ resumable_source_manager.save_state(MonteCarloResumeConfig(offset=monitor_index, window_after=start_time))
+ resumable_source_manager.safe_point()
+
+ for window_after, window_before in windows:
+ offset = 0
+ while True:
+ variables = {
+ "monitorId": monitor_uuid,
+ "startTime": window_after,
+ "endTime": window_before,
+ "first": config.page_size,
+ "offset": offset,
+ }
+ data = _execute_query(session, config.query, variables, logger)
+ events = (data.get(config.data_path) or {}).get("events") or []
+ if events:
+ yield [{**event, "monitorUuid": monitor_uuid} for event in events]
+ else:
+ resumable_source_manager.safe_point()
+ if len(events) < config.page_size:
+ break
+ offset += len(events)
+
+
+def _get_job_execution_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]]]:
+ """Fan out over monitors. getJobExecutions only filters by a whole number of days back, so
+ incremental syncs ask for the days since the watermark."""
+ now = datetime.now(UTC)
+ start = _window_start(db_incremental_field_last_value, now, overlap=JOB_EXECUTIONS_OVERLAP)
+ history_days = max(1, math.ceil((now - start) / timedelta(days=1)))
+ start_offset = resume.offset if resume is not None and resume.offset else 0
+
+ for monitor_index, monitor_uuid in _iter_monitor_uuids(session, logger, None, start_offset):
+ # Earlier monitors are fully yielded. A resume re-reads this monitor, and merge dedupes it.
+ resumable_source_manager.save_state(MonteCarloResumeConfig(offset=monitor_index))
+ resumable_source_manager.safe_point()
+
+ variables = {"monitorUuid": monitor_uuid, "historyDays": history_days}
+ for rows, _next_cursor in _relay_pages(session, config, logger, variables, None):
+ yield [{**row, "monitorUuid": monitor_uuid} for row in rows]
+
+
+def _get_job_schedule_rows(
+ session: requests.Session,
+ config: MonteCarloEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ warehouses = _execute_query(session, WAREHOUSES_QUERY, {}, logger).get("getWarehouses") or []
+ for warehouse in warehouses:
+ if not warehouse or not warehouse.get("uuid"):
+ continue
+ data = _execute_query(session, config.query, {"resourceUuid": warehouse["uuid"]}, logger)
+ rows = data.get(config.data_path) or []
+ if rows:
+ yield rows
+
+
def get_rows(
api_key_id: str,
api_key_secret: str,
@@ -341,6 +521,22 @@ def get_rows(
resume,
db_incremental_field_last_value if should_use_incremental_field else None,
)
+ elif endpoint in ("dbt_test_results", "fh_events", "job_executions"):
+ read_rows = {
+ "dbt_test_results": _get_dbt_test_result_rows,
+ "fh_events": _get_fh_event_rows,
+ "job_executions": _get_job_execution_rows,
+ }[endpoint]
+ yield from read_rows(
+ session,
+ config,
+ logger,
+ resumable_source_manager,
+ resume,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ )
+ elif endpoint == "job_schedules":
+ yield from _get_job_schedule_rows(session, config, logger)
elif config.pagination == "relay":
yield from _get_relay_rows(session, config, logger, resumable_source_manager, resume)
elif config.pagination == "offset":
@@ -377,10 +573,11 @@ def monte_carlo_source(
incremental_field=incremental_field,
),
primary_keys=endpoint_config.primary_keys,
- # 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 in ("alerts", "events") else "asc",
+ # No incremental endpoint documents an ordering guarantee we could verify (and fan-out
+ # endpoints interleave monitors), 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_config.incremental_fields 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 950863a349e4..5cedac40886d 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
@@ -225,6 +225,130 @@ query PostHogGetDomains($first: Int!, $after: String) {
}
"""
+DBT_RUNS_QUERY = """
+query PostHogGetDbtRuns($first: Int!, $after: String) {
+ getDbtRuns(first: $first, after: $after) {
+ edges {
+ node {
+ id
+ uuid
+ dbtRunId
+ createdTime
+ updatedTime
+ generatedAt
+ startedAt
+ command
+ branch
+ hasLogs
+ dbtProject { uuid projectName }
+ job { uuid jobId jobName mcon }
+ jobExecution { uuid status startedAt finishedAt displayName }
+ }
+ }
+ pageInfo { endCursor hasNextPage }
+ }
+}
+"""
+
+DBT_TEST_RESULTS_QUERY = """
+query PostHogGetDbtTestResults($first: Int!, $after: String, $runStartTime: DateTime!, $runEndTime: DateTime!) {
+ getDbtTestResults(first: $first, after: $after, runStartTime: $runStartTime, runEndTime: $runEndTime) {
+ edges {
+ node {
+ runUuid
+ nodeId
+ nodeName
+ runStartedAt
+ startedAt
+ executionTime
+ status
+ mcon
+ jobName
+ jobMcon
+ command
+ modelId
+ modelName
+ }
+ }
+ pageInfo { endCursor hasNextPage }
+ }
+}
+"""
+
+MONITOR_UUIDS_QUERY = """
+query PostHogGetMonitorUuids($limit: Int!, $offset: Int!, $monitorTypes: [UserDefinedMonitors]) {
+ getMonitors(limit: $limit, offset: $offset, monitorTypes: $monitorTypes) {
+ uuid
+ }
+}
+"""
+
+FH_EVENTS_QUERY = """
+query PostHogGetFhEventsByMonitor($monitorId: UUID!, $startTime: DateTime!, $endTime: DateTime!, $first: Int!, $offset: Int!) {
+ getFhEventsByMonitor(monitorId: $monitorId, startTime: $startTime, endTime: $endTime, first: $first, offset: $offset, descOrder: false) {
+ events {
+ eventUuid
+ alertUuid
+ eventType
+ date
+ metric
+ field
+ whereCondition
+ value
+ lowerThreshold
+ upperThreshold
+ thresholdType
+ comparisonOperator
+ autoOperator
+ historicalMean
+ aggTimeInterval
+ customMetricDisplayName
+ customMetricSqlExpression
+ timeSeriesUuid
+ parentTimeSeriesUuid
+ detectorFeedback { id reason }
+ }
+ }
+}
+"""
+
+JOB_EXECUTIONS_QUERY = """
+query PostHogGetJobExecutions($monitorUuid: String!, $historyDays: Int!, $first: Int!, $after: String) {
+ getJobExecutions(monitorUuid: $monitorUuid, historyDays: $historyDays, first: $first, after: $after) {
+ edges {
+ node {
+ jobExecutionUuid
+ startTime
+ endTime
+ status
+ exceptions
+ tableMonitorWarning
+ sizeCollectionTableMcon
+ sizeCollectionEnabled
+ totalInvocationsCount
+ totalResultCount
+ totalExecutionDuration
+ consolidatingJobUuid
+ }
+ }
+ pageInfo { endCursor hasNextPage }
+ }
+}
+"""
+
+JOB_SCHEDULES_QUERY = """
+query PostHogGetJobSchedules($resourceUuid: String!) {
+ getJobSchedules(resourceUuid: $resourceUuid) {
+ uuid
+ resourceId
+ connectionId
+ internalJobType
+ limits
+ intervalInSeconds
+ }
+}
+"""
+
VALIDATE_CREDENTIALS_QUERY = """
query PostHogValidateCredentials {
getUser { email }
@@ -271,6 +395,31 @@ MONTE_CARLO_ENDPOINTS: dict[str, MonteCarloEndpointConfig] = {
},
],
),
+ "dbt_runs": MonteCarloEndpointConfig(
+ name="dbt_runs",
+ query=DBT_RUNS_QUERY,
+ data_path="getDbtRuns",
+ pagination="relay",
+ primary_keys=["uuid"],
+ partition_key="createdTime",
+ ),
+ "dbt_test_results": MonteCarloEndpointConfig(
+ name="dbt_test_results",
+ query=DBT_TEST_RESULTS_QUERY,
+ data_path="getDbtTestResults",
+ pagination="relay",
+ # A dbt invocation runs each test node once, and results carry no id of their own.
+ primary_keys=["runUuid", "nodeId"],
+ default_incremental_field="runStartedAt",
+ incremental_fields=[
+ {
+ "label": "runStartedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "runStartedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
"domains": MonteCarloEndpointConfig(
name="domains",
query=DOMAINS_QUERY,
@@ -294,6 +443,47 @@ MONTE_CARLO_ENDPOINTS: dict[str, MonteCarloEndpointConfig] = {
},
],
),
+ "fh_events": MonteCarloEndpointConfig(
+ name="fh_events",
+ query=FH_EVENTS_QUERY,
+ data_path="getFhEventsByMonitor",
+ pagination="offset",
+ primary_keys=["monitorUuid", "eventUuid"],
+ default_incremental_field="date",
+ partition_key="date",
+ incremental_fields=[
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ page_size=1000,
+ ),
+ "job_executions": MonteCarloEndpointConfig(
+ name="job_executions",
+ query=JOB_EXECUTIONS_QUERY,
+ data_path="getJobExecutions",
+ pagination="relay",
+ primary_keys=["monitorUuid", "jobExecutionUuid"],
+ default_incremental_field="startTime",
+ incremental_fields=[
+ {
+ "label": "startTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "startTime",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "job_schedules": MonteCarloEndpointConfig(
+ name="job_schedules",
+ query=JOB_SCHEDULES_QUERY,
+ data_path="getJobSchedules",
+ pagination="none",
+ primary_keys=["uuid"],
+ ),
"monitors": MonteCarloEndpointConfig(
name="monitors",
query=MONITORS_QUERY,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/source.py
index c6c5884f6c59..74ef5d17f2f7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/source.py
@@ -107,7 +107,7 @@ You can create an API key from **Settings → API → Keys** in your Monte Carlo
api_version: str | None = None,
) -> list[SourceSchema]:
def _description(endpoint: str) -> str | None:
- if endpoint == "alerts":
+ if endpoint in ("alerts", "dbt_test_results", "fh_events", "job_executions"):
return "Only syncs the last 365 days on initial sync"
return None
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 65dc68e7cf64..2509aeebc5c1 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
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import UTC, datetime
import pytest
@@ -8,6 +9,7 @@ import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ RecordedRequest,
ScriptedResponse,
SourceDriver,
always,
@@ -17,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
MonteCarloSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.monte_carlo import (
+ MONITOR_PAGE_SIZE,
MonteCarloGraphQLError,
MonteCarloResumeConfig,
_execute_query,
@@ -43,6 +46,15 @@ def _response(data: dict) -> ScriptedResponse:
return ScriptedResponse(json={"data": data})
+def _by_operation(answers: dict[str, Callable[[dict], dict]]) -> Callable[[RecordedRequest], ScriptedResponse]:
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ body = request.json()
+ operation = body["query"].split("query ", 1)[1].split("(", 1)[0].split()[0]
+ return _response(answers[operation](body["variables"]))
+
+ return respond
+
+
class TestExecuteQuery:
def _response(self, status_code: int, payload: dict | None = None) -> MagicMock:
response = MagicMock()
@@ -106,7 +118,14 @@ class TestValidateCredentials:
class TestRelayEndpoints:
- @parameterized.expand([("domains", "getDomainsV2"), ("tables", "getTables"), ("users", "getUsersInAccount")])
+ @parameterized.expand(
+ [
+ ("dbt_runs", "getDbtRuns"),
+ ("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"),
@@ -299,12 +318,238 @@ class TestAlertsWindowing:
assert result.requests[1].json()["variables"]["createdTime"]["after"] == "2026-07-01T00:00:00Z"
+class TestDbtTestResultsWindowing:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-15T12:00:00Z", tick=False):
+ yield
+
+ @parameterized.expand(
+ [
+ ("first_sync", True, None, 13, "2025-07-15T12:00:00Z"),
+ # Re-reads two days before the watermark so late-arriving test results are not skipped.
+ ("incremental", True, datetime(2026, 6, 1, tzinfo=UTC), 2, "2026-05-30T00:00:00Z"),
+ ("full_refresh_ignores_watermark", False, datetime(2026, 6, 1, tzinfo=UTC), 13, "2025-07-15T12:00:00Z"),
+ ]
+ )
+ def test_walks_run_start_windows_to_now(
+ self,
+ _label: str,
+ use_incremental: bool,
+ watermark: datetime | None,
+ expected_windows: int,
+ expected_first_start: str,
+ ) -> None:
+ result = _driver().run(
+ "dbt_test_results",
+ always(_response(_relay_page("getDbtTestResults", [], None))),
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert result.raised is None
+ variables = [request.json()["variables"] for request in result.requests]
+ assert len(variables) == expected_windows
+ assert variables[0]["runStartTime"] == expected_first_start
+ assert variables[-1]["runEndTime"] == "2026-07-15T12:00:00Z"
+ # Windows are contiguous, so no run start falls between two of them.
+ for previous, current in zip(variables, variables[1:]):
+ assert current["runStartTime"] == previous["runEndTime"]
+
+ def test_stages_cursor_before_the_page_and_resumes_into_the_pinned_window(self) -> None:
+ responses = [
+ _relay_page("getDbtTestResults", [{"runUuid": "r-1", "nodeId": "test.a"}], "cursor-1"),
+ _relay_page("getDbtTestResults", [{"runUuid": "r-1", "nodeId": "test.b"}], None),
+ ]
+ first = _driver().run(
+ "dbt_test_results",
+ [_response(data) for data in responses],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 7, 1, tzinfo=UTC),
+ )
+
+ assert first.raised is None
+ assert [row["nodeId"] for row in first.rows] == ["test.a", "test.b"]
+ assert first.requests[1].json()["variables"]["after"] == "cursor-1"
+ assert (
+ MonteCarloResumeConfig(
+ cursor="cursor-1", window_after="2026-06-29T00:00:00Z", window_before="2026-07-15T12:00:00Z"
+ )
+ in first.committed_states
+ )
+
+ resumed = _driver().run(
+ "dbt_test_results",
+ [_response(_relay_page("getDbtTestResults", [], None))] * 2,
+ resume_state=MonteCarloResumeConfig(
+ cursor="cursor-9", window_after="2026-06-01T00:00:00Z", window_before="2026-07-01T00:00:00Z"
+ ),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 7, 10, tzinfo=UTC),
+ )
+
+ assert resumed.raised is None
+ variables = [request.json()["variables"] for request in resumed.requests]
+ assert variables[0] == {
+ "first": 100,
+ "after": "cursor-9",
+ "runStartTime": "2026-06-01T00:00:00Z",
+ "runEndTime": "2026-07-01T00:00:00Z",
+ }
+ assert variables[1]["after"] is None
+ assert variables[1]["runStartTime"] == "2026-07-01T00:00:00Z"
+
+
+class TestMonitorFanOut:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-15T12:00:00Z", tick=False):
+ yield
+
+ def test_fh_events_reads_each_metric_monitor_with_overlap_and_offset_pages(self) -> None:
+ page_size = MONTE_CARLO_ENDPOINTS["fh_events"].page_size
+ full_page = [{"eventUuid": f"e-{i}"} for i in range(page_size)]
+
+ def events(variables: dict) -> dict:
+ if variables["monitorId"] == "m-1" and variables["offset"] == 0:
+ return {"getFhEventsByMonitor": {"events": full_page}}
+ if variables["monitorId"] == "m-1":
+ return {"getFhEventsByMonitor": {"events": [{"eventUuid": "e-last"}]}}
+ return {"getFhEventsByMonitor": {"events": []}}
+
+ result = _driver().run(
+ "fh_events",
+ _by_operation(
+ {
+ "PostHogGetMonitorUuids": lambda _: {"getMonitors": [{"uuid": "m-1"}, {"uuid": "m-2"}]},
+ "PostHogGetFhEventsByMonitor": events,
+ }
+ ),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 7, 10, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert len(result.rows) == page_size + 1
+ assert {row["monitorUuid"] for row in result.rows} == {"m-1"}
+ monitor_list, *event_requests = [request.json()["variables"] for request in result.requests]
+ assert monitor_list["monitorTypes"] == ["STATS"]
+ assert [(v["monitorId"], v["offset"]) for v in event_requests] == [("m-1", 0), ("m-1", page_size), ("m-2", 0)]
+ # Re-reads two days before the watermark so late metric points are not skipped.
+ assert {v["startTime"] for v in event_requests} == {"2026-07-08T00:00:00Z"}
+ assert {v["endTime"] for v in event_requests} == {"2026-07-15T12:00:00Z"}
+ assert result.saved_states[-1] == MonteCarloResumeConfig(offset=1, window_after="2026-07-08T00:00:00Z")
+
+ def test_fh_events_resume_starts_at_saved_monitor_and_start_time(self) -> None:
+ result = _driver().run(
+ "fh_events",
+ _by_operation(
+ {
+ "PostHogGetMonitorUuids": lambda _: {"getMonitors": [{"uuid": "m-5"}]},
+ "PostHogGetFhEventsByMonitor": lambda _: {"getFhEventsByMonitor": {"events": []}},
+ }
+ ),
+ resume_state=MonteCarloResumeConfig(offset=4, window_after="2026-07-01T00:00:00Z"),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 7, 10, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ variables = [request.json()["variables"] for request in result.requests]
+ assert variables[0]["offset"] == 4
+ assert variables[1]["startTime"] == "2026-07-01T00:00:00Z"
+
+ @parameterized.expand(
+ [
+ # One extra day of overlap for jobs that finished after the last sync.
+ ("incremental", True, datetime(2026, 7, 10, 18, tzinfo=UTC), 6),
+ ("first_sync", True, None, 365),
+ ("full_refresh_ignores_watermark", False, datetime(2026, 7, 10, tzinfo=UTC), 365),
+ ]
+ )
+ def test_job_executions_asks_for_days_since_watermark_per_monitor(
+ self, _label: str, use_incremental: bool, watermark: datetime | None, expected_days: int
+ ) -> None:
+ def executions(variables: dict) -> dict:
+ node = {"jobExecutionUuid": f"x-{variables['monitorUuid']}"}
+ return _relay_page("getJobExecutions", [node], None)
+
+ result = _driver().run(
+ "job_executions",
+ _by_operation(
+ {
+ "PostHogGetMonitorUuids": lambda _: {"getMonitors": [{"uuid": "m-1"}, {"uuid": "m-2"}]},
+ "PostHogGetJobExecutions": executions,
+ }
+ ),
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert result.raised is None
+ assert [(row["monitorUuid"], row["jobExecutionUuid"]) for row in result.rows] == [
+ ("m-1", "x-m-1"),
+ ("m-2", "x-m-2"),
+ ]
+ monitor_list, *execution_requests = [request.json()["variables"] for request in result.requests]
+ assert "monitorTypes" not in monitor_list
+ assert {v["historyDays"] for v in execution_requests} == {expected_days}
+
+ def test_monitor_list_pages_until_short_page(self) -> None:
+ full_page = [{"uuid": f"m-{i}"} for i in range(MONITOR_PAGE_SIZE)]
+
+ def monitors(variables: dict) -> dict:
+ return {"getMonitors": full_page if variables["offset"] == 0 else []}
+
+ result = _driver().run(
+ "job_executions",
+ _by_operation(
+ {
+ "PostHogGetMonitorUuids": monitors,
+ "PostHogGetJobExecutions": lambda _: _relay_page("getJobExecutions", [], None),
+ }
+ ),
+ )
+
+ assert result.raised is None
+ monitor_offsets = [
+ request.json()["variables"]["offset"]
+ for request in result.requests
+ if "PostHogGetMonitorUuids" in request.json()["query"]
+ ]
+ assert monitor_offsets == [0, MONITOR_PAGE_SIZE]
+ assert len(result.requests) == MONITOR_PAGE_SIZE + 2
+
+ def test_job_schedules_reads_each_warehouse(self) -> None:
+ result = _driver().run(
+ "job_schedules",
+ _by_operation(
+ {
+ "PostHogGetWarehouses": lambda _: {"getWarehouses": [{"uuid": "w-1"}, {"uuid": "w-2"}]},
+ "PostHogGetJobSchedules": lambda v: {
+ "getJobSchedules": [] if v["resourceUuid"] == "w-1" else [{"uuid": "s-1", "resourceId": "w-2"}]
+ },
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert result.rows == [{"uuid": "s-1", "resourceId": "w-2"}]
+ assert [request.json()["variables"] for request in result.requests[1:]] == [
+ {"resourceUuid": "w-1"},
+ {"resourceUuid": "w-2"},
+ ]
+
+
class TestSourceResponse:
@parameterized.expand(
[
("alerts", ["uuid"], "desc"),
+ ("dbt_test_results", ["runUuid", "nodeId"], "desc"),
("domains", ["id"], "asc"),
("events", ["uuid"], "desc"),
+ ("fh_events", ["monitorUuid", "eventUuid"], "desc"),
+ ("job_executions", ["monitorUuid", "jobExecutionUuid"], "desc"),
("monitors", ["uuid"], "asc"),
("tables", ["id"], "asc"),
("users", ["id"], "asc"),
@@ -312,9 +557,12 @@ class TestSourceResponse:
]
)
def test_primary_keys_and_sort_mode(self, endpoint: str, primary_keys: list[str], sort_mode: str) -> None:
- if endpoint == "alerts":
+ if endpoint in ("alerts", "dbt_test_results"):
+ data_path = "getAlerts" if endpoint == "alerts" else "getDbtTestResults"
with time_machine.travel("2026-07-15T12:00:00Z", tick=False):
- result = _driver().run(endpoint, always(_response(_relay_page("getAlerts", [], None))))
+ result = _driver().run(endpoint, always(_response(_relay_page(data_path, [], None))))
+ elif endpoint in ("fh_events", "job_executions"):
+ result = _driver().run(endpoint, [_response({"getMonitors": []})])
elif endpoint in ("monitors", "warehouses"):
data_path = "getMonitors" if endpoint == "monitors" else "getWarehouses"
result = _driver().run(endpoint, [_response({data_path: []})])
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 81b2c006ef5a..a8989dc0ba64 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
@@ -22,8 +22,13 @@ class TestMonteCarloSource:
@parameterized.expand(
[
("alerts", True),
+ ("dbt_runs", False),
+ ("dbt_test_results", True),
("domains", False),
("events", True),
+ ("fh_events", True),
+ ("job_executions", True),
+ ("job_schedules", False),
("monitors", False),
("tables", False),
("users", False),