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 secoda import source (#68582)

Tom Owers8984c3f49c1f
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 71462d4d8fe8..63e9dbd02b80 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -289,6 +289,7 @@ the row lists both.
| rootly | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| salesloft | HTTP | requests | ✅ |
+| secoda | HTTP | requests | ✅ |
| segment | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -641,7 +642,6 @@ doesn't conflict with concurrent PRs.
- sap_successfactors
- savvycal
- search_ads_360
-- secoda
- sendowl
- sendpulse
- senseforce
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 8ee48ae721d1..79260c390d4f 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
@@ -2904,7 +2904,7 @@ class SearchAds360SourceConfig(config.Config):
@config.config
class SecodaSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/canonical_descriptions.py
new file mode 100644
index 000000000000..247a0ab54a8c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/canonical_descriptions.py
@@ -0,0 +1,83 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Secoda API docs (https://docs.secoda.co/api/reference).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "tables": {
+ "description": "A table catalogued in Secoda from a connected data integration.",
+ "docs_url": "https://docs.secoda.co/api/reference/tables",
+ "columns": {
+ "id": "The unique ID of the table.",
+ "title": "The table name.",
+ "description": "The table's documented description.",
+ "integration": "The ID of the integration the table was ingested from.",
+ "database": "The database the table belongs to.",
+ "schema": "The schema the table belongs to.",
+ "url": "The Secoda URL for the table.",
+ "created_at": "When the table was first catalogued in Secoda.",
+ "updated_at": "When the table's metadata was last updated.",
+ },
+ },
+ "columns": {
+ "description": "A column belonging to a catalogued table in Secoda.",
+ "docs_url": "https://docs.secoda.co/api/reference/columns",
+ "columns": {
+ "id": "The unique ID of the column.",
+ "title": "The column name.",
+ "description": "The column's documented description.",
+ "type": "The column's data type.",
+ "parent": "The ID of the table the column belongs to.",
+ "integration": "The ID of the integration the column was ingested from.",
+ "created_at": "When the column was first catalogued in Secoda.",
+ "updated_at": "When the column's metadata was last updated.",
+ },
+ },
+ "collections": {
+ "description": "A collection used to group and organise resources in Secoda.",
+ "docs_url": "https://docs.secoda.co/api/reference/collections",
+ "columns": {
+ "id": "The unique ID of the collection.",
+ "title": "The collection name.",
+ "description": "The collection's description.",
+ "owners": "The users who own the collection.",
+ "created_at": "When the collection was created.",
+ "updated_at": "When the collection was last updated.",
+ },
+ },
+ "users": {
+ "description": "A user in the Secoda workspace.",
+ "docs_url": "https://docs.secoda.co/api/reference/users",
+ "columns": {
+ "id": "The unique ID of the user.",
+ "email": "The user's email address.",
+ "first_name": "The user's first name.",
+ "last_name": "The user's last name.",
+ "display_name": "The user's display name.",
+ "role": "The user's workspace role.",
+ "is_active": "Whether the user account is active.",
+ },
+ },
+ "groups": {
+ "description": "A user group (team) in the Secoda workspace.",
+ "docs_url": "https://docs.secoda.co/api/reference/groups",
+ "columns": {
+ "id": "The unique ID of the group.",
+ "name": "The group name.",
+ "icon": "The group's icon.",
+ "users": "The users that belong to the group.",
+ "created_at": "When the group was created.",
+ },
+ },
+ "tags": {
+ "description": "A tag used to label and categorise resources in Secoda.",
+ "docs_url": "https://docs.secoda.co/api/reference/tags",
+ "columns": {
+ "id": "The unique ID of the tag.",
+ "name": "The tag name.",
+ "color": "The tag's display colour.",
+ "created_at": "When the tag was created.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/secoda.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/secoda.py
new file mode 100644
index 000000000000..f9013564adcf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/secoda.py
@@ -0,0 +1,156 @@
+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.secoda.settings import SECODA_ENDPOINTS
+
+# US cloud host. EU (eapi.secoda.co), APAC (aapi.secoda.co) and self-hosted domains are not yet
+# selectable — see the region caveat in the source docs.
+SECODA_BASE_URL = "https://api.secoda.co"
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap list endpoint used to confirm an API key is genuine. The key inherits its creator's
+# workspace permissions, so one probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/api/v1/user"
+
+
+class SecodaRetryableError(Exception):
+ pass
+
+
+class SecodaResumeConfig:
+ # Full URL of the next page to fetch, taken verbatim from the API's ``links.next``. Secoda uses
+ # DRF-style cursor pagination, so a crashed full-refresh sync resumes from the page after the
+ # last one yielded; merge dedupes the re-pulled page on ``id``.
+ next_url: str | None = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _extract_next_url(data: dict[str, Any]) -> Optional[str]:
+ # DRF pagination nests the follow link under ``links.next``; a couple of Secoda endpoints put it
+ # at the top level, so we accept either. ``next`` is a full URL (or null on the last page).
+ links = data.get("links")
+ if isinstance(links, dict) and links.get("next"):
+ return links["next"]
+ top_level = data.get("next")
+ return top_level if isinstance(top_level, str) and top_level else None
+
+
+@retry(
+ retry=retry_if_exception_type((SecodaRetryableError, 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,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], Optional[str]]:
+ # ``url`` is already absolute — either the initial endpoint URL or a verbatim ``links.next``, so
+ # we never re-send page params (they're baked into the cursor URL).
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SecodaRetryableError(f"Secoda API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Secoda API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):
+ raise SecodaRetryableError(f"Secoda returned an unexpected payload for {url}: {type(data).__name__}")
+
+ return data["results"], _extract_next_url(data)
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SecodaResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SECODA_ENDPOINTS[endpoint]
+ 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
+ url: Optional[str] = resume.next_url if (resume and resume.next_url) else f"{SECODA_BASE_URL}{config.path}"
+ if resume and resume.next_url:
+ logger.debug(f"Secoda: resuming {endpoint} from cursor {url}")
+
+ while url:
+ items, next_url = _fetch_page(session, url, logger)
+ if items:
+ yield items
+
+ # A null ``next`` link means we've reached the end of the collection.
+ if not next_url:
+ break
+
+ url = next_url
+ # Save AFTER yielding so a crash re-fetches from the next cursor (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(SecodaResumeConfig(next_url=next_url))
+
+
+def secoda_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SecodaResumeConfig],
+) -> SourceResponse:
+ config = SECODA_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"{SECODA_BASE_URL}{path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Secoda: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Secoda 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 Secoda API key"
+ return False, message or "Could not validate Secoda API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/settings.py
new file mode 100644
index 000000000000..271c28a44102
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/settings.py
@@ -0,0 +1,26 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class SecodaEndpointConfig:
+ name: str
+ path: str
+ # Secoda resource identifiers are workspace-unique UUIDs, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Secoda v1 REST list endpoints. All are full-refresh only: Secoda's List Resources filter supports
+# only exact/contains/in operators (no greater-than / on-or-after), so there is no server-side
+# timestamp cursor to advance an incremental sync (see the implementing-warehouse-sources skill).
+SECODA_ENDPOINTS: dict[str, SecodaEndpointConfig] = {
+ "tables": SecodaEndpointConfig(name="tables", path="/api/v1/table/tables"),
+ "columns": SecodaEndpointConfig(name="columns", path="/api/v1/table/columns"),
+ "collections": SecodaEndpointConfig(name="collections", path="/api/v1/collection/collections"),
+ "users": SecodaEndpointConfig(name="users", path="/api/v1/user"),
+ "groups": SecodaEndpointConfig(name="groups", path="/api/v1/auth/group"),
+ "tags": SecodaEndpointConfig(name="tags", path="/api/v1/tag"),
+}
+
+ENDPOINTS = tuple(SECODA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/source.py
index 07b0ab10fb23..a5e2037be6c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/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 SecodaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda.secoda import (
+ SecodaResumeConfig,
+ secoda_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda.settings import ENDPOINTS, SECODA_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SecodaSource(SimpleSource[SecodaSourceConfig]):
+class SecodaSource(ResumableSource[SecodaSourceConfig, SecodaResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SECODA
@@ -24,7 +44,86 @@ class SecodaSource(SimpleSource[SecodaSourceConfig]):
name=SchemaExternalDataSourceType.SECODA,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Secoda",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Secoda API key to pull your data catalog into the PostHog Data warehouse.
+
+You can create an API key under **Settings → API** in [Secoda](https://app.secoda.co). The key inherits your workspace permissions and grants read access to your tables, columns, collections, users, groups, and tags.
+""",
iconPath="/static/services/secoda.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/secoda",
+ 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.secoda.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.secoda.co": "Your Secoda API key is invalid or has been revoked. Generate a new key under Settings → API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.secoda.co": "Your Secoda API key does not have access to this data. Check the key owner's workspace permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SecodaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Secoda's filter syntax exposes no range operator, so
+ # there is no server-side timestamp cursor to advance an incremental sync.
+ 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: SecodaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is workspace-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[SecodaResumeConfig]:
+ return ResumableSourceManager[SecodaResumeConfig](inputs, SecodaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SecodaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SecodaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SECODA_ENDPOINTS:
+ raise ValueError(f"Unknown Secoda schema '{inputs.schema_name}'")
+
+ return secoda_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/secoda/tests/test_secoda.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/tests/test_secoda.py
new file mode 100644
index 000000000000..58a4b92f717c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/tests/test_secoda.py
@@ -0,0 +1,229 @@
+from collections.abc import Mapping
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda import secoda
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda.secoda import (
+ SECODA_BASE_URL,
+ SecodaResumeConfig,
+ SecodaRetryableError,
+ check_access,
+ get_rows,
+ secoda_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda.settings import ENDPOINTS, SECODA_ENDPOINTS
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = secoda._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: SecodaResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SecodaResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SecodaResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SecodaResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: Mapping[str, tuple[list[dict], Optional[str]]],
+ endpoint: str = "tables",
+ ) -> list[dict]:
+ def fake_fetch(session: Any, url: str, logger: Any) -> tuple[list[dict], Optional[str]]:
+ return pages[url]
+
+ monkeypatch.setattr(secoda, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(secoda, "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_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first = f"{SECODA_BASE_URL}/api/v1/table/tables"
+ rows = self._collect(manager, monkeypatch, {first: ([{"id": "a"}, {"id": "b"}], None)})
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # A null next link ends the sync without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_next_url_cursor_until_null(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first = f"{SECODA_BASE_URL}/api/v1/table/tables"
+ second = f"{SECODA_BASE_URL}/api/v1/table/tables?page=2"
+ pages = {first: ([{"id": "a"}], second), second: ([{"id": "b"}], None)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # State is saved once — after the first page, pointing at the next cursor — then we stop.
+ assert [s.next_url for s in manager.saved] == [second]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ second = f"{SECODA_BASE_URL}/api/v1/table/tables?page=2"
+ manager = _FakeResumableManager(SecodaResumeConfig(next_url=second))
+ # The first page URL must never be fetched on resume.
+ pages = {second: ([{"id": "b"}], None)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "b"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first = f"{SECODA_BASE_URL}/api/v1/table/tables"
+ rows = self._collect(manager, monkeypatch, {first: ([], None)})
+ 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 {"results": [], "links": {"next": None}}
+ 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(SecodaRetryableError):
+ _fetch_page_unwrapped(session, f"{SECODA_BASE_URL}/api/v1/table/tables", 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, f"{SECODA_BASE_URL}/api/v1/table/tables", MagicMock())
+
+ def test_success_returns_results_and_links_next(self) -> None:
+ next_url = f"{SECODA_BASE_URL}/api/v1/table/tables?page=2"
+ body = {"results": [{"id": "a"}], "links": {"next": next_url}, "count": 5}
+ session = self._session_returning(200, body)
+ rows, returned_next = _fetch_page_unwrapped(session, f"{SECODA_BASE_URL}/api/v1/table/tables", MagicMock())
+ assert rows == [{"id": "a"}]
+ assert returned_next == next_url
+
+ def test_top_level_next_is_accepted(self) -> None:
+ next_url = f"{SECODA_BASE_URL}/api/v1/tag?page=2"
+ body = {"results": [{"id": "a"}], "next": next_url}
+ session = self._session_returning(200, body)
+ _, returned_next = _fetch_page_unwrapped(session, f"{SECODA_BASE_URL}/api/v1/tag", MagicMock())
+ assert returned_next == next_url
+
+ def test_null_next_returns_none(self) -> None:
+ body = {"results": [{"id": "a"}], "links": {"next": None, "previous": None}}
+ session = self._session_returning(200, body)
+ _, returned_next = _fetch_page_unwrapped(session, f"{SECODA_BASE_URL}/api/v1/user", MagicMock())
+ assert returned_next is None
+
+ @parameterized.expand([("bare_list", [{"id": "a"}]), ("missing_results", {"count": 1})])
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(SecodaRetryableError):
+ _fetch_page_unwrapped(session, f"{SECODA_BASE_URL}/api/v1/user", MagicMock())
+
+ def test_request_uses_absolute_url_without_params(self) -> None:
+ session = self._session_returning(200, {"results": [], "links": {"next": None}})
+ url = f"{SECODA_BASE_URL}/api/v1/table/columns?page=3"
+ _fetch_page_unwrapped(session, url, MagicMock())
+ args, kwargs = session.get.call_args
+ assert args[0] == url
+ # The cursor URL already carries paging; we must not re-send page params.
+ assert "params" not in kwargs
+
+
+class TestCheckAccess:
+ def _session(self, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Secoda returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with patch.object(secoda, "make_tracked_session", return_value=self._session(response)):
+ assert check_access("sk-key") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ session = self._session(requests.ConnectionError("boom"))
+ with patch.object(secoda, "make_tracked_session", return_value=session):
+ status, message = check_access("sk-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Secoda API key"),
+ ("forbidden", 403, False, "Invalid Secoda API key"),
+ ("server_error", 500, False, "Secoda returned HTTP 500"),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ with patch.object(secoda, "make_tracked_session", return_value=self._session(response)):
+ assert validate_credentials("sk-key") == (expected_valid, expected_message)
+
+
+class TestSecodaSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = secoda_source(
+ api_key="sk-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # No stable creation timestamp is guaranteed across every object, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in SECODA_ENDPOINTS.values())
+ assert set(SECODA_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/tests/test_secoda_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/tests/test_secoda_source.py
new file mode 100644
index 000000000000..3f158bc974ab
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/secoda/tests/test_secoda_source.py
@@ -0,0 +1,123 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+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 SecodaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda.secoda import SecodaResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.secoda.source import SecodaSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSecodaSource:
+ def setup_method(self) -> None:
+ self.source = SecodaSource()
+ self.team_id = 123
+ self.config = SecodaSourceConfig(api_key="sk-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SECODA
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Secoda"
+ assert config.label == "Secoda"
+ 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/secoda"
+
+ 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=["collections"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "collections"
+
+ 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)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.secoda.co/api/v1/table/tables",),
+ ("403 Client Error: Forbidden for url: https://api.secoda.co/api/v1/user",),
+ ]
+ )
+ 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)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.secoda.co/api/v1/table/tables",),
+ ("429 Client Error: Too Many Requests for url: https://api.secoda.co/api/v1/user",),
+ ]
+ )
+ 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)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.secoda.source.validate_credentials")
+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:
+ # The source method forwards the workspace API key to the shared validator and returns its result verbatim.
+ mock_validate.return_value = (False, "Invalid Secoda API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ assert result == (False, "Invalid Secoda API key")
+ mock_validate.assert_called_once_with("sk-key")
+
+ 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 SecodaResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.secoda.source.secoda_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "tables"
+ 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"] == "tables"
+ 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 Secoda schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)