: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 new_relic import source (#71232)
Tom Owers326acfe4579a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4b54987b7bb1..5cf949da338d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -332,6 +332,7 @@ the row lists both.| n8n | HTTP | requests | ✅ || nebius_ai | HTTP | requests | ✅ || netlify | HTTP | requests | ✅ |+| new_relic | HTTP (GraphQL/NerdGraph) | requests | ✅ || new_york_times | HTTP | requests | ✅ || news_api | HTTP | requests | ✅ || newsdata | HTTP | requests | ✅ |@@ -797,7 +798,6 @@ doesn't conflict with concurrent PRs.- navan- neon- netsuite-- new_relic- news_api- nexiopay- ninjaone_rmmdiff --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 7dc3c7cdc45e..d36bfb370936 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@@ -2831,7 +2831,9 @@ class NetlifySourceConfig(config.Config):@config.configclass NewRelicSourceConfig(config.Config):- pass+ api_key: str+ account_id: int = config.value(converter=int)+ region: Literal["US", "EU"] = config.value(default="US")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/canonical_descriptions.pynew file mode 100644index 000000000000..73a1446e6587--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/canonical_descriptions.py@@ -0,0 +1,112 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "transactions": {+ "description": "APM Transaction events: one row per completed transaction (web request or background task) reported by a New Relic agent.",+ "docs_url": "https://docs.newrelic.com/attribute-dictionary/?event=Transaction",+ "columns": {+ "timestamp": "Time the transaction ended, recorded by the agent.",+ "appName": "Name of the application that reported the transaction.",+ "name": "Full metric name of the transaction, e.g. WebTransaction/Uri/api/users.",+ "duration": "Total server-side response time of the transaction, in seconds.",+ "transactionType": "Type of the transaction: Web or Other (non-web/background).",+ "error": "Whether an error was recorded during the transaction.",+ "httpResponseCode": "HTTP status code returned by web transactions.",+ "host": "Hostname of the server that processed the transaction.",+ "databaseDuration": "Total time spent in database calls during the transaction, in seconds.",+ "externalDuration": "Total time spent in external service calls during the transaction, in seconds.",+ "traceId": "Distributed tracing trace ID the transaction belongs to, when tracing is enabled.",+ },+ },+ "transaction_errors": {+ "description": "APM TransactionError events: one row per error captured inside a transaction by a New Relic agent.",+ "docs_url": "https://docs.newrelic.com/attribute-dictionary/?event=TransactionError",+ "columns": {+ "timestamp": "Time the error occurred.",+ "appName": "Name of the application that reported the error.",+ "error.class": "Exception class of the captured error.",+ "error.message": "Message of the captured error.",+ "transactionName": "Name of the transaction in which the error occurred.",+ "traceId": "Distributed tracing trace ID associated with the error, when tracing is enabled.",+ },+ },+ "page_views": {+ "description": "Browser PageView events: one row per full page load captured by New Relic browser monitoring.",+ "docs_url": "https://docs.newrelic.com/attribute-dictionary/?event=PageView",+ "columns": {+ "timestamp": "Time the page load started.",+ "appName": "Name of the browser application that reported the page view.",+ "pageUrl": "URL of the viewed page.",+ "duration": "Total page load time, in seconds.",+ "city": "City where the page view originated, derived from the request IP.",+ "countryCode": "Country where the page view originated, derived from the request IP.",+ "userAgentName": "Browser name parsed from the user agent.",+ "session": "Browser session identifier grouping page views from one visit.",+ },+ },+ "logs": {+ "description": "Log events forwarded to New Relic log management: one row per log line.",+ "docs_url": "https://docs.newrelic.com/attribute-dictionary/?event=Log",+ "columns": {+ "timestamp": "Time the log line was written.",+ "message": "The log line's message body.",+ "level": "Severity level of the log line, when parsed (e.g. INFO, ERROR).",+ "hostname": "Host that emitted the log line.",+ },+ },+ "spans": {+ "description": "Distributed tracing Span events: one row per operation segment within a trace.",+ "docs_url": "https://docs.newrelic.com/attribute-dictionary/?event=Span",+ "columns": {+ "timestamp": "Time the span started.",+ "guid": "Unique identifier of the span within its trace.",+ "traceId": "Identifier of the distributed trace the span belongs to.",+ "parentId": "Identifier of the span's parent span, empty for trace roots.",+ "name": "Name of the operation the span represents.",+ "duration": "Duration of the span, in seconds.",+ "appName": "Name of the application that reported the span.",+ "error.class": "Exception class recorded on the span, if an error occurred.",+ },+ },+ "entities": {+ "description": "Inventory of entities New Relic monitors on the account (applications, hosts, services, dashboards, monitors, ...), from NerdGraph entity search.",+ "docs_url": "https://docs.newrelic.com/docs/apis/nerdgraph/examples/nerdgraph-entities-api-tutorial/",+ "columns": {+ "guid": "Globally unique identifier of the entity.",+ "name": "Display name of the entity.",+ "accountId": "New Relic account the entity belongs to.",+ "domain": "Entity domain, e.g. APM, BROWSER, INFRA, SYNTH.",+ "type": "Entity type within its domain, e.g. APPLICATION, HOST, MONITOR.",+ "entityType": "Combined domain/type discriminator, e.g. APM_APPLICATION_ENTITY.",+ "reporting": "Whether the entity is currently reporting data.",+ "permalink": "Link to the entity in the New Relic UI.",+ "tags": "Key/value tags attached to the entity.",+ },+ },+ "alert_policies": {+ "description": "Alert policies configured on the account, which group alert conditions and control incident creation.",+ "docs_url": "https://docs.newrelic.com/docs/apis/nerdgraph/examples/nerdgraph-api-alerts-policies/",+ "columns": {+ "id": "Unique identifier of the alert policy.",+ "accountId": "New Relic account the policy belongs to.",+ "name": "Name of the alert policy.",+ "incidentPreference": "How incidents are created from the policy's conditions: PER_POLICY, PER_CONDITION, or PER_CONDITION_AND_TARGET.",+ },+ },+ "alert_conditions": {+ "description": "NRQL alert conditions configured on the account: the queries and thresholds that open violations.",+ "docs_url": "https://docs.newrelic.com/docs/apis/nerdgraph/examples/nerdgraph-api-nrql-condition-alerts/",+ "columns": {+ "id": "Unique identifier of the alert condition.",+ "name": "Name of the alert condition.",+ "policyId": "Alert policy the condition belongs to.",+ "enabled": "Whether the condition is currently enabled.",+ "description": "Custom description shown on violations opened by the condition.",+ "runbookUrl": "Runbook URL attached to violations opened by the condition.",+ "type": "Condition type, e.g. STATIC or BASELINE.",+ "nrql_query": "The NRQL query the condition evaluates.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/new_relic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/new_relic.pynew file mode 100644index 000000000000..bcdfe306aa5e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/new_relic.py@@ -0,0 +1,469 @@+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+import structlog+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.new_relic.settings import (+ NEW_RELIC_ENDPOINTS,+ NewRelicEndpointConfig,+)++# NerdGraph is region-scoped: EU-datacenter accounts only answer on the EU host.+NEW_RELIC_GRAPHQL_URLS: dict[str, str] = {+ "US": "https://api.newrelic.com/graphql",+ "EU": "https://api.eu.newrelic.com/graphql",+}++REQUEST_TIMEOUT_SECONDS = 130 # must exceed the 120s server-side NRQL timeout we request+MAX_RETRY_ATTEMPTS = 5++# NRQL returns at most 5,000 rows per query (LIMIT MAX), so event tables are read in+# time windows that are recursively halved whenever a window fills up.+NRQL_ROW_LIMIT = 5000+DEFAULT_WINDOW_MS = int(timedelta(hours=6).total_seconds() * 1000)+MIN_WINDOW_MS = 1000+# Events are queried UNTIL now minus this buffer: New Relic ingests with some lag, and an+# append-only sync would permanently miss events that land after their window was read.+INGEST_LAG_BUFFER_MS = int(timedelta(minutes=5).total_seconds() * 1000)+# First sync / full refresh reaches back this far. New Relic's raw event retention is+# plan-dependent (typically 8-90 days), so older windows simply come back empty.+DEFAULT_LOOKBACK_DAYS = 30++NRQL_QUERY = """+query ($accountId: Int!, $nrql: Nrql!) {+ actor {+ account(id: $accountId) {+ nrql(query: $nrql, timeout: 120) {+ results+ }+ }+ }+}+"""++# Conservative field set: only fields available on every EntityOutline type, so the query+# can't fail on accounts whose entities span domains we didn't anticipate.+ENTITY_SEARCH_QUERY = """+query ($query: String!, $cursor: String) {+ actor {+ entitySearch(query: $query) {+ results(cursor: $cursor) {+ entities {+ guid+ name+ accountId+ domain+ type+ entityType+ reporting+ permalink+ tags {+ key+ values+ }+ }+ nextCursor+ }+ }+ }+}+"""++ALERT_POLICIES_QUERY = """+query ($accountId: Int!, $cursor: String) {+ actor {+ account(id: $accountId) {+ alerts {+ policiesSearch(cursor: $cursor) {+ policies {+ id+ accountId+ name+ incidentPreference+ }+ nextCursor+ }+ }+ }+ }+}+"""++ALERT_CONDITIONS_QUERY = """+query ($accountId: Int!, $cursor: String) {+ actor {+ account(id: $accountId) {+ alerts {+ nrqlConditionsSearch(cursor: $cursor) {+ nrqlConditions {+ id+ name+ policyId+ enabled+ description+ runbookUrl+ type+ nrql {+ query+ }+ }+ nextCursor+ }+ }+ }+ }+}+"""++VALIDATE_QUERY = """+query ($accountId: Int!) {+ actor {+ account(id: $accountId) {+ id+ name+ }+ }+}+"""+++class NewRelicRetryableError(Exception):+ pass+++class NewRelicGraphQLError(Exception):+ """NerdGraph returned HTTP 200 with an `errors` array (bad query, missing account access, ...)."""+++class NewRelicResumeConfig:+ # Start (epoch ms) of the next NRQL time window still to fetch. Only event tables save+ # resume state: their windows stay valid indefinitely, whereas NerdGraph pagination+ # cursors can expire — resuming a stale cursor would wedge every retry until the+ # 24h state TTL passes, so entity-style tables restart from scratch instead.+ window_start_ms: int | None = None+++def get_graphql_url(region: str | None) -> str:+ return NEW_RELIC_GRAPHQL_URLS.get((region or "US").upper(), NEW_RELIC_GRAPHQL_URLS["US"])+++def _get_session(api_key: str) -> requests.Session:+ return make_tracked_session(headers={"API-Key": api_key}, redact_values=(api_key,))+++@retry(+ retry=retry_if_exception_type(+ (+ NewRelicRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _execute_graphql(+ session: requests.Session,+ url: str,+ query: str,+ variables: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.post(url, json={"query": query, "variables": variables}, timeout=REQUEST_TIMEOUT_SECONDS)++ # 25 concurrent NerdGraph requests per user / 3,000 NRQL queries per account per+ # minute surface as 429s; both clear on their own, so back off and retry.+ if response.status_code == 429 or response.status_code >= 500:+ raise NewRelicRetryableError(f"New Relic API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"New Relic API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ body = response.json()+ errors = body.get("errors")+ if errors:+ messages = "; ".join(str(error.get("message", error)) for error in errors)+ # NerdGraph reports server-side timeouts/deadlines inside `errors` on an HTTP 200.+ if any(term in messages.lower() for term in ("timeout", "deadline", "too many requests")):+ raise NewRelicRetryableError(f"New Relic GraphQL error (retryable): {messages}")+ raise NewRelicGraphQLError(f"New Relic GraphQL error: {messages}")++ return body.get("data") or {}+++GraphQLExecutor = Callable[[str, dict[str, Any]], dict[str, Any]]+++def _make_executor(api_key: str, region: str | None, logger: FilteringBoundLogger) -> GraphQLExecutor:+ # One session for the whole sync so urllib3 keeps the connection alive across queries.+ session = _get_session(api_key)+ url = get_graphql_url(region)++ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ return _execute_graphql(session, url, query, variables, logger)++ return execute+++def validate_credentials(api_key: str, account_id: int, region: str | None) -> tuple[bool, str | None]:+ # Credential validation runs outside a sync job, so there's no job-bound logger to pass.+ execute = _make_executor(api_key, region, structlog.get_logger(__name__))+ try:+ data = execute(VALIDATE_QUERY, {"accountId": account_id})+ except requests.HTTPError as exc:+ if exc.response is not None and exc.response.status_code in (401, 403):+ return False, "Invalid New Relic API key. Create a User API key in your New Relic account and try again."+ return False, f"Could not connect to New Relic: {exc}"+ except NewRelicGraphQLError as exc:+ return False, f"Could not access New Relic account {account_id}: {exc}"+ except Exception as exc:+ return False, f"Could not connect to New Relic: {exc}"++ account = (data.get("actor") or {}).get("account")+ if not account:+ return (+ False,+ f"Your API key is valid but has no access to account {account_id}. "+ "Check the account ID and that the key belongs to a user on that account.",+ )+ return True, None+++def _to_epoch_ms(value: Any) -> int:+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return int(aware.timestamp() * 1000)+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)+ if isinstance(value, int | float):+ return int(value)+ raise ValueError(f"Cannot convert incremental value to epoch milliseconds: {value!r}")+++def _normalize_event_row(row: dict[str, Any]) -> dict[str, Any]:+ # NRQL returns `timestamp` as epoch ms; store it as a datetime so incremental cursors+ # and datetime partitioning work on it directly.+ timestamp = row.get("timestamp")+ if isinstance(timestamp, int | float):+ row["timestamp"] = datetime.fromtimestamp(timestamp / 1000, tz=UTC)+ return row+++_EPOCH_MIN = datetime.min.replace(tzinfo=UTC)+++def _sort_timestamp(row: dict[str, Any]) -> datetime:+ # Rows without a parseable timestamp sort first so they can't inflate the pipeline's+ # per-batch incremental watermark past rows that follow them.+ timestamp = row.get("timestamp")+ return timestamp if isinstance(timestamp, datetime) else _EPOCH_MIN+++def _run_nrql(execute: GraphQLExecutor, account_id: int, nrql: str) -> list[dict[str, Any]]:+ data = execute(NRQL_QUERY, {"accountId": account_id, "nrql": nrql})+ account = (data.get("actor") or {}).get("account") or {}+ return (account.get("nrql") or {}).get("results") or []+++def _fetch_event_window(+ execute: GraphQLExecutor,+ account_id: int,+ table: str,+ start_ms: int,+ end_ms: int,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Fetch every event in [start_ms, end_ms), recursively halving windows that hit the+ 5,000-row NRQL cap. Yields each completed sub-window's rows sorted ascending by+ timestamp, in ascending sub-window order, so the overall stream is ascending and the+ pipeline's per-batch incremental watermark stays correct."""+ results = _run_nrql(+ execute,+ account_id,+ f"SELECT * FROM {table} SINCE {start_ms} UNTIL {end_ms} LIMIT MAX",+ )++ if len(results) >= NRQL_ROW_LIMIT and (end_ms - start_ms) > MIN_WINDOW_MS:+ mid_ms = (start_ms + end_ms) // 2+ yield from _fetch_event_window(execute, account_id, table, start_ms, mid_ms, logger)+ yield from _fetch_event_window(execute, account_id, table, mid_ms, end_ms, logger)+ return++ if len(results) >= NRQL_ROW_LIMIT:+ logger.warning(+ f"New Relic: {table} returned {len(results)} rows for a {end_ms - start_ms}ms window "+ f"[{start_ms}, {end_ms}); rows beyond the NRQL 5,000-row cap in this window are skipped"+ )++ if results:+ rows = [_normalize_event_row(row) for row in results]+ rows.sort(key=_sort_timestamp)+ yield rows+++def _get_event_rows(+ execute: GraphQLExecutor,+ account_id: int,+ config: NewRelicEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewRelicResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ assert config.nrql_table is not None++ now_ms = int(datetime.now(UTC).timestamp() * 1000)+ until_ms = now_ms - INGEST_LAG_BUFFER_MS++ if should_use_incremental_field and db_incremental_field_last_value is not None:+ # +1ms past the watermark: these tables sync append-only (no primary key to merge+ # on), so re-reading the boundary millisecond would materialize duplicate rows.+ since_ms = min(_to_epoch_ms(db_incremental_field_last_value) + 1, until_ms)+ else:+ since_ms = now_ms - int(timedelta(days=DEFAULT_LOOKBACK_DAYS).total_seconds() * 1000)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_start_ms is not None:+ since_ms = max(since_ms, resume.window_start_ms)+ logger.debug(f"New Relic: resuming {config.name} from window start {since_ms}")++ window_start_ms = since_ms+ while window_start_ms < until_ms:+ window_end_ms = min(window_start_ms + DEFAULT_WINDOW_MS, until_ms)++ yield from _fetch_event_window(execute, account_id, config.nrql_table, window_start_ms, window_end_ms, logger)++ # Save AFTER yielding (and only when more windows remain) so a crash re-yields the+ # last window rather than skipping it — losing data is worse than the duplicate+ # rows a re-yield can append.+ if window_end_ms < until_ms:+ resumable_source_manager.save_state(NewRelicResumeConfig(window_start_ms=window_end_ms))++ window_start_ms = window_end_ms+++def _iter_entities(execute: GraphQLExecutor, account_id: int) -> Iterator[list[dict[str, Any]]]:+ cursor: str | None = None+ while True:+ data = execute(ENTITY_SEARCH_QUERY, {"query": f"accountId = {account_id}", "cursor": cursor})+ results = (data.get("actor") or {}).get("entitySearch", {}).get("results") or {}+ entities = results.get("entities") or []+ if entities:+ yield entities+ cursor = results.get("nextCursor")+ if not cursor:+ return+++def _iter_alert_policies(execute: GraphQLExecutor, account_id: int) -> Iterator[list[dict[str, Any]]]:+ cursor: str | None = None+ while True:+ data = execute(ALERT_POLICIES_QUERY, {"accountId": account_id, "cursor": cursor})+ search = ((data.get("actor") or {}).get("account") or {}).get("alerts", {}).get("policiesSearch") or {}+ policies = search.get("policies") or []+ if policies:+ yield policies+ cursor = search.get("nextCursor")+ if not cursor:+ return+++def _flatten_alert_condition(condition: dict[str, Any]) -> dict[str, Any]:+ nrql = condition.pop("nrql", None)+ if isinstance(nrql, dict):+ condition["nrql_query"] = nrql.get("query")+ return condition+++def _iter_alert_conditions(execute: GraphQLExecutor, account_id: int) -> Iterator[list[dict[str, Any]]]:+ cursor: str | None = None+ while True:+ data = execute(ALERT_CONDITIONS_QUERY, {"accountId": account_id, "cursor": cursor})+ search = ((data.get("actor") or {}).get("account") or {}).get("alerts", {}).get("nrqlConditionsSearch") or {}+ conditions = search.get("nrqlConditions") or []+ if conditions:+ yield [_flatten_alert_condition(condition) for condition in conditions]+ cursor = search.get("nextCursor")+ if not cursor:+ return+++_ENTITY_STYLE_ITERATORS: dict[str, Callable[[GraphQLExecutor, int], Iterator[list[dict[str, Any]]]]] = {+ "entities": _iter_entities,+ "alert_policies": _iter_alert_policies,+ "alert_conditions": _iter_alert_conditions,+}+++def get_rows(+ api_key: str,+ account_id: int,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewRelicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = NEW_RELIC_ENDPOINTS[endpoint]+ execute = _make_executor(api_key, region, logger)++ if config.nrql_table is not None:+ yield from _get_event_rows(+ execute,+ account_id,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ return++ yield from _ENTITY_STYLE_ITERATORS[endpoint](execute, account_id)+++def new_relic_source(+ api_key: str,+ account_id: int,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewRelicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = NEW_RELIC_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ account_id=account_id,+ region=region,+ 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,+ ),+ primary_keys=endpoint_config.primary_keys,+ sort_mode="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="week" 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/new_relic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/settings.pynew file mode 100644index 000000000000..1eed770e2054--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/settings.py@@ -0,0 +1,89 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++_TIMESTAMP_INCREMENTAL_FIELD: list[IncrementalField] = [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class NewRelicEndpointConfig:+ name: str+ # NRQL event table to `SELECT * FROM` via NerdGraph (Transaction, Log, ...).+ # None for NerdGraph entity/config endpoints (entities, alert policies, ...).+ nrql_table: str | None = None+ # NRQL event rows have no unique identifier, so event tables ship with no primary+ # keys and sync append-only; entity/config tables carry their API id.+ primary_keys: list[str] | None = None+ partition_key: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ should_sync_default: bool = True+ description: str | None = None+++NEW_RELIC_ENDPOINTS: dict[str, NewRelicEndpointConfig] = {+ "transactions": NewRelicEndpointConfig(+ name="transactions",+ nrql_table="Transaction",+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ description="APM transaction events. Only syncs the last 30 days on initial sync",+ ),+ "transaction_errors": NewRelicEndpointConfig(+ name="transaction_errors",+ nrql_table="TransactionError",+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ description="APM transaction error events. Only syncs the last 30 days on initial sync",+ ),+ "page_views": NewRelicEndpointConfig(+ name="page_views",+ nrql_table="PageView",+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ description="Browser page view events. Only syncs the last 30 days on initial sync",+ ),+ "logs": NewRelicEndpointConfig(+ name="logs",+ nrql_table="Log",+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ should_sync_default=False,+ description="Log events. Can be very high volume, so it's off by default. Only syncs the last 30 days on initial sync",+ ),+ "spans": NewRelicEndpointConfig(+ name="spans",+ nrql_table="Span",+ partition_key="timestamp",+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ should_sync_default=False,+ description="Distributed tracing span events. Can be very high volume, so it's off by default. Only syncs the last 30 days on initial sync",+ ),+ "entities": NewRelicEndpointConfig(+ name="entities",+ primary_keys=["guid"],+ description="Inventory of monitored entities (applications, hosts, services, ...) from entity search",+ ),+ "alert_policies": NewRelicEndpointConfig(+ name="alert_policies",+ primary_keys=["id"],+ description="Alert policies configured on the account",+ ),+ "alert_conditions": NewRelicEndpointConfig(+ name="alert_conditions",+ primary_keys=["id"],+ description="NRQL alert conditions configured on the account",+ ),+}++ENDPOINTS = tuple(NEW_RELIC_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in NEW_RELIC_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/source.pyindex 4ce296cb97ed..c162ab484841 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/source.py@@ -1,19 +1,45 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 NewRelicSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.new_relic import (+ NewRelicResumeConfig,+ new_relic_source,+ validate_credentials as validate_new_relic_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NEW_RELIC_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NewRelicSource(SimpleSource[NewRelicSourceConfig]):+class NewRelicSource(ResumableSource[NewRelicSourceConfig, NewRelicResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NEWRELIC@@ -25,7 +51,128 @@ class NewRelicSource(SimpleSource[NewRelicSourceConfig]):category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,keywords=["new relic", "apm", "observability"],label="New Relic",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your New Relic User API key and account ID to pull your New Relic data into the PostHog Data warehouse.++You can create a User API key on the [API keys page](https://one.newrelic.com/admin-portal/api-keys/home) of your New Relic account. Your account ID is shown in the URL when viewing your account, or under **Administration** → **Access management** → **Accounts**.++If your account is hosted in New Relic's EU data center, select the EU region.+""",iconPath="/static/services/new_relic.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/new-relic",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="User API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="NRAK-...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.NUMBER,+ required=True,+ placeholder="1234567",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="US",+ options=[+ SourceFieldSelectConfigOption(label="US", value="US"),+ SourceFieldSelectConfigOption(label="EU", value="EU"),+ ],+ ),+ ],+ ),+ )++ @property+ def connection_host_fields(self) -> list[str]:+ # `region` picks the host the stored API key is sent to, and `account_id` selects which+ # New Relic account the key is used against. Retargeting either must re-require the secret+ # so a preserved key can't be pointed at a different endpoint or account without re-entry.+ return ["account_id", "region"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # An invalid or revoked User API key surfaces as a requests HTTPError from+ # `raise_for_status()`. Retrying can never fix a credential problem, so stop the+ # sync. Match the stable status text and base host (one entry per region), not the+ # per-request path.+ invalid_key = "Your New Relic API key is invalid or has been revoked. Create a new User API key in your New Relic account, then reconnect."+ missing_permissions = "Your New Relic API key does not have permission to read this data. Check the key's user permissions in New Relic, then reconnect."+ return {+ "401 Client Error: Unauthorized for url: https://api.newrelic.com": invalid_key,+ "401 Client Error: Unauthorized for url: https://api.eu.newrelic.com": invalid_key,+ "403 Client Error: Forbidden for url: https://api.newrelic.com": missing_permissions,+ "403 Client Error: Forbidden for url: https://api.eu.newrelic.com": missing_permissions,+ }++ def get_schemas(+ self,+ config: NewRelicSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = NEW_RELIC_ENDPOINTS[endpoint]+ # NRQL event rows are immutable and carry no unique identifier, so event tables+ # sync append-only; entity/config listings have no server-side updated-since+ # filter, so they are full refresh only.+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=endpoint_config.description,+ )++ 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: NewRelicSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_new_relic_credentials(config.api_key, config.account_id, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NewRelicResumeConfig]:+ return ResumableSourceManager[NewRelicResumeConfig](inputs, NewRelicResumeConfig)++ def source_for_pipeline(+ self,+ config: NewRelicSourceConfig,+ resumable_source_manager: ResumableSourceManager[NewRelicResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return new_relic_source(+ api_key=config.api_key,+ account_id=config.account_id,+ region=config.region,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic.pynew file mode 100644index 000000000000..14fc9180c4c2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic.py@@ -0,0 +1,450 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+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.new_relic.new_relic import (+ DEFAULT_LOOKBACK_DAYS,+ DEFAULT_WINDOW_MS,+ INGEST_LAG_BUFFER_MS,+ MIN_WINDOW_MS,+ NRQL_ROW_LIMIT,+ NewRelicGraphQLError,+ NewRelicResumeConfig,+ NewRelicRetryableError,+ _execute_graphql,+ _fetch_event_window,+ _iter_alert_conditions,+ _iter_alert_policies,+ _iter_entities,+ _to_epoch_ms,+ get_graphql_url,+ get_rows,+ new_relic_source,+ validate_credentials,+)++ACCOUNT_ID = 1234567+NEW_RELIC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.new_relic"+++class FakeResumableSourceManager:+ def __init__(self, state: NewRelicResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[NewRelicResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> NewRelicResumeConfig | None:+ return self.state++ def save_state(self, state: NewRelicResumeConfig) -> None:+ self.saved.append(state)+ self.state = state+++def _nrql_data(rows: list[dict[str, Any]]) -> dict[str, Any]:+ return {"actor": {"account": {"nrql": {"results": rows}}}}+++def _parse_since_until(nrql: str) -> tuple[int, int]:+ parts = nrql.split()+ return int(parts[parts.index("SINCE") + 1]), int(parts[parts.index("UNTIL") + 1])+++class RecordingNrqlExecutor:+ """Fake GraphQL executor that serves NRQL queries from a rows_for(start, until) callback."""++ def __init__(self, rows_for: Any) -> None:+ self.rows_for = rows_for+ self.queries: list[str] = []++ def __call__(self, query: str, variables: dict[str, Any]) -> dict[str, Any]:+ nrql = variables["nrql"]+ self.queries.append(nrql)+ start_ms, until_ms = _parse_since_until(nrql)+ return _nrql_data(self.rows_for(start_ms, until_ms))+++class TestToEpochMs:+ @parameterized.expand(+ [+ ("aware_datetime", datetime(2026, 1, 1, tzinfo=UTC), 1767225600000),+ ("naive_datetime_treated_as_utc", datetime(2026, 1, 1), 1767225600000),+ ("date_value", date(2026, 1, 1), 1767225600000),+ ("epoch_ms_int_passthrough", 1767225600000, 1767225600000),+ ("epoch_ms_float", 1767225600000.9, 1767225600000),+ ]+ )+ def test_converts_to_epoch_ms(self, _name: str, value: Any, expected: int) -> None:+ assert _to_epoch_ms(value) == expected++ def test_unsupported_type_raises(self) -> None:+ with pytest.raises(ValueError):+ _to_epoch_ms("2026-01-01")+++class TestGetGraphqlUrl:+ @parameterized.expand(+ [+ ("us", "US", "https://api.newrelic.com/graphql"),+ ("eu", "EU", "https://api.eu.newrelic.com/graphql"),+ ("lowercase_eu", "eu", "https://api.eu.newrelic.com/graphql"),+ ("none_defaults_to_us", None, "https://api.newrelic.com/graphql"),+ ("unknown_defaults_to_us", "MARS", "https://api.newrelic.com/graphql"),+ ]+ )+ def test_region_maps_to_url(self, _name: str, region: str | None, expected: str) -> None:+ assert get_graphql_url(region) == expected+++class TestExecuteGraphql:+ def _response(self, status_code: int = 200, body: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {}+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(response=response)+ return response++ def _execute(self, response: MagicMock) -> dict[str, Any]:+ session = MagicMock()+ session.post.return_value = response+ # Call the undecorated function so retryable-error tests don't sit through backoff.+ return _execute_graphql.__wrapped__( # type: ignore[attr-defined]+ session, "https://api.newrelic.com/graphql", "query", {}, MagicMock()+ )++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])+ def test_retryable_status_codes_raise_retryable_error(self, _name: str, status_code: int) -> None:+ with pytest.raises(NewRelicRetryableError):+ self._execute(self._response(status_code=status_code))++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_http_error(self, _name: str, status_code: int) -> None:+ with pytest.raises(requests.HTTPError):+ self._execute(self._response(status_code=status_code))++ def test_graphql_errors_raise(self) -> None:+ body = {"errors": [{"message": "authentication required"}]}+ with pytest.raises(NewRelicGraphQLError, match="authentication required"):+ self._execute(self._response(body=body))++ @parameterized.expand(+ [+ ("timeout", "NRQL query timeout after 120 seconds"),+ ("deadline", "Deadline exceeded"),+ ("throttled", "Too many requests"),+ ]+ )+ def test_transient_graphql_errors_are_retryable(self, _name: str, message: str) -> None:+ body = {"errors": [{"message": message}]}+ with pytest.raises(NewRelicRetryableError):+ self._execute(self._response(body=body))++ def test_returns_data_on_success(self) -> None:+ body = {"data": {"actor": {"account": {"id": ACCOUNT_ID}}}}+ assert self._execute(self._response(body=body)) == body["data"]+++class TestFetchEventWindow:+ def test_yields_rows_sorted_ascending_with_datetime_timestamps(self) -> None:+ executor = RecordingNrqlExecutor(+ lambda start, until: [{"timestamp": 2000, "name": "b"}, {"timestamp": 1000, "name": "a"}]+ )++ batches = list(_fetch_event_window(executor, ACCOUNT_ID, "Transaction", 0, 10_000, MagicMock()))++ assert len(batches) == 1+ assert [row["name"] for row in batches[0]] == ["a", "b"]+ assert batches[0][0]["timestamp"] == datetime.fromtimestamp(1, tz=UTC)+ assert "SELECT * FROM Transaction SINCE 0 UNTIL 10000" in executor.queries[0]++ def test_empty_window_yields_nothing(self) -> None:+ executor = RecordingNrqlExecutor(lambda start, until: [])+ assert list(_fetch_event_window(executor, ACCOUNT_ID, "Transaction", 0, 10_000, MagicMock())) == []++ def test_full_window_splits_recursively_until_under_cap(self) -> None:+ full_page = [{"timestamp": 1} for _ in range(NRQL_ROW_LIMIT)]++ def rows_for(start: int, until: int) -> list[dict[str, Any]]:+ # The whole window is over the cap; each half fits.+ return full_page if (until - start) > 5_000 else [{"timestamp": start}]++ executor = RecordingNrqlExecutor(rows_for)+ batches = list(_fetch_event_window(executor, ACCOUNT_ID, "Transaction", 0, 10_000, MagicMock()))++ assert [_parse_since_until(q) for q in executor.queries] == [(0, 10_000), (0, 5_000), (5_000, 10_000)]+ assert [row["timestamp"] for batch in batches for row in batch] == [+ datetime.fromtimestamp(0, tz=UTC),+ datetime.fromtimestamp(5, tz=UTC),+ ]++ def test_minimum_window_at_cap_yields_with_truncation_warning(self) -> None:+ full_page = [{"timestamp": i} for i in range(NRQL_ROW_LIMIT)]+ executor = RecordingNrqlExecutor(lambda start, until: full_page)+ logger = MagicMock()++ batches = list(_fetch_event_window(executor, ACCOUNT_ID, "Transaction", 0, MIN_WINDOW_MS, logger))++ assert len(executor.queries) == 1+ assert len(batches) == 1+ assert len(batches[0]) == NRQL_ROW_LIMIT+ logger.warning.assert_called_once()+++@freeze_time("2026-01-02 12:00:00")+class TestGetEventRows:+ def _now_ms(self) -> int:+ return int(datetime(2026, 1, 2, 12, tzinfo=UTC).timestamp() * 1000)++ def _get_rows(+ self,+ executor: RecordingNrqlExecutor,+ manager: FakeResumableSourceManager,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> list[list[dict[str, Any]]]:+ with patch(f"{NEW_RELIC_MODULE}._make_executor", return_value=executor):+ return list(+ get_rows(+ api_key="NRAK-x",+ account_id=ACCOUNT_ID,+ region="US",+ endpoint="transactions",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )++ def test_incremental_sync_starts_one_ms_past_the_watermark(self) -> None:+ watermark = datetime(2026, 1, 2, 10, tzinfo=UTC)+ executor = RecordingNrqlExecutor(lambda start, until: [])++ self._get_rows(+ executor,+ FakeResumableSourceManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ first_since, _ = _parse_since_until(executor.queries[0])+ assert first_since == int(watermark.timestamp() * 1000) + 1++ def test_first_sync_reaches_back_the_default_lookback(self) -> None:+ executor = RecordingNrqlExecutor(lambda start, until: [])++ self._get_rows(executor, FakeResumableSourceManager())++ first_since, _ = _parse_since_until(executor.queries[0])+ assert first_since == self._now_ms() - DEFAULT_LOOKBACK_DAYS * 24 * 60 * 60 * 1000++ def test_until_excludes_the_ingest_lag_buffer(self) -> None:+ watermark = datetime(2026, 1, 2, 11, 30, tzinfo=UTC)+ executor = RecordingNrqlExecutor(lambda start, until: [])++ self._get_rows(+ executor,+ FakeResumableSourceManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ _, last_until = _parse_since_until(executor.queries[-1])+ assert last_until == self._now_ms() - INGEST_LAG_BUFFER_MS++ def test_watermark_past_until_makes_no_queries(self) -> None:+ watermark = datetime(2026, 1, 2, 11, 59, tzinfo=UTC) # inside the ingest-lag buffer+ executor = RecordingNrqlExecutor(lambda start, until: [])++ batches = self._get_rows(+ executor,+ FakeResumableSourceManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ assert batches == []+ assert executor.queries == []++ def test_saves_resume_state_after_each_window_except_the_last(self) -> None:+ watermark = datetime(2026, 1, 2, tzinfo=UTC) # ~12h of data → 2 windows+ executor = RecordingNrqlExecutor(lambda start, until: [{"timestamp": start}])+ manager = FakeResumableSourceManager()++ batches = self._get_rows(+ executor,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ assert len(batches) == 2+ assert [state.window_start_ms for state in manager.saved] == [+ int(watermark.timestamp() * 1000) + 1 + DEFAULT_WINDOW_MS+ ]++ def test_resumes_from_saved_window_start(self) -> None:+ resume_start = int(datetime(2026, 1, 2, 11, tzinfo=UTC).timestamp() * 1000)+ executor = RecordingNrqlExecutor(lambda start, until: [])+ manager = FakeResumableSourceManager(state=NewRelicResumeConfig(window_start_ms=resume_start))++ self._get_rows(+ executor,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )++ first_since, _ = _parse_since_until(executor.queries[0])+ assert first_since == resume_start+++class TestEntityStyleIterators:+ def test_entities_paginate_until_cursor_exhausted(self) -> None:+ pages = [+ {"entities": [{"guid": "g1"}], "nextCursor": "cursor-2"},+ {"entities": [{"guid": "g2"}], "nextCursor": None},+ ]+ calls: list[str | None] = []++ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ calls.append(variables["cursor"])+ return {"actor": {"entitySearch": {"results": pages[len(calls) - 1]}}}++ batches = list(_iter_entities(execute, ACCOUNT_ID))++ assert batches == [[{"guid": "g1"}], [{"guid": "g2"}]]+ assert calls == [None, "cursor-2"]++ def test_alert_policies_paginate_and_scope_to_account(self) -> None:+ pages = [+ {"policies": [{"id": "1"}], "nextCursor": "next"},+ {"policies": [{"id": "2"}], "nextCursor": None},+ ]+ calls: list[dict[str, Any]] = []++ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ calls.append(variables)+ return {"actor": {"account": {"alerts": {"policiesSearch": pages[len(calls) - 1]}}}}++ batches = list(_iter_alert_policies(execute, ACCOUNT_ID))++ assert batches == [[{"id": "1"}], [{"id": "2"}]]+ assert all(call["accountId"] == ACCOUNT_ID for call in calls)++ def test_alert_conditions_flatten_nested_nrql_query(self) -> None:+ page = {+ "nrqlConditions": [{"id": "1", "name": "cond", "nrql": {"query": "SELECT count(*) FROM Transaction"}}],+ "nextCursor": None,+ }++ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ return {"actor": {"account": {"alerts": {"nrqlConditionsSearch": page}}}}++ batches = list(_iter_alert_conditions(execute, ACCOUNT_ID))++ assert batches == [[{"id": "1", "name": "cond", "nrql_query": "SELECT count(*) FROM Transaction"}]]+++class TestValidateCredentials:+ def _validate(self, execute: Any) -> tuple[bool, str | None]:+ with patch(f"{NEW_RELIC_MODULE}._make_executor", return_value=execute):+ return validate_credentials("NRAK-x", ACCOUNT_ID, "US")++ def test_valid_key_with_account_access(self) -> None:+ is_valid, error = self._validate(+ lambda query, variables: {"actor": {"account": {"id": ACCOUNT_ID, "name": "acme"}}}+ )+ assert is_valid is True+ assert error is None++ def test_valid_key_without_account_access(self) -> None:+ is_valid, error = self._validate(lambda query, variables: {"actor": {"account": None}})+ assert is_valid is False+ assert error is not None and str(ACCOUNT_ID) in error++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])+ def test_auth_http_errors_report_invalid_key(self, _name: str, status_code: int) -> None:+ response = MagicMock()+ response.status_code = status_code++ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ raise requests.HTTPError(response=response)++ is_valid, error = self._validate(execute)+ assert is_valid is False+ assert error is not None and "API key" in error++ def test_graphql_error_is_reported(self) -> None:+ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ raise NewRelicGraphQLError("boom")++ is_valid, error = self._validate(execute)+ assert is_valid is False+ assert error is not None and "boom" in error+++class TestNewRelicSourceResponse:+ def test_event_endpoint_is_append_only_with_datetime_partitions(self) -> None:+ response = new_relic_source(+ api_key="NRAK-x",+ account_id=ACCOUNT_ID,+ region="US",+ endpoint="transactions",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )++ assert response.name == "transactions"+ assert response.primary_keys is None+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_format == "week"+ assert response.partition_keys == ["timestamp"]++ @parameterized.expand(+ [+ ("entities", ["guid"]),+ ("alert_policies", ["id"]),+ ("alert_conditions", ["id"]),+ ]+ )+ def test_entity_endpoints_have_primary_keys_and_no_partitions(self, endpoint: str, primary_keys: list[str]) -> None:+ response = new_relic_source(+ api_key="NRAK-x",+ account_id=ACCOUNT_ID,+ region="US",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )++ assert response.primary_keys == primary_keys+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_entity_endpoint_rows_flow_through_get_rows(self) -> None:+ def execute(query: str, variables: dict[str, Any]) -> dict[str, Any]:+ return {"actor": {"entitySearch": {"results": {"entities": [{"guid": "g1"}], "nextCursor": None}}}}++ with patch(f"{NEW_RELIC_MODULE}._make_executor", return_value=execute):+ response = new_relic_source(+ api_key="NRAK-x",+ account_id=ACCOUNT_ID,+ region="US",+ endpoint="entities",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert list(cast(Iterable[Any], response.items())) == [[{"guid": "g1"}]]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic_source.pynew file mode 100644index 000000000000..3334727bbf39--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic_source.py@@ -0,0 +1,166 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NewRelicSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.new_relic import NewRelicResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.source import NewRelicSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.new_relic.source"+++class TestNewRelicSource:+ def setup_method(self):+ self.source = NewRelicSource()+ self.team_id = 123+ self.config = NewRelicSourceConfig(api_key="NRAK-x", account_id=1234567, region="US")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.NEWRELIC++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "NewRelic"+ assert config.label == "New Relic"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/new-relic"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "account_id", "region"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if f.name == "api_key")+ assert isinstance(key_field, SourceFieldInputConfig)+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_region_field_defaults_to_us_and_offers_eu(self):+ config = self.source.get_source_config+ region_field = next(f for f in config.fields if f.name == "region")+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.defaultValue == "US"+ assert [option.value for option in region_field.options] == ["US", "EU"]++ @parameterized.expand(+ [+ ("us_unauthorized", "401 Client Error: Unauthorized for url: https://api.newrelic.com/graphql"),+ ("eu_unauthorized", "401 Client Error: Unauthorized for url: https://api.eu.newrelic.com/graphql"),+ ("us_forbidden", "403 Client Error: Forbidden for url: https://api.newrelic.com/graphql"),+ ("eu_forbidden", "403 Client Error: Forbidden for url: https://api.eu.newrelic.com/graphql"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @parameterized.expand(+ [+ ("other_vendor", "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers"),+ ("server_error", "500 Server Error for url: https://api.newrelic.com/graphql"),+ ]+ )+ def test_non_retryable_errors_do_not_match_unrelated(self, _name, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_covers_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("transactions", True),+ ("transaction_errors", True),+ ("page_views", True),+ ("logs", True),+ ("spans", True),+ ("entities", False),+ ("alert_policies", False),+ ("alert_conditions", False),+ ]+ )+ def test_event_tables_are_append_only_and_entity_tables_full_refresh(self, endpoint, supports_append):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_append is supports_append+ assert schema.supports_incremental is False+ assert bool(schema.incremental_fields) is supports_append++ @parameterized.expand([("logs",), ("spans",)])+ def test_high_volume_tables_are_off_by_default(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.should_sync_default is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["entities"])+ assert [schema.name for schema in schemas] == ["entities"]++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_canonical_descriptions_cover_every_endpoint(self):+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)++ def test_documented_tables_render_without_credentials(self):+ tables = self.source.get_documented_tables()+ assert {table["name"] for table in tables} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid", (False, "Invalid New Relic API key")),+ ]+ )+ @patch(f"{SOURCE_MODULE}.validate_new_relic_credentials")+ def test_validate_credentials_plumbs_config(self, _name, result, mock_validate):+ mock_validate.return_value = result++ assert self.source.validate_credentials(self.config, self.team_id) == result+ mock_validate.assert_called_once_with(self.config.api_key, self.config.account_id, self.config.region)++ def test_connection_host_fields_require_secret_reentry_on_retarget(self):+ assert self.source.connection_host_fields == ["account_id", "region"]++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is NewRelicResumeConfig++ @patch(f"{SOURCE_MODULE}.new_relic_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):+ inputs = MagicMock()+ inputs.schema_name = "transactions"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "watermark"+ manager = MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key=self.config.api_key,+ account_id=self.config.account_id,+ region=self.config.region,+ endpoint="transactions",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="watermark",+ )++ @patch(f"{SOURCE_MODULE}.new_relic_source")+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_source):+ inputs = MagicMock()+ inputs.schema_name = "transactions"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "stale-watermark"++ self.source.source_for_pipeline(self.config, MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None