: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 sumo_logic import source (#71171)
Tom Owers194a88479b85
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex cba0e57b4ee1..51c2d60c2c36 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -433,6 +433,7 @@ the row lists both.| statuspage | HTTP | requests | ✅ || stigg | HTTP | requests | ✅ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |+| sumo_logic | HTTP | requests | ✅ || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ || surveymonkey | HTTP | requests | ✅ || surveysparrow | HTTP | requests | ✅ |@@ -910,7 +911,6 @@ doesn't conflict with concurrent PRs.- streamelements- streamlabs- stytch-- sumo_logic- sumsub- superwall- surveymonkeydiff --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 1a61d9edcec6..8ab36516dda4 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@@ -4061,7 +4061,10 @@ class StytchSourceConfig(config.Config):@config.configclass SumoLogicSourceConfig(config.Config):- pass+ access_id: str+ access_key: str+ deployment: Literal["us1", "us2", "au", "ca", "de", "eu", "fed", "in", "jp", "kr"] = config.value(default="us1")+ search_query: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/canonical_descriptions.pynew file mode 100644index 000000000000..d1c0ffd75952--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/canonical_descriptions.py@@ -0,0 +1,174 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "logs": {+ "description": "Raw log messages returned by your log search query, exported through the Search Job API over rolling time windows.",+ "docs_url": "https://help.sumologic.com/docs/api/search-job/",+ "columns": {+ "_raw": "The raw log message body as it was ingested.",+ "_messageid": "Unique identifier for the log message.",+ "_messagetime": "The message's parsed timestamp, in epoch milliseconds.",+ "message_time": "The message's parsed timestamp as a datetime (derived from _messagetime).",+ "_receipttime": "When Sumo Logic received the message, in epoch milliseconds.",+ "_sourcecategory": "Source category metadata assigned to the message.",+ "_sourcehost": "Host the message originated from.",+ "_sourcename": "Name (typically the file path) of the message's source.",+ "_source": "Name of the Sumo Logic source that ingested the message.",+ "_sourceid": "Identifier of the Sumo Logic source that ingested the message.",+ "_collector": "Name of the collector that ingested the message.",+ "_collectorid": "Identifier of the collector that ingested the message.",+ },+ },+ "users": {+ "description": "Users in your Sumo Logic organization.",+ "docs_url": "https://help.sumologic.com/docs/api/users/",+ "columns": {+ "id": "Unique identifier for the user.",+ "firstName": "First name of the user.",+ "lastName": "Last name of the user.",+ "email": "Email address of the user.",+ "roleIds": "Identifiers of the roles assigned to the user.",+ "isActive": "Whether the user is active.",+ "isMfaEnabled": "Whether multi-factor authentication is enabled for the user.",+ "lastLoginTimestamp": "Timestamp of the user's last login.",+ "createdAt": "When the user was created.",+ "modifiedAt": "When the user was last modified.",+ },+ },+ "roles": {+ "description": "Roles in your Sumo Logic organization and the capabilities they grant.",+ "docs_url": "https://help.sumologic.com/docs/api/roles/",+ "columns": {+ "id": "Unique identifier for the role.",+ "name": "Name of the role.",+ "description": "Description of the role.",+ "filterPredicate": "Search filter applied to the queries of users with this role.",+ "users": "Identifiers of users assigned to this role.",+ "capabilities": "Capabilities granted by this role.",+ },+ },+ "collectors": {+ "description": "Installed and hosted collectors that ingest data into Sumo Logic.",+ "docs_url": "https://help.sumologic.com/docs/api/collector-management/collector-api-methods-examples/",+ "columns": {+ "id": "Unique identifier for the collector.",+ "name": "Name of the collector.",+ "collectorType": "Type of the collector (Installable or Hosted).",+ "alive": "Whether the collector has recently checked in.",+ "category": "Default source category for sources on this collector.",+ "sourceSyncMode": "Whether sources are managed in the UI or via JSON configuration.",+ "lastSeenAlive": "When the collector last checked in, in epoch milliseconds.",+ },+ },+ "collector_sources": {+ "description": "Data sources configured on each collector, one row per source with its parent collector id.",+ "docs_url": "https://help.sumologic.com/docs/api/collector-management/source-api/",+ "columns": {+ "collector_id": "Identifier of the collector this source belongs to.",+ "id": "Identifier for the source, unique within its collector.",+ "name": "Name of the source.",+ "sourceType": "Type of the source (e.g. LocalFile, Syslog, HTTP).",+ "category": "Source category assigned to messages from this source.",+ "alive": "Whether the source is reporting data.",+ },+ },+ "dashboards": {+ "description": "Dashboards in your Sumo Logic organization.",+ "docs_url": "https://help.sumologic.com/docs/api/dashboards/",+ "columns": {+ "id": "Unique identifier for the dashboard.",+ "title": "Title of the dashboard.",+ "description": "Description of the dashboard.",+ "folderId": "Identifier of the folder containing the dashboard.",+ "panels": "Panels rendered on the dashboard.",+ "layout": "Layout configuration of the dashboard's panels.",+ },+ },+ "monitors": {+ "description": "Alerting monitors configured in your Sumo Logic organization.",+ "docs_url": "https://help.sumologic.com/docs/api/monitors/",+ "columns": {+ "id": "Unique identifier for the monitor.",+ "name": "Name of the monitor.",+ "monitorType": "Type of the monitor (Logs or Metrics).",+ "isDisabled": "Whether the monitor is disabled.",+ "status": "Current status of the monitor.",+ "queries": "Queries the monitor evaluates.",+ "triggers": "Trigger conditions configured on the monitor.",+ "path": "Content library path of the monitor.",+ "createdAt": "When the monitor was created.",+ "modifiedAt": "When the monitor was last modified.",+ },+ },+ "partitions": {+ "description": "Partitions that route your log data into separate indexes.",+ "docs_url": "https://help.sumologic.com/docs/api/partitions/",+ "columns": {+ "id": "Unique identifier for the partition.",+ "name": "Name of the partition.",+ "routingExpression": "Query expression that routes messages into this partition.",+ "retentionPeriod": "Retention period of the partition, in days.",+ "isActive": "Whether the partition is active.",+ "totalBytes": "Total data stored in the partition, in bytes.",+ },+ },+ "ingest_budgets": {+ "description": "Ingest budgets that cap daily data ingestion volume.",+ "docs_url": "https://help.sumologic.com/docs/api/ingest-budgets/",+ "columns": {+ "id": "Unique identifier for the ingest budget.",+ "name": "Name of the ingest budget.",+ "fieldValue": "Field value collectors use to attribute ingestion to this budget.",+ "capacityBytes": "Daily ingestion capacity of the budget, in bytes.",+ "usageBytes": "Data ingested against the budget in the current window, in bytes.",+ "status": "Current status of the budget.",+ "action": "Action taken when the budget's capacity is reached.",+ },+ },+ "connections": {+ "description": "Outbound connections (webhooks) used by monitors and scheduled searches to send notifications. Credential-bearing fields (the destination URL, headers, and default payload) are dropped on import.",+ "docs_url": "https://help.sumologic.com/docs/api/connections/",+ "columns": {+ "id": "Unique identifier for the connection.",+ "name": "Name of the connection.",+ "type": "Type of the connection.",+ "description": "Description of the connection.",+ },+ },+ "field_extraction_rules": {+ "description": "Field extraction rules that parse fields out of messages at ingest time.",+ "docs_url": "https://help.sumologic.com/docs/api/field-extraction-rules/",+ "columns": {+ "id": "Unique identifier for the field extraction rule.",+ "name": "Name of the rule.",+ "scope": "Scope query selecting the messages the rule applies to.",+ "parseExpression": "Parse expression the rule evaluates.",+ "enabled": "Whether the rule is enabled.",+ },+ },+ "scheduled_views": {+ "description": "Scheduled views that pre-aggregate log data into indexed views.",+ "docs_url": "https://help.sumologic.com/docs/api/scheduled-views/",+ "columns": {+ "id": "Unique identifier for the scheduled view.",+ "indexName": "Name of the index the view writes to.",+ "query": "Query that defines the view.",+ "startTime": "Timestamp the view starts aggregating from.",+ "retentionPeriod": "Retention period of the view's index, in days.",+ },+ },+ "health_events": {+ "description": "Health events reporting operational issues with collectors, sources, and ingest budgets.",+ "docs_url": "https://help.sumologic.com/docs/api/health-events/",+ "columns": {+ "eventId": "Unique identifier for the health event.",+ "eventName": "Name of the health event.",+ "details": "Details of the health event.",+ "resourceIdentity": "The resource (collector, source, ...) the event relates to.",+ "eventTime": "When the event occurred.",+ "severityLevel": "Severity of the event.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/settings.pynew file mode 100644index 000000000000..596506446242--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/settings.py@@ -0,0 +1,135 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# "token": Sumo Logic management APIs paginated with `limit` + `token` params; the response body+# carries the record list under `data_key` plus a `next` continuation token.+# "offset": `limit` + `offset` params; a short page signals the end.+# "search_job": the async Search Job API (submit / poll / fetch) — bespoke path in sumo_logic.py.+PaginationStyle = Literal["token", "offset", "search_job"]++# First sync of the logs table reaches back this far. Log volume through the Search Job API is+# expensive (one async job per time window), so this is deliberately shorter than typical retention.+DEFAULT_LOGS_LOOKBACK_DAYS = 7+++@dataclass+class SumoLogicEndpointConfig:+ name: str+ path: str+ # Key in the response body holding the list of records. ``None`` means the body itself is the list.+ data_key: Optional[str] = None+ pagination: PaginationStyle = "token"+ page_size: int = 100+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Each record is nested under this key (e.g. monitors search returns {"item": {...}, "path": ...});+ # the record is lifted to the root and the remaining sibling keys are kept alongside it.+ nest_key: Optional[str] = None+ # Extra query params sent on every request (e.g. the monitors search query).+ extra_params: dict[str, str] = field(default_factory=dict)+ # Fan out over every collector, fetching this endpoint per collector id. When True, ``path`` is a+ # template with a ``{collector_id}`` placeholder.+ fan_out_over_collectors: bool = False+ # Stable, immutable datetime field used for partitioning (never a last-modified field).+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Top-level keys stripped from every record before it's yielded. Used to drop credential-bearing+ # fields (e.g. webhook URLs and auth headers) that a warehouse reader must never see.+ redact_fields: frozenset[str] = frozenset()+ # Keys stripped wherever they appear in the record tree (any depth), for credential-bearing+ # fields that live below the top level — e.g. monitor notification payload overrides nested+ # under the `notifications` list.+ redact_nested_fields: frozenset[str] = frozenset()+++# Endpoint catalog. The headline stream is `logs` via the async Search Job API (the only Sumo Logic+# API that exports log data, and the only one with a genuine server-side time filter — hence the only+# incremental table). The management APIs are plain paginated GETs with no server-side timestamp+# filter, so they ship as full refresh.+#+# Endpoint paths and pagination follow the official API docs (https://api.sumologic.com/docs/).+# Sumo Logic returns 401 before routing, so unauthenticated probes can't confirm paths — the catalog+# is doc-verified only.+SUMO_LOGIC_ENDPOINTS: dict[str, SumoLogicEndpointConfig] = {+ "logs": SumoLogicEndpointConfig(+ name="logs",+ path="/v1/search/jobs",+ pagination="search_job",+ # Search Job message pages max out at 10,000 messages per fetch.+ page_size=10_000,+ # `_messageid` is documented as a unique message identifier; `_messagetime` is included+ # defensively so the key stays unique even if message ids ever repeat across sources.+ primary_keys=["_messageid", "_messagetime"],+ partition_key="message_time",+ incremental_fields=[+ {+ "label": "message_time",+ "type": IncrementalFieldType.DateTime,+ "field": "message_time",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ ),+ "users": SumoLogicEndpointConfig(name="users", path="/v1/users", data_key="data"),+ "roles": SumoLogicEndpointConfig(name="roles", path="/v1/roles", data_key="data"),+ "collectors": SumoLogicEndpointConfig(+ name="collectors",+ path="/v1/collectors",+ data_key="collectors",+ pagination="offset",+ ),+ "collector_sources": SumoLogicEndpointConfig(+ name="collector_sources",+ path="/v1/collectors/{collector_id}/sources",+ data_key="sources",+ pagination="offset", # applies to the parent collectors listing; the sources call is unpaginated+ # Source ids are only unique within their collector, so the parent id is part of the key.+ primary_keys=["collector_id", "id"],+ fan_out_over_collectors=True,+ # HTTP-source records carry a generated `url` that is itself a bearer credential for log+ # ingestion — anyone with it can inject arbitrary logs into the account. Drop it so a+ # warehouse reader sees the source metadata (id, name, type) without the ingestion secret.+ redact_fields=frozenset({"url"}),+ ),+ "dashboards": SumoLogicEndpointConfig(name="dashboards", path="/v2/dashboards", data_key="dashboards"),+ "monitors": SumoLogicEndpointConfig(+ name="monitors",+ path="/v1/monitors/search",+ pagination="offset",+ nest_key="item",+ extra_params={"query": "type:monitor"},+ # A monitor's `notifications` embed destination secrets in `payloadOverride` /+ # `resolutionPayloadOverride` (nested below the top level). Drop them wherever they appear+ # so a warehouse reader sees the monitor and its notification routing without the secrets.+ redact_nested_fields=frozenset({"payloadOverride", "resolutionPayloadOverride"}),+ ),+ "partitions": SumoLogicEndpointConfig(name="partitions", path="/v1/partitions", data_key="data"),+ "ingest_budgets": SumoLogicEndpointConfig(name="ingest_budgets", path="/v1/ingestBudgets", data_key="data"),+ "connections": SumoLogicEndpointConfig(+ name="connections",+ path="/v1/connections",+ data_key="data",+ # A connection definition embeds the outbound webhook secret: the destination URL carries+ # the auth token for Slack/PagerDuty-style webhooks, and the header fields can carry an+ # Authorization credential. Drop them so a warehouse reader sees that a connection exists+ # (name, type, description) without the credentials needed to forge notifications through it.+ redact_fields=frozenset({"url", "headers", "customHeaders", "defaultPayload"}),+ ),+ "field_extraction_rules": SumoLogicEndpointConfig(+ name="field_extraction_rules", path="/v1/extractionRules", data_key="data"+ ),+ "scheduled_views": SumoLogicEndpointConfig(name="scheduled_views", path="/v1/scheduledViews", data_key="data"),+ "health_events": SumoLogicEndpointConfig(+ name="health_events",+ path="/v1/healthEvents",+ data_key="data",+ primary_keys=["eventId"],+ ),+}++ENDPOINTS = tuple(SUMO_LOGIC_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SUMO_LOGIC_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/source.pyindex f015f39cd8b3..8cc2c01c4af1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/source.py@@ -1,30 +1,184 @@-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 SumoLogicSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.settings import (+ DEFAULT_LOGS_LOOKBACK_DAYS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SUMO_LOGIC_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.sumo_logic import (+ SumoLogicResumeConfig,+ sumo_logic_source,+ validate_credentials as validate_sumo_logic_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SumoLogicSource(SimpleSource[SumoLogicSourceConfig]):+class SumoLogicSource(ResumableSource[SumoLogicSourceConfig, SumoLogicResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SUMOLOGIC+ @property+ def connection_host_fields(self) -> list[str]:+ # The access keys are sent to the regional host derived from `deployment`, so changing the+ # deployment must re-require the secrets rather than reusing them against a different host.+ return ["deployment"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SUMO_LOGIC,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Sumo Logic",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Connect your Sumo Logic account to sync log search results, collectors, monitors, dashboards, users, and more into the PostHog Data warehouse.++Create an access ID and access key in your [Sumo Logic preferences](https://help.sumologic.com/docs/manage/security/access-keys/) (or use a service account's access key). Pick the deployment region your account lives on — it's the subdomain of your Sumo Logic URL (e.g. `service.eu.sumologic.com` is the EU deployment).++The `logs` table runs your log search query through the Search Job API over rolling time windows. Leave the query as `*` to sync everything, or narrow it (e.g. `_sourceCategory=prod/api`) to control volume.""",iconPath="/static/services/sumo_logic.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/sumo-logic",+ keywords=["sumologic", "siem", "logs"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="deployment",+ label="Deployment region",+ required=True,+ defaultValue="us1",+ options=[+ SourceFieldSelectConfigOption(label="US1 (api.sumologic.com)", value="us1"),+ SourceFieldSelectConfigOption(label="US2 (api.us2.sumologic.com)", value="us2"),+ SourceFieldSelectConfigOption(label="AU (api.au.sumologic.com)", value="au"),+ SourceFieldSelectConfigOption(label="CA (api.ca.sumologic.com)", value="ca"),+ SourceFieldSelectConfigOption(label="DE (api.de.sumologic.com)", value="de"),+ SourceFieldSelectConfigOption(label="EU (api.eu.sumologic.com)", value="eu"),+ SourceFieldSelectConfigOption(label="FED (api.fed.sumologic.com)", value="fed"),+ SourceFieldSelectConfigOption(label="IN (api.in.sumologic.com)", value="in"),+ SourceFieldSelectConfigOption(label="JP (api.jp.sumologic.com)", value="jp"),+ SourceFieldSelectConfigOption(label="KR (api.kr.sumologic.com)", value="kr"),+ ],+ ),+ SourceFieldInputConfig(+ name="access_id",+ label="Access ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="su...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="access_key",+ label="Access key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="search_query",+ label="Log search query",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="*",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Sumo Logic access ID or access key is invalid or has been deactivated. Create a new access key and reconnect.",+ "403 Client Error": "Your Sumo Logic access key is missing the role capability required for this data. Grant the capability to the key's user (or deselect the table) and try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SumoLogicSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=SUMO_LOGIC_ENDPOINTS[endpoint].pagination == "search_job",+ supports_append=SUMO_LOGIC_ENDPOINTS[endpoint].pagination == "search_job",+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=(+ f"Raw log messages matching your search query. Only syncs the last {DEFAULT_LOGS_LOOKBACK_DAYS} days on initial sync"+ if endpoint == "logs"+ else None+ ),+ )+ 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: SumoLogicSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_sumo_logic_credentials(config.deployment, config.access_id, config.access_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SumoLogicResumeConfig]:+ return ResumableSourceManager[SumoLogicResumeConfig](inputs, SumoLogicResumeConfig)++ def source_for_pipeline(+ self,+ config: SumoLogicSourceConfig,+ resumable_source_manager: ResumableSourceManager[SumoLogicResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return sumo_logic_source(+ deployment=config.deployment,+ access_id=config.access_id,+ access_key=config.access_key,+ endpoint=inputs.schema_name,+ search_query=config.search_query,+ 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/sumo_logic/sumo_logic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/sumo_logic.pynew file mode 100644index 000000000000..9e4b4a43d92d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/sumo_logic.py@@ -0,0 +1,496 @@+import time+import dataclasses+from collections import deque+from collections.abc import 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.sumo_logic.settings import (+ DEFAULT_LOGS_LOOKBACK_DAYS,+ SUMO_LOGIC_ENDPOINTS,+ SumoLogicEndpointConfig,+)++# Sumo Logic deployments. The deployment selects which regional API host the credentials are sent+# to; the set is a fixed allow-list, so the host can't be retargeted at an arbitrary server.+SUMO_LOGIC_DEPLOYMENTS = ("us1", "us2", "au", "ca", "de", "eu", "fed", "in", "jp", "kr")+DEFAULT_DEPLOYMENT = "us1"++REQUEST_TIMEOUT_SECONDS = 60+# Sumo Logic rate-limits at ~4 requests/second per access key (429 when exceeded); retries back off+# exponentially rather than hammering the window.+RETRY_ATTEMPTS = 5++# Search Job API tuning. Jobs run over bounded time windows; a window whose job hits the per-job+# message cap is split in half and re-run so no messages are silently dropped.+SEARCH_JOB_POLL_INTERVAL_SECONDS = 5+SEARCH_JOB_MAX_WAIT_SECONDS = 1800+SEARCH_JOB_MAX_MESSAGES = 100_000+SEARCH_JOB_INITIAL_WINDOW = timedelta(hours=24)+SEARCH_JOB_MIN_WINDOW = timedelta(minutes=1)+DEFAULT_SEARCH_QUERY = "*"+++class SumoLogicRetryableError(Exception):+ pass+++class SumoLogicResumeConfig:+ # Continuation token for token-paginated management endpoints.+ token: str | None = None+ # Row offset for offset-paginated management endpoints (also the collectors offset during the+ # collector_sources fan-out).+ offset: int | None = None+ # Start (epoch millis) of the next unprocessed search-job window for the logs endpoint.+ log_window_start_ms: int | None = None+++def base_url(deployment: Optional[str]) -> str:+ resolved = deployment or DEFAULT_DEPLOYMENT+ if resolved not in SUMO_LOGIC_DEPLOYMENTS:+ resolved = DEFAULT_DEPLOYMENT+ if resolved == "us1":+ return "https://api.sumologic.com/api"+ return f"https://api.{resolved}.sumologic.com/api"+++def _make_session(access_id: str, access_key: str) -> requests.Session:+ # One session for the whole run: Sumo Logic issues a session cookie on search-job creation that+ # must accompany the poll/fetch/delete calls, and `requests.Session` persists it automatically.+ # `capture=False`: raw log bodies (`_raw`) are free-form customer data that can embed credentials+ # the name-based sample scrubbers can't recognise, so keep response bodies out of HTTP sample+ # storage entirely. Requests are still metered and logged (status + url).+ session = make_tracked_session(redact_values=(access_key,), capture=False)+ session.auth = (access_id, access_key)+ session.headers.update({"Accept": "application/json", "Content-Type": "application/json"})+ return session+++def _to_epoch_ms(value: Any) -> int:+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return int(dt.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)+ return int(datetime.fromisoformat(str(value)).replace(tzinfo=UTC).timestamp() * 1000)+++def validate_credentials(deployment: Optional[str], access_id: str, access_key: str) -> tuple[bool, str | None]:+ """Validate Sumo Logic credentials with a single cheap probe.++ Every Sumo Logic endpoint is gated by a role capability, so a 403 means the key pair is genuine+ but this key lacks the probed capability — that must not block source creation (missing+ capabilities on selected tables surface at sync time via ``get_non_retryable_errors``). Only a+ 401 proves the access ID / access key pair itself is invalid.+ """+ url = f"{base_url(deployment)}/v1/collectors?limit=1"+ try:+ session = _make_session(access_id, access_key)+ response = session.get(url, timeout=10)+ if response.status_code in (200, 403):+ return True, None+ if response.status_code == 401:+ return False, "Invalid Sumo Logic access ID or access key. Check the credentials and deployment region."+ return False, f"Sumo Logic credential validation failed (status {response.status_code})."+ except requests.exceptions.RequestException as e:+ return False, str(e)+++def _make_fetch(session: requests.Session, logger: FilteringBoundLogger) -> Any:+ @retry(+ retry=retry_if_exception_type((SumoLogicRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch(method: str, url: str, json_body: dict[str, Any] | None = None) -> Any:+ response = session.request(method, url, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SumoLogicRetryableError(f"Sumo Logic API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Sumo Logic API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ if response.status_code == 204 or not response.content:+ return None+ return response.json()++ return fetch+++def _build_url(host: str, path: str, params: dict[str, Any]) -> str:+ url = f"{host}{path}"+ if not params:+ return url+ return f"{url}?{urlencode(params)}"+++def _extract_items(response_json: Any, config: SumoLogicEndpointConfig) -> list[dict[str, Any]]:+ if config.data_key is None:+ return response_json if isinstance(response_json, list) else []+ if isinstance(response_json, dict):+ items = response_json.get(config.data_key, [])+ return items if isinstance(items, list) else []+ return []+++def _redact_nested(value: Any, redact_fields: frozenset[str]) -> Any:+ """Drop credential-bearing keys wherever they appear in a nested record (any depth).++ Monitor notifications embed destination secrets in ``payloadOverride`` /+ ``resolutionPayloadOverride`` below the top level, so a shallow key filter can't reach them.+ """+ if isinstance(value, dict):+ return {key: _redact_nested(val, redact_fields) for key, val in value.items() if key not in redact_fields}+ if isinstance(value, list):+ return [_redact_nested(item, redact_fields) for item in value]+ return value+++def _redact_row(row: dict[str, Any], config: SumoLogicEndpointConfig) -> dict[str, Any]:+ """Drop credential-bearing keys from a record before it reaches the warehouse."""+ if config.redact_fields:+ row = {key: value for key, value in row.items() if key not in config.redact_fields}+ if config.redact_nested_fields:+ row = _redact_nested(row, config.redact_nested_fields)+ return row+++def _unnest_item(item: dict[str, Any], config: SumoLogicEndpointConfig) -> dict[str, Any]:+ """Lift a nested record (e.g. monitors search's ``item``) to the root, keeping sibling keys."""+ if config.nest_key is None:+ return item+ nested = item.get(config.nest_key)+ if not isinstance(nested, dict):+ return item+ row = dict(nested)+ for key, value in item.items():+ if key != config.nest_key:+ row.setdefault(key, value)+ return row+++def _get_token_paginated_rows(+ fetch: Any,+ host: str,+ config: SumoLogicEndpointConfig,+ resumable_source_manager: ResumableSourceManager[SumoLogicResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ token = resume.token if resume else None++ while True:+ params: dict[str, Any] = {"limit": config.page_size, **config.extra_params}+ if token:+ params["token"] = token++ data = fetch("GET", _build_url(host, config.path, params))+ items = _extract_items(data, config)+ next_token = data.get("next") if isinstance(data, dict) else None++ if items:+ yield [_unnest_item(item, config) for item in items]++ if not next_token:+ break+ # Save AFTER yielding the batch — a crash re-yields the last page (merge dedupes on the+ # primary key) instead of skipping it.+ resumable_source_manager.save_state(SumoLogicResumeConfig(token=next_token))+ token = next_token+++def _get_offset_paginated_rows(+ fetch: Any,+ host: str,+ config: SumoLogicEndpointConfig,+ resumable_source_manager: ResumableSourceManager[SumoLogicResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume and resume.offset is not None else 0++ while True:+ params: dict[str, Any] = {"limit": config.page_size, "offset": offset, **config.extra_params}+ data = fetch("GET", _build_url(host, config.path, params))+ items = _extract_items(data, config)++ if items:+ yield [_unnest_item(item, config) for item in items]++ if len(items) < config.page_size:+ break+ offset += config.page_size+ resumable_source_manager.save_state(SumoLogicResumeConfig(offset=offset))+++def _get_collector_fan_out_rows(+ fetch: Any,+ host: str,+ config: SumoLogicEndpointConfig,+ resumable_source_manager: ResumableSourceManager[SumoLogicResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every collector, fetching this endpoint once per collector.++ Resume state tracks the collectors-list offset: a crash re-fetches the current collectors page+ and its children (merge dedupes on the composite primary key) rather than restarting the scan.+ """+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume and resume.offset is not None else 0+ collectors_config = SUMO_LOGIC_ENDPOINTS["collectors"]++ while True:+ params: dict[str, Any] = {"limit": collectors_config.page_size, "offset": offset}+ data = fetch("GET", _build_url(host, collectors_config.path, params))+ collectors = _extract_items(data, collectors_config)++ rows: list[dict[str, Any]] = []+ for collector in collectors:+ collector_id = collector.get("id")+ if collector_id is None:+ continue+ child_path = config.path.format(collector_id=collector_id)+ child_data = fetch("GET", _build_url(host, child_path, dict(config.extra_params)))+ for item in _extract_items(child_data, config):+ rows.append({**item, "collector_id": collector_id})++ if rows:+ yield rows++ if len(collectors) < collectors_config.page_size:+ break+ offset += collectors_config.page_size+ resumable_source_manager.save_state(SumoLogicResumeConfig(offset=offset))+++def _message_row(message: dict[str, Any]) -> dict[str, Any]:+ """Flatten a Search Job message's ``map`` and derive a typed ``message_time`` datetime."""+ row = dict(message.get("map", {}))+ raw_time = row.get("_messagetime")+ try:+ row["message_time"] = datetime.fromtimestamp(int(raw_time) / 1000, tz=UTC) if raw_time is not None else None+ except (TypeError, ValueError):+ row["message_time"] = None+ return row+++def _delete_search_job(fetch: Any, host: str, job_id: str, logger: FilteringBoundLogger) -> None:+ # Best-effort cleanup; jobs also expire server-side, but the org caps concurrent search jobs.+ try:+ fetch("DELETE", f"{host}/v1/search/jobs/{job_id}")+ except Exception:+ logger.warning(f"Sumo Logic: failed to delete search job {job_id}")+++def _submit_and_poll_search_job(+ fetch: Any,+ host: str,+ query: str,+ start_ms: int,+ end_ms: int,+ logger: FilteringBoundLogger,+) -> tuple[str, int]:+ """Submit a search job for [start_ms, end_ms) and poll it to completion.++ Returns ``(job_id, message_count)``; the caller decides whether to fetch the messages or split+ the window when the job hit the per-job message cap."""+ job = fetch(+ "POST",+ f"{host}/v1/search/jobs",+ json_body={"query": query, "from": start_ms, "to": end_ms, "timeZone": "UTC"},+ )+ job_id = str(job["id"])+ job_url = f"{host}/v1/search/jobs/{job_id}"++ deadline = time.monotonic() + SEARCH_JOB_MAX_WAIT_SECONDS+ while True:+ status = fetch("GET", job_url)+ state = status.get("state")+ if state == "DONE GATHERING RESULTS":+ return job_id, int(status.get("messageCount", 0))+ if state == "CANCELLED":+ raise ValueError(f"Sumo Logic search job {job_id} was cancelled")+ if time.monotonic() > deadline:+ _delete_search_job(fetch, host, job_id, logger)+ raise SumoLogicRetryableError(+ f"Sumo Logic search job {job_id} did not complete within {SEARCH_JOB_MAX_WAIT_SECONDS}s"+ )+ time.sleep(SEARCH_JOB_POLL_INTERVAL_SECONDS)+++def _fetch_search_job_messages(+ fetch: Any, host: str, job_id: str, message_count: int, page_size: int+) -> Iterator[list[dict[str, Any]]]:+ offset = 0+ while offset < message_count:+ data = fetch(+ "GET",+ _build_url(host, f"/v1/search/jobs/{job_id}/messages", {"offset": offset, "limit": page_size}),+ )+ messages = data.get("messages", []) if isinstance(data, dict) else []+ if not messages:+ break+ yield [_message_row(message) for message in messages]+ offset += len(messages)+++def _get_log_rows(+ fetch: Any,+ host: str,+ query: str,+ config: SumoLogicEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SumoLogicResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Export logs via the async Search Job API over bounded time windows.++ Windows run chronologically from the incremental watermark (or the default lookback) to the+ stream's start time. A window whose job hits the per-job message cap is split in half and+ re-run, so no messages are silently dropped. Resume state advances one whole window at a time —+ a crash mid-window re-runs that window and merge dedupes the re-yielded rows.+ """+ end_ms = int(datetime.now(UTC).timestamp() * 1000)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.log_window_start_ms is not None:+ start_ms = resume.log_window_start_ms+ logger.debug(f"Sumo Logic: resuming logs from window start {start_ms}")+ elif 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 = end_ms - int(timedelta(days=DEFAULT_LOGS_LOOKBACK_DAYS).total_seconds() * 1000)++ if start_ms >= end_ms:+ return++ window_ms = int(SEARCH_JOB_INITIAL_WINDOW.total_seconds() * 1000)+ min_window_ms = int(SEARCH_JOB_MIN_WINDOW.total_seconds() * 1000)+ pending: deque[tuple[int, int]] = deque()+ cursor = start_ms+ while cursor < end_ms:+ pending.append((cursor, min(cursor + window_ms, end_ms)))+ cursor += window_ms++ while pending:+ window_start, window_end = pending.popleft()+ job_id, message_count = _submit_and_poll_search_job(fetch, host, query, window_start, window_end, logger)++ if message_count >= SEARCH_JOB_MAX_MESSAGES and (window_end - window_start) > min_window_ms:+ _delete_search_job(fetch, host, job_id, logger)+ middle = window_start + (window_end - window_start) // 2+ pending.appendleft((middle, window_end))+ pending.appendleft((window_start, middle))+ logger.debug(+ f"Sumo Logic: window {window_start}-{window_end} hit the {SEARCH_JOB_MAX_MESSAGES} message cap, splitting"+ )+ continue++ if message_count >= SEARCH_JOB_MAX_MESSAGES:+ logger.warning(+ f"Sumo Logic: window {window_start}-{window_end} is already at the minimum size but "+ f"still reports {message_count} messages; results beyond the cap are truncated"+ )++ try:+ yield from _fetch_search_job_messages(fetch, host, job_id, message_count, config.page_size)+ finally:+ _delete_search_job(fetch, host, job_id, logger)++ if pending:+ # Save AFTER the window's rows are yielded so a crash re-runs this window instead of+ # skipping it; merge dedupes the re-yielded rows on the primary key.+ resumable_source_manager.save_state(SumoLogicResumeConfig(log_window_start_ms=window_end))+++def get_rows(+ deployment: Optional[str],+ access_id: str,+ access_key: str,+ endpoint: str,+ search_query: Optional[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SumoLogicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SUMO_LOGIC_ENDPOINTS[endpoint]+ host = base_url(deployment)+ session = _make_session(access_id, access_key)+ fetch = _make_fetch(session, logger)++ if config.pagination == "search_job":+ query = (search_query or "").strip() or DEFAULT_SEARCH_QUERY+ batches = _get_log_rows(+ fetch,+ host,+ query,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif config.fan_out_over_collectors:+ batches = _get_collector_fan_out_rows(fetch, host, config, resumable_source_manager)+ elif config.pagination == "offset":+ batches = _get_offset_paginated_rows(fetch, host, config, resumable_source_manager)+ else:+ batches = _get_token_paginated_rows(fetch, host, config, resumable_source_manager)++ if config.redact_fields or config.redact_nested_fields:+ for batch in batches:+ yield [_redact_row(row, config) for row in batch]+ else:+ yield from batches+++def sumo_logic_source(+ deployment: Optional[str],+ access_id: str,+ access_key: str,+ endpoint: str,+ search_query: Optional[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SumoLogicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SUMO_LOGIC_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ deployment=deployment,+ access_id=access_id,+ access_key=access_key,+ endpoint=endpoint,+ search_query=search_query,+ 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=config.primary_keys,+ # Search Job messages come back newest-first within each window, so the logs stream isn't+ # globally ascending; "desc" makes the pipeline persist the incremental watermark only when+ # the whole run succeeds. Management endpoints are full refresh, where sort mode is moot.+ sort_mode="desc" if config.pagination == "search_job" else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/tests/test_sumo_logic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/tests/test_sumo_logic.pynew file mode 100644index 000000000000..42af158fc0e9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/tests/test_sumo_logic.py@@ -0,0 +1,539 @@+from datetime import UTC, date, datetime, timedelta+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic import sumo_logic as sl+from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.settings import SUMO_LOGIC_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.sumo_logic import (+ SumoLogicResumeConfig,+ _extract_items,+ _message_row,+ _to_epoch_ms,+ _unnest_item,+ base_url,+ sumo_logic_source,+ validate_credentials,+)+++def _response(json_data: Any = None, status: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status+ resp.ok = status < 400+ resp.content = b"{}" if json_data is not None else b""+ resp.json.return_value = json_data+ return resp+++def _make_manager(resume_state: SumoLogicResumeConfig | None = None) -> tuple[mock.MagicMock, list[Any]]:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ saved: list[Any] = []+ manager.save_state.side_effect = lambda state: saved.append(state)+ return manager, saved+++def _run_get_rows(+ endpoint: str,+ request_handler: Any,+ manager: mock.MagicMock,+ search_query: str | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> list[list[dict[str, Any]]]:+ with mock.patch.object(sl, "make_tracked_session") as mock_session:+ mock_session.return_value.request.side_effect = request_handler+ return list(+ sl.get_rows(+ deployment="us1",+ access_id="id",+ access_key="key",+ endpoint=endpoint,+ search_query=search_query,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+++class TestBaseUrl:+ @pytest.mark.parametrize(+ ("deployment", "expected"),+ [+ ("us1", "https://api.sumologic.com/api"),+ ("eu", "https://api.eu.sumologic.com/api"),+ ("jp", "https://api.jp.sumologic.com/api"),+ # Unknown / spoofed deployments fall back to the default US1 host.+ ("evil.example.com", "https://api.sumologic.com/api"),+ (None, "https://api.sumologic.com/api"),+ ],+ )+ def test_base_url(self, deployment: Any, expected: str) -> None:+ assert base_url(deployment) == expected+++class TestToEpochMs:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (datetime(2026, 1, 1, tzinfo=UTC), 1767225600000),+ (datetime(2026, 1, 1), 1767225600000), # naive treated as UTC+ (date(2026, 1, 1), 1767225600000),+ (1767225600000, 1767225600000),+ ("2026-01-01T00:00:00", 1767225600000),+ ],+ )+ def test_to_epoch_ms(self, value: Any, expected: int) -> None:+ assert _to_epoch_ms(value) == expected+++class TestExtractAndUnnest:+ def test_wrapped_data_key(self) -> None:+ config = SUMO_LOGIC_ENDPOINTS["users"]+ assert _extract_items({"data": [{"id": "u1"}]}, config) == [{"id": "u1"}]++ def test_missing_data_key_returns_empty(self) -> None:+ config = SUMO_LOGIC_ENDPOINTS["users"]+ assert _extract_items({"next": None}, config) == []++ def test_top_level_list(self) -> None:+ config = SUMO_LOGIC_ENDPOINTS["monitors"] # data_key=None+ assert _extract_items([{"item": {"id": 1}}], config) == [{"item": {"id": 1}}]++ def test_unnest_lifts_item_and_keeps_siblings(self) -> None:+ config = SUMO_LOGIC_ENDPOINTS["monitors"] # nest_key="item"+ row = _unnest_item({"item": {"id": 1, "name": "mon"}, "path": "/Monitors/mon"}, config)+ assert row == {"id": 1, "name": "mon", "path": "/Monitors/mon"}++ def test_unnest_noop_without_nest_key(self) -> None:+ config = SUMO_LOGIC_ENDPOINTS["users"]+ assert _unnest_item({"id": "u1"}, config) == {"id": "u1"}+++class TestMessageRow:+ def test_derives_message_time_from_epoch_millis(self) -> None:+ row = _message_row({"map": {"_messageid": "-9", "_messagetime": "1767225600000", "_raw": "boom"}})+ assert row["message_time"] == datetime(2026, 1, 1, tzinfo=UTC)+ assert row["_raw"] == "boom"++ @pytest.mark.parametrize("raw_time", [None, "not-a-number"])+ def test_unparseable_message_time_is_none(self, raw_time: Any) -> None:+ message = {"map": {"_messageid": "-9"}}+ if raw_time is not None:+ message["map"]["_messagetime"] = raw_time+ assert _message_row(message)["message_time"] is None+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [+ (200, True),+ # 403 = genuine key missing the probed capability; must not block source creation.+ (403, True),+ (401, False),+ (500, False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.sumo_logic.make_tracked_session"+ )+ def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected_valid: bool) -> None:+ mock_session.return_value.get.return_value = _response(status=status_code)++ is_valid, error = validate_credentials("us1", "id", "key")++ assert is_valid is expected_valid+ if expected_valid:+ assert error is None+ else:+ assert error is not None++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.sumo_logic.make_tracked_session"+ )+ def test_request_exception_is_caught(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")+ is_valid, error = validate_credentials("us1", "id", "key")+ assert is_valid is False+ assert error is not None+++class TestSessionPrivacy:+ def test_session_excludes_bodies_from_sample_capture(self) -> None:+ # Raw `_raw` log bodies are free-form customer data; re-enabling sample capture would copy+ # them into HTTP sample storage where the name-based scrubbers can't redact embedded secrets.+ manager, _saved = _make_manager()+ with mock.patch.object(sl, "make_tracked_session") as mock_session_factory:+ mock_session_factory.return_value.request.return_value = _response({"data": [], "next": None})+ list(+ sl.get_rows(+ deployment="us1",+ access_id="id",+ access_key="key",+ endpoint="users",+ search_query=None,+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )+ )+ assert mock_session_factory.call_args.kwargs["capture"] is False+ assert "key" in mock_session_factory.call_args.kwargs["redact_values"]+++class TestCredentialRedaction:+ def test_connections_drop_webhook_secrets_but_keep_metadata(self) -> None:+ # A connection's destination URL carries the webhook auth token (Slack/PagerDuty put the+ # secret in the URL itself) and header fields can carry an Authorization credential; a+ # warehouse reader must never see them, only the connection's non-secret metadata.+ manager, _saved = _make_manager()++ def handler(method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ return _response(+ {+ "data": [+ {+ "id": "c1",+ "name": "prod-alerts",+ "type": "WebhookConnection",+ "description": "Slack alerts",+ "url": "https://hooks.slack.com/services/T00/B00/secret-token",+ "headers": [{"name": "Authorization", "value": "Bearer secret"}],+ "customHeaders": {"X-Api-Key": "secret"},+ "defaultPayload": "{...}",+ }+ ],+ "next": None,+ }+ )++ rows = _run_get_rows("connections", handler, manager)++ assert rows == [+ [{"id": "c1", "name": "prod-alerts", "type": "WebhookConnection", "description": "Slack alerts"}]+ ]++ def test_monitors_drop_nested_notification_payload_overrides(self) -> None:+ # A monitor's notification payload overrides live below the top level (under the+ # `notifications` list) and can carry destination credentials, so the shallow key filter+ # can't reach them; they must be stripped while the rest of the notification routing stays.+ manager, _saved = _make_manager()++ def handler(method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ return _response(+ [+ {+ "item": {+ "id": "m1",+ "name": "high-errors",+ "notifications": [+ {+ "notification": {+ "connectionType": "Webhook",+ "connectionId": "conn-1",+ "payloadOverride": '{"token": "secret"}',+ "resolutionPayloadOverride": '{"token": "secret"}',+ },+ "runForTriggerTypes": ["Critical"],+ }+ ],+ },+ "path": "/m/m1",+ }+ ]+ )++ rows = _run_get_rows("monitors", handler, manager)++ assert rows == [+ [+ {+ "id": "m1",+ "name": "high-errors",+ "notifications": [+ {+ "notification": {"connectionType": "Webhook", "connectionId": "conn-1"},+ "runForTriggerTypes": ["Critical"],+ }+ ],+ "path": "/m/m1",+ }+ ]+ ]+++class TestTokenPagination:+ def test_yields_pages_saves_token_after_yield_and_sends_it(self) -> None:+ manager, saved = _make_manager()+ requested: list[str] = []++ def handler(method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ requested.append(url)+ if len(requested) == 1:+ return _response({"data": [{"id": "u1"}], "next": "tok-2"})+ return _response({"data": [{"id": "u2"}], "next": None})++ rows = _run_get_rows("users", handler, manager)++ assert rows == [[{"id": "u1"}], [{"id": "u2"}]]+ assert [s.token for s in saved] == ["tok-2"]+ second_query = parse_qs(urlparse(requested[1]).query)+ assert second_query["token"] == ["tok-2"]++ def test_resumes_from_saved_token(self) -> None:+ manager, _saved = _make_manager(SumoLogicResumeConfig(token="tok-resume"))+ requested: list[str] = []++ def handler(method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ requested.append(url)+ return _response({"data": [{"id": "u9"}], "next": None})++ _run_get_rows("users", handler, manager)++ first_query = parse_qs(urlparse(requested[0]).query)+ assert first_query["token"] == ["tok-resume"]+++class TestOffsetPagination:+ def test_advances_offset_and_terminates_on_short_page(self) -> None:+ manager, saved = _make_manager()+ page_size = SUMO_LOGIC_ENDPOINTS["monitors"].page_size+ requested: list[str] = []++ def handler(method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ requested.append(url)+ if len(requested) == 1:+ return _response([{"item": {"id": i}, "path": f"/m/{i}"} for i in range(page_size)])+ return _response([{"item": {"id": "last"}, "path": "/m/last"}])++ rows = _run_get_rows("monitors", handler, manager)++ assert len(rows) == 2+ assert rows[0][0] == {"id": 0, "path": "/m/0"}+ assert rows[1] == [{"id": "last", "path": "/m/last"}]+ assert [s.offset for s in saved] == [page_size]+ second_query = parse_qs(urlparse(requested[1]).query)+ assert second_query["offset"] == [str(page_size)]+ assert second_query["query"] == ["type:monitor"]+++class TestCollectorFanOut:+ def test_rows_carry_collector_id_and_drop_ingestion_url(self) -> None:+ # An HTTP source's `url` is itself a bearer credential for log ingestion, so it must be+ # redacted even though it arrives via the collector fan-out path; the parent collector id+ # is still stitched onto every row.+ manager, _saved = _make_manager()+ requested: list[str] = []++ def handler(method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ requested.append(url)+ path = urlparse(url).path+ if path.endswith("/v1/collectors"):+ return _response({"collectors": [{"id": 1}, {"id": 2}]})+ if path.endswith("/v1/collectors/1/sources"):+ return _response(+ {"sources": [{"id": 10, "name": "s10", "url": "https://collectors.sumologic.com/receiver/secret"}]}+ )+ if path.endswith("/v1/collectors/2/sources"):+ return _response({"sources": [{"id": 10, "name": "other-s10"}]})+ raise AssertionError(f"unexpected URL {url}")++ rows = _run_get_rows("collector_sources", handler, manager)++ assert rows == [+ [+ {"id": 10, "name": "s10", "collector_id": 1},+ {"id": 10, "name": "other-s10", "collector_id": 2},+ ]+ ]+++class FakeSearchJobApi:+ """Fakes the submit/poll/fetch/delete Search Job flow, recording created jobs and deletions."""++ def __init__(self, message_count_per_job: list[int]) -> None:+ self.message_count_per_job = message_count_per_job+ self.created_jobs: list[dict[str, Any]] = []+ self.deleted_job_ids: list[str] = []+ self.fetched_message_job_ids: list[str] = []++ def _count(self, job_id: str) -> int:+ return self.message_count_per_job[int(job_id) - 1]++ def __call__(self, method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ parsed = urlparse(url)+ if method == "POST" and parsed.path.endswith("/v1/search/jobs"):+ self.created_jobs.append(json)+ return _response({"id": str(len(self.created_jobs))})+ if method == "DELETE":+ self.deleted_job_ids.append(parsed.path.rsplit("/", 1)[-1])+ return _response(None, status=204)+ if method == "GET" and parsed.path.endswith("/messages"):+ job_id = parsed.path.split("/")[-2]+ self.fetched_message_job_ids.append(job_id)+ query = parse_qs(parsed.query)+ offset = int(query["offset"][0])+ count = self._count(job_id)+ messages = [+ {"map": {"_messageid": f"{job_id}-{i}", "_messagetime": "1767225600000"}} for i in range(offset, count)+ ]+ return _response({"messages": messages})+ if method == "GET":+ job_id = parsed.path.rsplit("/", 1)[-1]+ return _response({"state": "DONE GATHERING RESULTS", "messageCount": self._count(job_id)})+ raise AssertionError(f"unexpected request {method} {url}")+++class TestLogSearchJobs:+ ONE_HOUR_MS = 3_600_000++ def test_windows_start_at_watermark_and_are_contiguous(self) -> None:+ manager, saved = _make_manager()+ api = FakeSearchJobApi(message_count_per_job=[1, 1])+ watermark = datetime.now(UTC).timestamp() * 1000 - 90 * 60 * 1000 # 90 minutes ago++ with mock.patch.object(sl, "SEARCH_JOB_INITIAL_WINDOW", timedelta(hours=1)):+ rows = _run_get_rows(+ "logs",+ api,+ manager,+ search_query="_sourceCategory=prod",+ should_use_incremental_field=True,+ db_incremental_field_last_value=int(watermark),+ )++ assert len(api.created_jobs) == 2+ first, second = api.created_jobs+ assert first["query"] == "_sourceCategory=prod"+ assert first["from"] == int(watermark)+ assert first["to"] == int(watermark) + self.ONE_HOUR_MS+ assert second["from"] == first["to"]+ assert second["to"] > second["from"]+ # Rows carry the derived message_time; both jobs' pages were yielded and both jobs deleted.+ assert [row["message_time"] for page in rows for row in page] == [datetime(2026, 1, 1, tzinfo=UTC)] * 2+ assert api.deleted_job_ids == ["1", "2"]+ # State saved once — after the first window's rows, never after the final window.+ assert [s.log_window_start_ms for s in saved] == [first["to"]]++ def test_resumes_from_saved_window_start(self) -> None:+ resume_start = int(datetime.now(UTC).timestamp() * 1000) - 10 * 60 * 1000+ manager, _saved = _make_manager(SumoLogicResumeConfig(log_window_start_ms=resume_start))+ api = FakeSearchJobApi(message_count_per_job=[1])++ _run_get_rows("logs", api, manager, should_use_incremental_field=True, db_incremental_field_last_value=0)++ assert api.created_jobs[0]["from"] == resume_start++ def test_blank_search_query_defaults_to_wildcard(self) -> None:+ manager, _saved = _make_manager()+ api = FakeSearchJobApi(message_count_per_job=[0])+ watermark = int(datetime.now(UTC).timestamp() * 1000) - 60_000++ _run_get_rows(+ "logs",+ api,+ manager,+ search_query=" ",+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ assert api.created_jobs[0]["query"] == "*"++ def test_window_at_message_cap_is_split_without_fetching(self) -> None:+ manager, _saved = _make_manager()+ # Job 1 (the full window) hits the cap; jobs 2 and 3 (the halves) fit.+ api = FakeSearchJobApi(message_count_per_job=[2, 1, 1])+ watermark = int(datetime.now(UTC).timestamp() * 1000) - 60 * 60 * 1000++ with mock.patch.object(sl, "SEARCH_JOB_MAX_MESSAGES", 2):+ rows = _run_get_rows(+ "logs",+ api,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ assert len(api.created_jobs) == 3+ first, first_half, second_half = api.created_jobs+ assert first_half["from"] == first["from"]+ assert first_half["to"] == second_half["from"]+ assert second_half["to"] == first["to"]+ # The capped job was deleted without its messages being fetched.+ assert "1" not in api.fetched_message_job_ids+ assert api.deleted_job_ids[0] == "1"+ assert len([row for page in rows for row in page]) == 2++ def test_cancelled_job_raises(self) -> None:+ manager, _saved = _make_manager()++ def handler(method: str, url: str, json: Any = None, timeout: Any = None) -> Any:+ if method == "POST":+ return _response({"id": "1"})+ return _response({"state": "CANCELLED"})++ with pytest.raises(ValueError, match="cancelled"):+ _run_get_rows(+ "logs",+ handler,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=int(datetime.now(UTC).timestamp() * 1000) - 60_000,+ )++ def test_watermark_in_future_yields_nothing(self) -> None:+ manager, _saved = _make_manager()+ api = FakeSearchJobApi(message_count_per_job=[])++ rows = _run_get_rows(+ "logs",+ api,+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=int(datetime.now(UTC).timestamp() * 1000) + 60 * 60 * 1000,+ )++ assert rows == []+ assert api.created_jobs == []+++class TestSumoLogicSourceResponse:+ @pytest.mark.parametrize(+ ("endpoint", "expected_pks", "expected_sort_mode", "expect_partition"),+ [+ ("logs", ["_messageid", "_messagetime"], "desc", True),+ ("users", ["id"], "asc", False),+ ("collector_sources", ["collector_id", "id"], "asc", False),+ ("health_events", ["eventId"], "asc", False),+ ],+ )+ def test_source_response_shape(+ self, endpoint: str, expected_pks: list[str], expected_sort_mode: str, expect_partition: bool+ ) -> None:+ response = sumo_logic_source(+ deployment="us1",+ access_id="id",+ access_key="key",+ endpoint=endpoint,+ search_query=None,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_pks+ assert response.sort_mode == expected_sort_mode+ if expect_partition:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["message_time"]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/tests/test_sumo_logic_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/tests/test_sumo_logic_source.pynew file mode 100644index 000000000000..850af050bd97--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sumo_logic/tests/test_sumo_logic_source.py@@ -0,0 +1,186 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++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 SumoLogicSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.source import SumoLogicSource+from products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.sumo_logic import SumoLogicResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "logs",+ "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 TestSumoLogicSource:+ def setup_method(self) -> None:+ self.source = SumoLogicSource()+ self.team_id = 123+ self.config = SumoLogicSourceConfig(+ access_id="suAbc", access_key="sk-secret", deployment="eu", search_query="_sourceCategory=prod"+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SUMOLOGIC++ def test_deployment_is_a_connection_host_field(self) -> None:+ # Changing the deployment must force the secrets to be re-entered so they're never+ # sent to a freshly-specified host.+ assert self.source.connection_host_fields == ["deployment"]++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "SumoLogic"+ assert config.label == "Sumo Logic"+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/sumo-logic"++ deployment_field, access_id_field, access_key_field, search_query_field = config.fields++ assert isinstance(deployment_field, SourceFieldSelectConfig)+ assert deployment_field.name == "deployment"+ assert deployment_field.required is True+ assert deployment_field.defaultValue == "us1"+ assert {o.value for o in deployment_field.options} == {+ "us1",+ "us2",+ "au",+ "ca",+ "de",+ "eu",+ "fed",+ "in",+ "jp",+ "kr",+ }++ assert isinstance(access_id_field, SourceFieldInputConfig)+ assert access_id_field.name == "access_id"+ assert access_id_field.required is True+ assert access_id_field.secret is False++ assert isinstance(access_key_field, SourceFieldInputConfig)+ assert access_key_field.name == "access_key"+ assert access_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert access_key_field.required is True+ assert access_key_field.secret is True++ assert isinstance(search_query_field, SourceFieldInputConfig)+ assert search_query_field.name == "search_query"+ assert search_query_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_returns_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_only_logs_is_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["logs"].supports_incremental is True+ assert schemas["logs"].supports_append is True+ assert schemas["logs"].incremental_fields == [+ {+ "label": "message_time",+ "type": "datetime",+ "field": "message_time",+ "field_type": "datetime",+ }+ ]++ for name in set(ENDPOINTS) - {"logs"}:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["monitors"])+ assert len(schemas) == 1+ assert schemas[0].name == "monitors"++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid"),+ [+ ((True, None), True),+ ((False, "Invalid Sumo Logic access ID or access key."), False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.source.validate_sumo_logic_credentials"+ )+ def test_validate_credentials(+ self, mock_validate: mock.MagicMock, mock_return: tuple[bool, str | None], expected_valid: bool+ ) -> 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 == mock_return[1]+ mock_validate.assert_called_once_with("eu", "suAbc", "sk-secret")++ 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 SumoLogicResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.source.sumo_logic_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="monitors")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ deployment="eu",+ access_id="suAbc",+ access_key="sk-secret",+ endpoint="monitors",+ search_query="_sourceCategory=prod",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sumo_logic.source.sumo_logic_source")+ def test_source_for_pipeline_passes_incremental_value_when_enabled(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(+ schema_name="logs",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="message_time",+ )+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"