Skip to content

: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.

feat(data-warehouse): implement signoz import source (#70724)

Tom Owersbc06aa4178eb
diff --git a/frontend/public/services/signoz.svg b/frontend/public/services/signoz.svg
new file mode 100644
index 000000000000..cdfe945052b8
--- /dev/null
+++ b/frontend/public/services/signoz.svg
@@ -0,0 +1,4 @@
+<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="0.9" d="M20.0557 39.9666C8.91365 39.9666 0 31.2241 0 20.2958C0 9.47687 8.91365 0.625 20.0557 0.625H32.6462C36.7688 0.625 40 3.90347 40 7.83763V20.2958C40 31.2241 31.0863 39.9666 20.0557 39.9666Z" fill="#DD431F"/>
+<path d="M19.8991 11.7803C11.5768 11.7803 6.889 18.6718 6.69348 18.9652C6.21149 19.6878 6.21149 20.6224 6.69384 21.3455C6.889 21.6384 11.5768 28.5299 19.8991 28.5299C28.2214 28.5299 32.9092 21.6384 33.1047 21.345C33.5868 20.6224 33.5868 19.6878 33.1044 18.9647C32.9092 18.6718 28.2214 11.7803 19.8991 11.7803ZM7.84542 20.5774C7.67429 20.3208 7.67429 19.9894 7.84542 19.7328C8.00265 19.4968 11.3403 14.5942 17.3076 13.4182C14.6035 14.462 12.6793 17.0872 12.6793 20.1551C12.6793 23.2229 14.6035 25.8482 17.3076 26.892C11.3403 25.7159 8.00265 20.8133 7.84542 20.5774ZM16.5721 20.1551C16.5721 20.5374 16.2622 20.8472 15.8799 20.8472C15.4977 20.8472 15.1878 20.5374 15.1878 20.1551C15.1878 17.5573 17.3012 15.4438 19.8991 15.4438C20.2813 15.4438 20.5912 15.7536 20.5912 16.1359C20.5912 16.5183 20.2814 16.8281 19.8991 16.8281C18.0645 16.8281 16.5721 18.3205 16.5721 20.1551ZM19.8991 21.8378C18.9713 21.8378 18.2164 21.083 18.2164 20.1551C18.2164 19.2272 18.9713 18.4723 19.8991 18.4723C20.827 18.4723 21.5819 19.2272 21.5819 20.1551C21.5819 21.083 20.827 21.8378 19.8991 21.8378ZM31.9528 20.5774C31.7956 20.8133 28.458 25.7159 22.4907 26.892C25.1949 25.8481 27.1189 23.2229 27.1189 20.1551C27.1189 17.0873 25.1949 14.462 22.4907 13.4182C28.458 14.5943 31.7956 19.4968 31.9528 19.7328C32.124 19.9894 32.124 20.3208 31.9528 20.5774Z" fill="#F9F2F9"/>
+</svg>
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 7494f0d76903..3101f7eae9c1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -387,6 +387,7 @@ the row lists both.
| shopwired | HTTP | requests | ✅ |
| shortcut | HTTP | requests | ✅ |
| shortio | HTTP | requests | ✅ |
+| signoz | HTTP | requests | ✅ |
| simplecast | HTTP | requests | ✅ |
| simplesat | HTTP | requests | ✅ |
| skyvern | HTTP | requests | ✅ |
@@ -869,7 +870,6 @@ doesn't conflict with concurrent PRs.
- shutterstock
- sigma_computing
- signnow
-- signoz
- sim
- simfin
- simplecast
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 1ef35a35c5d1..12abbcd031df 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
@@ -3777,7 +3777,8 @@ class ShutterstockSourceConfig(config.Config):
@config.config
class SigNozSourceConfig(config.Config):
- pass
+ host: str
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/canonical_descriptions.py
new file mode 100644
index 000000000000..0b1b064c8081
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/canonical_descriptions.py
@@ -0,0 +1,86 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "logs": {
+ "description": "Raw log records ingested into SigNoz, one row per log line.",
+ "docs_url": "https://signoz.io/docs/logs-management/logs-api/overview/",
+ "columns": {
+ "id": "Unique identifier of the log record.",
+ "timestamp": "Time the log record was produced.",
+ "body": "The log message body.",
+ "severity_text": "Severity level as text (e.g. INFO, ERROR).",
+ "severity_number": "Numeric severity level per the OpenTelemetry log data model.",
+ "trace_id": "Trace ID of the request the log was emitted in, if correlated.",
+ "span_id": "Span ID of the operation the log was emitted in, if correlated.",
+ "trace_flags": "W3C trace flags of the correlated trace context.",
+ "scope_name": "Name of the instrumentation scope that produced the log.",
+ "scope_version": "Version of the instrumentation scope that produced the log.",
+ "attributes_string": "String-valued log attributes.",
+ "attributes_number": "Number-valued log attributes.",
+ "attributes_bool": "Boolean-valued log attributes.",
+ "resources_string": "Resource attributes of the emitting service (e.g. service name, host).",
+ },
+ },
+ "traces": {
+ "description": "Spans from distributed traces ingested into SigNoz, one row per span.",
+ "docs_url": "https://signoz.io/docs/traces-management/trace-api/payload-model/",
+ "columns": {
+ "trace_id": "Identifier of the trace the span belongs to.",
+ "span_id": "Unique identifier of the span within its trace.",
+ "parent_span_id": "Span ID of the parent span; empty for root spans.",
+ "timestamp": "Start time of the span.",
+ "name": "Operation name of the span.",
+ "duration_nano": "Duration of the span in nanoseconds.",
+ },
+ },
+ "alert_rules": {
+ "description": "Alert rule definitions configured in SigNoz.",
+ "docs_url": "https://signoz.io/docs/userguide/alerts-management/",
+ "columns": {
+ "id": "Unique identifier of the alert rule.",
+ "state": "Current evaluation state of the rule (e.g. inactive, pending, firing).",
+ "alert": "Name of the alert rule.",
+ "alertType": "Signal the rule evaluates (metrics, logs, traces, or exceptions).",
+ "ruleType": "Rule engine type (threshold or PromQL).",
+ "evalWindow": "Time window the rule condition is evaluated over.",
+ "frequency": "How often the rule is evaluated.",
+ "condition": "Rule condition, including the composite query and target threshold.",
+ "labels": "Labels attached to alerts fired by the rule.",
+ "annotations": "Annotations attached to alerts fired by the rule.",
+ "disabled": "Whether the rule is disabled.",
+ "preferredChannels": "Notification channels the rule routes alerts to.",
+ "createAt": "Time the rule was created.",
+ "createBy": "User who created the rule.",
+ "updateAt": "Time the rule was last updated.",
+ "updateBy": "User who last updated the rule.",
+ },
+ },
+ "dashboards": {
+ "description": "Dashboard definitions configured in SigNoz.",
+ "docs_url": "https://signoz.io/docs/userguide/manage-dashboards/",
+ "columns": {
+ "id": "Unique identifier of the dashboard.",
+ "data": "Full dashboard definition (layout, panels, variables).",
+ "locked": "Whether the dashboard is locked against edits.",
+ "createdAt": "Time the dashboard was created.",
+ "createdBy": "User who created the dashboard.",
+ "updatedAt": "Time the dashboard was last updated.",
+ "updatedBy": "User who last updated the dashboard.",
+ },
+ },
+ "notification_channels": {
+ # The receiver config `data` field is intentionally not imported: it holds secrets
+ # (Slack webhook URLs, PagerDuty keys) that must not land in a warehouse table.
+ "description": "Notification channels alerts can be routed to (Slack, PagerDuty, webhook, etc.). The receiver configuration payload is omitted because it contains credentials.",
+ "docs_url": "https://signoz.io/docs/userguide/alerts-management/",
+ "columns": {
+ "id": "Unique identifier of the notification channel.",
+ "name": "Name of the notification channel.",
+ "type": "Channel type (e.g. slack, pagerduty, webhook, email).",
+ "createdAt": "Time the channel was created.",
+ "updatedAt": "Time the channel was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/settings.py
new file mode 100644
index 000000000000..28a1b718ff2b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/settings.py
@@ -0,0 +1,120 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _timestamp_incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+@dataclass
+class SigNozEndpointConfig:
+ name: str
+ kind: Literal["telemetry", "config"]
+ # Telemetry endpoints query POST /api/v5/query_range with a composite query.
+ signal: Optional[str] = None # "logs" | "traces"
+ # Stable, monotonic sort keys sent as the query's `order`. The secondary key breaks
+ # timestamp ties so limit/offset paging is deterministic.
+ order_keys: tuple[str, ...] = ()
+ # Config endpoints are plain GET list endpoints without pagination.
+ path: Optional[str] = None
+ # Key path from the response's `data` payload to the list of records. Empty means
+ # `data` itself is the list.
+ data_keys: tuple[str, ...] = ()
+ # When set, config records are projected down to exactly these fields before they are
+ # yielded — a strict allowlist that keeps credential-bearing fields (e.g. a notification
+ # channel's receiver config) out of the warehouse. None means keep every field.
+ allowed_fields: Optional[tuple[str, ...]] = None
+ primary_keys: tuple[str, ...] = ("id",)
+ # Stable, immutable datetime field used for partitioning (never an updated-at field).
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ page_size: int = 1000
+ # First-sync lookback for telemetry endpoints. The query_range API requires an explicit
+ # start, so without a stored watermark we reach back this far; SigNoz simply has no data
+ # older than the account's retention, so a generous window is harmless.
+ default_lookback_days: Optional[int] = None
+
+ @property
+ def supports_incremental(self) -> bool:
+ # The query_range `start` param is a genuine server-side timestamp filter; config
+ # list endpoints have no time filter and stay full-refresh.
+ return self.kind == "telemetry"
+
+
+# Endpoint catalog. Telemetry rows (logs, traces) come from the v5 query_range API with
+# `requestType: "raw"`; config entities (alert rules, dashboards, notification channels)
+# come from the versioned management REST API. Metric series are intentionally excluded:
+# the raw request type only supports logs and traces, and metrics require a per-metric
+# aggregation query, which doesn't map to a generic warehouse table.
+SIGNOZ_ENDPOINTS: dict[str, SigNozEndpointConfig] = {
+ # --- Telemetry (server-side time window -> incremental) ---
+ "logs": SigNozEndpointConfig(
+ name="logs",
+ kind="telemetry",
+ signal="logs",
+ # Per the SigNoz logs API docs: order by timestamp with `id` as the tiebreaker.
+ order_keys=("timestamp", "id"),
+ primary_keys=("id",),
+ partition_key="timestamp",
+ incremental_fields=_timestamp_incremental_fields(),
+ default_lookback_days=30,
+ ),
+ "traces": SigNozEndpointConfig(
+ name="traces",
+ kind="telemetry",
+ signal="traces",
+ order_keys=("timestamp", "span_id"),
+ # span_id is only guaranteed unique within a trace, so include the trace id.
+ primary_keys=("trace_id", "span_id"),
+ partition_key="timestamp",
+ incremental_fields=_timestamp_incremental_fields(),
+ default_lookback_days=30,
+ ),
+ # --- Config entities (no server-side time filter -> full refresh) ---
+ "alert_rules": SigNozEndpointConfig(
+ name="alert_rules",
+ kind="config",
+ path="/api/v1/rules",
+ data_keys=("rules",),
+ primary_keys=("id",),
+ # `createAt` is SigNoz's (sic) creation timestamp on rules — stable, unlike updateAt.
+ partition_key="createAt",
+ ),
+ "dashboards": SigNozEndpointConfig(
+ name="dashboards",
+ kind="config",
+ path="/api/v1/dashboards",
+ primary_keys=("id",),
+ partition_key="createdAt",
+ ),
+ "notification_channels": SigNozEndpointConfig(
+ name="notification_channels",
+ kind="config",
+ path="/api/v1/channels",
+ # The `data` field holds each channel's Alertmanager receiver config — Slack webhook
+ # URLs, PagerDuty keys, and similar secrets. Allowlist the safe metadata so those
+ # credentials are never persisted to a warehouse table other project members can read.
+ allowed_fields=("id", "name", "type", "createdAt", "updatedAt"),
+ primary_keys=("id",),
+ partition_key="createdAt",
+ ),
+}
+
+ENDPOINTS = tuple(SIGNOZ_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SIGNOZ_ENDPOINTS.items()
+}
+
+# Logs and traces are bounded by the SigNoz account's retention, so the first sync can only
+# reach back as far as retention allows.
+LIMITED_RETENTION_ENDPOINTS = {"logs", "traces"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/signoz.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/signoz.py
new file mode 100644
index 000000000000..b8f1d7b5cfe8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/signoz.py
@@ -0,0 +1,402 @@
+import re
+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 RetryCallState, 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.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.settings import (
+ SIGNOZ_ENDPOINTS,
+ SigNozEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 60
+DEFAULT_LOOKBACK_DAYS = 30
+
+QUERY_RANGE_PATH = "/api/v5/query_range"
+
+HOST_NOT_ALLOWED_ERROR = "SigNoz host is not allowed"
+
+
+class SigNozRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class SigNozHostNotAllowedError(Exception):
+ pass
+
+
+class SigNozResumeConfig:
+ """Position within a telemetry sync: the current time window plus the row offset into it.
+
+ ``window_end_ms`` is pinned at sync start so a resume doesn't silently extend the window,
+ and ``window_start_ms`` advances to the last yielded row's timestamp after each page so
+ offsets stay small (the query_range API's offset paging scans offset+limit rows server-side).
+ """
+
+ window_start_ms: int
+ window_end_ms: int
+ offset: int
+
+
+def normalize_host(host: str) -> str:
+ """Turn whatever the user typed into a bare SigNoz host.
+
+ Accepts values like ``example.signoz.io``, ``https://example.signoz.io/``, or
+ ``example.signoz.io/api`` and returns ``example.signoz.io``.
+ """
+ host = host.strip()
+ host = re.sub(r"^https?://", "", host, flags=re.IGNORECASE)
+ host = host.split("/")[0]
+ return host.strip().rstrip("/")
+
+
+def _base_url(host: str) -> str:
+ return f"https://{normalize_host(host)}"
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "SIGNOZ-API-KEY": api_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+def _to_epoch_ms(value: Any) -> int | None:
+ """Convert an incremental cursor / row timestamp into epoch milliseconds."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value
+ 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):
+ # Values this large are already epoch milliseconds; smaller ones are epoch seconds.
+ return int(value if value >= 1_000_000_000_000 else value * 1000)
+ if isinstance(value, str):
+ try:
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt
+ return int(dt.timestamp() * 1000)
+ return None
+
+
+def validate_credentials(
+ host: str, api_key: str, schema_name: Optional[str] = None, team_id: Optional[int] = None
+) -> tuple[bool, str | None]:
+ """Probe a cheap list endpoint to confirm the API key is genuine.
+
+ At source-create (``schema_name is None``) a 403 is accepted: the key is valid but its
+ service account may lack the role for this particular probe. A scoped probe
+ (``schema_name`` set) treats 403 as a hard failure.
+ """
+ try:
+ normalized = normalize_host(host)
+ except Exception:
+ return False, "Invalid SigNoz host"
+
+ if not normalized or not re.match(r"^[A-Za-z0-9.\-]+$", normalized):
+ return False, "Invalid SigNoz host"
+
+ # The host is fully customer-controlled (cloud tenant or self-hosted URL), so block hosts
+ # that resolve to private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(normalized, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ url = f"https://{normalized}/api/v1/rules"
+ try:
+ # Don't follow redirects: the validated host could 3xx to an internal address,
+ # defeating the host check above (SSRF). capture=False keeps the probe out of HTTP
+ # sample capture — the response can echo tokens the name-based scrubber can't catch.
+ response = make_tracked_session(redact_values=(api_key,), capture=False).get(
+ url, headers=_get_headers(api_key), timeout=10, allow_redirects=False
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 401:
+ return False, "Invalid SigNoz API key. Generate a new key from a service account and try again."
+
+ if response.status_code == 403:
+ if schema_name is None:
+ # Valid key, missing role for this probe — let source creation through.
+ return True, None
+ return False, "Your SigNoz API key lacks the required permissions for this endpoint."
+
+ return False, f"SigNoz credential validation failed (status {response.status_code})."
+
+
+def _build_query_range_body(
+ config: SigNozEndpointConfig,
+ window_start_ms: int,
+ window_end_ms: int,
+ offset: int,
+) -> dict[str, Any]:
+ return {
+ "start": window_start_ms,
+ "end": window_end_ms,
+ "requestType": "raw",
+ "compositeQuery": {
+ "queries": [
+ {
+ "type": "builder_query",
+ "spec": {
+ "name": "A",
+ "signal": config.signal,
+ "order": [{"key": {"name": key}, "direction": "asc"} for key in config.order_keys],
+ "offset": offset,
+ "limit": config.page_size,
+ },
+ }
+ ]
+ },
+ }
+
+
+def _extract_raw_rows(response_json: Any) -> list[dict[str, Any]]:
+ """Pull the raw rows out of a v5 query_range response.
+
+ Shape: ``{"status": "success", "data": {"type": "raw", "data": {"results":
+ [{"queryName": "A", "rows": [{"timestamp": ..., "data": {...}}]}]}}}``.
+ """
+ data = response_json.get("data") if isinstance(response_json, dict) else None
+ inner = data.get("data") if isinstance(data, dict) else None
+ results = inner.get("results") if isinstance(inner, dict) else None
+ if not isinstance(results, list) or not results:
+ return []
+ rows = results[0].get("rows") if isinstance(results[0], dict) else None
+ if not isinstance(rows, list):
+ return []
+ return [row for row in rows if isinstance(row, dict)]
+
+
+def _raw_row_to_item(row: dict[str, Any]) -> dict[str, Any]:
+ """Flatten a raw row's ``data`` map to the root, with the envelope timestamp winning.
+
+ The envelope ``timestamp`` is a consistent RFC 3339 string, while the column value's
+ format varies by signal, so the envelope value is what we key incremental syncs and
+ partitioning on.
+ """
+ item = dict(row.get("data") or {})
+ if row.get("timestamp") is not None:
+ item["timestamp"] = row["timestamp"]
+ return item
+
+
+def _extract_config_items(response_json: Any, config: SigNozEndpointConfig) -> list[dict[str, Any]]:
+ """Pull records out of a management endpoint response (``{"status": ..., "data": ...}``)."""
+ node = response_json.get("data") if isinstance(response_json, dict) else None
+ for key in config.data_keys:
+ node = node.get(key) if isinstance(node, dict) else None
+ if not isinstance(node, list):
+ return []
+ items = [item for item in node if isinstance(item, dict)]
+ if config.allowed_fields is not None:
+ # Strict allowlist — drop everything else so credential-bearing fields never leak
+ # into the warehouse table (see SigNozEndpointConfig.allowed_fields).
+ allowed = set(config.allowed_fields)
+ items = [{k: v for k, v in item.items() if k in allowed} for item in items]
+ return items
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ raw = response.headers.get("Retry-After")
+ if raw and raw.strip().isdigit():
+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ """Honor a server-provided Retry-After when present, else exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, SigNozRetryableError) and exc.retry_after is not None:
+ return exc.retry_after
+ return wait_exponential_jitter(initial=1, max=30)(retry_state)
+
+
+def _initial_window(
+ config: SigNozEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> tuple[int, int]:
+ end_ms = int(datetime.now(UTC).timestamp() * 1000)
+ start_ms: int | None = None
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ start_ms = _to_epoch_ms(db_incremental_field_last_value)
+ if start_ms is None:
+ lookback_days = config.default_lookback_days or DEFAULT_LOOKBACK_DAYS
+ start_ms = int((datetime.now(UTC) - timedelta(days=lookback_days)).timestamp() * 1000)
+ return start_ms, end_ms
+
+
+def get_rows(
+ host: str,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SigNozResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SIGNOZ_ENDPOINTS[endpoint]
+
+ # Re-check at run time (not just at source-create) in case the host was edited or now
+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(normalize_host(host), team_id)
+ if not host_ok:
+ raise SigNozHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ base = _base_url(host)
+ # One tracked session reused across pages and retries; the API key is redacted from
+ # logged URLs. capture=False excludes responses from HTTP sample capture: imported log
+ # bodies, dashboard/notification config, etc. can carry secrets the name-based scrubber
+ # can't reliably strip, so they must never reach the shared sample bucket.
+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,), capture=False)
+
+ @retry(
+ retry=retry_if_exception_type((SigNozRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+ )
+ def fetch(url: str, json_body: dict[str, Any] | None = None) -> Any:
+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal
+ # address, bypassing the host validation done before the request (SSRF).
+ if json_body is not None:
+ response = session.post(url, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)
+ else:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None
+ raise SigNozRetryableError(
+ f"SigNoz API error (retryable): status={response.status_code}, url={url}",
+ retry_after=retry_after,
+ )
+
+ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather
+ # than silently parsing the redirect body as data.
+ if response.is_redirect or response.is_permanent_redirect:
+ raise SigNozHostNotAllowedError(
+ f"SigNoz API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+ if not response.ok:
+ logger.error(f"SigNoz API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ if config.kind == "config":
+ items = _extract_config_items(fetch(f"{base}{config.path}"), config)
+ if items:
+ yield items
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ window_start, window_end, offset = resume.window_start_ms, resume.window_end_ms, resume.offset
+ logger.debug(f"SigNoz: resuming {endpoint} at window_start={window_start}, offset={offset}")
+ else:
+ window_start, window_end = _initial_window(
+ config, should_use_incremental_field, db_incremental_field_last_value
+ )
+ offset = 0
+
+ url = f"{base}{QUERY_RANGE_PATH}"
+
+ while True:
+ body = _build_query_range_body(config, window_start, window_end, offset)
+ rows = _extract_raw_rows(fetch(url, json_body=body))
+ if not rows:
+ break
+
+ yield [_raw_row_to_item(row) for row in rows]
+
+ if len(rows) < config.page_size:
+ break
+
+ # Advance the window start to the last row's timestamp instead of paging with an
+ # ever-growing offset — query_range scans offset+limit rows server-side, so deep
+ # offsets get quadratically expensive. The window start is inclusive, so rows sharing
+ # the last row's millisecond are re-listed on the next request and skipped via the
+ # offset; anything re-yielded across a crash is deduped by primary-key merge.
+ last_ts = _to_epoch_ms(rows[-1].get("timestamp"))
+ if last_ts is None or last_ts < window_start:
+ # No usable timestamp to advance on — fall back to plain offset paging.
+ offset += len(rows)
+ elif last_ts == window_start:
+ # The entire window start millisecond spans multiple pages.
+ offset += len(rows)
+ else:
+ trailing = 0
+ for row in reversed(rows):
+ if _to_epoch_ms(row.get("timestamp")) == last_ts:
+ trailing += 1
+ else:
+ break
+ window_start = last_ts
+ offset = trailing
+
+ # Save state AFTER yielding the batch — a crash re-yields the last batch (merge
+ # dedupes on primary key) instead of skipping it.
+ resumable_source_manager.save_state(
+ SigNozResumeConfig(window_start_ms=window_start, window_end_ms=window_end, offset=offset)
+ )
+
+
+def signoz_source(
+ host: str,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SigNozResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = SIGNOZ_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ api_key=api_key,
+ endpoint=endpoint,
+ team_id=team_id,
+ 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=list(config.primary_keys),
+ sort_mode="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/signoz/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/source.py
index 4f879292c86f..c3fc370263e7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/source.py
@@ -1,19 +1,45 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SigNozSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ LIMITED_RETENTION_ENDPOINTS,
+ SIGNOZ_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz import (
+ HOST_NOT_ALLOWED_ERROR,
+ SigNozResumeConfig,
+ signoz_source,
+ validate_credentials as validate_signoz_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SigNozSource(SimpleSource[SigNozSourceConfig]):
+class SigNozSource(ResumableSource[SigNozSourceConfig, SigNozResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SIGNOZ
@@ -24,8 +50,102 @@ class SigNozSource(SimpleSource[SigNozSourceConfig]):
name=SchemaExternalDataSourceType.SIG_NOZ,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="SigNoz",
- iconPath="/static/services/signoz.png",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Connect your SigNoz workspace to sync logs, traces, alert rules, dashboards, and notification channels into the PostHog Data warehouse.
+
+Enter your SigNoz host (your SigNoz Cloud tenant, e.g. `example.signoz.io`, or your self-hosted URL) and an API key.
+
+Create the API key in SigNoz under **Settings > Service Accounts**: create a service account, then generate a key from its **Keys** tab. Only users with the Admin role can create service accounts; a key with the Viewer role is enough for syncing.""",
+ iconPath="/static/services/signoz.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/signoz",
keywords=["observability", "apm", "traces", "logs"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="SigNoz host",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="example.signoz.io",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="SigNoz API key",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid SigNoz API key. Generate a new key from a service account and reconnect.",
+ "403 Client Error": "Your SigNoz API key lacks the required permissions for this data. Check the service account's role and reconnect.",
+ HOST_NOT_ALLOWED_ERROR: "The configured SigNoz host is not allowed. Check the host and try again.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SigNozSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=SIGNOZ_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=SIGNOZ_ENDPOINTS[endpoint].supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=(
+ "Limited to your SigNoz retention window on initial sync"
+ if endpoint in LIMITED_RETENTION_ENDPOINTS
+ 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: SigNozSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_signoz_credentials(config.host, config.api_key, schema_name=schema_name, team_id=team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SigNozResumeConfig]:
+ return ResumableSourceManager[SigNozResumeConfig](inputs, SigNozResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SigNozSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SigNozResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return signoz_source(
+ host=config.host,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ 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/signoz/tests/test_signoz.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz.py
new file mode 100644
index 000000000000..9e231f148191
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz.py
@@ -0,0 +1,484 @@
+import dataclasses
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz import signoz as sgz
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.settings import SIGNOZ_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz import (
+ SigNozResumeConfig,
+ _build_query_range_body,
+ _extract_config_items,
+ _extract_raw_rows,
+ _raw_row_to_item,
+ _to_epoch_ms,
+ normalize_host,
+ signoz_source,
+ validate_credentials,
+)
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("example.signoz.io", "example.signoz.io"),
+ ("https://example.signoz.io", "example.signoz.io"),
+ ("https://example.signoz.io/", "example.signoz.io"),
+ ("http://example.signoz.io/api/v1", "example.signoz.io"),
+ (" example.signoz.io ", "example.signoz.io"),
+ ],
+ )
+ def test_normalize_host(self, raw: str, expected: str) -> None:
+ assert normalize_host(raw) == expected
+
+
+class TestToEpochMs:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (datetime(2026, 1, 1, tzinfo=UTC), 1767225600000),
+ (datetime(2026, 1, 1), 1767225600000), # naive -> UTC
+ (date(2026, 1, 1), 1767225600000),
+ (1767225600000, 1767225600000), # already ms
+ (1767225600, 1767225600000), # seconds -> ms
+ ("2026-01-01T00:00:00Z", 1767225600000),
+ # Go marshals time.Time with nanosecond precision; must still parse.
+ ("2026-01-01T00:00:00.123456789Z", 1767225600123),
+ ("not-a-timestamp", None),
+ (None, None),
+ ],
+ )
+ def test_to_epoch_ms(self, value: Any, expected: int | None) -> None:
+ assert _to_epoch_ms(value) == expected
+
+
+class TestBuildQueryRangeBody:
+ def test_logs_body_shape(self) -> None:
+ body = _build_query_range_body(SIGNOZ_ENDPOINTS["logs"], 1000, 2000, 50)
+
+ assert body["start"] == 1000
+ assert body["end"] == 2000
+ assert body["requestType"] == "raw"
+ spec = body["compositeQuery"]["queries"][0]["spec"]
+ assert spec["signal"] == "logs"
+ assert spec["offset"] == 50
+ assert spec["limit"] == SIGNOZ_ENDPOINTS["logs"].page_size
+ # Ascending timestamp+id ordering keeps offset paging deterministic and the
+ # pipeline's incremental watermark correct.
+ assert spec["order"] == [
+ {"key": {"name": "timestamp"}, "direction": "asc"},
+ {"key": {"name": "id"}, "direction": "asc"},
+ ]
+
+ def test_traces_order_uses_span_id_tiebreaker(self) -> None:
+ body = _build_query_range_body(SIGNOZ_ENDPOINTS["traces"], 0, 1, 0)
+ spec = body["compositeQuery"]["queries"][0]["spec"]
+ assert spec["signal"] == "traces"
+ assert [o["key"]["name"] for o in spec["order"]] == ["timestamp", "span_id"]
+
+
+class TestExtractRawRows:
+ def test_extracts_rows_from_v5_envelope(self) -> None:
+ response = {
+ "status": "success",
+ "data": {
+ "type": "raw",
+ "data": {
+ "results": [
+ {
+ "queryName": "A",
+ "nextCursor": "",
+ "rows": [{"timestamp": "2026-01-01T00:00:00Z", "data": {"id": "1"}}],
+ }
+ ]
+ },
+ },
+ }
+ assert _extract_raw_rows(response) == [{"timestamp": "2026-01-01T00:00:00Z", "data": {"id": "1"}}]
+
+ @pytest.mark.parametrize(
+ "response",
+ [
+ {},
+ {"data": {}},
+ {"data": {"data": {}}},
+ {"data": {"data": {"results": []}}},
+ {"data": {"data": {"results": [{"queryName": "A", "rows": None}]}}},
+ "unexpected",
+ None,
+ ],
+ )
+ def test_malformed_envelope_returns_empty(self, response: Any) -> None:
+ assert _extract_raw_rows(response) == []
+
+
+class TestRawRowToItem:
+ def test_flattens_data_and_envelope_timestamp_wins(self) -> None:
+ row = {
+ "timestamp": "2026-01-01T00:00:00Z",
+ "data": {"id": "1", "body": "hello", "timestamp": 1767225600000000000},
+ }
+ item = _raw_row_to_item(row)
+ assert item == {"id": "1", "body": "hello", "timestamp": "2026-01-01T00:00:00Z"}
+
+ def test_missing_data_map(self) -> None:
+ assert _raw_row_to_item({"timestamp": "2026-01-01T00:00:00Z"}) == {"timestamp": "2026-01-01T00:00:00Z"}
+
+
+class TestExtractConfigItems:
+ def test_rules_nested_under_data_rules(self) -> None:
+ response = {"status": "success", "data": {"rules": [{"id": "r1"}, {"id": "r2"}]}}
+ assert _extract_config_items(response, SIGNOZ_ENDPOINTS["alert_rules"]) == [{"id": "r1"}, {"id": "r2"}]
+
+ def test_dashboards_list_directly_under_data(self) -> None:
+ response = {"status": "success", "data": [{"id": "d1"}]}
+ assert _extract_config_items(response, SIGNOZ_ENDPOINTS["dashboards"]) == [{"id": "d1"}]
+
+ def test_notification_channels_allowlist_strips_credential_data(self) -> None:
+ # The `data` field carries receiver secrets (Slack webhook URLs, PagerDuty keys); the
+ # allowlist must drop it (and anything else off-list) before it reaches the warehouse.
+ response = {
+ "status": "success",
+ "data": [
+ {
+ "id": "c1",
+ "name": "oncall",
+ "type": "slack",
+ "data": {"url": "https://hooks.slack.com/services/SECRET"},
+ "createdAt": "2026-01-01T00:00:00Z",
+ "updatedAt": "2026-01-02T00:00:00Z",
+ "internal_field": "drop me",
+ }
+ ],
+ }
+ assert _extract_config_items(response, SIGNOZ_ENDPOINTS["notification_channels"]) == [
+ {
+ "id": "c1",
+ "name": "oncall",
+ "type": "slack",
+ "createdAt": "2026-01-01T00:00:00Z",
+ "updatedAt": "2026-01-02T00:00:00Z",
+ }
+ ]
+
+ @pytest.mark.parametrize(
+ "response",
+ [{}, {"data": None}, {"data": {"rules": "nope"}}, None],
+ )
+ def test_malformed_response_returns_empty(self, response: Any) -> None:
+ assert _extract_config_items(response, SIGNOZ_ENDPOINTS["alert_rules"]) == []
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "schema_name", "expected_valid"),
+ [
+ (200, None, True),
+ (401, None, False),
+ # 403 at source-create is a valid key without the probe's role -> accept.
+ (403, None, True),
+ # 403 on a scoped probe is a hard failure.
+ (403, "logs", False),
+ (500, None, False),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz.make_tracked_session")
+ def test_status_mapping(
+ self, mock_session: mock.MagicMock, status_code: int, schema_name: str | None, expected_valid: bool
+ ) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.is_redirect = False
+ response.is_permanent_redirect = False
+ mock_session.return_value.get.return_value = response
+
+ is_valid, error = validate_credentials("example.signoz.io", "key", schema_name=schema_name)
+
+ 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.signoz.signoz.make_tracked_session")
+ def test_probe_disables_sample_capture(self, mock_session: mock.MagicMock) -> None:
+ # The probe response can echo the token, which the name-based scrubber can't strip, so
+ # the session must be created with capture=False to keep it out of HTTP sample capture.
+ response = mock.MagicMock()
+ response.status_code = 200
+ response.is_redirect = False
+ response.is_permanent_redirect = False
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("example.signoz.io", "key")
+
+ assert mock_session.call_args.kwargs["capture"] is False
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz.make_tracked_session")
+ def test_redirect_is_rejected(self, mock_session: mock.MagicMock) -> None:
+ response = mock.MagicMock()
+ response.status_code = 302
+ response.is_redirect = True
+ mock_session.return_value.get.return_value = response
+
+ is_valid, error = validate_credentials("example.signoz.io", "key")
+ assert is_valid is False
+ assert error is not None
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz.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("example.signoz.io", "key")
+ assert is_valid is False
+ assert error is not None
+
+ @pytest.mark.parametrize("host", ["", "not a host!", "bad_host/"])
+ def test_invalid_host_is_rejected_without_a_request(self, host: str) -> None:
+ is_valid, error = validate_credentials(host, "key")
+ assert is_valid is False
+ assert error == "Invalid SigNoz host"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz._is_host_safe")
+ def test_unsafe_host_is_blocked(self, mock_host_safe: mock.MagicMock) -> None:
+ mock_host_safe.return_value = (False, "Hosts with internal IP addresses are not allowed")
+ is_valid, error = validate_credentials("10.0.0.1", "key", team_id=42)
+ assert is_valid is False
+ assert error == "Hosts with internal IP addresses are not allowed"
+
+
+class TestSigNozSourceResponse:
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_pks", "expected_partition_key"),
+ [
+ ("logs", ["id"], "timestamp"),
+ ("traces", ["trace_id", "span_id"], "timestamp"),
+ ("alert_rules", ["id"], "createAt"),
+ ("dashboards", ["id"], "createdAt"),
+ ("notification_channels", ["id"], "createdAt"),
+ ],
+ )
+ def test_source_response_shape(self, endpoint: str, expected_pks: list[str], expected_partition_key: str) -> None:
+ response = signoz_source(
+ host="example.signoz.io",
+ api_key="key",
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pks
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [expected_partition_key]
+
+
+def _page(rows: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"status": "success", "data": {"type": "raw", "data": {"results": [{"queryName": "A", "rows": rows}]}}}
+
+
+def _with_page_size(endpoint: str, page_size: int) -> Any:
+ return dataclasses.replace(SIGNOZ_ENDPOINTS[endpoint], page_size=page_size)
+
+
+def _log_row(ts: str, row_id: str) -> dict[str, Any]:
+ return {"timestamp": ts, "data": {"id": row_id, "body": f"line {row_id}"}}
+
+
+class TestGetRows:
+ def _run(
+ self,
+ endpoint: str,
+ responses: list[Any],
+ can_resume: bool = False,
+ resume_state: SigNozResumeConfig | None = None,
+ page_size: int = 2,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> tuple[list[list[dict[str, Any]]], list[SigNozResumeConfig], list[dict[str, Any]]]:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = resume_state
+ saved: list[SigNozResumeConfig] = []
+ manager.save_state.side_effect = lambda state: saved.append(state)
+
+ requests_made: list[dict[str, Any]] = []
+
+ def fake_post(url: str, json: Any = None, timeout: Any = None, allow_redirects: Any = None) -> Any:
+ requests_made.append({"url": url, "body": json})
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.ok = True
+ resp.is_redirect = False
+ resp.is_permanent_redirect = False
+ resp.json.return_value = responses[len(requests_made) - 1]
+ return resp
+
+ def fake_get(url: str, timeout: Any = None, allow_redirects: Any = None) -> Any:
+ requests_made.append({"url": url, "body": None})
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.ok = True
+ resp.is_redirect = False
+ resp.is_permanent_redirect = False
+ resp.json.return_value = responses[len(requests_made) - 1]
+ return resp
+
+ with (
+ mock.patch.object(sgz, "make_tracked_session") as mock_session,
+ mock.patch.dict(sgz.SIGNOZ_ENDPOINTS, {endpoint: _with_page_size(endpoint, page_size)}),
+ ):
+ mock_session.return_value.post.side_effect = fake_post
+ mock_session.return_value.get.side_effect = fake_get
+ batches = list(
+ sgz.get_rows(
+ host="example.signoz.io",
+ api_key="key",
+ endpoint=endpoint,
+ team_id=1,
+ 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,
+ )
+ )
+ return batches, saved, requests_made
+
+ def test_config_endpoint_yields_items_from_single_get(self) -> None:
+ responses = [{"status": "success", "data": {"rules": [{"id": "r1"}]}}]
+ batches, saved, requests_made = self._run("alert_rules", responses)
+
+ assert batches == [[{"id": "r1"}]]
+ assert saved == []
+ assert requests_made[0]["url"] == "https://example.signoz.io/api/v1/rules"
+ assert requests_made[0]["body"] is None
+
+ def test_notification_channels_endpoint_drops_credential_data(self) -> None:
+ # End-to-end guard on the sync path: the receiver `data` payload never reaches the
+ # yielded rows, so imported channel secrets can't land in the warehouse table.
+ responses = [
+ {
+ "status": "success",
+ "data": [{"id": "c1", "name": "oncall", "type": "slack", "data": {"url": "https://secret"}}],
+ }
+ ]
+ batches, _saved, _requests = self._run("notification_channels", responses)
+
+ assert batches == [[{"id": "c1", "name": "oncall", "type": "slack"}]]
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz.make_tracked_session")
+ def test_sync_session_disables_sample_capture(self, mock_session: mock.MagicMock) -> None:
+ # Imported telemetry/config can carry secrets the name-based scrubber can't strip, so
+ # the sync session must be created with capture=False.
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.ok = True
+ resp.is_redirect = False
+ resp.is_permanent_redirect = False
+ resp.json.return_value = _page([])
+ mock_session.return_value.post.return_value = resp
+
+ list(
+ sgz.get_rows(
+ host="example.signoz.io",
+ api_key="key",
+ endpoint="logs",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(can_resume=lambda: False),
+ )
+ )
+
+ assert mock_session.call_args.kwargs["capture"] is False
+
+ def test_short_page_terminates_without_saving_state(self) -> None:
+ responses = [_page([_log_row("2026-01-01T00:00:00Z", "1")])]
+ batches, saved, requests_made = self._run("logs", responses, page_size=2)
+
+ assert len(batches) == 1
+ assert batches[0][0]["id"] == "1"
+ assert saved == []
+ assert len(requests_made) == 1
+ assert requests_made[0]["url"] == "https://example.signoz.io/api/v5/query_range"
+
+ def test_full_page_advances_window_start_and_saves_state_after_yield(self) -> None:
+ responses = [
+ _page([_log_row("2026-01-01T00:00:00Z", "1"), _log_row("2026-01-01T00:00:01Z", "2")]),
+ _page([_log_row("2026-01-01T00:00:02Z", "3")]),
+ ]
+ batches, saved, requests_made = self._run(
+ "logs",
+ responses,
+ can_resume=True,
+ resume_state=SigNozResumeConfig(window_start_ms=1767225600000, window_end_ms=1767312000000, offset=0),
+ page_size=2,
+ )
+
+ assert [len(b) for b in batches] == [2, 1]
+ # Window start advanced to the last row's timestamp; one trailing row at that ms is
+ # skipped via the offset instead of an ever-growing window offset.
+ assert len(saved) == 1
+ assert saved[0].window_start_ms == 1767225601000
+ assert saved[0].offset == 1
+ # The second request starts at the advanced window with the trailing-row offset.
+ second_spec = requests_made[1]["body"]["compositeQuery"]["queries"][0]["spec"]
+ assert requests_made[1]["body"]["start"] == 1767225601000
+ assert second_spec["offset"] == 1
+
+ def test_full_page_within_one_millisecond_grows_offset(self) -> None:
+ same_ts = "2026-01-01T00:00:00Z"
+ responses = [
+ _page([_log_row(same_ts, "1"), _log_row(same_ts, "2")]),
+ _page([_log_row(same_ts, "3"), _log_row(same_ts, "4")]),
+ _page([]),
+ ]
+ _batches, saved, requests_made = self._run(
+ "logs",
+ responses,
+ can_resume=True,
+ resume_state=SigNozResumeConfig(window_start_ms=1767225600000, window_end_ms=1767225700000, offset=0),
+ page_size=2,
+ )
+
+ # The whole window-start millisecond spans multiple pages: offset accumulates so no
+ # rows are skipped and none are refetched.
+ assert [s.offset for s in saved] == [2, 4]
+ assert all(s.window_start_ms == 1767225600000 for s in saved)
+ assert [r["body"]["compositeQuery"]["queries"][0]["spec"]["offset"] for r in requests_made] == [0, 2, 4]
+
+ def test_resumes_from_saved_window(self) -> None:
+ responses = [_page([])]
+ _batches, _saved, requests_made = self._run(
+ "logs",
+ responses,
+ can_resume=True,
+ resume_state=SigNozResumeConfig(window_start_ms=123, window_end_ms=456, offset=7),
+ )
+
+ body = requests_made[0]["body"]
+ assert body["start"] == 123
+ assert body["end"] == 456
+ assert body["compositeQuery"]["queries"][0]["spec"]["offset"] == 7
+
+ def test_incremental_watermark_sets_window_start(self) -> None:
+ responses = [_page([])]
+ _batches, _saved, requests_made = self._run(
+ "logs",
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ assert requests_made[0]["body"]["start"] == 1767225600000
+
+ def test_first_sync_uses_lookback_window(self) -> None:
+ responses = [_page([])]
+ _batches, _saved, requests_made = self._run("logs", responses)
+
+ body = requests_made[0]["body"]
+ lookback_days = (body["end"] - body["start"]) / 1000 / 86400
+ assert round(lookback_days) == SIGNOZ_ENDPOINTS["logs"].default_lookback_days
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz_source.py
new file mode 100644
index 000000000000..e9f51ad62341
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz_source.py
@@ -0,0 +1,178 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SigNozSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.settings import (
+ ENDPOINTS,
+ LIMITED_RETENTION_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz import SigNozResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.source import SigNozSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"logs", "traces"}
+
+
+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 TestSigNozSource:
+ def setup_method(self) -> None:
+ self.source = SigNozSource()
+ self.team_id = 123
+ self.config = SigNozSourceConfig(host="example.signoz.io", api_key="signoz-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SIGNOZ
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "SigNoz"
+ assert config.label == "SigNoz"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/signoz.svg"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/signoz"
+
+ host_field, api_key_field = config.fields
+
+ assert isinstance(host_field, SourceFieldInputConfig)
+ assert host_field.name == "host"
+ assert host_field.required is True
+ assert host_field.secret is False
+
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ @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_incremental_flags(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ for name in INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert schemas[name].incremental_fields == [
+ {
+ "label": "timestamp",
+ "type": "datetime",
+ "field": "timestamp",
+ "field_type": "datetime",
+ }
+ ]
+
+ for name in set(ENDPOINTS) - INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_retention_description(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ for name in LIMITED_RETENTION_ENDPOINTS:
+ assert schemas[name].description is not None
+ assert schemas["dashboards"].description is None
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["traces"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "traces"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ ((True, None), True, None),
+ ((False, "Invalid SigNoz API key."), False, "Invalid SigNoz API key."),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.signoz.source.validate_signoz_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name="logs")
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(
+ "example.signoz.io", "signoz-key", schema_name="logs", team_id=self.team_id
+ )
+
+ 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 SigNozResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.signoz.source.signoz_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="alert_rules", team_id=99, job_id="job-xyz")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ host="example.signoz.io",
+ api_key="signoz-key",
+ endpoint="alert_rules",
+ team_id=99,
+ 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.signoz.source.signoz_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="timestamp",
+ )
+ 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"