: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 logz_io import source (#71198)
Tom Owersb750b507d24b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex cc1af5acae4c..30cf97dd3ce3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -298,6 +298,7 @@ the row lists both.| linode | HTTP | requests | ✅ || llama_cloud | HTTP | requests | ✅ || lob | HTTP | requests | ✅ |+| logz_io | HTTP | requests | ✅ || luma | HTTP | requests | ✅ || mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ || mem0 | HTTP | requests | ✅ |@@ -762,7 +763,6 @@ doesn't conflict with concurrent PRs.- linkedin_pages- linnworks- llama_cloud-- logz_io- lokalise- looker- loopsdiff --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 17e2ac88a22b..7a8b0af04d35 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@@ -2494,7 +2494,8 @@ class LobSourceConfig(config.Config):@config.configclass LogzIOSourceConfig(config.Config):- pass+ api_token: str+ region: Literal["us", "eu", "uk", "ca", "au", "wa"] = config.value(default="us")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/canonical_descriptions.pynew file mode 100644index 000000000000..b9e9476f900e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/canonical_descriptions.py@@ -0,0 +1,55 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "search_logs": {+ "description": "Individual log documents returned by the Logz.io search API, one row per Elasticsearch document. Bounded by the account's log retention window.",+ "docs_url": "https://api-docs.logz.io/docs/logz/search",+ "columns": {+ "_id": "Elasticsearch document id, unique across the account's indices.",+ "_index": "Elasticsearch index the document was read from (typically time-based).",+ "@timestamp": "Timestamp of the log event, in UTC.",+ "message": "The log message body.",+ "type": "Log type assigned at shipping time.",+ },+ },+ "alerts": {+ "description": "Alert definitions configured in the account.",+ "docs_url": "https://api-docs.logz.io/docs/logz/get-all-alerts",+ "columns": {+ "id": "Unique identifier for the alert definition.",+ "title": "Human-readable alert title.",+ "enabled": "Whether the alert is currently active.",+ "createdAt": "When the alert was created.",+ "updatedAt": "When the alert was last modified.",+ },+ },+ "triggered_alerts": {+ "description": "History of alert firings — one row per triggered alert event.",+ "docs_url": "https://api-docs.logz.io/docs/logz/search-triggered-alerts",+ "columns": {+ "alertEventId": "Unique identifier for the triggered alert event.",+ "name": "Name of the alert that fired.",+ "severity": "Severity assigned to the firing.",+ "date": "When the alert fired.",+ },+ },+ "notification_endpoints": {+ "description": "Notification endpoints (Slack, PagerDuty, webhooks, etc.) available to route alerts to.",+ "docs_url": "https://api-docs.logz.io/docs/logz/get-all-endpoints",+ "columns": {+ "id": "Unique identifier for the notification endpoint.",+ "title": "Human-readable endpoint title.",+ "type": "Endpoint type (e.g. slack, pagerduty, custom).",+ },+ },+ "drop_filters": {+ "description": "Drop filters configured to discard matching logs before indexing.",+ "docs_url": "https://api-docs.logz.io/docs/logz/get-all-drop-filters",+ "columns": {+ "id": "Unique identifier for the drop filter.",+ "active": "Whether the drop filter is currently applied.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.pynew file mode 100644index 000000000000..a48ce99938a5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py@@ -0,0 +1,332 @@+import json+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.settings import (+ DEFAULT_REGION,+ LOGZIO_ENDPOINTS,+ REGION_BASE_URLS,+ LogzIOEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+# Elasticsearch scroll page size. Logz.io caps a single search response and the scroll cursor walks+# the rest; 1000 balances round-trips against per-response memory.+SCROLL_PAGE_SIZE = 1000+# Body-paginated list endpoints (triggered alerts, drop filters).+PAGE_SIZE = 100+# Hard cap on body-paginated pages per sync so a mis-terminating cursor can't scan unbounded.+MAX_PAGES = 10_000+# First incremental sync of logs backfills this many days. Logz.io retention is account-bounded, so+# only data still within the retention window is actually returned regardless.+INITIAL_LOOKBACK_DAYS = 3+++class LogzIORetryableError(Exception):+ pass+++class LogzIOResumeConfig:+ # Elasticsearch scroll cursor for `search_logs`. Valid for ~20 minutes, so it only enables+ # within-run heartbeat resume; across runs the incremental `@timestamp` watermark is the durable+ # cursor. None for the non-scroll endpoints.+ scroll_id: str | None = None+++def base_url_for_region(region: str | None) -> str:+ return REGION_BASE_URLS.get((region or DEFAULT_REGION).lower(), REGION_BASE_URLS[DEFAULT_REGION])+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "X-API-TOKEN": api_token,+ "Content-Type": "application/json",+ "Accept": "application/json",+ # Logz.io recommends compression for large search/scroll responses.+ "Accept-Encoding": "gzip, deflate",+ }+++def _format_timestamp(value: Any) -> str:+ """Format an incremental watermark value as an ISO 8601 UTC string for an Elasticsearch range query."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ else:+ return str(value)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")+++@retry(+ retry=retry_if_exception_type(+ (LogzIORetryableError, 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,+ method: str,+ url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ json_body: dict[str, Any] | None = None,+) -> Any:+ # Returns the decoded JSON body — a dict for search/paged endpoints, a bare array for the+ # list endpoints (e.g. /v2/alerts).+ response = session.request(method, url, headers=headers, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise LogzIORetryableError(f"Logz.io API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Logz.io API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_token: str, region: str | None, schema_name: str | None = None) -> tuple[bool, str | None]:+ """Probe the token against the account's region.++ At source-create (`schema_name is None`) a 403 is accepted: the token may simply lack scope for+ the alerts endpoint while still being valid for logs. A 401 is always a bad token.+ """+ base_url = base_url_for_region(region)+ url = f"{base_url}/v2/alerts"+ try:+ # X-API-TOKEN isn't in the tracked transport's auth-header denylist, so the raw token must be+ # registered for redaction or sample capture would persist it. Redirects stay disabled so a+ # 3xx to another host can't replay the token in this custom header.+ response = make_tracked_session(redact_values=(api_token,), allow_redirects=False).get(+ url, headers=_get_headers(api_token), timeout=10+ )+ except Exception:+ return False, "Could not reach Logz.io. Check the selected region and try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Your Logz.io API token is invalid. Create a new token in your Logz.io account settings."+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ return False, "Your Logz.io API token does not have access to this data."+ return False, f"Logz.io returned an unexpected response (status {response.status_code})."+++def _select(data: dict[str, Any] | list[dict[str, Any]], selector: str) -> list[dict[str, Any]]:+ """Pull the row array out of a response body, tolerating a bare-array or wrapped shape."""+ if isinstance(data, list):+ return data+ if not selector:+ return data.get("results", []) or []+ value = data.get(selector)+ return value if isinstance(value, list) else []+++def _parse_scroll_hits(response: dict[str, Any]) -> list[dict[str, Any]]:+ """Extract and flatten the log documents from a scroll response.++ Logz.io returns `hits` as a JSON-encoded string wrapping the standard Elasticsearch+ `{"total": ..., "hits": [...]}` structure. Each hit is flattened so `_source` fields sit at the+ top level alongside the document metadata (`_id`, `_index`).+ """+ raw_hits = response.get("hits")+ if isinstance(raw_hits, str):+ try:+ raw_hits = json.loads(raw_hits)+ except (ValueError, TypeError):+ return []+ if not isinstance(raw_hits, dict):+ return []++ rows: list[dict[str, Any]] = []+ for hit in raw_hits.get("hits", []):+ source = hit.get("_source", {})+ row = {**source} if isinstance(source, dict) else {"_source": source}+ row["_id"] = hit.get("_id")+ row["_index"] = hit.get("_index")+ rows.append(row)+ return rows+++def _build_log_query(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Build the Elasticsearch DSL body for a windowed log search.++ Incremental syncs bound the lower edge with the stored watermark; first syncs fall back to a+ fixed lookback. Results are sorted ascending on the timestamp field so the pipeline can advance+ the watermark safely after each batch (SourceResponse.sort_mode == "asc").+ """+ timestamp_field = incremental_field or "@timestamp"++ if should_use_incremental_field and db_incremental_field_last_value:+ start = db_incremental_field_last_value+ else:+ start = datetime.now(UTC) - timedelta(days=INITIAL_LOOKBACK_DAYS)++ range_filter = {+ "range": {timestamp_field: {"gte": _format_timestamp(start), "format": "strict_date_optional_time"}}+ }++ return {+ "query": {"bool": {"filter": [range_filter]}},+ "sort": [{timestamp_field: {"order": "asc"}}],+ "size": SCROLL_PAGE_SIZE,+ }+++def _iter_scroll_rows(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LogzIOResumeConfig],+ query_body: dict[str, Any],+) -> Iterator[list[dict[str, Any]]]:+ url = f"{base_url}/v1/scroll"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.scroll_id:+ try:+ data = _fetch(session, "POST", url, headers, logger, json_body={"scroll_id": resume.scroll_id})+ logger.debug("Logz.io: resuming scroll from saved cursor")+ except requests.HTTPError:+ # A scroll cursor expires after ~20 minutes, so a stale resume can't continue. Restart+ # the windowed search from the watermark instead — merge dedupes the re-pulled rows.+ logger.warning("Logz.io: saved scroll cursor expired, restarting search from watermark")+ data = _fetch(session, "POST", url, headers, logger, json_body=query_body)+ else:+ data = _fetch(session, "POST", url, headers, logger, json_body=query_body)++ while True:+ rows = _parse_scroll_hits(data)+ if not rows:+ break++ yield rows++ scroll_id = data.get("scrollId")+ if not scroll_id:+ break+ # Save AFTER yielding so a crash re-yields the last batch rather than skipping it.+ resumable_source_manager.save_state(LogzIOResumeConfig(scroll_id=scroll_id))+ data = _fetch(session, "POST", url, headers, logger, json_body={"scroll_id": scroll_id})+++def _iter_paged_rows(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: LogzIOEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{base_url}{config.path}"+ page_number = 1+ while page_number <= MAX_PAGES:+ body = {"pagination": {"pageNumber": page_number, "pageSize": PAGE_SIZE}}+ data = _fetch(session, config.method, url, headers, logger, json_body=body)+ rows = _select(data, config.data_selector)+ if not rows:+ break++ yield rows++ if len(rows) < PAGE_SIZE:+ break+ page_number += 1+ else:+ logger.warning(f"Logz.io: hit page cap ({MAX_PAGES}) for {config.name}; stopping pagination")+++def _iter_list_rows(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: LogzIOEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{base_url}{config.path}"+ data = _fetch(session, config.method, url, headers, logger)+ rows = _select(data, config.data_selector)+ if rows:+ yield rows+++def get_rows(+ api_token: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LogzIOResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = LOGZIO_ENDPOINTS[endpoint]+ base_url = base_url_for_region(region)+ headers = _get_headers(api_token)+ # X-API-TOKEN isn't in the tracked transport's auth-header denylist, so the raw token must be+ # registered for redaction or sample capture would persist it. Redirects stay disabled so a+ # 3xx to another host can't replay the token in this custom header.+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)++ if config.transport == "scroll":+ query_body = _build_log_query(should_use_incremental_field, db_incremental_field_last_value, incremental_field)+ yield from _iter_scroll_rows(session, base_url, headers, logger, resumable_source_manager, query_body)+ elif config.transport == "page":+ yield from _iter_paged_rows(session, base_url, headers, logger, config)+ else:+ yield from _iter_list_rows(session, base_url, headers, logger, config)+++def logz_io_source(+ api_token: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LogzIOResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = LOGZIO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Logs are searched ascending on `@timestamp`; the definition/config endpoints aren't+ # incremental, so asc is a safe default there too.+ sort_mode="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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.pynew file mode 100644index 000000000000..78b1bc451ba5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/settings.py@@ -0,0 +1,105 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Logz.io hosts its API behind a region-specific domain matching the account's data region. The+# stored API token is only valid against the account's own region, so the region is a required+# source field. Codes verified to resolve as of implementation; `wa` (West US 2) is documented by+# Logz.io but was transiently unavailable when probed, so it's included on the documented value.+REGION_BASE_URLS: dict[str, str] = {+ "us": "https://api.logz.io",+ "eu": "https://api-eu.logz.io",+ "uk": "https://api-uk.logz.io",+ "ca": "https://api-ca.logz.io",+ "au": "https://api-au.logz.io",+ "wa": "https://api-wa.logz.io",+}+DEFAULT_REGION = "us"+++@dataclass+class LogzIOEndpointConfig:+ name: str+ path: str+ # How rows are extracted from the upstream API:+ # - "scroll": POST /v1/scroll, an Elasticsearch scroll cursor over log documents.+ # - "list": a single GET returning a full array (small config/definition snapshots).+ # - "page": POST with body-driven page-number pagination.+ transport: Literal["scroll", "list", "page"]+ method: Literal["GET", "POST"] = "GET"+ # Dotted path to the array of rows in the JSON response (e.g. "results"). Empty means the+ # response body is itself the array.+ data_selector: str = ""+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Field to partition the warehouse table by. Must be a STABLE creation/event timestamp, never an+ # updated_at-style field that would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ should_sync_default: bool = True+++# Only `search_logs` has a genuine server-side time filter: the Elasticsearch DSL `range` query on+# `@timestamp` IS the query, so a mapped `db_incremental_field_last_value` is honored by construction+# (an ignored range filter would break search entirely). The definition/config endpoints+# (alerts, notification_endpoints, drop_filters) return small full-array snapshots with no+# updated-since filter, so they ship full refresh only.+LOGZIO_ENDPOINTS: dict[str, LogzIOEndpointConfig] = {+ "search_logs": LogzIOEndpointConfig(+ name="search_logs",+ path="/v1/scroll",+ transport="scroll",+ method="POST",+ # Elasticsearch document id, globally unique across the account's indices. Even if an+ # incremental window over-fetches at its boundary, merge dedupes on `_id`.+ primary_keys=["_id"],+ # `@timestamp` is the immutable log event time. Identifier normalization renders it as the+ # `atimestamp` column in the warehouse.+ partition_key="@timestamp",+ incremental_fields=[+ {+ "label": "@timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "@timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "alerts": LogzIOEndpointConfig(+ name="alerts",+ path="/v2/alerts",+ transport="list",+ method="GET",+ partition_key="createdAt",+ ),+ "triggered_alerts": LogzIOEndpointConfig(+ name="triggered_alerts",+ path="/v1/alerts/triggered-alerts",+ transport="page",+ method="POST",+ data_selector="results",+ primary_keys=["alertEventId"],+ partition_key="date",+ should_sync_default=False,+ ),+ "notification_endpoints": LogzIOEndpointConfig(+ name="notification_endpoints",+ path="/v1/endpoints",+ transport="list",+ method="GET",+ ),+ "drop_filters": LogzIOEndpointConfig(+ name="drop_filters",+ path="/v1/drop-filters/search",+ transport="page",+ method="POST",+ data_selector="results",+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(LOGZIO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LOGZIO_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/source.pyindex 42dafcd57947..70b2593d4ba6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/source.py@@ -1,30 +1,167 @@-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 LogzIOSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.logz_io import (+ REGION_BASE_URLS,+ LogzIOResumeConfig,+ logz_io_source,+ validate_credentials as validate_logz_io_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LOGZIO_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LogzIOSource(SimpleSource[LogzIOSourceConfig]):+class LogzIOSource(ResumableSource[LogzIOSourceConfig, LogzIOResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LOGZIO+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` selects the host the stored API token is sent to. Retargeting it must re-require+ # the token so a preserved credential can't be aimed at a different regional endpoint.+ return ["region"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.LOGZ_IO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Logz.io",+ releaseStatus=ReleaseStatus.ALPHA,+ caption=(+ "Enter your Logz.io API token to sync your log data, alerts, and account configuration "+ "into the PostHog Data warehouse. Create a token under **Settings → Tools → Manage tokens → "+ "API tokens** in your Logz.io account, and pick the region that matches your account.\n\n"+ "Log search is bounded by your account's retention window."+ ),iconPath="/static/services/logz_io.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/logz-io",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US East (api.logz.io)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api-eu.logz.io)", value="eu"),+ SourceFieldSelectConfigOption(label="UK (api-uk.logz.io)", value="uk"),+ SourceFieldSelectConfigOption(label="Canada (api-ca.logz.io)", value="ca"),+ SourceFieldSelectConfigOption(label="Australia (api-au.logz.io)", value="au"),+ SourceFieldSelectConfigOption(label="West US 2 (api-wa.logz.io)", value="wa"),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # A 401 is always a bad/revoked token; a sync-time 403 means the token lacks scope for the+ # endpoint being synced. Neither is fixable by retrying. Match the stable status text + host+ # across every region so a newly added region stays covered.+ invalid = "Your Logz.io API token is invalid or has been revoked. Create a new token in your Logz.io account settings, then reconnect."+ forbidden = "Your Logz.io API token does not have access to this data. Grant the token the required permissions, then reconnect."+ errors: dict[str, str | None] = {}+ for url in REGION_BASE_URLS.values():+ errors[f"401 Client Error: Unauthorized for url: {url}"] = invalid+ errors[f"403 Client Error: Forbidden for url: {url}"] = forbidden+ return errors++ def get_schemas(+ self,+ config: LogzIOSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = LOGZIO_ENDPOINTS[endpoint]+ has_incremental = len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0+ 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,+ )++ 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: LogzIOSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_logz_io_credentials(config.api_token, config.region, schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LogzIOResumeConfig]:+ return ResumableSourceManager[LogzIOResumeConfig](inputs, LogzIOResumeConfig)++ def source_for_pipeline(+ self,+ config: LogzIOSourceConfig,+ resumable_source_manager: ResumableSourceManager[LogzIOResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return logz_io_source(+ api_token=config.api_token,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io.pynew file mode 100644index 000000000000..77263a6d02f7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io.py@@ -0,0 +1,254 @@+import json+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.logz_io import (+ LogzIOResumeConfig,+ _build_log_query,+ _parse_scroll_hits,+ base_url_for_region,+ get_rows,+ logz_io_source,+ validate_credentials,+)++TRANSPORT = "products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.logz_io"+++def _resp(json_body: Any, status: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = json_body+ resp.status_code = status+ resp.ok = status < 400+ return resp+++def _make_manager(resume_state: LogzIOResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _scroll_response(scroll_id: str | None, hits: list[dict[str, Any]]) -> dict[str, Any]:+ # Logz.io returns `hits` as a JSON-encoded string wrapping the Elasticsearch hits structure.+ return {"scrollId": scroll_id, "hits": json.dumps({"total": len(hits), "hits": hits})}+++def _hit(doc_id: str, source: dict[str, Any]) -> dict[str, Any]:+ return {"_id": doc_id, "_index": "logs-2026", "_source": source}+++class TestBaseUrlForRegion:+ @pytest.mark.parametrize(+ "region, expected",+ [+ ("us", "https://api.logz.io"),+ ("eu", "https://api-eu.logz.io"),+ ("EU", "https://api-eu.logz.io"),+ ("uk", "https://api-uk.logz.io"),+ (None, "https://api.logz.io"),+ ("unknown", "https://api.logz.io"),+ ],+ )+ def test_base_url_for_region(self, region: str | None, expected: str) -> None:+ assert base_url_for_region(region) == expected+++class TestParseScrollHits:+ def test_parses_stringified_hits_and_flattens_source(self) -> None:+ response = _scroll_response("s1", [_hit("a", {"@timestamp": "2026-07-01T00:00:00Z", "message": "hi"})])+ rows = _parse_scroll_hits(response)+ assert rows == [{"@timestamp": "2026-07-01T00:00:00Z", "message": "hi", "_id": "a", "_index": "logs-2026"}]++ def test_handles_hits_already_parsed_as_dict(self) -> None:+ response = {"scrollId": "s1", "hits": {"total": 1, "hits": [_hit("a", {"message": "hi"})]}}+ rows = _parse_scroll_hits(response)+ assert rows[0]["_id"] == "a"+ assert rows[0]["message"] == "hi"++ @pytest.mark.parametrize("response", [{}, {"hits": "not json"}, {"hits": None}, {"hits": {"hits": []}}])+ def test_missing_or_malformed_hits_yield_no_rows(self, response: dict[str, Any]) -> None:+ assert _parse_scroll_hits(response) == []+++class TestBuildLogQuery:+ def test_incremental_uses_watermark_as_lower_bound(self) -> None:+ watermark = datetime(2026, 7, 1, 12, 0, 0, tzinfo=UTC)+ query = _build_log_query(True, watermark, "@timestamp")+ range_filter = query["query"]["bool"]["filter"][0]["range"]["@timestamp"]+ assert range_filter["gte"] == "2026-07-01T12:00:00.000000Z"+ # Ascending sort so the pipeline can advance the watermark safely after each batch.+ assert query["sort"] == [{"@timestamp": {"order": "asc"}}]++ def test_first_sync_falls_back_to_a_bounded_lookback(self) -> None:+ # With no stored watermark the query must still be time-bounded, not an unbounded match-all.+ query = _build_log_query(True, None, "@timestamp")+ assert "gte" in query["query"]["bool"]["filter"][0]["range"]["@timestamp"]++ def test_honors_user_selected_incremental_field(self) -> None:+ query = _build_log_query(True, datetime(2026, 7, 1, tzinfo=UTC), "event_ts")+ assert "event_ts" in query["query"]["bool"]["filter"][0]["range"]+ assert query["sort"] == [{"event_ts": {"order": "asc"}}]+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, schema_name, expected_valid",+ [+ (200, None, True),+ (401, None, False),+ # A missing scope at source-create is accepted — the token may only grant log access.+ (403, None, True),+ # ...but when checking a specific schema, a 403 means that table is unreachable.+ (403, "alerts", False),+ (500, None, False),+ ],+ )+ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_status_mapping(+ self, mock_session: mock.MagicMock, status_code: int, schema_name: str | None, expected_valid: bool+ ) -> None:+ mock_session.return_value.get.return_value = _resp({}, status=status_code)+ is_valid, _ = validate_credentials("token", "us", schema_name)+ assert is_valid is expected_valid++ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_network_error_is_not_valid(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ is_valid, message = validate_credentials("token", "us")+ assert is_valid is False+ assert message is not None++ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_eu_region_probes_eu_host(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _resp({}, status=200)+ validate_credentials("token", "eu")+ assert mock_session.return_value.get.call_args.args[0].startswith("https://api-eu.logz.io")++ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_token_registered_for_sample_redaction(self, mock_session: mock.MagicMock) -> None:+ # X-API-TOKEN isn't in the transport's auth-header denylist; dropping redact_values would+ # persist the raw token in captured HTTP samples, and following a redirect would replay the+ # token to another host.+ mock_session.return_value.get.return_value = _resp({}, status=200)+ validate_credentials("secret-token", "us")+ assert mock_session.call_args.kwargs["redact_values"] == ("secret-token",)+ assert mock_session.call_args.kwargs["allow_redirects"] is False+++class TestSearchLogsScroll:+ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_walks_scroll_cursor_until_empty(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.request.side_effect = [+ _resp(_scroll_response("s1", [_hit("a", {"@timestamp": "t1"})])),+ _resp(_scroll_response("s2", [_hit("b", {"@timestamp": "t2"})])),+ _resp(_scroll_response("s2", [])),+ ]++ manager = _make_manager()+ rows = [r for batch in get_rows("token", "us", "search_logs", mock.MagicMock(), manager) for r in batch]++ assert [r["_id"] for r in rows] == ["a", "b"]+ # State is saved after each yielded batch that has a following cursor (never after the last).+ saved_ids = [c.args[0].scroll_id for c in manager.save_state.call_args_list]+ assert saved_ids == ["s1", "s2"]+ # The sync session must register the token for redaction and refuse redirects (X-API-TOKEN+ # isn't in the transport's auth-header denylist, so a redirect would leak it to another host).+ assert mock_session.call_args.kwargs["redact_values"] == ("token",)+ assert mock_session.call_args.kwargs["allow_redirects"] is False++ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_resumes_from_saved_scroll_cursor(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.request.side_effect = [+ _resp(_scroll_response("s9", [_hit("r", {"@timestamp": "t"})])),+ _resp(_scroll_response("s9", [])),+ ]++ manager = _make_manager(LogzIOResumeConfig(scroll_id="saved-cursor"))+ rows = [r for batch in get_rows("token", "us", "search_logs", mock.MagicMock(), manager) for r in batch]++ assert [r["_id"] for r in rows] == ["r"]+ # The first request continues the saved cursor rather than starting a fresh search.+ first_body = mock_session.return_value.request.call_args_list[0].kwargs["json"]+ assert first_body == {"scroll_id": "saved-cursor"}++ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_expired_cursor_restarts_search_from_watermark(self, mock_session: mock.MagicMock) -> None:+ expired = requests.HTTPError("400 scroll expired", response=mock.MagicMock())+ mock_session.return_value.request.side_effect = [+ expired,+ _resp(_scroll_response("s1", [_hit("a", {"@timestamp": "t"})])),+ _resp(_scroll_response("s1", [])),+ ]++ manager = _make_manager(LogzIOResumeConfig(scroll_id="stale"))+ rows = [r for batch in get_rows("token", "us", "search_logs", mock.MagicMock(), manager) for r in batch]++ assert [r["_id"] for r in rows] == ["a"]+ # After the stale cursor 400s, the restart posts the windowed search query, not the cursor.+ restart_body = mock_session.return_value.request.call_args_list[1].kwargs["json"]+ assert "query" in restart_body+++class TestPagedEndpoints:+ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_walks_pages_until_short_page(self, mock_session: mock.MagicMock) -> None:+ full_page = [{"alertEventId": str(i)} for i in range(100)]+ mock_session.return_value.request.side_effect = [+ _resp({"results": full_page}),+ _resp({"results": [{"alertEventId": "100"}]}),+ ]++ manager = _make_manager()+ rows = [r for batch in get_rows("token", "us", "triggered_alerts", mock.MagicMock(), manager) for r in batch]++ assert len(rows) == 101+ page_numbers = [+ c.kwargs["json"]["pagination"]["pageNumber"] for c in mock_session.return_value.request.call_args_list+ ]+ assert page_numbers == [1, 2]++ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_empty_first_page_yields_nothing(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.request.return_value = _resp({"results": []})+ manager = _make_manager()+ assert list(get_rows("token", "us", "triggered_alerts", mock.MagicMock(), manager)) == []+++class TestListEndpoints:+ @mock.patch(f"{TRANSPORT}.make_tracked_session")+ def test_bare_array_response_is_yielded(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.request.return_value = _resp([{"id": "1"}, {"id": "2"}])+ manager = _make_manager()+ rows = [r for batch in get_rows("token", "us", "alerts", mock.MagicMock(), manager) for r in batch]+ assert [r["id"] for r in rows] == ["1", "2"]+++class TestSourceResponseShape:+ @pytest.mark.parametrize(+ "endpoint, primary_keys, partition_key",+ [+ ("search_logs", ["_id"], "@timestamp"),+ ("alerts", ["id"], "createdAt"),+ ("triggered_alerts", ["alertEventId"], "date"),+ ("notification_endpoints", ["id"], None),+ ],+ )+ def test_response_metadata_per_endpoint(+ self, endpoint: str, primary_keys: list[str], partition_key: str | None+ ) -> None:+ response = logz_io_source("token", "us", endpoint, mock.MagicMock(), _make_manager())+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == "asc"+ if partition_key is None:+ assert response.partition_mode is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io_source.pynew file mode 100644index 000000000000..2eac39b28de9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/tests/test_logz_io_source.py@@ -0,0 +1,150 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++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 LogzIOSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.logz_io import LogzIOResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.source import LogzIOSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE = "products.warehouse_sources.backend.temporal.data_imports.sources.logz_io.source"+++class TestLogzIOSource:+ def setup_method(self):+ self.source = LogzIOSource()+ self.team_id = 123+ self.config = LogzIOSourceConfig(api_token="token", region="us")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.LOGZIO++ def test_connection_host_fields_includes_region(self):+ # region picks the host the stored token is sent to, so editing it must re-require the secret.+ assert self.source.connection_host_fields == ["region"]++ def test_get_source_config(self):+ config = self.source.get_source_config+ assert config.name.value == "LogzIO"+ assert config.label == "Logz.io"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/logz-io"+ # A finished source must never keep the scaffold's unreleasedSource flag (it hides the source).+ assert config.unreleasedSource is None++ def test_source_config_fields(self):+ fields = self.source.get_source_config.fields+ assert [f.name for f in fields] == ["api_token", "region"]++ api_token = next(f for f in fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert api_token.type == SourceFieldInputConfigType.PASSWORD+ assert api_token.secret is True+ assert api_token.required is True++ region = next(f for f in fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")+ assert region.defaultValue == "us"+ assert {opt.value for opt in region.options} == {"us", "eu", "uk", "ca", "au", "wa"}++ def test_lists_tables_without_credentials(self):+ # get_schemas iterates a static endpoint catalog with no I/O, so the public docs catalog renders.+ assert self.source.lists_tables_without_credentials is True+ documented = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(documented) == set(ENDPOINTS)+ assert "Incremental" in documented["search_logs"]["sync_methods"]+ assert documented["alerts"]["sync_methods"] == ["Full refresh"]++ @pytest.mark.parametrize(+ "endpoint, expected_incremental",+ [+ # Only search_logs has a genuine server-side time filter (the ES @timestamp range query).+ ("search_logs", True),+ ("alerts", False),+ ("triggered_alerts", False),+ ("notification_endpoints", False),+ ("drop_filters", False),+ ],+ )+ def test_incremental_support_per_endpoint(self, endpoint: str, expected_incremental: bool):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert set(schemas) == set(ENDPOINTS)+ assert schemas[endpoint].supports_incremental is expected_incremental+ assert schemas[endpoint].incremental_fields == INCREMENTAL_FIELDS[endpoint]++ def test_get_schemas_filtered_by_names(self):+ assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["alerts"])] == ["alerts"]+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.logz.io/v1/scroll",+ "403 Client Error: Forbidden for url: https://api-eu.logz.io/v2/alerts",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_error",+ [+ "500 Server Error: Internal Server Error for url: https://api.logz.io/v1/scroll",+ "429 Client Error: Too Many Requests for url: https://api.logz.io/v1/scroll",+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ ],+ )+ def test_non_retryable_errors_ignore_transient_and_unrelated(self, other_error: str):+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ @mock.patch(f"{SOURCE}.validate_logz_io_credentials")+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock):+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id, "alerts") == (True, None)+ mock_validate.assert_called_once_with("token", "us", "alerts")++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LogzIOResumeConfig++ @mock.patch(f"{SOURCE}.logz_io_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock):+ inputs = mock.MagicMock()+ inputs.schema_name = "search_logs"+ inputs.should_use_incremental_field = True+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_token"] == "token"+ assert kwargs["region"] == "us"+ assert kwargs["endpoint"] == "search_logs"+ assert kwargs["resumable_source_manager"] is manager++ @mock.patch(f"{SOURCE}.logz_io_source")+ def test_source_for_pipeline_omits_watermark_when_not_incremental(self, mock_source: mock.MagicMock):+ inputs = mock.MagicMock()+ inputs.schema_name = "alerts"+ inputs.should_use_incremental_field = False++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_keyed_by_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "search_logs" in descriptions