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 svix import source (#68555)

Tom Owers21e30f4a8c5c
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 703c1fa765c8..ca85282e72b1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -321,6 +321,7 @@ the row lists both.
| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |
| surveymonkey | HTTP | requests | ✅ |
+| svix | HTTP | requests | ✅ |
| taboola | HTTP | requests | ✅ |
| teamtailor | HTTP | requests | ✅ |
| teamwork | HTTP | requests | ✅ |
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 ae6de1e248d0..fd11750fe96d 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
@@ -3198,7 +3198,7 @@ class SurvicateSourceConfig(config.Config):
@config.config
class SvixSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/svix/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/canonical_descriptions.py
new file mode 100644
index 000000000000..fecf1df9cc27
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/canonical_descriptions.py
@@ -0,0 +1,36 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Svix API docs (https://api.svix.com/docs).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "applications": {
+ "description": "A Svix application — an isolated tenant that owns its own endpoints and receives webhook messages.",
+ "docs_url": "https://api.svix.com/docs",
+ "columns": {
+ "id": "The unique Svix-generated ID of the application.",
+ "uid": "Your optional custom unique identifier for the application.",
+ "name": "The application's display name.",
+ "rateLimit": "The per-application message rate limit, if set.",
+ "metadata": "Arbitrary key-value metadata attached to the application.",
+ "createdAt": "When the application was created.",
+ "updatedAt": "When the application was last modified.",
+ },
+ },
+ "event_types": {
+ "description": "A Svix event type — the schema and metadata for a category of webhook messages your application sends.",
+ "docs_url": "https://api.svix.com/docs",
+ "columns": {
+ "name": "The unique name of the event type (e.g. `invoice.paid`).",
+ "description": "A human-readable description of the event type.",
+ "schemas": "The JSON schema(s) describing the payload for this event type.",
+ "archived": "Whether the event type has been archived.",
+ "deprecated": "Whether the event type is marked as deprecated.",
+ "featureFlag": "The feature flag gating this event type, if any.",
+ "groupName": "The group the event type belongs to, used for organising event types.",
+ "createdAt": "When the event type was created.",
+ "updatedAt": "When the event type was last modified.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/svix/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/settings.py
new file mode 100644
index 000000000000..023c0afb82e1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/settings.py
@@ -0,0 +1,22 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class SvixEndpointConfig:
+ name: str
+ path: str
+ # Primary key differs per endpoint: applications carry an opaque `id`, while event types are
+ # keyed by their unique `name`.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Svix Management API top-level list endpoints. Both are cursor-paginated and full-refresh only —
+# neither exposes a server-side updated-since filter, so there is no incremental cursor to advance.
+# Per-application fan-out endpoints (endpoints, messages, message attempts) require an app id and
+# are intentionally excluded from v1.
+SVIX_ENDPOINTS: dict[str, SvixEndpointConfig] = {
+ "applications": SvixEndpointConfig(name="applications", path="/app", primary_keys=["id"]),
+ "event_types": SvixEndpointConfig(name="event_types", path="/event-type", primary_keys=["name"]),
+}
+
+ENDPOINTS = tuple(SVIX_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/svix/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/source.py
index 7b6489411e2c..d54e95d81f19 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/svix/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/source.py
@@ -1,19 +1,39 @@
-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 SvixSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix.settings import ENDPOINTS, SVIX_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix.svix import (
+ SvixResumeConfig,
+ svix_source,
+ validate_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SvixSource(SimpleSource[SvixSourceConfig]):
+class SvixSource(ResumableSource[SvixSourceConfig, SvixResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SVIX
@@ -24,7 +44,86 @@ class SvixSource(SimpleSource[SvixSourceConfig]):
name=SchemaExternalDataSourceType.SVIX,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Svix",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Svix API key to pull your webhook platform data into the PostHog Data warehouse.
+
+You can create an API key under **Settings → API Access** in the [Svix dashboard](https://dashboard.svix.com/). The region is encoded in the key (the `sk_` prefix), so use the key for the environment you want to sync. The key grants read access to your applications and event types.
+""",
iconPath="/static/services/svix.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/svix",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.svix.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.svix.com": "Your Svix API key is invalid or has been revoked. Generate a new key under Settings → API Access, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.svix.com": "Your Svix API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SvixSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Svix's list endpoints expose no server-side
+ # updated-since filter, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: SvixSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is account-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SvixResumeConfig]:
+ return ResumableSourceManager[SvixResumeConfig](inputs, SvixResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SvixSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SvixResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SVIX_ENDPOINTS:
+ raise ValueError(f"Unknown Svix schema '{inputs.schema_name}'")
+
+ return svix_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/svix/svix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/svix.py
new file mode 100644
index 000000000000..17bdb8dff822
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/svix.py
@@ -0,0 +1,160 @@
+import dataclasses
+from collections.abc import Iterator
+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.svix.settings import SVIX_ENDPOINTS
+
+SVIX_BASE_URL = "https://api.svix.com/api/v1"
+# The list endpoints accept a `limit` of up to 250; the largest page minimises round trips.
+PAGE_SIZE = 250
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/event-type"
+
+
+class SvixRetryableError(Exception):
+ pass
+
+
+class SvixResumeConfig:
+ # Opaque cursor returned by the previous page. Svix cursor pagination is deterministic, so a
+ # crashed full-refresh sync resumes from the page after the last one yielded; merge dedupes on
+ # the primary key. `None` means start from the beginning.
+ iterator: Optional[str] = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((SvixRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ iterator: Optional[str],
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": limit}
+ # Omit `iterator` on the first request; Svix rejects an empty cursor value.
+ if iterator is not None:
+ params["iterator"] = iterator
+
+ response = session.get(
+ f"{SVIX_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SvixRetryableError(f"Svix API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Svix API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Svix list endpoints return a `{"data": [...], "iterator": "...", "done": bool}` envelope.
+ if not isinstance(data, dict) or "data" not in data:
+ raise SvixRetryableError(f"Svix returned an unexpected payload for {path}: {type(data).__name__}")
+ return data
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SvixResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SVIX_ENDPOINTS[endpoint]
+ # `redact_values` masks the API key in logged URLs and captured samples.
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ iterator = resume.iterator if resume else None
+ if resume and resume.iterator is not None:
+ logger.debug(f"Svix: resuming {endpoint} from saved cursor")
+
+ while True:
+ data = _fetch_page(session, config.path, iterator, PAGE_SIZE, logger)
+
+ items = data["data"]
+ if items:
+ yield items
+
+ # `done` signals the last page; a missing/absent cursor is treated as terminal too.
+ if data.get("done", True):
+ break
+ iterator = data.get("iterator")
+ if iterator is None:
+ break
+
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(SvixResumeConfig(iterator=iterator))
+
+
+def svix_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SvixResumeConfig],
+) -> SourceResponse:
+ config = SVIX_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{SVIX_BASE_URL}{path}", params={"limit": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Svix: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Svix returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Svix API key"
+ return False, message or "Could not validate Svix API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/svix/tests/test_svix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/tests/test_svix.py
new file mode 100644
index 000000000000..1ecede0d2f32
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/tests/test_svix.py
@@ -0,0 +1,230 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix import svix
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix.settings import ENDPOINTS, SVIX_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix.svix import (
+ PAGE_SIZE,
+ SvixResumeConfig,
+ SvixRetryableError,
+ check_access,
+ get_rows,
+ svix_source,
+ validate_credentials,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = svix._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: SvixResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SvixResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SvixResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SvixResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(items: list[dict], iterator: str | None, done: bool) -> dict:
+ return {"data": items, "iterator": iterator, "done": done}
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str | None, dict],
+ endpoint: str = "applications",
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, iterator: str | None, limit: int, logger: Any) -> dict:
+ return pages[iterator]
+
+ monkeypatch.setattr(svix, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(svix, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="sk-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_done_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: dict[str | None, dict] = {None: _page([{"id": "app_1"}, {"id": "app_2"}], iterator="c1", done=True)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "app_1"}, {"id": "app_2"}]
+ # `done` on the first page means we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_cursor_until_done(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ None: _page([{"id": "app_1"}], iterator="c1", done=False),
+ "c1": _page([{"id": "app_2"}], iterator="c2", done=True),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "app_1"}, {"id": "app_2"}]
+ # State saved once, carrying the cursor that fetches the second page.
+ assert [s.iterator for s in manager.saved] == ["c1"]
+
+ def test_stops_when_iterator_missing(self, monkeypatch: Any) -> None:
+ # A page that isn't `done` but returns no next cursor must still terminate.
+ manager = _FakeResumableManager()
+ pages: dict[str | None, dict] = {None: _page([{"id": "app_1"}], iterator=None, done=False)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "app_1"}]
+ assert manager.saved == []
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(SvixResumeConfig(iterator="c1"))
+ # The first (None) page must never be fetched on resume.
+ pages: dict[str | None, dict] = {"c1": _page([{"id": "app_2"}], iterator="c2", done=True)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "app_2"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: dict[str | None, dict] = {None: _page([], iterator=None, done=True)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == []
+ assert manager.saved == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"data": [], "done": True}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(SvixRetryableError):
+ _fetch_page_unwrapped(session, "/app", None, PAGE_SIZE, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/app", None, PAGE_SIZE, MagicMock())
+
+ def test_success_returns_envelope(self) -> None:
+ body = {"data": [{"id": "app_1"}], "iterator": "c1", "done": True}
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "/app", None, PAGE_SIZE, MagicMock())
+ assert result == body
+
+ def test_body_without_data_key_is_retryable(self) -> None:
+ session = self._session_returning(200, {"error": "nope"})
+ with pytest.raises(SvixRetryableError):
+ _fetch_page_unwrapped(session, "/app", None, PAGE_SIZE, MagicMock())
+
+ def test_first_request_omits_iterator_param(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/app", None, PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE}
+
+ def test_subsequent_request_includes_iterator_param(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/app", "c1", PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE, "iterator": "c1"}
+
+
+class TestCheckAccess:
+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ monkeypatch.setattr(svix, "make_tracked_session", lambda **kwargs: session)
+ return session
+
+ @pytest.mark.parametrize(
+ "status, ok, expected_status, expected_message",
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "Svix returned HTTP 500"),
+ ],
+ )
+ def test_status_mapping(
+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ self._patch_session(monkeypatch, response)
+ assert check_access("sk-key") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:
+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))
+ status, message = check_access("sk-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @pytest.mark.parametrize(
+ "status, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid Svix API key"),
+ (403, False, "Invalid Svix API key"),
+ (500, False, "Svix returned HTTP 500"),
+ ],
+ )
+ def test_validate_credentials(
+ self, status: int, expected_valid: bool, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ self._patch_session(monkeypatch, response)
+ assert validate_credentials("sk-key") == (expected_valid, expected_message)
+
+
+class TestSvixSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = svix_source(
+ api_key="sk-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == SVIX_ENDPOINTS[endpoint].primary_keys
+ # No stable creation timestamp is guaranteed across every object, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_primary_keys_per_endpoint(self) -> None:
+ assert SVIX_ENDPOINTS["applications"].primary_keys == ["id"]
+ assert SVIX_ENDPOINTS["event_types"].primary_keys == ["name"]
+ assert set(SVIX_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/svix/tests/test_svix_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/tests/test_svix_source.py
new file mode 100644
index 000000000000..a5a91606d7c0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/svix/tests/test_svix_source.py
@@ -0,0 +1,141 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+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 SvixSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix.source import SvixSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.svix.svix import SvixResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSvixSource:
+ def setup_method(self) -> None:
+ self.source = SvixSource()
+ self.team_id = 123
+ self.config = SvixSourceConfig(api_key="sk-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SVIX
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Svix"
+ assert config.label == "Svix"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/svix"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another account.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["event_types"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "event_types"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.svix.com/api/v1/app?limit=250",
+ "403 Client Error: Forbidden for url: https://api.svix.com/api/v1/event-type?limit=250",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "unrelated_error",
+ [
+ "500 Server Error: Internal Server Error for url: https://api.svix.com/api/v1/app",
+ "429 Client Error: Too Many Requests for url: https://api.svix.com/api/v1/event-type",
+ ],
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "status, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid Svix API key"),
+ (403, False, "Invalid Svix API key"),
+ (500, False, "Svix returned HTTP 500"),
+ (0, False, "Could not connect to Svix: boom"),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.svix.svix.check_access")
+ def test_validate_credentials(
+ self,
+ mock_check: mock.MagicMock,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ message = (
+ "Svix returned HTTP 500" if status == 500 else ("Could not connect to Svix: boom" if status == 0 else None)
+ )
+ mock_check.return_value = (status, message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SvixResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.svix.source.svix_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "applications"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "sk-key"
+ assert kwargs["endpoint"] == "applications"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Svix schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)