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 coralogix import source (#71346)

Tom Owerscaf7cbf0f42a
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 c0e9daa25aab..fffbf1a0a582 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -152,6 +152,7 @@ the row lists both.
| convertkit | HTTP | requests | ✅ |
| convex | HTTP | requests | ✅ |
| copper | HTTP | requests | ✅ |
+| coralogix | HTTP | requests | ✅ |
| coupa | HTTP | requests | ✅ |
| coveralls | HTTP | requests | ✅ |
| crates_io | HTTP | requests | ✅ |
@@ -650,7 +651,6 @@ doesn't conflict with concurrent PRs.
- codecov
- constant_contact
- copper
-- coralogix
- cosmosdb
- couchbase
- criteo
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/canonical_descriptions.py
new file mode 100644
index 000000000000..d6785e65a204
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/canonical_descriptions.py
@@ -0,0 +1,29 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "logs": {
+ "description": "Raw log records returned by the DataPrime query API (`source logs`), one row per log entry.",
+ "docs_url": "https://coralogix.com/docs/dataprime/API/direct-archive-query-http/",
+ "columns": {
+ "logid": "Unique identifier Coralogix assigns to the log entry.",
+ "timestamp": "Event time of the log entry, in UTC.",
+ "severity": "Log severity level (e.g. Debug, Info, Warning, Error, Critical).",
+ "priorityclass": "Priority class assigned to the log by Coralogix's TCO pipeline (high, medium, low).",
+ "applicationname": "Application the log was ingested under.",
+ "subsystemname": "Subsystem the log was ingested under.",
+ "user_data": "The raw log body as a JSON-encoded string.",
+ },
+ },
+ "spans": {
+ "description": "Raw trace spans returned by the DataPrime query API (`source spans`), one row per span.",
+ "docs_url": "https://coralogix.com/docs/dataprime/API/direct-archive-query-http/",
+ "columns": {
+ "timestamp": "Start time of the span, in UTC.",
+ "applicationname": "Application the span was ingested under.",
+ "subsystemname": "Subsystem the span was ingested under.",
+ "user_data": "The raw span (attributes, IDs, duration) as a JSON-encoded string.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/coralogix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/coralogix.py
new file mode 100644
index 000000000000..afb41d09b764
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/coralogix.py
@@ -0,0 +1,358 @@
+import json
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, 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.coralogix.settings import (
+ CORALOGIX_DOMAINS,
+ CORALOGIX_ENDPOINTS,
+ DEFAULT_LOOKBACK_DAYS,
+ QUERY_LIMIT,
+)
+
+# The team's Coralogix domain must match the cluster its account lives on — a query against the
+# wrong cluster fails outright, so the domain is a fixed choice on the source form.
+TIERS = {
+ "frequent_search": "TIER_FREQUENT_SEARCH",
+ "archive": "TIER_ARCHIVE",
+}
+
+# Adaptive time-window slicing: the query API has no cursor pagination, only a per-query row cap,
+# so we advance a [start, end) window through time. A window that hits the cap is bisected and
+# retried; sparse windows grow back up to the max so quiet ranges don't cost one query per hour.
+INITIAL_WINDOW = timedelta(hours=1)
+MIN_WINDOW = timedelta(seconds=10)
+MAX_WINDOW = timedelta(hours=24)
+
+_MIN_DATETIME = datetime.min.replace(tzinfo=UTC)
+
+
+class CoralogixRetryableError(Exception):
+ """Raised for Coralogix responses that are safe to retry (429 / 5xx / mid-stream breaks)."""
+
+
+class CoralogixResumeConfig:
+ # ISO timestamp of the last fully-yielded window's end. Windows are half-open [start, end),
+ # so resuming inclusively from this boundary neither skips nor re-yields rows.
+ synced_until: str | None = None
+
+
+def _query_url(domain: str) -> str:
+ if domain not in CORALOGIX_DOMAINS:
+ raise ValueError(f"Unknown Coralogix domain: {domain}")
+ return f"https://api.{domain}/api/v1/dataprime/query"
+
+
+def _make_session(api_key: str) -> requests.Session:
+ """Session for all Coralogix traffic. The bearer token is set once on the session so its
+ redaction policy applies everywhere, and redirects are pinned off so a credentialed request
+ can't be replayed against another host. Response capture is disabled because log/span bodies
+ are free-form user telemetry — they can carry credentials or PII the name-based sample
+ scrubbers can't reliably recognise."""
+ return make_tracked_session(
+ headers={
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ },
+ redact_values=(api_key,),
+ allow_redirects=False,
+ capture=False,
+ )
+
+
+def _format_datetime(dt: datetime) -> str:
+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z"
+
+
+def _parse_timestamp(value: Any) -> datetime | None:
+ """Best-effort parse of a Coralogix timestamp into an aware UTC datetime.
+
+ The query API's metadata timestamps are ISO 8601 strings, potentially with nanosecond
+ precision (trimmed to microseconds — Python datetimes can't hold more). Numeric epochs are
+ handled defensively by magnitude in case a cluster returns them instead.
+ """
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ if isinstance(value, int | float):
+ return _parse_epoch(float(value))
+ if isinstance(value, str):
+ stripped = value.strip()
+ if not stripped:
+ return None
+ try:
+ return _parse_epoch(float(stripped))
+ except ValueError:
+ pass
+ iso = stripped.removesuffix("Z") + "+00:00" if stripped.endswith("Z") else stripped
+ if "." in iso:
+ head, _, tail = iso.partition(".")
+ frac = ""
+ offset = ""
+ for index, char in enumerate(tail):
+ if char.isdigit():
+ frac += char
+ else:
+ offset = tail[index:]
+ break
+ iso = f"{head}.{frac[:6]}{offset}"
+ try:
+ parsed = datetime.fromisoformat(iso)
+ except ValueError:
+ return None
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+ return None
+
+
+def _parse_epoch(value: float) -> datetime:
+ # Disambiguate epoch precision by magnitude: seconds (<1e11), millis, micros, nanos.
+ for threshold, divisor in ((1e11, 1), (1e14, 1e3), (1e17, 1e6)):
+ if abs(value) < threshold:
+ return datetime.fromtimestamp(value / divisor, tz=UTC)
+ return datetime.fromtimestamp(value / 1e9, tz=UTC)
+
+
+def _normalize_row(result: dict[str, Any]) -> dict[str, Any]:
+ """Flatten a query result row ({metadata: [{key, value}], labels: [...], userData: "..."}).
+
+ Metadata keys (timestamp, severity, logid, ...) and label keys (applicationname,
+ subsystemname, ...) become top-level columns; metadata wins on collision. The log/span body
+ stays as the raw JSON string in `user_data` — flattening arbitrary user telemetry would
+ produce an unstable column set.
+ """
+ row: dict[str, Any] = {}
+ for pair in result.get("metadata") or []:
+ key = pair.get("key")
+ if key:
+ row[key] = pair.get("value")
+ for pair in result.get("labels") or []:
+ key = pair.get("key")
+ if key and key not in row:
+ row[key] = pair.get("value")
+ row["user_data"] = result.get("userData")
+ row["timestamp"] = _parse_timestamp(row.get("timestamp"))
+ return row
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ CoralogixRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ # Mid-stream connection break while consuming the NDJSON body.
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _run_query(
+ session: requests.Session,
+ url: str,
+ dataprime_source: str,
+ tier: str,
+ start: datetime,
+ end: datetime,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ """Run one DataPrime query and parse its NDJSON stream into normalized rows.
+
+ The stream interleaves `{"queryId": ...}`, `{"result": {"results": [...]}}`,
+ `{"warning": ...}` and `{"statistics": ...}` lines; only result lines carry rows. The whole
+ request/parse runs inside the retry so a mid-stream break re-issues the query.
+ """
+ body = {
+ "query": f"source {dataprime_source}",
+ "metadata": {
+ "tier": tier,
+ "syntax": "QUERY_SYNTAX_DATAPRIME",
+ "startDate": _format_datetime(start),
+ "endDate": _format_datetime(end),
+ "limit": QUERY_LIMIT,
+ },
+ }
+
+ response = session.post(url, json=body, stream=True, timeout=(10, 180))
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CoralogixRetryableError(f"Coralogix API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Coralogix API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ rows: list[dict[str, Any]] = []
+ for line in response.iter_lines():
+ if not line:
+ continue
+ message = json.loads(line)
+ result = message.get("result")
+ if result is not None:
+ rows.extend(_normalize_row(item) for item in result.get("results") or [])
+ # The server honors the requested limit; stop reading defensively once we have it so
+ # a misbehaving response can't grow memory unboundedly. Reaching the limit already
+ # means the window gets bisected (or warned about) by the caller.
+ if len(rows) >= QUERY_LIMIT:
+ break
+ elif "error" in message:
+ raise Exception(f"Coralogix query error: {message['error']}")
+ elif "warning" in message:
+ logger.warning(f"Coralogix query warning: {message['warning']}")
+
+ return rows
+
+
+def _filter_and_sort(
+ rows: list[dict[str, Any]], start: datetime, end: datetime, exclusive_start: bool
+) -> list[dict[str, Any]]:
+ """Enforce half-open [start, end) semantics client-side and sort ascending by timestamp.
+
+ The API doesn't document whether startDate/endDate are inclusive, so the client filter is
+ what guarantees adjacent windows never double-count a boundary row. `exclusive_start` drops
+ rows at exactly the incremental watermark — they were yielded by the run that set it. Rows
+ whose timestamp fails to parse are kept (they arrived inside this window server-side) and
+ sort first so they never advance the watermark past parseable rows.
+ """
+ kept: list[dict[str, Any]] = []
+ for row in rows:
+ ts = row.get("timestamp")
+ if isinstance(ts, datetime):
+ if ts < start or ts >= end:
+ continue
+ if exclusive_start and ts == start:
+ continue
+ kept.append(row)
+ kept.sort(key=lambda row: row["timestamp"] if isinstance(row.get("timestamp"), datetime) else _MIN_DATETIME)
+ return kept
+
+
+def get_rows(
+ api_key: str,
+ domain: str,
+ tier: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoralogixResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = CORALOGIX_ENDPOINTS[endpoint]
+ session = _make_session(api_key)
+ url = _query_url(domain)
+ tier_value = TIERS.get(tier, TIERS["frequent_search"])
+
+ end = datetime.now(UTC)
+ last_value = _parse_timestamp(db_incremental_field_last_value) if should_use_incremental_field else None
+ exclusive_start = last_value is not None
+ start = last_value if last_value is not None else end - timedelta(days=DEFAULT_LOOKBACK_DAYS)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.synced_until:
+ resumed = _parse_timestamp(resume.synced_until)
+ if resumed is not None and resumed > start:
+ # `synced_until` is a half-open window boundary, so the inclusive restart is exact.
+ start = resumed
+ exclusive_start = False
+ logger.debug(f"Coralogix: resuming {endpoint} from {resume.synced_until}")
+
+ window = INITIAL_WINDOW
+ cursor = start
+ while cursor < end:
+ window_end = min(cursor + window, end)
+ rows = _run_query(session, url, config.dataprime_source, tier_value, cursor, window_end, logger)
+
+ if len(rows) >= QUERY_LIMIT and window_end - cursor > MIN_WINDOW:
+ # Cap hit — the API drops an arbitrary remainder, so bisect and re-query rather than
+ # silently skipping rows.
+ window = max((window_end - cursor) / 2, MIN_WINDOW)
+ continue
+ if len(rows) >= QUERY_LIMIT:
+ logger.warning(
+ f"Coralogix: {endpoint} window {_format_datetime(cursor)}..{_format_datetime(window_end)} still "
+ f"hits the {QUERY_LIMIT}-row cap at the minimum window size; rows beyond the cap are skipped"
+ )
+
+ batch = _filter_and_sort(rows, cursor, window_end, exclusive_start)
+ exclusive_start = False
+ if batch:
+ yield batch
+
+ # Save AFTER yielding so a crash re-runs the last window rather than skipping it.
+ resumable_source_manager.save_state(CoralogixResumeConfig(synced_until=_format_datetime(window_end)))
+ cursor = window_end
+
+ if len(rows) < QUERY_LIMIT // 4:
+ window = min(window * 2, MAX_WINDOW)
+
+ # A retry of a fully-walked run must start fresh from the new watermark, not resume mid-stream.
+ resumable_source_manager.clear_state()
+
+
+def coralogix_source(
+ api_key: str,
+ domain: str,
+ tier: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoralogixResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = CORALOGIX_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ domain=domain,
+ tier=tier,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Rows are sorted ascending within each window and windows advance chronologically, so the
+ # stream is globally ascending and per-batch watermark checkpointing is safe.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="day",
+ partition_keys=[endpoint_config.partition_key],
+ )
+
+
+def validate_credentials(api_key: str, domain: str) -> bool:
+ """Cheapest probe that confirms the key is genuine and on the right cluster: a 1-row
+ frequent-search query over the last few minutes. A wrong-cluster or invalid key returns 403."""
+ end = datetime.now(UTC)
+ body = {
+ "query": "source logs | limit 1",
+ "metadata": {
+ "tier": TIERS["frequent_search"],
+ "syntax": "QUERY_SYNTAX_DATAPRIME",
+ "startDate": _format_datetime(end - timedelta(minutes=15)),
+ "endDate": _format_datetime(end),
+ "limit": 1,
+ },
+ }
+ try:
+ response = _make_session(api_key).post(_query_url(domain), json=body, timeout=30)
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/settings.py
new file mode 100644
index 000000000000..dc0dfd87108a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/settings.py
@@ -0,0 +1,71 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# The regional clusters the query API lives on (the `domain` select options in source.py).
+# Enforced at request time: the generated config's Literal type is NOT validated when parsing
+# job inputs, so without this allowlist a crafted `domain` would redirect the credentialed
+# request to an arbitrary host (SSRF / API-key exfiltration).
+CORALOGIX_DOMAINS = frozenset(
+ {
+ "coralogix.us",
+ "cx498.coralogix.com",
+ "coralogix.com",
+ "eu2.coralogix.com",
+ "coralogix.in",
+ "coralogixsg.com",
+ "ap3.coralogix.com",
+ }
+)
+
+# Rows requested per DataPrime query. Both tiers accept more (12,000 frequent search / 50,000
+# archive), but a whole window is held in memory for sorting before it is yielded, so the limit
+# doubles as the memory bound. Windows that hit this cap are bisected (see coralogix.py).
+QUERY_LIMIT = 10_000
+
+# Initial sync and full refresh pull this many days of history. Coralogix holds arbitrarily
+# large volumes of telemetry, so an unbounded backfill isn't viable through the query API;
+# append syncs advance from the newest synced timestamp after the first run.
+DEFAULT_LOOKBACK_DAYS = 7
+
+_TIMESTAMP_INCREMENTAL_FIELD: list[IncrementalField] = [
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class CoralogixEndpointConfig:
+ name: str
+ # The DataPrime data source this table streams (`source logs` / `source spans`).
+ dataprime_source: str
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: _TIMESTAMP_INCREMENTAL_FIELD)
+ # Rows are immutable telemetry keyed on their event time, which never changes — a stable
+ # partition key by construction.
+ partition_key: str = "timestamp"
+ primary_keys: list[str] | None = None
+
+
+CORALOGIX_ENDPOINTS: dict[str, CoralogixEndpointConfig] = {
+ "logs": CoralogixEndpointConfig(
+ name="logs",
+ dataprime_source="logs",
+ # Every log row carries a `logid` metadata entry (verified against the query API docs);
+ # spans expose no documented equivalent, so only logs declare a primary key.
+ primary_keys=["logid"],
+ ),
+ "spans": CoralogixEndpointConfig(
+ name="spans",
+ dataprime_source="spans",
+ ),
+}
+
+ENDPOINTS = tuple(CORALOGIX_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CORALOGIX_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/source.py
index b454d22f8e36..065867ef0dfd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/source.py
@@ -1,19 +1,46 @@
-from typing import cast
+from typing import Optional, cast
from 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 SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix import (
+ CoralogixResumeConfig,
+ coralogix_source,
+ validate_credentials as validate_coralogix_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.settings import (
+ CORALOGIX_ENDPOINTS,
+ DEFAULT_LOOKBACK_DAYS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CoralogixSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CoralogixSource(SimpleSource[CoralogixSourceConfig]):
+class CoralogixSource(ResumableSource[CoralogixSourceConfig, CoralogixResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CORALOGIX
@@ -24,7 +51,145 @@ class CoralogixSource(SimpleSource[CoralogixSourceConfig]):
name=SchemaExternalDataSourceType.CORALOGIX,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Coralogix",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["logs", "observability", "traces", "dataprime"],
+ caption="""Enter a Coralogix API key to pull your logs and spans into the PostHog Data warehouse via the DataPrime query API.
+
+Create a personal or team API key in Coralogix under **Settings** → **API keys** and grant it the **DataQuerying** permission preset.
+
+Pick the domain that matches your Coralogix account (shown in your Coralogix URL) — querying the wrong cluster fails with a permission error.
+
+The **Frequent search** tier queries your indexed retention and works out of the box. Choose **Archive** to query your S3 archive instead (requires archiving to be enabled on your Coralogix account).
+""",
iconPath="/static/services/coralogix.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/coralogix",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="domain",
+ label="Coralogix domain",
+ required=True,
+ defaultValue="coralogix.us",
+ options=[
+ SourceFieldSelectConfigOption(label="US1 (coralogix.us)", value="coralogix.us"),
+ SourceFieldSelectConfigOption(
+ label="US2 (cx498.coralogix.com)", value="cx498.coralogix.com"
+ ),
+ SourceFieldSelectConfigOption(label="EU1 (coralogix.com)", value="coralogix.com"),
+ SourceFieldSelectConfigOption(label="EU2 (eu2.coralogix.com)", value="eu2.coralogix.com"),
+ SourceFieldSelectConfigOption(label="AP1 (coralogix.in)", value="coralogix.in"),
+ SourceFieldSelectConfigOption(label="AP2 (coralogixsg.com)", value="coralogixsg.com"),
+ SourceFieldSelectConfigOption(label="AP3 (ap3.coralogix.com)", value="ap3.coralogix.com"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="tier",
+ label="Query tier",
+ required=True,
+ defaultValue="frequent_search",
+ options=[
+ SourceFieldSelectConfigOption(label="Frequent search", value="frequent_search"),
+ SourceFieldSelectConfigOption(label="Archive", value="archive"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `domain` selects the cluster the stored API key is sent to; retargeting it must
+ # re-require the key.
+ return ["domain"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid/revoked key, a key without the DataQuerying preset, or a key used against
+ # the wrong regional cluster all surface as a requests HTTPError when `_run_query`
+ # calls `raise_for_status()`. Retrying can never fix a credential problem. All of this
+ # source's URLs start with `https://api.<coralogix domain>`, so matching on the stable
+ # status text + URL prefix is precise within this source.
+ "401 Client Error: Unauthorized for url: https://api.": "Your Coralogix API key is invalid or has been revoked. Create a new key with the DataQuerying permission preset, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.": "Coralogix rejected the API key. Check that the key has the DataQuerying permission preset and that the selected domain matches your Coralogix account, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CoralogixSourceConfig,
+ 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 = CORALOGIX_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ # Logs and spans are immutable telemetry with no server-side "updated" filter, so
+ # append (advancing the timestamp watermark) is the only incremental mode —
+ # merge-based incremental would pointlessly re-merge a huge immutable table.
+ supports_incremental=False,
+ supports_append=True,
+ incremental_fields=INCREMENTAL_FIELDS[endpoint],
+ detected_primary_keys=endpoint_config.primary_keys,
+ description=(
+ f"Raw {endpoint} queried via DataPrime (`source {endpoint_config.dataprime_source}`). "
+ f"Only syncs the last {DEFAULT_LOOKBACK_DAYS} days on initial sync and full refresh."
+ ),
+ )
+
+ 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: CoralogixSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_coralogix_credentials(config.api_key, config.domain):
+ return True, None
+
+ return (
+ False,
+ "Invalid Coralogix API key — check that the key has the DataQuerying permission preset "
+ "and that the selected domain matches your Coralogix account",
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CoralogixResumeConfig]:
+ return ResumableSourceManager[CoralogixResumeConfig](inputs, CoralogixResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CoralogixSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CoralogixResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return coralogix_source(
+ api_key=config.api_key,
+ domain=config.domain,
+ tier=config.tier,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix.py
new file mode 100644
index 000000000000..b96cd67c8295
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix.py
@@ -0,0 +1,395 @@
+import json
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix import coralogix as coralogix_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix import (
+ CoralogixResumeConfig,
+ CoralogixRetryableError,
+ _format_datetime,
+ _make_session,
+ _normalize_row,
+ _parse_timestamp,
+ _run_query,
+ coralogix_source,
+ get_rows,
+ validate_credentials,
+)
+
+NOW = datetime(2026, 1, 15, 12, 0, 0, tzinfo=UTC)
+QUERY_URL = "https://api.eu2.coralogix.com/api/v1/dataprime/query"
+
+
+def _result_item(ts: str, logid: str) -> dict:
+ return {
+ "metadata": [{"key": "logid", "value": logid}, {"key": "timestamp", "value": ts}],
+ "labels": [{"key": "applicationname", "value": "app"}],
+ "userData": '{"msg": "x"}',
+ }
+
+
+def _ndjson_response(results: list[dict], status: int = 200, extra_lines: list[dict] | None = None) -> Response:
+ lines = [json.dumps({"queryId": {"queryId": "q-1"}})]
+ if results:
+ lines.append(json.dumps({"result": {"results": results}}))
+ for extra in extra_lines or []:
+ lines.append(json.dumps(extra))
+ lines.append(json.dumps({"statistics": {"status": "COMPLETED"}}))
+ resp = Response()
+ resp.status_code = status
+ resp._content = "\n".join(lines).encode()
+ # Make iter_lines() serve the canned body instead of reading a (nonexistent) raw socket.
+ resp._content_consumed = True # type: ignore[attr-defined]
+ resp.url = QUERY_URL
+ return resp
+
+
+class _FakeServer:
+ # Simulates the query endpoint: returns fixture rows whose timestamp falls inside the
+ # requested window, treating BOTH boundaries as inclusive — the client-side half-open filter
+ # is what must prevent adjacent windows from double-counting boundary rows.
+ def __init__(self, rows: list[tuple[datetime, str]]):
+ self.rows = rows
+ self.calls: list[dict[str, Any]] = []
+
+ def post(self, url: str, json: dict | None = None, stream: bool = False, timeout: Any = None) -> Response:
+ assert json is not None
+ meta = json["metadata"]
+ start = datetime.strptime(meta["startDate"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=UTC)
+ end = datetime.strptime(meta["endDate"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=UTC)
+ self.calls.append(
+ {"start": start, "end": end, "limit": meta["limit"], "query": json["query"], "tier": meta["tier"]}
+ )
+ matching = [(ts, logid) for ts, logid in self.rows if start <= ts <= end]
+ items = [_result_item(_format_datetime(ts), logid) for ts, logid in matching[: meta["limit"]]]
+ return _ndjson_response(items)
+
+
+def _run_walker(
+ server: _FakeServer,
+ manager: MagicMock | None = None,
+ endpoint: str = "logs",
+ tier: str = "frequent_search",
+ should_use_incremental_field: bool = False,
+ last_value: Any = None,
+) -> tuple[list[str], MagicMock, MagicMock]:
+ manager = manager or _manager()
+ logger = MagicMock()
+ session = MagicMock()
+ session.post.side_effect = server.post
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix.make_tracked_session",
+ return_value=session,
+ ):
+ batches = list(
+ get_rows(
+ api_key="k",
+ domain="eu2.coralogix.com",
+ tier=tier,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+ logids = [row["logid"] for batch in batches for row in batch]
+ return logids, manager, logger
+
+
+def _manager(resume: CoralogixResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+class TestParseTimestamp:
+ @parameterized.expand(
+ [
+ ("iso_z", "2026-01-15T10:00:00.500Z", datetime(2026, 1, 15, 10, 0, 0, 500000, tzinfo=UTC)),
+ # Nanosecond fractions overflow datetime.fromisoformat; they must trim, not fail —
+ # otherwise every row loses its timestamp and the watermark never advances.
+ ("iso_nanoseconds", "2026-01-15T10:00:00.123456789Z", datetime(2026, 1, 15, 10, 0, 0, 123456, tzinfo=UTC)),
+ ("iso_offset", "2026-01-15T02:00:00.00-08:00", datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("iso_naive", "2026-01-15T10:00:00", datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("epoch_seconds", 1768471200, datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("epoch_millis", 1768471200000, datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("epoch_micros", 1768471200000000, datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("epoch_nanos", 1768471200000000000, datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("epoch_string", "1768471200000", datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("datetime_naive", datetime(2026, 1, 15, 10, 0, 0), datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)),
+ ("garbage", "not-a-timestamp", None),
+ ("empty", "", None),
+ ("none", None, None),
+ ]
+ )
+ def test_parses_to_utc(self, _name: str, value: Any, expected: datetime | None) -> None:
+ assert _parse_timestamp(value) == expected
+
+
+class TestNormalizeRow:
+ def test_flattens_metadata_and_labels_and_keeps_user_data_raw(self) -> None:
+ row = _normalize_row(
+ {
+ "metadata": [
+ {"key": "timestamp", "value": "2026-01-15T10:00:00.000Z"},
+ {"key": "logid", "value": "log-1"},
+ {"key": "severity", "value": "Info"},
+ ],
+ "labels": [
+ {"key": "applicationname", "value": "app"},
+ # Collides with metadata; metadata must win.
+ {"key": "severity", "value": "label-severity"},
+ ],
+ "userData": '{"nested": {"deep": 1}}',
+ }
+ )
+ assert row == {
+ "timestamp": datetime(2026, 1, 15, 10, 0, tzinfo=UTC),
+ "logid": "log-1",
+ "severity": "Info",
+ "applicationname": "app",
+ # The body stays a JSON string — flattening arbitrary telemetry would produce an
+ # unstable column set.
+ "user_data": '{"nested": {"deep": 1}}',
+ }
+
+
+class TestMakeSession:
+ def test_disables_sample_capture_and_redirects(self) -> None:
+ # Log/span bodies are free-form user telemetry that can carry secrets the name-based
+ # scrubbers can't recognise, so response capture must stay off; redirects stay pinned off
+ # so a credentialed request can't be replayed against another host.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix.make_tracked_session"
+ ) as make_session:
+ _make_session("secret-key")
+ assert make_session.call_args.kwargs["capture"] is False
+ assert make_session.call_args.kwargs["allow_redirects"] is False
+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)
+
+
+class TestRunQuery:
+ def _query(self, response: Response) -> list[dict]:
+ session = MagicMock()
+ session.post.return_value = response
+ return _run_query.__wrapped__( # type: ignore[attr-defined]
+ session, QUERY_URL, "logs", "TIER_FREQUENT_SEARCH", NOW - timedelta(hours=1), NOW, MagicMock()
+ )
+
+ def test_parses_result_lines_and_ignores_bookkeeping_lines(self) -> None:
+ response = _ndjson_response(
+ [_result_item("2026-01-15T10:00:00.000Z", "log-1")],
+ extra_lines=[
+ {"warning": {"timeRangeWarning": {}}},
+ {"result": {"results": [_result_item("2026-01-15T10:01:00.000Z", "log-2")]}},
+ ],
+ )
+ rows = self._query(response)
+ assert [row["logid"] for row in rows] == ["log-1", "log-2"]
+
+ def test_error_line_raises(self) -> None:
+ with pytest.raises(Exception, match="Coralogix query error"):
+ self._query(_ndjson_response([], extra_lines=[{"error": {"message": "boom"}}]))
+
+ @parameterized.expand([(429,), (500,), (503,)])
+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:
+ with pytest.raises(CoralogixRetryableError):
+ self._query(_ndjson_response([], status=status))
+
+ def test_forbidden_raises_http_error(self) -> None:
+ # 403 must surface as an HTTPError whose message the non-retryable matcher recognises.
+ with pytest.raises(requests.HTTPError, match="403 Client Error"):
+ self._query(_ndjson_response([], status=403))
+
+ def test_stops_reading_a_misbehaving_stream_at_the_row_cap(self) -> None:
+ # The request asks the server for at most QUERY_LIMIT rows; a response that keeps
+ # streaming past it must not be accumulated unboundedly into memory.
+ response = _ndjson_response(
+ [_result_item("2026-01-15T10:00:00.000Z", "log-1")],
+ extra_lines=[
+ {"result": {"results": [_result_item("2026-01-15T10:01:00.000Z", "log-2")]}},
+ {"result": {"results": [_result_item("2026-01-15T10:02:00.000Z", "log-3")]}},
+ ],
+ )
+ with patch.object(coralogix_module, "QUERY_LIMIT", 2):
+ rows = self._query(response)
+ assert [row["logid"] for row in rows] == ["log-1", "log-2"]
+
+
+class TestGetRows:
+ def test_rejects_domains_outside_the_allowlist(self) -> None:
+ # The generated config's Literal type is not validated when job inputs are parsed, so
+ # the transport allowlist is what stops a crafted domain from redirecting the
+ # credentialed request (SSRF / API-key exfiltration). It must fail before any HTTP.
+ session = MagicMock()
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix.make_tracked_session",
+ return_value=session,
+ ),
+ pytest.raises(ValueError, match="Unknown Coralogix domain"),
+ ):
+ list(
+ get_rows(
+ api_key="k",
+ domain="[email protected]",
+ tier="frequent_search",
+ endpoint="logs",
+ logger=MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ )
+ session.post.assert_not_called()
+
+ @freeze_time(NOW)
+ def test_walks_windows_without_double_counting_boundaries(self) -> None:
+ watermark = NOW - timedelta(hours=2)
+ boundary = NOW - timedelta(hours=1)
+ server = _FakeServer(
+ [
+ # At the incremental watermark: yielded by the run that set it, must be dropped.
+ (watermark, "at-watermark"),
+ (NOW - timedelta(minutes=115), "in-first-window"),
+ # Exactly on the window boundary: the inclusive fake server returns it for both
+ # windows; the half-open client filter must keep it exactly once.
+ (boundary, "on-boundary"),
+ # Out of fixture-order relative to `on-boundary` to prove within-window sorting.
+ (NOW - timedelta(minutes=30), "in-second-window"),
+ ]
+ )
+
+ logids, manager, _logger = _run_walker(server, should_use_incremental_field=True, last_value=watermark)
+
+ assert logids == ["in-first-window", "on-boundary", "in-second-window"]
+ # First window is [watermark, watermark+1h); the second grows (sparse) and clamps to now.
+ assert (server.calls[0]["start"], server.calls[0]["end"]) == (watermark, boundary)
+ assert (server.calls[1]["start"], server.calls[1]["end"]) == (boundary, NOW)
+ assert server.calls[0]["query"] == "source logs"
+ assert server.calls[0]["tier"] == "TIER_FREQUENT_SEARCH"
+ # State is saved at each completed window boundary and cleared once fully walked, so a
+ # retry starts fresh from the new watermark instead of resuming mid-stream.
+ saved = [call.args[0].synced_until for call in manager.save_state.call_args_list]
+ assert saved == [_format_datetime(boundary), _format_datetime(NOW)]
+ manager.clear_state.assert_called_once()
+
+ @freeze_time(NOW)
+ def test_bisects_windows_that_hit_the_row_cap(self) -> None:
+ start = NOW - timedelta(hours=2)
+ server = _FakeServer(
+ [
+ (start + timedelta(minutes=10), "r1"),
+ (start + timedelta(minutes=40), "r2"),
+ (start + timedelta(minutes=50), "r3"),
+ ]
+ )
+
+ with patch.object(coralogix_module, "QUERY_LIMIT", 2):
+ logids, _unused_manager, _unused_logger = _run_walker(
+ server, should_use_incremental_field=True, last_value=start
+ )
+
+ # Capped windows are re-queried with a smaller span rather than silently dropping the
+ # rows beyond the cap: every fixture row arrives exactly once, in timestamp order.
+ assert logids == ["r1", "r2", "r3"]
+ assert server.calls[0]["start"] == server.calls[1]["start"] # first bisection retried the cursor
+ assert server.calls[1]["end"] - server.calls[1]["start"] < server.calls[0]["end"] - server.calls[0]["start"]
+
+ @freeze_time(NOW)
+ def test_min_window_cap_warns_and_advances(self) -> None:
+ # A window at the minimum size that still hits the cap must warn (no silent truncation)
+ # and advance — not bisect forever.
+ start = NOW - timedelta(seconds=10)
+ server = _FakeServer([(NOW - timedelta(seconds=8), "r1"), (NOW - timedelta(seconds=6), "r2")])
+
+ with patch.object(coralogix_module, "QUERY_LIMIT", 1):
+ logids, _unused_manager, logger = _run_walker(server, should_use_incremental_field=True, last_value=start)
+
+ assert logids == ["r1"]
+ assert logger.warning.call_count == 1
+ assert "cap" in logger.warning.call_args.args[0]
+
+ @freeze_time(NOW)
+ def test_resumes_inclusively_from_saved_state(self) -> None:
+ watermark = NOW - timedelta(hours=2)
+ synced_until = NOW - timedelta(hours=1)
+ server = _FakeServer(
+ [
+ (NOW - timedelta(minutes=90), "before-resume-point"),
+ # Exactly at the resume boundary: it belonged to the *next* (unfinished) window,
+ # so the inclusive restart must pick it up.
+ (synced_until, "at-resume-point"),
+ ]
+ )
+
+ logids, _unused_manager, _unused_logger = _run_walker(
+ server,
+ manager=_manager(CoralogixResumeConfig(synced_until=_format_datetime(synced_until))),
+ should_use_incremental_field=True,
+ last_value=watermark,
+ )
+
+ assert server.calls[0]["start"] == synced_until
+ assert logids == ["at-resume-point"]
+
+ @freeze_time(NOW)
+ def test_initial_sync_covers_the_default_lookback_contiguously(self) -> None:
+ server = _FakeServer([])
+
+ logids, _unused_manager, _unused_logger = _run_walker(server)
+
+ assert logids == []
+ assert server.calls[0]["start"] == NOW - timedelta(days=coralogix_module.DEFAULT_LOOKBACK_DAYS)
+ assert server.calls[-1]["end"] == NOW
+ for previous, current in zip(server.calls, server.calls[1:]):
+ assert current["start"] == previous["end"]
+
+
+class TestCoralogixSource:
+ @parameterized.expand([("logs", ["logid"]), ("spans", None)])
+ def test_source_response_shape(self, endpoint: str, expected_primary_keys: list[str] | None) -> None:
+ response = coralogix_source(
+ api_key="k",
+ domain="eu2.coralogix.com",
+ tier="archive",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_primary_keys
+ # Rows are sorted per window and windows advance chronologically, so per-batch watermark
+ # checkpointing (asc) is safe; the partition key is the immutable event timestamp.
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == ["timestamp"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("forbidden", 403, False)])
+ def test_maps_status_to_validity(self, _name: str, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.post.return_value = _ndjson_response([], status=status)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix.make_tracked_session",
+ return_value=session,
+ ):
+ assert validate_credentials("k", "coralogix.us") is expected
+ assert session.post.call_args.args[0] == "https://api.coralogix.us/api/v1/dataprime/query"
+
+ def test_network_error_is_invalid(self) -> None:
+ session = MagicMock()
+ session.post.side_effect = requests.ConnectionError("boom")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix.make_tracked_session",
+ return_value=session,
+ ):
+ assert validate_credentials("k", "coralogix.us") is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix_source.py
new file mode 100644
index 000000000000..6174559d227d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix_source.py
@@ -0,0 +1,153 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.coralogix import CoralogixResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.source import CoralogixSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CoralogixSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(
+ api_key: str = "test-key", domain: str = "eu2.coralogix.com", tier: str = "frequent_search"
+) -> CoralogixSourceConfig:
+ return CoralogixSourceConfig.from_dict({"api_key": api_key, "domain": domain, "tier": tier})
+
+
+def _inputs(schema_name: str, should_use_incremental_field: bool = False, last_value: Any = None) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="timestamp" if should_use_incremental_field else None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestCoralogixSource:
+ def test_source_type(self) -> None:
+ assert CoralogixSource().source_type == ExternalDataSourceType.CORALOGIX
+
+ def test_source_config_shape(self) -> None:
+ config = CoralogixSource().get_source_config
+ # A finished source must be visible: unreleasedSource hides the connector from every user.
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/coralogix"
+ assert [f.name for f in config.fields] == ["domain", "api_key", "tier"]
+ api_key_field = config.fields[1]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.secret is True
+
+ def test_domain_options_match_the_transport_allowlist(self) -> None:
+ # The transport rejects domains outside CORALOGIX_DOMAINS, so an option added to the
+ # form without extending the allowlist would break that region at sync time (and an
+ # allowlist entry without an option would be unreachable).
+ from products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.settings import (
+ CORALOGIX_DOMAINS,
+ )
+
+ domain_field = CoralogixSource().get_source_config.fields[0]
+ assert isinstance(domain_field, SourceFieldSelectConfig)
+ assert {option.value for option in domain_field.options} == CORALOGIX_DOMAINS
+
+ def test_domain_is_a_connection_host_field(self) -> None:
+ # `domain` picks the cluster the stored API key is sent to, so retargeting it must force
+ # the editor to re-enter the key.
+ assert CoralogixSource().connection_host_fields == ["domain"]
+
+ def test_get_schemas_are_append_only(self) -> None:
+ # Logs and spans are immutable telemetry: append (timestamp watermark) is the only
+ # incremental mode. Advertising merge-based incremental would re-merge huge immutable
+ # tables for no benefit.
+ schemas = CoralogixSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == {"logs", "spans"}
+ for schema in schemas:
+ assert schema.supports_incremental is False
+ assert schema.supports_append is True
+ assert [f["field"] for f in schema.incremental_fields] == ["timestamp"]
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = CoralogixSource().get_schemas(_config(), team_id=1, names=["logs"])
+ assert [s.name for s in schemas] == ["logs"]
+
+ @parameterized.expand([("valid", True), ("invalid", False)])
+ def test_validate_credentials(self, _name: str, probe_result: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.source.validate_coralogix_credentials",
+ return_value=probe_result,
+ ) as probe:
+ valid, error = CoralogixSource().validate_credentials(_config("key-1", "coralogix.us"), team_id=1)
+
+ probe.assert_called_once_with("key-1", "coralogix.us")
+ assert valid is probe_result
+ assert (error is None) is probe_result
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.eu2.coralogix.com/api/v1/dataprime/query",),
+ ("403 Client Error: Forbidden for url: https://api.coralogix.us/api/v1/dataprime/query",),
+ ]
+ )
+ def test_non_retryable_errors_match_credential_failures(self, raised_message: str) -> None:
+ # A revoked key or wrong-cluster domain must permanently fail the sync rather than retry
+ # forever; the matcher keys on the stable status text + URL prefix shared by every domain.
+ errors = CoralogixSource().get_non_retryable_errors()
+ assert any(pattern in raised_message and friendly for pattern, friendly in errors.items())
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = CoralogixSource().get_resumable_source_manager(_inputs("logs"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CoralogixResumeConfig
+
+ @parameterized.expand([("incremental", True, "2026-01-01"), ("full_refresh", False, None)])
+ def test_source_for_pipeline_plumbs_arguments(
+ self, _name: str, should_use_incremental_field: bool, expected_last_value: Any
+ ) -> None:
+ sentinel = object()
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coralogix.source.coralogix_source",
+ return_value=sentinel,
+ ) as mock_source:
+ inputs = _inputs("spans", should_use_incremental_field, last_value="2026-01-01")
+ result = CoralogixSource().source_for_pipeline(
+ _config("key-123", "coralogix.in", "archive"), manager, inputs
+ )
+
+ assert result is sentinel
+ mock_source.assert_called_once_with(
+ api_key="key-123",
+ domain="coralogix.in",
+ tier="archive",
+ endpoint="spans",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=expected_last_value,
+ )
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # `lists_tables_without_credentials=True` powers the public docs table catalog; it must
+ # resolve from the static endpoint catalog with no network call and merge canonical
+ # descriptions.
+ tables = CoralogixSource().get_documented_tables()
+ by_name: dict[str, dict[str, Any]] = {t["name"]: t for t in tables}
+ assert set(by_name) == {"logs", "spans"}
+ assert by_name["logs"]["sync_methods"] == ["Append only", "Full refresh"]
+ assert by_name["logs"]["primary_keys"] == ["logid"]
+ assert by_name["spans"]["description"]
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 1724d14b9fff..e05d21723e73 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
@@ -1093,7 +1093,17 @@ class CopperSourceConfig(config.Config):
@config.config
class CoralogixSourceConfig(config.Config):
- pass
+ api_key: str
+ domain: Literal[
+ "coralogix.us",
+ "cx498.coralogix.com",
+ "coralogix.com",
+ "eu2.coralogix.com",
+ "coralogix.in",
+ "coralogixsg.com",
+ "ap3.coralogix.com",
+ ] = config.value(default="coralogix.us")
+ tier: Literal["frequent_search", "archive"] = config.value(default="frequent_search")
@config.config