: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 splunk_observability_cloud import source (#71249)
Tom Owers318a7dc88bc2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b08210cdef42..f1c2bec1a5f2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -917,7 +917,6 @@ doesn't conflict with concurrent PRs.- sonatype_nexus- sourcegraph- spacelift-- splunk_observability_cloud- spotify_ads- spotlercrm- squadcastdiff --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 24e6f61d2fb9..740fd9695c04 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@@ -4040,7 +4040,9 @@ class SplitIoSourceConfig(config.Config):@config.configclass SplunkObservabilityCloudSourceConfig(config.Config):- pass+ realm: str+ access_token: str+ signalflow_program: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/canonical_descriptions.pynew file mode 100644index 000000000000..5d9870d78e85--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/canonical_descriptions.py@@ -0,0 +1,170 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "detectors": {+ "description": "Detectors that monitor signals and trigger alert events when their conditions are met.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/detectors/latest",+ "columns": {+ "id": "Unique identifier of the detector.",+ "name": "Display name of the detector.",+ "description": "Human-readable description of what the detector monitors.",+ "programText": "SignalFlow program that defines the detector's computation and detect blocks.",+ "rules": "Alert rules mapping each detect label to a severity and notification settings.",+ "labelResolutions": "Resolution (in milliseconds) of the data the detector evaluates, per detect label.",+ "maxDelay": "Maximum time (in milliseconds) the detector waits for late datapoints.",+ "teams": "Identifiers of the teams linked to the detector.",+ "tags": "Tags applied to the detector.",+ "creator": "Identifier of the user who created the detector.",+ "lastUpdatedBy": "Identifier of the user who last updated the detector.",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "detector_events": {+ "description": "Alert events generated by detectors: one row per trigger or clear of a detect condition.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/detectors/latest",+ "columns": {+ "id": "Unique identifier of the alert event.",+ "detectorId": "Identifier of the detector that generated the event.",+ "detectorName": "Name of the detector that generated the event.",+ "detectLabel": "Label of the detect block that fired.",+ "incidentId": "Identifier of the incident this event belongs to.",+ "anomalyState": "State transition the event records, such as ANOMALOUS or CLEARED.",+ "severity": "Severity of the alert, such as Critical, Major, Minor, Warning, or Info.",+ "inputs": "Signal values that triggered the event.",+ "timestamp": "Time the event occurred (converted from milliseconds since the Unix epoch).",+ },+ },+ "incidents": {+ "description": "Incidents opened by detectors, grouping the trigger and clear events of one anomaly.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/incidents/latest",+ "columns": {+ "incidentId": "Unique identifier of the incident.",+ "active": "Whether the incident is still active.",+ "anomalyState": "Current anomaly state of the incident.",+ "detectorId": "Identifier of the detector that opened the incident.",+ "detectorName": "Name of the detector that opened the incident.",+ "detectLabel": "Label of the detect block that opened the incident.",+ "severity": "Severity of the incident.",+ "isMuted": "Whether notifications for the incident are muted.",+ "events": "Alert events that make up the incident.",+ "triggeredWhileMuted": "Whether the incident was triggered while muting was in effect.",+ },+ },+ "alert_muting_rules": {+ "description": "Rules that silence alert notifications for matching detectors or dimensions during a time window.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/alert_muting_rules/latest",+ "columns": {+ "id": "Unique identifier of the muting rule.",+ "description": "Human-readable description of the muting rule.",+ "filters": "Property/value filters selecting which alerts the rule mutes.",+ "startTime": "Start of the muting window, in milliseconds since the Unix epoch.",+ "stopTime": "End of the muting window, in milliseconds since the Unix epoch (0 means indefinite).",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "dashboards": {+ "description": "Dashboards: named collections of charts arranged in a grid.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/dashboards/latest",+ "columns": {+ "id": "Unique identifier of the dashboard.",+ "name": "Display name of the dashboard.",+ "description": "Human-readable description of the dashboard.",+ "groupId": "Identifier of the dashboard group the dashboard belongs to.",+ "charts": "Chart placements (chart id, row, column, height, width) on the dashboard.",+ "filters": "Default variables and filters applied to the dashboard.",+ "creator": "Identifier of the user who created the dashboard.",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "dashboard_groups": {+ "description": "Dashboard groups that organize related dashboards and control their permissions.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/dashboard_groups/latest",+ "columns": {+ "id": "Unique identifier of the dashboard group.",+ "name": "Display name of the dashboard group.",+ "description": "Human-readable description of the dashboard group.",+ "dashboards": "Identifiers of the dashboards in the group.",+ "teams": "Identifiers of the teams linked to the dashboard group.",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "charts": {+ "description": "Charts that visualize the output of a SignalFlow program on dashboards.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/charts/latest",+ "columns": {+ "id": "Unique identifier of the chart.",+ "name": "Display name of the chart.",+ "description": "Human-readable description of the chart.",+ "programText": "SignalFlow program that produces the data the chart displays.",+ "options": "Visualization options, including the chart type and axis settings.",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "teams": {+ "description": "Teams that group organization members and link to detectors and dashboard groups.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/teams/latest",+ "columns": {+ "id": "Unique identifier of the team.",+ "name": "Display name of the team.",+ "description": "Human-readable description of the team.",+ "members": "Identifiers of the organization members on the team.",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "organization_members": {+ "description": "Members of the organization and their roles.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/organizations/latest",+ "columns": {+ "id": "Unique identifier of the membership record.",+ "userId": "Identifier of the member's user account.",+ "email": "Email address of the member.",+ "fullName": "Full name of the member.",+ "admin": "Whether the member is an organization administrator.",+ "created": "Time the member joined the organization, in milliseconds since the Unix epoch.",+ },+ },+ "metrics": {+ "description": "Metric metadata: one row per metric name known to the organization.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/metrics_metadata/latest",+ "columns": {+ "name": "Name of the metric.",+ "type": "Metric type: GAUGE, COUNTER, or CUMULATIVE_COUNTER.",+ "description": "Human-readable description of the metric.",+ "customProperties": "Custom properties attached to the metric.",+ "tags": "Tags attached to the metric.",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "dimensions": {+ "description": "Dimension metadata: one row per dimension key/value pair used by time series.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/metrics_metadata/latest",+ "columns": {+ "key": "Name of the dimension.",+ "value": "Value of the dimension.",+ "customProperties": "Custom properties attached to the dimension.",+ "tags": "Tags attached to the dimension.",+ "created": "Creation time, in milliseconds since the Unix epoch.",+ "lastUpdated": "Last modification time, in milliseconds since the Unix epoch.",+ },+ },+ "metric_time_series": {+ "description": "Datapoints published by the SignalFlow program configured on the source, one row per time series per timestamp.",+ "docs_url": "https://dev.splunk.com/observability/reference/api/signalflow/latest",+ "columns": {+ "tsId": "Identifier of the output time series within the SignalFlow computation.",+ "timestamp": "Logical timestamp of the datapoint.",+ "value": "Value of the datapoint.",+ "metric": "Metric name of the time series (sf_metric), when published.",+ "properties": "JSON object of the time series metadata, including its dimensions.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/settings.pynew file mode 100644index 000000000000..180b6a1f763a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/settings.py@@ -0,0 +1,144 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Splunk Observability Cloud (formerly SignalFx) REST endpoints live under /v2 on the+# realm-scoped API host. Most list/search endpoints paginate with offset/limit and wrap+# results as {"count": N, "results": [...]}; a couple (incidents, detector events) return+# a bare JSON array instead. Shapes verified against the official signalfx-go client.+PAGE_SIZE = 100++# Splunk Observability Cloud returns at most 10,000 events per detector regardless of+# paging (documented retrieve-operation cap), so log when a detector hits it.+DETECTOR_EVENTS_RESULT_CAP = 10_000++# Hard stop for offset paging so a server that ignores `offset` can't loop us forever.+MAX_OFFSET = 1_000_000++# First metric_time_series sync pulls this window of datapoints when no watermark exists;+# subsequent incremental syncs resume from the stored timestamp watermark.+SIGNALFLOW_DEFAULT_LOOKBACK_DAYS = 30++ResponseStyle = Literal["wrapped", "list"]++_TIMESTAMP_INCREMENTAL_FIELD: list[IncrementalField] = [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class SplunkObservabilityCloudEndpointConfig:+ name: str+ # Path under /v2 on the realm API host. Empty for the SignalFlow-backed endpoint.+ path: str+ # "wrapped" = {"count": N, "results": [...]}; "list" = bare JSON array.+ response_style: ResponseStyle = "wrapped"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Extra query params sent on every request (e.g. required search queries).+ extra_params: dict[str, str] = field(default_factory=dict)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Fan out one request per detector (path holds a {detector_id} placeholder).+ fan_out_over_detectors: bool = False+ # Rows stream from a SignalFlow computation instead of a REST list endpoint.+ uses_signalflow: bool = False+ # Stable datetime field to partition by; only endpoints whose rows are immutable+ # events set this (metadata objects are small enough to skip partitioning).+ partition_key: Optional[str] = None+ should_sync_default: bool = True+++SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS: dict[str, SplunkObservabilityCloudEndpointConfig] = {+ "detectors": SplunkObservabilityCloudEndpointConfig(+ name="detectors",+ path="/detector",+ ),+ # Alert events generated by each detector. The API takes server-side `from`/`to`+ # epoch-ms bounds, so this endpoint is genuinely incremental on `timestamp`.+ "detector_events": SplunkObservabilityCloudEndpointConfig(+ name="detector_events",+ path="/detector/{detector_id}/events",+ response_style="list",+ # Event ids are not documented as globally unique, so the parent detector id is+ # part of the key. `detectorId` is already a field on every event row.+ primary_keys=["detectorId", "id"],+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ fan_out_over_detectors=True,+ partition_key="timestamp",+ ),+ "incidents": SplunkObservabilityCloudEndpointConfig(+ name="incidents",+ path="/incident",+ response_style="list",+ primary_keys=["incidentId"],+ # Without this flag the API only returns currently-active incidents.+ extra_params={"includeResolved": "true"},+ ),+ "alert_muting_rules": SplunkObservabilityCloudEndpointConfig(+ name="alert_muting_rules",+ path="/alertmuting",+ ),+ "dashboards": SplunkObservabilityCloudEndpointConfig(+ name="dashboards",+ path="/dashboard",+ ),+ "dashboard_groups": SplunkObservabilityCloudEndpointConfig(+ name="dashboard_groups",+ path="/dashboardgroup",+ ),+ "charts": SplunkObservabilityCloudEndpointConfig(+ name="charts",+ path="/chart",+ ),+ "teams": SplunkObservabilityCloudEndpointConfig(+ name="teams",+ path="/team",+ ),+ "organization_members": SplunkObservabilityCloudEndpointConfig(+ name="organization_members",+ path="/organization/member",+ ),+ # Metric metadata search. The search endpoints require an Elasticsearch-style query;+ # `name:*` is the documented way to match every metric by name.+ "metrics": SplunkObservabilityCloudEndpointConfig(+ name="metrics",+ path="/metric",+ primary_keys=["name"],+ extra_params={"query": "name:*"},+ ),+ # Dimension metadata search. Off by default: large orgs can have millions of+ # dimension values, and the `key:*` match-everything query is derived from the+ # documented ES query-string syntax but hasn't been verified against a live org.+ "dimensions": SplunkObservabilityCloudEndpointConfig(+ name="dimensions",+ path="/dimension",+ primary_keys=["key", "value"],+ extra_params={"query": "key:*"},+ should_sync_default=False,+ ),+ # Metric datapoints streamed from a SignalFlow computation (SSE), windowed by+ # start/stop epoch-ms params — incremental on the datapoint timestamp. Requires the+ # optional "SignalFlow program" source field, so it's off by default.+ "metric_time_series": SplunkObservabilityCloudEndpointConfig(+ name="metric_time_series",+ path="",+ primary_keys=["tsId", "timestamp"],+ incremental_fields=_TIMESTAMP_INCREMENTAL_FIELD,+ uses_signalflow=True,+ partition_key="timestamp",+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields+ for name, config in SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS.items()+ if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/source.pyindex 82b78d23aa48..971b91714888 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/source.py@@ -1,32 +1,185 @@-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 (SplunkObservabilityCloudSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.splunk_observability_cloud import (+ SplunkObservabilityCloudResumeConfig,+ splunk_observability_cloud_source,+ validate_credentials as validate_splunk_observability_cloud_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SplunkObservabilityCloudSource(SimpleSource[SplunkObservabilityCloudSourceConfig]):+class SplunkObservabilityCloudSource(+ ResumableSource[SplunkObservabilityCloudSourceConfig, SplunkObservabilityCloudResumeConfig]+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SPLUNKOBSERVABILITYCLOUD+ @property+ def connection_host_fields(self) -> list[str]:+ # The realm is interpolated into the request hostname the stored token is sent to;+ # retargeting it must re-require the token.+ return ["realm"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SPLUNK_OBSERVABILITY_CLOUD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Splunk (Cisco) - Splunk Observability Cloud",+ label="Splunk Observability Cloud",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync your Splunk Observability Cloud (formerly SignalFx) detectors, alert history, dashboards, and metric metadata into the PostHog Data warehouse.++You need an access token with **API** permission — an org access token or a user session token both work. Create one under **Settings > Access tokens** in Splunk Observability Cloud. Your realm (e.g. `us0`, `eu0`) is shown on your profile page.++To sync the optional `metric_time_series` table, also provide a [SignalFlow program](https://dev.splunk.com/observability/docs/signalflow/) whose published output is pulled incrementally by time window.""",iconPath="/static/services/splunk_observability_cloud.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/splunk-observability-cloud",+ keywords=["signalfx", "splunk", "cisco", "observability", "apm"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="realm",+ label="Realm",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="us0",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="signalflow_program",+ label="SignalFlow program (optional, for metric_time_series)",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="data('cpu.utilization').mean().publish()",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Splunk Observability Cloud access token is invalid or has expired. Create a new access token with API permission and reconnect.",+ "403 Client Error": "Your Splunk Observability Cloud access token does not have the required permissions. Use an access token with API permission (admin, power, or read_only role) and reconnect.",+ "Invalid Splunk Observability Cloud realm": None,+ }++ def get_schemas(+ self,+ config: SplunkObservabilityCloudSourceConfig,+ 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 == "detector_events":+ return (+ "Alert events generated by every detector. The API returns at most 10,000 events per "+ "detector, so older history beyond that cap is not synced"+ )+ if endpoint == "dimensions":+ return "Dimension metadata. Off by default because large organizations can have a very high dimension count"+ if endpoint == "metric_time_series":+ return (+ "Datapoints published by the SignalFlow program configured on the source, pulled "+ "incrementally by time window. Requires the 'SignalFlow program' source field"+ )+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS[endpoint]+ has_incremental = INCREMENTAL_FIELDS.get(endpoint) is not None+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ 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: SplunkObservabilityCloudSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_splunk_observability_cloud_credentials(config.realm, config.access_token)++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[SplunkObservabilityCloudResumeConfig]:+ return ResumableSourceManager[SplunkObservabilityCloudResumeConfig](+ inputs, SplunkObservabilityCloudResumeConfig+ )++ def source_for_pipeline(+ self,+ config: SplunkObservabilityCloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[SplunkObservabilityCloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return splunk_observability_cloud_source(+ realm=config.realm,+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ signalflow_program=config.signalflow_program,+ 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/splunk_observability_cloud/splunk_observability_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/splunk_observability_cloud.pynew file mode 100644index 000000000000..2b3e5731318a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/splunk_observability_cloud.py@@ -0,0 +1,511 @@+import re+import json+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++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.splunk_observability_cloud.settings import (+ DETECTOR_EVENTS_RESULT_CAP,+ MAX_OFFSET,+ PAGE_SIZE,+ SIGNALFLOW_DEFAULT_LOOKBACK_DAYS,+ SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS,+ SplunkObservabilityCloudEndpointConfig,+)++# Realms are short lowercase alphanumeric codes (us0, us1, eu0, jp0, ...). The realm is+# interpolated into the request hostname, so anything else is rejected up front — both to+# fail fast on typos and to stop a crafted "realm" from retargeting the stored token.+_REALM_RE = re.compile(r"^[a-z0-9]{1,32}$")++# Rows per yielded batch; the pipeline re-batches, this just bounds source-side memory.+_BATCH_SIZE = 5000++REQUEST_TIMEOUT_SECONDS = 60+# (connect, read) for the SignalFlow SSE stream; the read timeout applies between chunks,+# and historical computations emit control/data messages well within this.+STREAM_TIMEOUT_SECONDS = (30, 180)+++class SplunkObservabilityCloudRetryableError(Exception):+ pass+++class SplunkObservabilityCloudResumeConfig:+ # Offset of the next page to fetch within the current endpoint (or current detector+ # for the detector_events fan-out).+ offset: int = 0+ # Stable bookmark for the detector_events fan-out: the detector currently being+ # processed. None for every other endpoint.+ detector_id: str | None = None+++def normalize_realm(realm: str) -> str:+ normalized = realm.strip().lower()+ if not _REALM_RE.match(normalized):+ raise ValueError(+ "Invalid Splunk Observability Cloud realm. Use the short realm code from your profile page (e.g. us0, eu0)."+ )+ return normalized+++def _api_base_url(realm: str) -> str:+ return f"https://api.{normalize_realm(realm)}.signalfx.com"+++def _stream_base_url(realm: str) -> str:+ return f"https://stream.{normalize_realm(realm)}.signalfx.com"+++def _get_headers(access_token: str) -> dict[str, str]:+ return {"X-SF-TOKEN": access_token, "Accept": "application/json"}+++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)+ return int(value)+++def _ms_to_datetime(value: Any) -> datetime | None:+ if value is None:+ return None+ return datetime.fromtimestamp(int(value) / 1000, tz=UTC)+++@retry(+ retry=retry_if_exception_type(+ (+ SplunkObservabilityCloudRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SplunkObservabilityCloudRetryableError(+ f"Splunk Observability Cloud API error (retryable): status={response.status_code}, url={url}"+ )++ # Redirects are never followed (the session pins allow_redirects=False so the+ # X-SF-TOKEN header can't be replayed to another host); the API answers directly,+ # so a 3xx means the realm doesn't point at a real API tenant.+ if response.is_redirect:+ raise Exception(+ f"Splunk Observability Cloud returned a redirect, which usually means the realm is wrong. url={url}"+ )++ if not response.ok:+ logger.error(+ f"Splunk Observability Cloud API error: status={response.status_code}, body={response.text}, url={url}"+ )+ response.raise_for_status()++ return response.json()+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ query = urlencode({key: str(value) for key, value in params.items()})+ return f"{base_url}/v2{path}?{query}" if query else f"{base_url}/v2{path}"+++def _extract_page(config: SplunkObservabilityCloudEndpointConfig, data: Any) -> list[dict[str, Any]]:+ if config.response_style == "wrapped":+ results = data.get("results", []) if isinstance(data, dict) else []+ else:+ results = data if isinstance(data, list) else []+ return [row for row in results if isinstance(row, dict)]+++def _paginate(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ config: SplunkObservabilityCloudEndpointConfig,+ logger: FilteringBoundLogger,+ path: str | None = None,+ extra_params: dict[str, Any] | None = None,+ start_offset: int = 0,+ on_page: Callable[[int | None], None] | None = None,+) -> Iterator[list[dict[str, Any]]]:+ """Walk an offset/limit-paginated endpoint, yielding one list of rows per page.++ `on_page(next_offset | None)` is called after each page is yielded so callers can+ checkpoint resume state (None means the endpoint is exhausted).+ """+ offset = start_offset+ while True:+ params: dict[str, Any] = {"offset": offset, "limit": PAGE_SIZE}+ params.update(config.extra_params)+ params.update(extra_params or {})+ url = _build_url(base_url, path if path is not None else config.path, params)+ data = _fetch(session, url, headers, logger)+ rows = _extract_page(config, data)++ if not rows:+ if on_page is not None:+ on_page(None)+ return++ offset += len(rows)+ has_more = len(rows) >= PAGE_SIZE and offset < MAX_OFFSET+ yield rows+ if on_page is not None:+ on_page(offset if has_more else None)++ if offset >= MAX_OFFSET:+ logger.warning(+ f"Splunk Observability Cloud: offset cap reached, truncating results. endpoint={config.name}, offset={offset}"+ )+ if not has_more:+ return+++def _iter_detector_ids(+ session: requests.Session, base_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ detectors_config = SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS["detectors"]+ for page in _paginate(session, base_url, headers, detectors_config, logger):+ for row in page:+ detector_id = row.get("id")+ if detector_id:+ yield str(detector_id)+++def _get_detector_event_rows(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ config: SplunkObservabilityCloudEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SplunkObservabilityCloudResumeConfig],+ from_ms: int,+ to_ms: int,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every detector and pull its alert events within [from_ms, to_ms].++ The bookmark is the detector id (stable across runs, unlike a positional index) plus+ the offset within that detector. If the bookmarked detector was deleted between a+ crash and the retry, we start over from the first detector — merge dedupes re-pulled+ rows on the primary key.+ """+ detector_ids = list(_iter_detector_ids(session, base_url, headers, logger))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = detector_ids+ resume_offset = 0+ if resume is not None and resume.detector_id is not None and resume.detector_id in detector_ids:+ remaining = detector_ids[detector_ids.index(resume.detector_id) :]+ resume_offset = resume.offset+ logger.debug(+ f"Splunk Observability Cloud: resuming detector_events from detector_id={resume.detector_id}, offset={resume_offset}"+ )++ for index, detector_id in enumerate(remaining):+ path = config.path.format(detector_id=detector_id)++ def _checkpoint(next_offset: int | None, detector_id: str = detector_id) -> None:+ # Save AFTER the page is yielded so a crash re-yields the last page rather+ # than skipping it — merge dedupes on the primary key.+ if next_offset is None:+ return+ resumable_source_manager.save_state(+ SplunkObservabilityCloudResumeConfig(offset=next_offset, detector_id=detector_id)+ )+ if next_offset >= DETECTOR_EVENTS_RESULT_CAP:+ logger.warning(+ f"Splunk Observability Cloud: detector events cap reached; older events may be truncated. detector_id={detector_id}"+ )++ for page in _paginate(+ session,+ base_url,+ headers,+ config,+ logger,+ path=path,+ extra_params={"from": from_ms, "to": to_ms},+ start_offset=resume_offset,+ on_page=_checkpoint,+ ):+ yield [_normalize_event_row(row) for row in page]++ resume_offset = 0++ # Advance the bookmark to the next detector so a crash between detectors resumes+ # in the right place.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(+ SplunkObservabilityCloudResumeConfig(offset=0, detector_id=remaining[index + 1])+ )+++def _normalize_event_row(row: dict[str, Any]) -> dict[str, Any]:+ # Epoch-ms timestamps don't work as datetime incremental/partition fields, so surface+ # the event time as a real datetime.+ normalized = dict(row)+ normalized["timestamp"] = _ms_to_datetime(row.get("timestamp"))+ return normalized+++def _iter_sse_events(response: requests.Response) -> Iterator[tuple[str, str]]:+ """Minimal Server-Sent Events parser: yields (event_name, data) per event."""+ event_name: str | None = None+ data_lines: list[str] = []+ for line in response.iter_lines(decode_unicode=True):+ if line is None:+ continue+ if line == "":+ if data_lines:+ yield event_name or "message", "\n".join(data_lines)+ event_name = None+ data_lines = []+ continue+ if line.startswith(":"):+ continue+ if line.startswith("event:"):+ event_name = line[len("event:") :].strip()+ elif line.startswith("data:"):+ data_lines.append(line[len("data:") :].strip())+ if data_lines:+ yield event_name or "message", "\n".join(data_lines)+++def _get_signalflow_rows(+ session: requests.Session,+ realm: str,+ access_token: str,+ program: str,+ start_ms: int,+ stop_ms: int,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Run a SignalFlow computation over [start_ms, stop_ms] and yield datapoint rows.++ The computation streams back as Server-Sent Events: `metadata` messages describe each+ output time series ({tsId, properties}), `data` messages carry one batch of values per+ logical timestamp ({logicalTimestampMs, data: [{tsId, value}]}), and a final+ END_OF_CHANNEL control message closes the stream. Message shapes follow the official+ SignalFlow SSE transport (signalfx-python).+ """+ url = f"{_stream_base_url(realm)}/v2/signalflow/execute"+ params = {"start": str(start_ms), "stop": str(stop_ms), "immediate": "true"}+ headers = {"X-SF-TOKEN": access_token, "Content-Type": "text/plain"}++ response = session.post(+ url,+ params=params,+ data=program.encode("utf-8"),+ headers=headers,+ stream=True,+ timeout=STREAM_TIMEOUT_SECONDS,+ )+ # A 3xx passes `response.ok`, and the session never follows redirects (token+ # replay protection) — fail loudly instead of ending the stream empty.+ if response.is_redirect:+ raise Exception(+ "Splunk Observability Cloud SignalFlow returned a redirect, which usually means the realm is wrong"+ )+ if not response.ok:+ logger.error(+ f"Splunk Observability Cloud SignalFlow error: status={response.status_code}, body={response.text[:2000]}"+ )+ response.raise_for_status()++ metadata_by_tsid: dict[str, dict[str, Any]] = {}+ batch: list[dict[str, Any]] = []++ try:+ for event_name, data in _iter_sse_events(response):+ try:+ payload = json.loads(data)+ except json.JSONDecodeError:+ logger.warning(+ f"Splunk Observability Cloud: skipping undecodable SignalFlow message. event={event_name}"+ )+ continue++ if event_name == "metadata":+ metadata_by_tsid[payload["tsId"]] = payload.get("properties") or {}+ elif event_name == "data":+ timestamp = _ms_to_datetime(payload.get("logicalTimestampMs"))+ for datum in payload.get("data", []):+ tsid = datum.get("tsId")+ properties = metadata_by_tsid.get(tsid, {})+ batch.append(+ {+ "tsId": tsid,+ "timestamp": timestamp,+ "value": datum.get("value"),+ "metric": properties.get("sf_metric"),+ # Dimensions vary per time series, so keep them as one JSON column+ # instead of exploding an unbounded set of columns.+ "properties": json.dumps(properties) if properties else None,+ }+ )+ if len(batch) >= _BATCH_SIZE:+ yield batch+ batch = []+ elif event_name == "error":+ raise Exception(f"SignalFlow computation failed: {payload.get('errors')}")+ elif event_name == "control-message":+ control_event = payload.get("event")+ if control_event == "CHANNEL_ABORT":+ raise Exception(f"SignalFlow computation aborted: {payload.get('abortInfo')}")+ if control_event == "END_OF_CHANNEL":+ break+ finally:+ response.close()++ if batch:+ yield batch+++def get_rows(+ realm: str,+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SplunkObservabilityCloudResumeConfig],+ signalflow_program: str | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS[endpoint]+ base_url = _api_base_url(realm)+ headers = _get_headers(access_token)+ # allow_redirects=False pins every credentialed request to the Splunk hosts:+ # requests only strips `Authorization` on a cross-host redirect, so a followed+ # redirect would replay the X-SF-TOKEN header to whatever host the 3xx names.+ # capture=False: detector/dashboard/chart response bodies and the SignalFlow+ # program hold arbitrary customer content the name-based scrubber can't redact.+ session = make_tracked_session(redact_values=(access_token,), allow_redirects=False, capture=False)+ now_ms = _to_epoch_ms(datetime.now(UTC))++ if config.uses_signalflow:+ program = (signalflow_program or "").strip()+ if not program:+ raise ValueError(+ "The metric_time_series table requires a SignalFlow program. Edit the source and fill in the "+ "'SignalFlow program' field (e.g. data('cpu.utilization').publish())."+ )+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ start_ms = _to_epoch_ms(db_incremental_field_last_value)+ else:+ start_ms = now_ms - int(timedelta(days=SIGNALFLOW_DEFAULT_LOOKBACK_DAYS).total_seconds() * 1000)+ yield from _get_signalflow_rows(session, realm, access_token, program, start_ms, now_ms, logger)+ return++ if config.fan_out_over_detectors:+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ from_ms = _to_epoch_ms(db_incremental_field_last_value)+ else:+ from_ms = 0+ yield from _get_detector_event_rows(+ session, base_url, headers, config, logger, resumable_source_manager, from_ms, now_ms+ )+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_offset = resume.offset if resume is not None else 0++ def _checkpoint(next_offset: int | None) -> None:+ # Save AFTER the page is yielded so a crash re-yields the last page rather than+ # skipping it — merge dedupes on the primary key.+ if next_offset is not None:+ resumable_source_manager.save_state(SplunkObservabilityCloudResumeConfig(offset=next_offset))++ yield from _paginate(+ session,+ base_url,+ headers,+ config,+ logger,+ start_offset=start_offset,+ on_page=_checkpoint,+ )+++def splunk_observability_cloud_source(+ realm: str,+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SplunkObservabilityCloudResumeConfig],+ signalflow_program: str | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ realm=realm,+ access_token=access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ signalflow_program=signalflow_program,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ # The detector_events fan-out is not globally time-ordered (events arrive grouped+ # by detector), so declare desc to persist the incremental watermark only at+ # successful job end instead of checkpointing a misleading per-batch max.+ # SignalFlow data messages stream in ascending logical-timestamp order.+ sort_mode="desc" if endpoint_config.fan_out_over_detectors else "asc",+ partition_count=1,+ partition_size=1,+ 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,+ )+++def validate_credentials(realm: str, access_token: str) -> tuple[bool, str | None]:+ try:+ base_url = _api_base_url(realm)+ except ValueError as e:+ return False, str(e)++ try:+ # One cheap probe: /v2/organization answers for any valid API-scoped token.+ # allow_redirects=False so the X-SF-TOKEN header can't be replayed off-host.+ # capture=False: the org response body carries arbitrary customer content.+ response = make_tracked_session(redact_values=(access_token,), allow_redirects=False, capture=False).get(+ f"{base_url}/v2/organization",+ headers=_get_headers(access_token),+ timeout=10,+ )+ except Exception as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Splunk Observability Cloud access token or realm"+ if response.is_redirect:+ return False, "Splunk Observability Cloud redirected the request, which usually means the realm is wrong"+ return False, f"Splunk Observability Cloud returned an unexpected status code: {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/tests/test_splunk_observability_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/tests/test_splunk_observability_cloud.pynew file mode 100644index 000000000000..cb10f818b5b9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/tests/test_splunk_observability_cloud.py@@ -0,0 +1,515 @@+import json+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock, patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.settings import (+ PAGE_SIZE,+ SIGNALFLOW_DEFAULT_LOOKBACK_DAYS,+ SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.splunk_observability_cloud import (+ SplunkObservabilityCloudResumeConfig,+ _iter_sse_events,+ _ms_to_datetime,+ _to_epoch_ms,+ get_rows,+ normalize_realm,+ splunk_observability_cloud_source,+ validate_credentials,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.splunk_observability_cloud"+++def _json_response(body: Any, status_code: int = 200) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.is_redirect = False+ response.json.return_value = body+ response.text = json.dumps(body)+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=response)+ return response+++def _wrapped(rows: list[dict[str, Any]], count: int | None = None) -> dict[str, Any]:+ return {"count": count if count is not None else len(rows), "results": rows}+++def _make_manager(resume: SplunkObservabilityCloudResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _drive_rest(+ endpoint: str,+ responses: list[MagicMock],+ manager: MagicMock | None = None,+ **kwargs: Any,+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], MagicMock]:+ """Run get_rows against canned responses; returns (rows, per-request query params, manager)."""+ manager = manager if manager is not None else _make_manager()+ requested: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_get(url: str, **_kw: Any) -> MagicMock:+ parsed = urlparse(url)+ params = {key: values[0] for key, values in parse_qs(parsed.query).items()}+ params["__path"] = parsed.path+ requested.append(params)+ return next(response_iter)++ with patch(f"{_MODULE}.make_tracked_session") as mock_session_factory:+ mock_session_factory.return_value.get.side_effect = fake_get+ rows = [+ row+ for page in get_rows(+ realm="us0",+ access_token="test-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ **kwargs,+ )+ for row in page+ ]+ return rows, requested, manager+++class TestNormalizeRealm:+ @pytest.mark.parametrize(("raw", "expected"), [("us0", "us0"), (" EU0 ", "eu0"), ("jp0", "jp0")])+ def test_valid(self, raw: str, expected: str) -> None:+ assert normalize_realm(raw) == expected++ @pytest.mark.parametrize("raw", ["", "evil.com", "us0/", "us0.attacker", "us 0", "us_0", "a" * 33])+ def test_invalid_raises(self, raw: str) -> None:+ # The realm is interpolated into the request hostname, so anything that isn't a+ # bare realm code must be rejected before a request is built.+ with pytest.raises(ValueError, match="realm"):+ normalize_realm(raw)+++class TestTimestampConversion:+ @pytest.mark.parametrize(+ ("value", "expected_ms"),+ [+ (datetime(2026, 1, 1, tzinfo=UTC), 1767225600000),+ (datetime(2026, 1, 1), 1767225600000), # naive treated as UTC+ (date(2026, 1, 1), 1767225600000),+ (1767225600000, 1767225600000),+ ],+ )+ def test_to_epoch_ms(self, value: Any, expected_ms: int) -> None:+ assert _to_epoch_ms(value) == expected_ms++ def test_ms_round_trip(self) -> None:+ assert _ms_to_datetime(1767225600000) == datetime(2026, 1, 1, tzinfo=UTC)+ assert _ms_to_datetime(None) is None+++class TestRestPagination:+ def test_full_page_then_short_page(self) -> None:+ full_page = [{"id": str(i)} for i in range(PAGE_SIZE)]+ responses = [+ _json_response(_wrapped(full_page, count=PAGE_SIZE + 1)),+ _json_response(_wrapped([{"id": "last"}], count=PAGE_SIZE + 1)),+ ]+ rows, requested, manager = _drive_rest("detectors", responses)++ assert len(rows) == PAGE_SIZE + 1+ assert [(p["offset"], p["limit"]) for p in requested] == [+ ("0", str(PAGE_SIZE)),+ (str(PAGE_SIZE), str(PAGE_SIZE)),+ ]+ # Resume state is saved only while there is a next page to resume to, and after+ # the page has been yielded.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [SplunkObservabilityCloudResumeConfig(offset=PAGE_SIZE)]++ def test_single_short_page_saves_no_state(self) -> None:+ rows, requested, manager = _drive_rest("detectors", [_json_response(_wrapped([{"id": "a"}]))])++ assert [row["id"] for row in rows] == ["a"]+ assert len(requested) == 1+ manager.save_state.assert_not_called()++ def test_resume_seeds_offset(self) -> None:+ manager = _make_manager(SplunkObservabilityCloudResumeConfig(offset=PAGE_SIZE))+ rows, requested, _ = _drive_rest("detectors", [_json_response(_wrapped([{"id": "resumed"}]))], manager)++ assert [row["id"] for row in rows] == ["resumed"]+ assert requested[0]["offset"] == str(PAGE_SIZE)++ def test_incidents_parses_bare_array_and_includes_resolved(self) -> None:+ responses = [_json_response([{"incidentId": "inc-1"}, {"incidentId": "inc-2"}])]+ rows, requested, _ = _drive_rest("incidents", responses)++ assert [row["incidentId"] for row in rows] == ["inc-1", "inc-2"]+ assert requested[0]["includeResolved"] == "true"+ assert requested[0]["__path"] == "/v2/incident"++ def test_metrics_sends_match_all_query(self) -> None:+ _, requested, _ = _drive_rest("metrics", [_json_response(_wrapped([]))])+ assert requested[0]["query"] == "name:*"++ def test_client_error_raises_without_retry(self) -> None:+ with pytest.raises(requests.HTTPError):+ _drive_rest("detectors", [_json_response({"message": "unauthorized"}, status_code=401)])+++class TestDetectorEventsFanOut:+ def _detector_page(self, ids: list[str]) -> MagicMock:+ return _json_response(_wrapped([{"id": detector_id} for detector_id in ids]))++ def test_fans_out_and_normalizes_timestamps(self) -> None:+ responses = [+ self._detector_page(["det-1", "det-2"]),+ _json_response([{"id": "ev-1", "detectorId": "det-1", "timestamp": 1767225600000}]),+ _json_response([{"id": "ev-2", "detectorId": "det-2", "timestamp": 1767225660000}]),+ ]+ rows, requested, manager = _drive_rest("detector_events", responses)++ assert [row["id"] for row in rows] == ["ev-1", "ev-2"]+ # Epoch-ms timestamps become real datetimes so incremental/partitioning works.+ assert rows[0]["timestamp"] == datetime(2026, 1, 1, tzinfo=UTC)++ event_requests = [p for p in requested if "/events" in p["__path"]]+ assert [p["__path"] for p in event_requests] == [+ "/v2/detector/det-1/events",+ "/v2/detector/det-2/events",+ ]+ # Full refresh pulls all history: from=0, to=now.+ assert all(p["from"] == "0" for p in event_requests)+ assert all(int(p["to"]) > 0 for p in event_requests)++ # Bookmark advances to the next detector between detectors so a crash resumes+ # in the right place.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert SplunkObservabilityCloudResumeConfig(offset=0, detector_id="det-2") in saved++ def test_incremental_watermark_sets_from(self) -> None:+ responses = [+ self._detector_page(["det-1"]),+ _json_response([]),+ ]+ watermark = datetime(2026, 1, 1, tzinfo=UTC)+ _, requested, _ = _drive_rest(+ "detector_events",+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ event_requests = [p for p in requested if "/events" in p["__path"]]+ assert event_requests[0]["from"] == "1767225600000"++ def test_resume_skips_earlier_detectors_and_seeds_offset(self) -> None:+ manager = _make_manager(SplunkObservabilityCloudResumeConfig(offset=PAGE_SIZE, detector_id="det-2"))+ responses = [+ self._detector_page(["det-1", "det-2", "det-3"]),+ _json_response([{"id": "ev", "detectorId": "det-2", "timestamp": 1}]),+ _json_response([]),+ ]+ _, requested, _ = _drive_rest("detector_events", responses, manager)++ event_requests = [p for p in requested if "/events" in p["__path"]]+ assert [p["__path"] for p in event_requests] == [+ "/v2/detector/det-2/events",+ "/v2/detector/det-3/events",+ ]+ # The bookmarked detector resumes at its saved offset; the next one starts fresh.+ assert [p["offset"] for p in event_requests] == [str(PAGE_SIZE), "0"]++ def test_resume_with_deleted_detector_starts_over(self) -> None:+ manager = _make_manager(SplunkObservabilityCloudResumeConfig(offset=50, detector_id="det-gone"))+ responses = [+ self._detector_page(["det-1"]),+ _json_response([]),+ ]+ _, requested, _ = _drive_rest("detector_events", responses, manager)++ event_requests = [p for p in requested if "/events" in p["__path"]]+ assert [p["__path"] for p in event_requests] == ["/v2/detector/det-1/events"]+ assert event_requests[0]["offset"] == "0"+++def _sse_lines(events: list[tuple[str, dict[str, Any]]]) -> list[str]:+ lines: list[str] = []+ for name, payload in events:+ lines.append(f"event: {name}")+ lines.append(f"data: {json.dumps(payload)}")+ lines.append("")+ return lines+++def _stream_response(events: list[tuple[str, dict[str, Any]]]) -> MagicMock:+ response = MagicMock()+ response.ok = True+ response.status_code = 200+ response.is_redirect = False+ response.iter_lines.return_value = _sse_lines(events)+ return response+++class TestSignalFlow:+ def _drive(+ self,+ events: list[tuple[str, dict[str, Any]]],+ **kwargs: Any,+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ with patch(f"{_MODULE}.make_tracked_session") as mock_session_factory:+ mock_session = mock_session_factory.return_value+ mock_session.post.return_value = _stream_response(events)+ rows = [+ row+ for page in get_rows(+ realm="us0",+ access_token="test-token",+ endpoint="metric_time_series",+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ signalflow_program="data('cpu.utilization').publish()",+ **kwargs,+ )+ for row in page+ ]+ post_kwargs = mock_session.post.call_args.kwargs+ return rows, post_kwargs++ def test_sse_parser_handles_multi_event_stream(self) -> None:+ response = MagicMock()+ response.iter_lines.return_value = [+ ": keep-alive comment",+ "event: metadata",+ 'data: {"tsId": "A"}',+ "",+ 'data: {"note": "default event name"}',+ "",+ ]+ events = list(_iter_sse_events(response))+ assert events == [("metadata", '{"tsId": "A"}'), ("message", '{"note": "default event name"}')]++ def test_datapoints_join_metadata_and_convert_timestamps(self) -> None:+ rows, _ = self._drive(+ [+ ("control-message", {"event": "JOB_START", "timestampMs": 1, "handle": "h"}),+ ("metadata", {"tsId": "AAAA", "properties": {"sf_metric": "cpu.utilization", "host": "web-1"}}),+ ("data", {"logicalTimestampMs": 1767225600000, "data": [{"tsId": "AAAA", "value": 42.5}]}),+ ("data", {"logicalTimestampMs": 1767225660000, "data": [{"tsId": "AAAA", "value": 43.0}]}),+ ("control-message", {"event": "END_OF_CHANNEL", "timestampMs": 2}),+ ]+ )++ assert [row["value"] for row in rows] == [42.5, 43.0]+ assert rows[0]["tsId"] == "AAAA"+ assert rows[0]["timestamp"] == datetime(2026, 1, 1, tzinfo=UTC)+ assert rows[0]["metric"] == "cpu.utilization"+ assert json.loads(rows[0]["properties"])["host"] == "web-1"++ def test_datapoint_without_metadata_still_yields(self) -> None:+ rows, _ = self._drive(+ [+ ("data", {"logicalTimestampMs": 1767225600000, "data": [{"tsId": "B", "value": 1.0}]}),+ ("control-message", {"event": "END_OF_CHANNEL", "timestampMs": 2}),+ ]+ )+ assert rows[0]["metric"] is None+ assert rows[0]["properties"] is None++ def test_error_message_raises(self) -> None:+ with pytest.raises(Exception, match="SignalFlow computation failed"):+ self._drive([("error", {"errors": [{"code": "ANALYTICS_PROGRAM_NAME_ERROR"}]})])++ def test_channel_abort_raises(self) -> None:+ with pytest.raises(Exception, match="aborted"):+ self._drive(+ [+ (+ "control-message",+ {"event": "CHANNEL_ABORT", "timestampMs": 1, "abortInfo": {"sf_job_abortState": "FAILED"}},+ )+ ]+ )++ def test_missing_program_is_actionable_error(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session"), pytest.raises(ValueError, match="SignalFlow program"):+ list(+ get_rows(+ realm="us0",+ access_token="test-token",+ endpoint="metric_time_series",+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ signalflow_program=" ",+ )+ )++ def test_incremental_watermark_sets_start(self) -> None:+ watermark = datetime(2026, 1, 1, tzinfo=UTC)+ _, post_kwargs = self._drive(+ [("control-message", {"event": "END_OF_CHANNEL", "timestampMs": 1})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ assert post_kwargs["params"]["start"] == "1767225600000"++ def test_full_refresh_uses_default_lookback(self) -> None:+ _, post_kwargs = self._drive([("control-message", {"event": "END_OF_CHANNEL", "timestampMs": 1})])+ params = post_kwargs["params"]+ expected_window_ms = SIGNALFLOW_DEFAULT_LOOKBACK_DAYS * 24 * 60 * 60 * 1000+ assert int(params["stop"]) - int(params["start"]) == expected_window_ms+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", list(SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS.keys()))+ def test_primary_keys_and_partitioning_match_settings(self, endpoint: str) -> None:+ config = SPLUNK_OBSERVABILITY_CLOUD_ENDPOINTS[endpoint]+ response = splunk_observability_cloud_source(+ realm="us0",+ access_token="test-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ )++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None++ def test_detector_events_defers_watermark_to_job_end(self) -> None:+ # The fan-out is not globally time-ordered, so the watermark must not+ # checkpoint per batch (desc mode persists it only at successful job end).+ response = splunk_observability_cloud_source(+ realm="us0",+ access_token="test-token",+ endpoint="detector_events",+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ )+ assert response.sort_mode == "desc"++ def test_metric_time_series_streams_ascending(self) -> None:+ response = splunk_observability_cloud_source(+ realm="us0",+ access_token="test-token",+ endpoint="metric_time_series",+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ )+ assert response.sort_mode == "asc"+++class TestRedirectHardening:+ # requests strips only `Authorization` when a redirect crosses hosts, so a session+ # that follows redirects would replay the X-SF-TOKEN header to whatever host a 3xx+ # names. Both session constructions must pin redirects off.+ def test_get_rows_session_never_follows_redirects(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session") as factory:+ factory.return_value.get.side_effect = [_json_response(_wrapped([]))]+ list(+ get_rows(+ realm="us0",+ access_token="test-token",+ endpoint="detectors",+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ )+ )+ assert factory.call_args.kwargs["allow_redirects"] is False++ def test_validate_credentials_session_never_follows_redirects(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session") as factory:+ response = MagicMock()+ response.status_code = 200+ factory.return_value.get.return_value = response+ validate_credentials("us0", "test-token")+ assert factory.call_args.kwargs["allow_redirects"] is False+++class TestSampleCaptureDisabled:+ # Detector/dashboard/chart response bodies and the SignalFlow program hold arbitrary+ # customer content the name-based scrubber can't redact. Dropping capture=False (back+ # to the default) would serialize that tenant content into the HTTP sample bucket.+ def test_get_rows_disables_capture(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session") as factory:+ factory.return_value.get.side_effect = [_json_response(_wrapped([]))]+ list(+ get_rows(+ realm="us0",+ access_token="test-token",+ endpoint="detectors",+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ )+ )+ assert factory.call_args.kwargs["capture"] is False++ def test_validate_credentials_disables_capture(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session") as factory:+ response = MagicMock()+ response.status_code = 200+ factory.return_value.get.return_value = response+ validate_credentials("us0", "test-token")+ assert factory.call_args.kwargs["capture"] is False+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [(200, True), (401, False), (403, False), (500, False)],+ )+ def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:+ with patch(f"{_MODULE}.make_tracked_session") as mock_session_factory:+ response = MagicMock()+ response.status_code = status_code+ response.is_redirect = False+ mock_session_factory.return_value.get.return_value = response++ valid, error = validate_credentials("us0", "test-token")++ assert valid is expected_valid+ assert (error is None) is expected_valid++ def test_redirect_returns_actionable_realm_message(self) -> None:+ # A 3xx passes `status_code < 400` checks; with redirects pinned off it must+ # surface as "wrong realm", not a confusing unexpected-status error.+ with patch(f"{_MODULE}.make_tracked_session") as mock_session_factory:+ response = MagicMock()+ response.status_code = 302+ response.is_redirect = True+ mock_session_factory.return_value.get.return_value = response++ valid, error = validate_credentials("us0", "test-token")++ assert valid is False+ assert error is not None and "realm" in error++ def test_invalid_realm_fails_without_request(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session") as mock_session_factory:+ valid, error = validate_credentials("not a realm!", "test-token")++ assert valid is False+ assert error is not None and "realm" in error+ mock_session_factory.assert_not_called()++ def test_network_error_returns_message(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session") as mock_session_factory:+ mock_session_factory.return_value.get.side_effect = Exception("boom")+ valid, error = validate_credentials("us0", "test-token")++ assert valid is False+ assert error == "boom"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/tests/test_splunk_observability_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/tests/test_splunk_observability_cloud_source.pynew file mode 100644index 000000000000..25081a9b0f26--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/splunk_observability_cloud/tests/test_splunk_observability_cloud_source.py@@ -0,0 +1,189 @@+from typing import Any++import pytest+from unittest import mock++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 (+ SplunkObservabilityCloudSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.settings import (+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.source import (+ SplunkObservabilityCloudSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.splunk_observability_cloud import (+ SplunkObservabilityCloudResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "detectors",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "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-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestSplunkObservabilityCloudSource:+ def setup_method(self) -> None:+ self.source = SplunkObservabilityCloudSource()+ self.team_id = 123+ self.config = SplunkObservabilityCloudSourceConfig(realm="us0", access_token="test-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SPLUNKOBSERVABILITYCLOUD++ def test_realm_is_a_connection_host_field(self) -> None:+ # The realm becomes the request hostname the stored token is sent to, so+ # changing it must force the token to be re-entered.+ assert self.source.connection_host_fields == ["realm"]++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "SplunkObservabilityCloud"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/splunk-observability-cloud"++ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert [f.name for f in fields] == ["realm", "access_token", "signalflow_program"]++ realm_field, token_field, program_field = fields+ assert realm_field.type == SourceFieldInputConfigType.TEXT+ assert realm_field.required is True++ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True++ assert program_field.type == SourceFieldInputConfigType.TEXTAREA+ assert program_field.required is False++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_incremental_flags(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Only the two endpoints with a server-side time filter (detector events'+ # from/to, SignalFlow's start/stop) advertise incremental sync.+ incremental = {name for name, s in schemas.items() if s.supports_incremental}+ assert incremental == {"detector_events", "metric_time_series"}+ for name in incremental:+ assert [f["field"] for f in schemas[name].incremental_fields] == ["timestamp"]++ def test_get_schemas_default_sync_selection(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ # dimensions (unbounded volume) and metric_time_series (needs the optional+ # SignalFlow program) must not be force-enabled by one-shot setup.+ off_by_default = {name for name, s in schemas.items() if not s.should_sync_default}+ assert off_by_default == {"dimensions", "metric_time_series"}++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["detectors"])+ assert [s.name for s in schemas] == ["detectors"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_canonical_descriptions_cover_known_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ # Keyed by endpoint name: an entry for a non-existent endpoint silently never+ # applies, and a missing entry falls back to paid LLM enrichment.+ assert set(descriptions) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid", "expected_message"),+ [+ ((True, None), True, None),+ (+ (False, "Invalid Splunk Observability Cloud access token or realm"),+ False,+ "Invalid Splunk Observability Cloud access token or realm",+ ),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.source.validate_splunk_observability_cloud_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ mock_return: tuple[bool, str | None],+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.realm, self.config.access_token)++ def test_get_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 SplunkObservabilityCloudResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.source.splunk_observability_cloud_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ config = SplunkObservabilityCloudSourceConfig(+ realm="eu0", access_token="tok", signalflow_program="data('cpu.utilization').publish()"+ )+ inputs = _make_inputs(+ schema_name="detector_events",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01",+ incremental_field="timestamp",+ )+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(config, manager, inputs)++ mock_source.assert_called_once_with(+ realm="eu0",+ access_token="tok",+ endpoint="detector_events",+ logger=inputs.logger,+ resumable_source_manager=manager,+ signalflow_program="data('cpu.utilization').publish()",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01",+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.splunk_observability_cloud.source.splunk_observability_cloud_source"+ )+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_source: mock.MagicMock) -> None:+ # A leftover watermark from a previous incremental config must not narrow a+ # full-refresh run.+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None