: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): implement monte_carlo import source (#71247)
Tom Owersa8576d099f19
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1df503dca6fe..b08210cdef42 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -322,6 +322,7 @@ the row lists both.| mollie | HTTP | requests | ✅ || monday | HTTP (GraphQL) | requests | ✅ || mongodb | DB protocol | pymongo | ➖ |+| monte_carlo | HTTP (GraphQL) | requests | ✅ || mssql | DB protocol | pyodbc / pymssql | ➖ || mux | HTTP | requests | ✅ || my_hours | HTTP | requests | ✅ |@@ -789,7 +790,6 @@ doesn't conflict with concurrent PRs.- missive- mode- mono-- monte_carlo- nasa- navan- neondiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 2d5688e98430..24e6f61d2fb9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2753,7 +2753,8 @@ class MonoSourceConfig(config.Config):@config.configclass MonteCarloSourceConfig(config.Config):- pass+ api_key_id: str+ api_key_secret: str@config.configdiff --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.pynew file mode 100644index 000000000000..c815adc08c69--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/canonical_descriptions.py@@ -0,0 +1,145 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "alerts": {+ "description": "Data quality alerts raised by Monte Carlo monitors — a collection of related anomaly events with severity, status, and triage metadata.",+ "docs_url": "https://docs.getmontecarlo.com/docs/interacting-with-incidents",+ "columns": {+ "uuid": "Unique identifier for the alert.",+ "title": "Human-readable title of the alert.",+ "name": "Internal name of the alert.",+ "type": "Type of alert (e.g. anomalies, schema changes, custom rule breaches).",+ "subTypes": "More specific alert sub-types (e.g. freshness_anomaly, volume_anomaly).",+ "status": "Current status of the alert (e.g. acknowledged, resolved, expected).",+ "severity": "Severity assigned to the alert. Present when the alert has been marked as an incident.",+ "priority": "Priority inherited from the associated monitor.",+ "triagePriority": "Consolidated triage priority derived from the latest triage run.",+ "feedback": "User feedback recorded on the alert.",+ "createdTime": "When the alert was created.",+ "updatedTime": "When the alert was last updated.",+ "sloStatus": "Status of the alert against its service level objective.",+ "sloType": "Type of service level objective associated with the alert.",+ "sloBreachedTime": "When the alert breached its service level objective.",+ "url": "Link to the alert in the Monte Carlo UI.",+ "commentCount": "Number of comments on the alert.",+ "lastCommentText": "Text of the most recent comment.",+ "invalidRows": "Count of invalid rows detected, where applicable.",+ "monitorUuids": "UUIDs of the monitors that produced this alert.",+ "owner": "User the alert is assigned to (email and full name).",+ "tables": "Tables affected by the alert (MCON, table id, key-asset flag).",+ "assets": "Assets affected by the alert (MCON, asset id, asset type).",+ "audiences": "Audiences notified about the alert.",+ "monitorTags": "Tags on the monitors that produced this alert.",+ },+ },+ "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",+ "columns": {+ "uuid": "Unique identifier for the monitor.",+ "monitorType": "Type of monitor (e.g. stats, categories, custom SQL).",+ "udmType": "User-defined monitor category (rule, monitor, table monitor, bulk monitor).",+ "createdTime": "When the monitor was created (UTC).",+ "lastUpdateTime": "When the monitor was last updated (UTC).",+ "creatorId": "Identifier of the user who created the monitor.",+ "updaterId": "Identifier of the user who last updated the monitor.",+ "resourceId": "UUID of the warehouse/resource the monitor runs against.",+ "entities": "Entities (tables or views) the monitor watches.",+ "entityMcons": "MCONs of the entities the monitor watches.",+ "entityCount": "Number of entities the monitor watches.",+ "scheduleType": "How the monitor is scheduled (e.g. fixed, dynamic).",+ "name": "Name of the monitor.",+ "ruleName": "Name of the underlying rule.",+ "description": "Description of the monitor.",+ "notes": "Free-form notes on the monitor.",+ "labels": "Labels applied to the monitor.",+ "severity": "Default severity for alerts raised by this monitor.",+ "priority": "Priority assigned to the monitor.",+ "isSnoozeable": "Whether the monitor can be snoozed.",+ "isPaused": "Whether the monitor is currently paused.",+ "isDraft": "Whether the monitor is a draft.",+ "isTemplateManaged": "Whether the monitor is managed as code via monitors-as-code.",+ "namespace": "Monitors-as-code namespace the monitor belongs to.",+ "nextExecutionTime": "When the monitor is next scheduled to run.",+ "prevExecutionTime": "When the monitor last ran.",+ "connectionId": "UUID of the connection the monitor uses.",+ "isOotbMonitor": "Whether this is an out-of-the-box monitor.",+ "monitorRunStatus": "Status of the monitor's most recent run.",+ "monitorStatus": "Consolidated status of the monitor.",+ "consolidatedMonitorStatus": "Overall status combining run, configuration, and training state.",+ "exceptions": "Details of any exceptions from the monitor's last run.",+ },+ },+ "tables": {+ "description": "Tables and views Monte Carlo observes across your connected warehouses, with health and activity metadata.",+ "docs_url": "https://docs.getmontecarlo.com/docs/assets",+ "columns": {+ "id": "Globally unique identifier for the table record.",+ "mcon": "Monte Carlo object name — the global identifier for the asset.",+ "tableId": "Table identifier within its project and dataset.",+ "fullTableId": "Fully qualified table identifier (project:dataset.table).",+ "discoveredTime": "When Monte Carlo first discovered the table.",+ "friendlyName": "Display name for the table.",+ "location": "Physical location of the table, where applicable.",+ "projectName": "Project or database the table belongs to.",+ "dataset": "Dataset or schema the table belongs to.",+ "description": "Description of the table.",+ "tableType": "Type of the asset (e.g. table, view, external).",+ "isEncrypted": "Whether the table is encrypted.",+ "createdTime": "When the table was created in the warehouse.",+ "lastModified": "When the table was last modified.",+ "viewIsMaterialized": "Whether the view is materialized.",+ "path": "Storage path of the table, where applicable.",+ "priority": "Priority assigned to the table.",+ "tracked": "Whether Monte Carlo tracks this table.",+ "dynamicTable": "Whether this is a dynamic table.",+ "isDeleted": "Whether the table has been deleted from the warehouse.",+ "deletedAt": "When the table was deleted.",+ "lastObserved": "When Monte Carlo last observed the table.",+ "isExcluded": "Whether the table is excluded from monitoring.",+ "isMonitored": "Whether the table is actively monitored.",+ "dataProvider": "Data provider backing the table.",+ "ingestType": "How metadata for the table is ingested.",+ "importanceScore": "Monte Carlo's computed importance score for the table.",+ "isImportant": "Whether the table is flagged as a key asset.",+ "lastActivity": "Most recent activity observed on the table.",+ "lastRead": "Most recent read observed on the table.",+ "lastWrite": "Most recent write observed on the table.",+ "lastVolumeChange": "Most recent volume change observed on the table.",+ "warehouse": "Warehouse the table belongs to (UUID and name).",+ },+ },+ "users": {+ "description": "Users in your Monte Carlo account, useful for attributing alert ownership and monitor authorship.",+ "docs_url": "https://docs.getmontecarlo.com/docs/authorization-overview",+ "columns": {+ "id": "Globally unique identifier for the user record.",+ "cognitoUserId": "Authentication provider identifier for the user.",+ "email": "Email address of the user.",+ "firstName": "First name of the user.",+ "lastName": "Last name of the user.",+ "displayName": "Display name of the user.",+ "state": "Account state of the user (e.g. active, pending).",+ "createdOn": "When the user was created.",+ "isSso": "Whether the user signs in via SSO.",+ "isDeleted": "Whether the user has been removed from the account.",+ "deletedAt": "When the user was removed.",+ },+ },+ "warehouses": {+ "description": "Warehouse connections integrated with Monte Carlo (e.g. Snowflake, BigQuery, Redshift).",+ "docs_url": "https://docs.getmontecarlo.com/docs/integrations-overview",+ "columns": {+ "uuid": "Unique identifier for the warehouse connection.",+ "name": "Name of the warehouse connection.",+ "connectionType": "Type of the warehouse (e.g. snowflake, bigquery, redshift).",+ "createdTime": "When the warehouse connection was created.",+ "updatedTime": "When the warehouse connection was last updated.",+ "isDeleted": "Whether the warehouse connection has been deleted.",+ "deletedAt": "When the warehouse connection was deleted.",+ "bqProjectId": "BigQuery project id, for BigQuery connections.",+ },+ },+}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.pynew file mode 100644index 000000000000..fcd2ff20a54a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/monte_carlo.py@@ -0,0 +1,353 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.settings import (+ MONTE_CARLO_ENDPOINTS,+ VALIDATE_CREDENTIALS_QUERY,+ MonteCarloEndpointConfig,+)++MONTE_CARLO_GRAPHQL_URL = "https://api.getmontecarlo.com/graphql"+REQUEST_TIMEOUT_SECONDS = 60+# getAlerts requires a createdTime/updatedTime range and caps it at 2 months; we walk+# smaller windows so a single filter never risks tripping the server-side limit.+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+++class MonteCarloRetryableError(Exception):+ pass+++class MonteCarloGraphQLError(Exception):+ pass+++class MonteCarloResumeConfig:+ # Relay `endCursor` (or, for offset-paginated endpoints, unused) to resume pagination from.+ cursor: str | None = None+ # Row offset for offset-paginated endpoints (monitors).+ offset: int | None = None+ # In-flight alerts time window. Both bounds are pinned so a resumed cursor is replayed+ # against the exact filter it was issued for — a shifted `before` would change page+ # contents under the cursor.+ window_after: str | None = None+ window_before: str | None = None+++def _get_headers(api_key_id: str, api_key_secret: str) -> dict[str, str]:+ return {+ "x-mcd-id": api_key_id,+ "x-mcd-token": api_key_secret,+ "Content-Type": "application/json",+ }+++def _format_datetime(dt: datetime) -> str:+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S") + "Z"+++def _parse_incremental_value(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(UTC)+ except ValueError:+ return None+ return None+++@retry(+ retry=retry_if_exception_type(+ (+ MonteCarloRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _execute_query(+ session: requests.Session,+ query: str,+ variables: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.post(+ MONTE_CARLO_GRAPHQL_URL,+ json={"query": query, "variables": variables},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ # Monte Carlo publishes no rate-limit headers; treat 429 and transient 5xx as retryable.+ if response.status_code == 429 or response.status_code >= 500:+ raise MonteCarloRetryableError(f"Monte Carlo API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error(f"Monte Carlo API error: status={response.status_code}, body={response.text[:500]}")+ response.raise_for_status()++ payload = response.json()+ errors = payload.get("errors")+ if errors:+ messages = "; ".join(str(error.get("message", error)) for error in errors)+ raise MonteCarloGraphQLError(f"Monte Carlo GraphQL error: {messages}")++ return payload.get("data") or {}+++def validate_credentials(api_key_id: str, api_key_secret: str) -> bool:+ # Both credentials ride in nonstandard x-mcd-* headers the tracked transport's denylist+ # can't recognise, so redact them explicitly from captured samples. allow_redirects=False+ # keeps those headers from being forwarded across a cross-host redirect.+ session = make_tracked_session(+ headers=_get_headers(api_key_id, api_key_secret),+ redact_values=(api_key_id, api_key_secret),+ allow_redirects=False,+ )+ try:+ response = session.post(+ MONTE_CARLO_GRAPHQL_URL,+ json={"query": VALIDATE_CREDENTIALS_QUERY, "variables": {}},+ timeout=30,+ )+ if response.status_code != 200:+ return False+ return not response.json().get("errors")+ except Exception:+ return False+++def _relay_pages(+ session: requests.Session,+ config: MonteCarloEndpointConfig,+ logger: FilteringBoundLogger,+ extra_variables: dict[str, Any],+ cursor: str | None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield (rows, next_cursor) per page. next_cursor is None on the final page."""+ while True:+ variables: dict[str, Any] = {"first": config.page_size, "after": cursor, **extra_variables}+ data = _execute_query(session, config.query, variables, logger)+ connection = data.get(config.data_path) or {}+ rows = [edge["node"] for edge in connection.get("edges") or [] if edge.get("node")]+ page_info = connection.get("pageInfo") or {}+ next_cursor = page_info.get("endCursor") if page_info.get("hasNextPage") else None++ if rows:+ yield rows, next_cursor+ if not next_cursor:+ break+ cursor = next_cursor+++def _get_relay_rows(+ session: requests.Session,+ config: MonteCarloEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MonteCarloResumeConfig],+ resume: MonteCarloResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ cursor = resume.cursor if resume else None+ if cursor:+ logger.debug(f"Monte Carlo: resuming {config.name} from cursor {cursor}")++ for rows, next_cursor in _relay_pages(session, config, logger, {}, cursor):+ yield rows+ # Save AFTER yielding so a crash re-yields the last page instead of skipping it —+ # merge dedupes on the primary key.+ if next_cursor:+ resumable_source_manager.save_state(MonteCarloResumeConfig(cursor=next_cursor))+++def _get_offset_rows(+ session: requests.Session,+ config: MonteCarloEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MonteCarloResumeConfig],+ resume: MonteCarloResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ offset = resume.offset if resume and resume.offset else 0+ if offset:+ logger.debug(f"Monte Carlo: resuming {config.name} from offset {offset}")++ while True:+ variables = {"limit": config.page_size, "offset": offset}+ data = _execute_query(session, config.query, variables, logger)+ rows = data.get(config.data_path) or []+ if not rows:+ break++ yield rows++ if len(rows) < config.page_size:+ break+ offset += len(rows)+ resumable_source_manager.save_state(MonteCarloResumeConfig(offset=offset))+++def _alert_windows(start: datetime, end: datetime) -> Iterator[tuple[datetime, datetime]]:+ window_start = start+ while window_start < end:+ window_end = min(window_start + ALERT_WINDOW, end)+ yield window_start, window_end+ window_start = window_end+++def _get_alert_rows(+ session: requests.Session,+ config: MonteCarloEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MonteCarloResumeConfig],+ resume: MonteCarloResumeConfig | None,+ incremental_field: str | None,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Walk getAlerts oldest-window-first. The API requires a created/updated time range per+ query (capped at 2 months), so both the initial backfill and incremental syncs page a+ rolling window forward to now."""+ filter_field = incremental_field or config.default_incremental_field+ # getAlerts filters on createdTime or updatedTime only; anything else would silently+ # window the wrong column, so fall back to the default.+ 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))]++ for index, (window_after, window_before) in enumerate(windows):+ time_range = {"after": _format_datetime(window_after), "before": _format_datetime(window_before)}+ cursor = resume_cursor+ resume_cursor = None # only the resumed-into window starts from the saved cursor++ for rows, next_cursor in _relay_pages(session, config, logger, {filter_arg: time_range}, cursor):+ yield rows+ if next_cursor:+ resumable_source_manager.save_state(+ MonteCarloResumeConfig(+ cursor=next_cursor,+ window_after=time_range["after"],+ window_before=time_range["before"],+ )+ )++ # Bookmark the next window so a crash between windows doesn't restart the backfill.+ if index + 1 < len(windows):+ resumable_source_manager.save_state(MonteCarloResumeConfig(window_after=time_range["before"]))+++def get_rows(+ api_key_id: str,+ api_key_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MonteCarloResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = MONTE_CARLO_ENDPOINTS[endpoint]+ # One session reused across every page so urllib3 keeps the connection alive. Redact both+ # credentials (they travel in nonstandard x-mcd-* headers the denylist can't recognise) from+ # captured samples, and pin redirects off so the headers aren't forwarded cross-host.+ session = make_tracked_session(+ headers=_get_headers(api_key_id, api_key_secret),+ redact_values=(api_key_id, api_key_secret),+ allow_redirects=False,+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if endpoint == "alerts":+ yield from _get_alert_rows(+ session,+ config,+ logger,+ resumable_source_manager,+ resume,+ incremental_field if should_use_incremental_field else None,+ 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":+ yield from _get_offset_rows(session, config, logger, resumable_source_manager, resume)+ else:+ data = _execute_query(session, config.query, {}, logger)+ rows = data.get(config.data_path) or []+ if rows:+ yield rows+++def monte_carlo_source(+ api_key_id: str,+ api_key_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MonteCarloResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = MONTE_CARLO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key_id=api_key_id,+ api_key_secret=api_key_secret,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ 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+ # than checkpointed per batch against an assumed ascending order.+ sort_mode="desc" if endpoint == "alerts" 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,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] 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.pynew file mode 100644index 000000000000..7525dbd239ce--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/settings.py@@ -0,0 +1,249 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Selection sets stick to fields verified against Monte Carlo's published GraphQL schema+# (the one bundled with their pycarlo SDK). Nested objects are limited to small, stable+# reference types so a schema change on a rich sub-object can't break the whole stream.++ALERTS_QUERY = """+query PostHogGetAlerts($first: Int!, $after: String, $createdTime: DateTimeRangeInput, $updatedTime: DateTimeRangeInput) {+ getAlerts(first: $first, after: $after, createdTime: $createdTime, updatedTime: $updatedTime) {+ edges {+ node {+ uuid+ title+ name+ type+ subTypes+ status+ severity+ priority+ triagePriority+ feedback+ createdTime+ updatedTime+ sloStatus+ sloType+ sloBreachedTime+ url+ commentCount+ lastCommentText+ invalidRows+ monitorUuids+ owner { email fullName }+ tables { mcon tableId isKeyAsset }+ assets { mcon assetId assetType }+ audiences { uuid label }+ monitorTags { name value }+ }+ }+ pageInfo { endCursor hasNextPage }+ }+}+"""++MONITORS_QUERY = """+query PostHogGetMonitors($limit: Int!, $offset: Int!) {+ getMonitors(limit: $limit, offset: $offset) {+ uuid+ monitorType+ udmType+ createdTime+ lastUpdateTime+ creatorId+ updaterId+ resourceId+ entities+ entityMcons+ entityCount+ scheduleType+ name+ ruleName+ description+ notes+ labels+ severity+ priority+ isSnoozeable+ isPaused+ isDraft+ isTemplateManaged+ namespace+ nextExecutionTime+ prevExecutionTime+ connectionId+ isOotbMonitor+ monitorRunStatus+ monitorStatus+ consolidatedMonitorStatus+ exceptions+ }+}+"""++TABLES_QUERY = """+query PostHogGetTables($first: Int!, $after: String) {+ getTables(first: $first, after: $after) {+ edges {+ node {+ id+ mcon+ tableId+ fullTableId+ discoveredTime+ friendlyName+ location+ projectName+ dataset+ description+ tableType+ isEncrypted+ createdTime+ lastModified+ viewIsMaterialized+ path+ priority+ tracked+ dynamicTable+ isDeleted+ deletedAt+ lastObserved+ isExcluded+ isMonitored+ dataProvider+ ingestType+ importanceScore+ isImportant+ lastActivity+ lastRead+ lastWrite+ lastVolumeChange+ warehouse { uuid name }+ }+ }+ pageInfo { endCursor hasNextPage }+ }+}+"""++USERS_QUERY = """+query PostHogGetUsers($first: Int!, $after: String) {+ getUsersInAccount(first: $first, after: $after) {+ edges {+ node {+ id+ cognitoUserId+ firstName+ lastName+ displayName+ state+ createdOn+ isSso+ isDeleted+ deletedAt+ }+ }+ pageInfo { endCursor hasNextPage }+ }+}+"""++WAREHOUSES_QUERY = """+query PostHogGetWarehouses {+ getWarehouses {+ uuid+ name+ connectionType+ createdTime+ updatedTime+ isDeleted+ deletedAt+ bqProjectId+ }+}+"""++VALIDATE_CREDENTIALS_QUERY = """+query PostHogValidateCredentials {+ getUser { email }+}+"""++PaginationStyle = Literal["relay", "offset", "none"]+++@dataclass+class MonteCarloEndpointConfig:+ name: str+ query: str+ # Top-level query field the rows live under in the response `data` object.+ data_path: str+ pagination: PaginationStyle+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str = "createdTime"+ partition_key: Optional[str] = None+ page_size: int = 100+++MONTE_CARLO_ENDPOINTS: dict[str, MonteCarloEndpointConfig] = {+ "alerts": MonteCarloEndpointConfig(+ name="alerts",+ query=ALERTS_QUERY,+ data_path="getAlerts",+ pagination="relay",+ primary_keys=["uuid"],+ partition_key="createdTime",+ incremental_fields=[+ {+ "label": "createdTime",+ "type": IncrementalFieldType.DateTime,+ "field": "createdTime",+ "field_type": IncrementalFieldType.DateTime,+ },+ {+ "label": "updatedTime",+ "type": IncrementalFieldType.DateTime,+ "field": "updatedTime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "monitors": MonteCarloEndpointConfig(+ name="monitors",+ query=MONITORS_QUERY,+ data_path="getMonitors",+ pagination="offset",+ primary_keys=["uuid"],+ ),+ "tables": MonteCarloEndpointConfig(+ name="tables",+ query=TABLES_QUERY,+ data_path="getTables",+ pagination="relay",+ primary_keys=["id"],+ ),+ "users": MonteCarloEndpointConfig(+ name="users",+ query=USERS_QUERY,+ data_path="getUsersInAccount",+ pagination="relay",+ primary_keys=["id"],+ ),+ "warehouses": MonteCarloEndpointConfig(+ name="warehouses",+ query=WAREHOUSES_QUERY,+ data_path="getWarehouses",+ pagination="none",+ primary_keys=["uuid"],+ ),+}++ENDPOINTS = tuple(MONTE_CARLO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in MONTE_CARLO_ENDPOINTS.items()+}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.pyindex 721e4dbf53f7..3ae9f88ed6d0 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@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MonteCarloSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.monte_carlo import (+ MonteCarloResumeConfig,+ monte_carlo_source,+ validate_credentials as validate_monte_carlo_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class MonteCarloSource(SimpleSource[MonteCarloSourceConfig]):+class MonteCarloSource(ResumableSource[MonteCarloSourceConfig, MonteCarloResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MONTECARLO@@ -23,8 +46,112 @@ class MonteCarloSource(SimpleSource[MonteCarloSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.MONTE_CARLO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Monte Carlo Data, Inc.",+ label="Monte Carlo",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["montecarlo", "data observability"],+ caption="""Enter your Monte Carlo API key to pull your data observability history into the PostHog Data warehouse.++You can create an API key from **Settings → API → Keys** in your Monte Carlo dashboard. Keys are created with an expiration date, so you will need to reconnect with a new key when it expires.+""",iconPath="/static/services/monte_carlo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/monte-carlo",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key_id",+ label="API key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key_secret",+ label="API key secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # An invalid or expired Monte Carlo API key surfaces as a requests HTTPError when+ # `_execute_query` calls `raise_for_status()`. Retrying can never fix a credential+ # problem, so stop the sync.+ return {+ "401 Client Error: Unauthorized for url: https://api.getmontecarlo.com": "Your Monte Carlo API key is invalid or has expired. Create a new API key in your Monte Carlo settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.getmontecarlo.com": "Your Monte Carlo API key does not have permission to read this data. Check the key's permissions in your Monte Carlo settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: MonteCarloSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "alerts":+ return "Only syncs the last 365 days on initial sync"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint, [])+ has_incremental = len(incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ # Alerts mutate in place (status, severity, comments), so merge is the only+ # sync mode that keeps rows current; append would materialize stale versions.+ supports_append=False,+ incremental_fields=incremental_fields,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: MonteCarloSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_monte_carlo_credentials(config.api_key_id, config.api_key_secret):+ return True, None++ return False, "Invalid Monte Carlo API key ID or secret"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MonteCarloResumeConfig]:+ return ResumableSourceManager[MonteCarloResumeConfig](inputs, MonteCarloResumeConfig)++ def source_for_pipeline(+ self,+ config: MonteCarloSourceConfig,+ resumable_source_manager: ResumableSourceManager[MonteCarloResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return monte_carlo_source(+ api_key_id=config.api_key_id,+ api_key_secret=config.api_key_secret,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)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.pynew file mode 100644index 000000000000..3d9dd103a4e0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py@@ -0,0 +1,386 @@+from datetime import UTC, datetime+from typing import Any++from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo import monte_carlo+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.monte_carlo import (+ MonteCarloGraphQLError,+ MonteCarloResumeConfig,+ _execute_query,+ get_rows,+ monte_carlo_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.settings import MONTE_CARLO_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: MonteCarloResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[MonteCarloResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> MonteCarloResumeConfig | None:+ return self._state++ def save_state(self, data: MonteCarloResumeConfig) -> None:+ self.saved.append(data)+++def _relay_page(data_path: str, nodes: list[dict], end_cursor: str | None) -> dict:+ return {+ data_path: {+ "edges": [{"node": node} for node in nodes],+ "pageInfo": {"endCursor": end_cursor, "hasNextPage": end_cursor is not None},+ }+ }+++class _FakeExecutor:+ """Replaces `_execute_query`, serving responses in call order and recording variables."""++ def __init__(self, responses: list[dict]) -> None:+ self._responses = list(responses)+ self.calls: list[dict[str, Any]] = []++ def __call__(self, session: Any, query: str, variables: dict, logger: Any) -> dict:+ self.calls.append(variables)+ return self._responses.pop(0)+++def _collect(+ endpoint: str,+ responses: list[dict],+ manager: _FakeResumableManager | None = None,+ **incremental: Any,+) -> tuple[list[dict], _FakeExecutor, _FakeResumableManager]:+ manager = manager or _FakeResumableManager()+ executor = _FakeExecutor(responses)+ with (+ patch.object(monte_carlo, "_execute_query", executor),+ patch.object(monte_carlo, "make_tracked_session", MagicMock()),+ ):+ rows: list[dict] = []+ for batch in get_rows(+ api_key_id="key-id",+ api_key_secret="key-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **incremental,+ ):+ rows.extend(batch)+ return rows, executor, manager+++class TestExecuteQuery:+ def _response(self, status_code: int, payload: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = payload or {}+ return response++ def test_returns_data_object(self) -> None:+ session = MagicMock()+ session.post.return_value = self._response(200, {"data": {"getWarehouses": []}})+ assert _execute_query(session, "query {}", {}, MagicMock()) == {"getWarehouses": []}++ def test_raises_on_graphql_errors(self) -> None:+ session = MagicMock()+ session.post.return_value = self._response(200, {"errors": [{"message": "not allowed"}]})+ try:+ _execute_query(session, "query {}", {}, MagicMock())+ raise AssertionError("expected MonteCarloGraphQLError")+ except MonteCarloGraphQLError as e:+ assert "not allowed" in str(e)++ @parameterized.expand([(429,), (500,), (503,)])+ def test_retries_retryable_statuses_then_succeeds(self, status_code: int) -> None:+ session = MagicMock()+ session.post.side_effect = [+ self._response(status_code),+ self._response(200, {"data": {"getWarehouses": []}}),+ ]+ with patch.object(_execute_query.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ assert _execute_query(session, "query {}", {}, MagicMock()) == {"getWarehouses": []}+ assert session.post.call_count == 2++ def test_raises_http_error_on_unauthorized(self) -> None:+ session = MagicMock()+ response = self._response(401)+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session.post.return_value = response+ try:+ _execute_query(session, "query {}", {}, MagicMock())+ raise AssertionError("expected HTTPError")+ except requests.HTTPError:+ pass+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, {"data": {"getUser": {"email": "[email protected]"}}}, True),+ ("unauthorized", 401, {"message": "Unauthorized"}, False),+ ("graphql_error", 200, {"errors": [{"message": "boom"}]}, False),+ ]+ )+ def test_status_mapping(self, _label: str, status_code: int, payload: dict, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = payload+ session = MagicMock()+ session.post.return_value = response+ with patch.object(monte_carlo, "make_tracked_session", return_value=session):+ assert validate_credentials("key-id", "key-secret") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.post.side_effect = requests.ConnectionError("boom")+ with patch.object(monte_carlo, "make_tracked_session", return_value=session):+ assert validate_credentials("key-id", "key-secret") is False+++class TestRelayEndpoints:+ @parameterized.expand([("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"),+ _relay_page(data_path, [{"id": "3"}], None),+ ]+ rows, executor, manager = _collect(endpoint, responses)++ assert [row["id"] for row in rows] == ["1", "2", "3"]+ assert executor.calls[0]["after"] is None+ assert executor.calls[1]["after"] == "cursor-1"+ # State saved after the yielded page, only while more pages remain.+ assert [state.cursor for state in manager.saved] == ["cursor-1"]++ def test_resumes_from_saved_cursor(self) -> None:+ responses = [_relay_page("getTables", [{"id": "9"}], None)]+ manager = _FakeResumableManager(MonteCarloResumeConfig(cursor="cursor-42"))+ rows, executor, _ = _collect("tables", responses, manager=manager)++ assert [row["id"] for row in rows] == ["9"]+ assert executor.calls[0]["after"] == "cursor-42"++ def test_empty_first_page_yields_nothing(self) -> None:+ responses = [_relay_page("getTables", [], None)]+ rows, _, manager = _collect("tables", responses)+ assert rows == []+ assert manager.saved == []+++class TestOffsetEndpoint:+ def test_paginates_until_short_page(self) -> None:+ page_size = MONTE_CARLO_ENDPOINTS["monitors"].page_size+ full_page = [{"uuid": f"m-{i}"} for i in range(page_size)]+ responses = [{"getMonitors": full_page}, {"getMonitors": [{"uuid": "last"}]}]+ rows, executor, manager = _collect("monitors", responses)++ assert len(rows) == page_size + 1+ assert executor.calls[0]["offset"] == 0+ assert executor.calls[1]["offset"] == page_size+ assert [state.offset for state in manager.saved] == [page_size]++ def test_resumes_from_saved_offset(self) -> None:+ responses = [{"getMonitors": [{"uuid": "m-200"}]}]+ manager = _FakeResumableManager(MonteCarloResumeConfig(offset=200))+ _, executor, _ = _collect("monitors", responses, manager=manager)+ assert executor.calls[0]["offset"] == 200++ def test_empty_first_page_yields_nothing(self) -> None:+ rows, _, _ = _collect("monitors", [{"getMonitors": []}])+ assert rows == []+++class TestUnpaginatedEndpoint:+ def test_warehouses_single_query(self) -> None:+ responses = [{"getWarehouses": [{"uuid": "w-1"}, {"uuid": "w-2"}]}]+ rows, executor, manager = _collect("warehouses", responses)+ assert [row["uuid"] for row in rows] == ["w-1", "w-2"]+ assert len(executor.calls) == 1+ assert manager.saved == []+++@freeze_time("2026-07-15T12:00:00Z")+class TestAlertsWindowing:+ def test_first_sync_walks_year_of_30_day_windows(self) -> None:+ empty = _relay_page("getAlerts", [], None)+ responses = [empty] * 13 # 365 days / 30-day windows+ rows, executor, _ = _collect(+ "alerts", responses, should_use_incremental_field=True, db_incremental_field_last_value=None+ )++ assert rows == []+ assert len(executor.calls) == 13+ first_window = executor.calls[0]["createdTime"]+ assert first_window["after"] == "2025-07-15T12:00:00Z"+ assert first_window["before"] == "2025-08-14T12:00:00Z"+ last_window = executor.calls[-1]["createdTime"]+ assert last_window["before"] == "2026-07-15T12:00:00Z"++ def test_incremental_sync_windows_forward_from_watermark(self) -> None:+ watermark = datetime(2026, 7, 1, tzinfo=UTC)+ responses = [_relay_page("getAlerts", [{"uuid": "a-1", "createdTime": "2026-07-02T00:00:00Z"}], None)]+ rows, executor, _ = _collect(+ "alerts", responses, should_use_incremental_field=True, db_incremental_field_last_value=watermark+ )++ assert [row["uuid"] for row in rows] == ["a-1"]+ assert executor.calls[0]["createdTime"] == {+ "after": "2026-07-01T00:00:00Z",+ "before": "2026-07-15T12:00:00Z",+ }++ def test_updated_time_incremental_field_filters_updated_time(self) -> None:+ watermark = datetime(2026, 7, 10, tzinfo=UTC)+ responses = [_relay_page("getAlerts", [], None)]+ _, executor, _ = _collect(+ "alerts",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ incremental_field="updatedTime",+ )+ assert "updatedTime" in executor.calls[0]+ assert "createdTime" not in executor.calls[0]++ def test_future_watermark_falls_back_to_lookback(self) -> None:+ # A future-dated watermark would produce an empty/invalid window; fall back to the+ # default lookback so the sync self-heals.+ watermark = datetime(2027, 1, 1, tzinfo=UTC)+ responses = [_relay_page("getAlerts", [], None)] * 13+ _, executor, _ = _collect(+ "alerts", responses, should_use_incremental_field=True, db_incremental_field_last_value=watermark+ )+ assert executor.calls[0]["createdTime"]["after"] == "2025-07-15T12:00:00Z"++ def test_saves_cursor_state_mid_window_and_bookmark_between_windows(self) -> None:+ watermark = datetime(2026, 6, 1, tzinfo=UTC) # two windows: Jun 1 - Jul 1, Jul 1 - now+ responses = [+ _relay_page("getAlerts", [{"uuid": "a-1"}], "cursor-1"),+ _relay_page("getAlerts", [{"uuid": "a-2"}], None),+ _relay_page("getAlerts", [{"uuid": "a-3"}], None),+ ]+ rows, executor, manager = _collect(+ "alerts", responses, should_use_incremental_field=True, db_incremental_field_last_value=watermark+ )++ assert [row["uuid"] for row in rows] == ["a-1", "a-2", "a-3"]+ # Mid-window state pins both bounds so the cursor replays against the same filter.+ mid_window = manager.saved[0]+ assert mid_window.cursor == "cursor-1"+ assert mid_window.window_after == "2026-06-01T00:00:00Z"+ assert mid_window.window_before == "2026-07-01T00:00:00Z"+ # Between windows, only the next lower bound is bookmarked.+ between_windows = manager.saved[1]+ assert between_windows.cursor is None+ assert between_windows.window_after == "2026-07-01T00:00:00Z"+ # Second window resumed pagination from scratch.+ assert executor.calls[2]["after"] is None++ def test_resumes_mid_window_with_pinned_bounds_and_cursor(self) -> None:+ manager = _FakeResumableManager(+ MonteCarloResumeConfig(+ cursor="cursor-7",+ window_after="2026-06-01T00:00:00Z",+ window_before="2026-07-01T00:00:00Z",+ )+ )+ responses = [+ _relay_page("getAlerts", [{"uuid": "a-4"}], None), # rest of the pinned window+ _relay_page("getAlerts", [{"uuid": "a-5"}], None), # fresh window to now+ ]+ rows, executor, _ = _collect(+ "alerts",+ responses,+ manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )++ assert [row["uuid"] for row in rows] == ["a-4", "a-5"]+ assert executor.calls[0]["after"] == "cursor-7"+ assert executor.calls[0]["createdTime"] == {+ "after": "2026-06-01T00:00:00Z",+ "before": "2026-07-01T00:00:00Z",+ }+ # Continuation starts at the pinned upper bound, not the stale watermark.+ assert executor.calls[1]["after"] is None+ assert executor.calls[1]["createdTime"]["after"] == "2026-07-01T00:00:00Z"++ def test_resumes_between_windows_without_cursor(self) -> None:+ manager = _FakeResumableManager(MonteCarloResumeConfig(window_after="2026-07-01T00:00:00Z"))+ responses = [_relay_page("getAlerts", [], None)]+ _, executor, _ = _collect(+ "alerts",+ responses,+ manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert executor.calls[0]["after"] is None+ assert executor.calls[0]["createdTime"]["after"] == "2026-07-01T00:00:00Z"++ def test_full_refresh_ignores_watermark_and_uses_lookback(self) -> None:+ responses = [_relay_page("getAlerts", [], None)] * 13+ _, executor, _ = _collect(+ "alerts",+ responses,+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2026, 7, 14, tzinfo=UTC),+ )+ assert executor.calls[0]["createdTime"]["after"] == "2025-07-15T12:00:00Z"+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("alerts", ["uuid"], "desc"),+ ("monitors", ["uuid"], "asc"),+ ("tables", ["id"], "asc"),+ ("users", ["id"], "asc"),+ ("warehouses", ["uuid"], "asc"),+ ]+ )+ def test_primary_keys_and_sort_mode(self, endpoint: str, primary_keys: list[str], sort_mode: str) -> None:+ response = monte_carlo_source(+ api_key_id="key-id",+ api_key_secret="key-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == sort_mode++ def test_only_alerts_is_partitioned_on_stable_created_time(self) -> None:+ alerts = monte_carlo_source(+ api_key_id="key-id",+ api_key_secret="key-secret",+ endpoint="alerts",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert alerts.partition_mode == "datetime"+ assert alerts.partition_keys == ["createdTime"]++ monitors = monte_carlo_source(+ api_key_id="key-id",+ api_key_secret="key-secret",+ endpoint="monitors",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert monitors.partition_mode is None+ assert monitors.partition_keys is Nonediff --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.pynew file mode 100644index 000000000000..16bbdc5cf218--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo_source.py@@ -0,0 +1,160 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MonteCarloSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.monte_carlo import (+ MonteCarloResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.source import MonteCarloSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "alerts",+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestMonteCarloSource:+ def setup_method(self) -> None:+ self.source = MonteCarloSource()+ self.config = MonteCarloSourceConfig(api_key_id="key-id", api_key_secret="key-secret")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.MONTECARLO++ def test_source_config_is_released_alpha(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Monte Carlo"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_source_config_fields(self) -> None:+ fields = {f.name: f for f in self.source.get_source_config.fields}+ assert set(fields.keys()) == {"api_key_id", "api_key_secret"}+ api_key_id = fields["api_key_id"]+ api_key_secret = fields["api_key_secret"]+ assert isinstance(api_key_id, SourceFieldInputConfig)+ assert isinstance(api_key_secret, SourceFieldInputConfig)+ assert api_key_id.type == SourceFieldInputConfigType.TEXT+ assert api_key_id.required is True+ assert api_key_secret.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_secret.secret is True++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert [s.name for s in schemas] == list(ENDPOINTS)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["alerts", "monitors"])+ assert {s.name for s in schemas} == {"alerts", "monitors"}++ @parameterized.expand(+ [+ ("alerts", True),+ ("monitors", False),+ ("tables", False),+ ("users", False),+ ("warehouses", False),+ ]+ )+ def test_incremental_support_per_endpoint(self, endpoint: str, supports_incremental: bool) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is supports_incremental+ # Alerts mutate in place (status/severity), so no endpoint offers append mode.+ assert schema.supports_append is False++ def test_alerts_offers_created_and_updated_time_cursors(self) -> None:+ alerts = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == "alerts")+ assert [f["field"] for f in alerts.incremental_fields] == ["createdTime", "updatedTime"]++ @parameterized.expand([(True, None), (False, "Invalid Monte Carlo API key ID or secret")])+ def test_validate_credentials(self, is_valid: bool, expected_error: str | None) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.source.validate_monte_carlo_credentials",+ return_value=is_valid,+ ) as mock_validate:+ result, error = self.source.validate_credentials(self.config, team_id=1)++ assert result is is_valid+ assert error == expected_error+ mock_validate.assert_called_once_with("key-id", "key-secret")++ def test_non_retryable_errors_cover_auth_failures(self) -> None:+ errors = self.source.get_non_retryable_errors()+ assert any("401" in key and "api.getmontecarlo.com" in key for key in errors)+ assert any("403" in key and "api.getmontecarlo.com" in key for key in errors)++ def test_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MonteCarloResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = _make_inputs(+ schema_name="alerts",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-06-01T00:00:00Z",+ incremental_field="createdTime",+ )+ manager = MagicMock()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.source.monte_carlo_source"+ ) as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key_id="key-id",+ api_key_secret="key-secret",+ endpoint="alerts",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-06-01T00:00:00Z",+ incremental_field="createdTime",+ )++ def test_source_for_pipeline_drops_watermark_for_full_refresh(self) -> None:+ inputs = _make_inputs(+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-06-01T00:00:00Z",+ )+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.monte_carlo.source.monte_carlo_source"+ ) as mock_source:+ self.source.source_for_pipeline(self.config, MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)+ for entry in descriptions.values():+ assert entry["description"]+ assert entry["columns"]++ def test_documented_tables_render_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)